1
0
forked from wrenn/wrenn

Added basic frontend (#1)

Reviewed-on: wrenn/sandbox#1
Co-authored-by: pptx704 <rafeed@omukk.dev>
Co-committed-by: pptx704 <rafeed@omukk.dev>
This commit is contained in:
2026-03-22 19:01:38 +00:00
committed by Rafeed M. Bhuiyan
parent 866f3ac012
commit 97292ba0bf
76 changed files with 5770 additions and 683 deletions

9
.gitignore vendored
View File

@ -37,3 +37,12 @@ e2b/
## Builds ## Builds
builds/ builds/
## Frontend
frontend/node_modules/
frontend/.svelte-kit/
frontend/build/
## Dashboard embedded static (built from frontend, not committed)
internal/dashboard/static/*
!internal/dashboard/static/.gitkeep

212
CLAUDE.md
View File

@ -12,14 +12,16 @@ All commands go through the Makefile. Never use raw `go build` or `go run`.
```bash ```bash
make build # Build all binaries → builds/ make build # Build all binaries → builds/
make build-cp # Control plane only make build-cp # Control plane only (builds frontend first)
make build-agent # Host agent only make build-agent # Host agent only
make build-envd # envd static binary (verified statically linked) make build-envd # envd static binary (verified statically linked)
make build-frontend # SvelteKit dashboard → internal/dashboard/static/
make dev # Full local dev: infra + migrate + control plane make dev # Full local dev: infra + migrate + control plane
make dev-infra # Start PostgreSQL + Prometheus + Grafana (Docker) make dev-infra # Start PostgreSQL + Prometheus + Grafana (Docker)
make dev-down # Stop dev infra make dev-down # Stop dev infra
make dev-cp # Control plane with hot reload (if air installed) make dev-cp # Control plane with hot reload (if air installed)
make dev-frontend # Vite dev server with HMR (port 5173)
make dev-agent # Host agent (sudo required) make dev-agent # Host agent (sudo required)
make dev-envd # envd in TCP debug mode make dev-envd # envd in TCP debug mode
@ -62,13 +64,13 @@ envd is a **completely independent Go module**. It is never imported by the main
### Control Plane ### Control Plane
**Packages:** `internal/api/`, `internal/admin/`, `internal/auth/`, `internal/scheduler/`, `internal/lifecycle/`, `internal/config/`, `internal/db/` **Packages:** `internal/api/`, `internal/dashboard/`, `internal/auth/`, `internal/scheduler/`, `internal/lifecycle/`, `internal/config/`, `internal/db/`
Startup (`cmd/control-plane/main.go`) wires: config (env vars) → pgxpool → `db.Queries` (sqlc-generated) → Connect RPC client to host agent → `api.Server`. Everything flows through constructor injection. Startup (`cmd/control-plane/main.go`) wires: config (env vars) → pgxpool → `db.Queries` (sqlc-generated) → Connect RPC client to host agent → `api.Server`. Everything flows through constructor injection.
- **API Server** (`internal/api/server.go`): chi router with middleware. Creates handler structs (`sandboxHandler`, `execHandler`, `filesHandler`, etc.) injected with `db.Queries` and the host agent Connect RPC client. Routes under `/v1/sandboxes/*`. - **API Server** (`internal/api/server.go`): chi router with middleware. Creates handler structs (`sandboxHandler`, `execHandler`, `filesHandler`, etc.) injected with `db.Queries` and the host agent Connect RPC client. Routes under `/v1/sandboxes/*`.
- **Reconciler** (`internal/api/reconciler.go`): background goroutine (every 30s) that compares DB records against `agent.ListSandboxes()` RPC. Marks orphaned DB entries as "stopped". - **Reconciler** (`internal/api/reconciler.go`): background goroutine (every 30s) that compares DB records against `agent.ListSandboxes()` RPC. Marks orphaned DB entries as "stopped".
- **Admin UI** at `/admin/` (htmx + basecoat + alpine.js + Go html/template, no SPA, no build step) - **Dashboard** (SvelteKit + Tailwind + Bits UI, statically built and embedded via `go:embed`, served as catch-all at root)
- **Database**: PostgreSQL via pgx/v5. Queries generated by sqlc from `db/queries/sandboxes.sql`. Migrations in `db/migrations/` (goose, plain SQL). - **Database**: PostgreSQL via pgx/v5. Queries generated by sqlc from `db/queries/sandboxes.sql`. Migrations in `db/migrations/` (goose, plain SQL).
- **Config** (`internal/config/config.go`): purely environment variables (`DATABASE_URL`, `CP_LISTEN_ADDR`, `CP_HOST_AGENT_ADDR`), no YAML/file config. - **Config** (`internal/config/config.go`): purely environment variables (`DATABASE_URL`, `CP_LISTEN_ADDR`, `CP_HOST_AGENT_ADDR`), no YAML/file config.
@ -95,6 +97,22 @@ Runs as PID 1 inside the microVM via `wrenn-init.sh` (mounts procfs/sysfs/dev, s
- **FilesystemService**: stat/list/mkdir/move/remove/watch files - **FilesystemService**: stat/list/mkdir/move/remove/watch files
- **Health**: GET `/health` - **Health**: GET `/health`
### Dashboard (Frontend)
**Directory:** `frontend/` — standalone SvelteKit app (Svelte 5, runes mode)
- **Stack**: SvelteKit + `adapter-static` + Tailwind CSS v4 + Bits UI (headless accessible components)
- **Package manager**: pnpm
- **Routing**: SvelteKit file-based routing under `frontend/src/routes/`
- **Routing layout**: `/login` and `/signup` at root, authenticated pages under `/dashboard/*` (e.g. `/dashboard/capsules`, `/dashboard/keys`)
- **Build output**: `frontend/build/` → copied to `internal/dashboard/static/` → embedded via `go:embed` into the control plane binary
- **Serving**: `internal/dashboard/dashboard.go` registers a `NotFound` catch-all SPA handler with fallback to `index.html`. API routes (`/v1/*`, `/openapi.yaml`, `/docs`) are registered first and take priority
- **Dev workflow**: `make dev-frontend` runs Vite dev server on port 5173 with HMR. API calls proxy to `http://localhost:8000`
- **Fonts**: Manrope (UI), Instrument Serif (headings), JetBrains Mono (code), Alice (brand wordmark) — all self-hosted via `@fontsource`
- **Dark mode**: class-based (`.dark` on `<html>`) with system preference detection + localStorage persistence
To add a new page: create `frontend/src/routes/your-page/+page.svelte`.
### Networking (per sandbox) ### Networking (per sandbox)
Each sandbox gets its own Linux network namespace (`ns-{idx}`). Slot index (1-based, up to 65534) determines all addressing: Each sandbox gets its own Linux network namespace (`ns-{idx}`). Slot index (1-based, up to 65534) determines all addressing:
@ -183,7 +201,7 @@ To add a new query: add it to the appropriate `.sql` file in `db/queries/` → `
- **TAP networking** (not vsock) for host-to-envd communication - **TAP networking** (not vsock) for host-to-envd communication
- **Device-mapper snapshots** for rootfs CoW — shared read-only loop device per base template, per-sandbox sparse CoW file, Firecracker gets `/dev/mapper/wrenn-{id}` - **Device-mapper snapshots** for rootfs CoW — shared read-only loop device per base template, per-sandbox sparse CoW file, Firecracker gets `/dev/mapper/wrenn-{id}`
- **PostgreSQL** via pgx/v5 + sqlc (type-safe query generation). Goose for migrations (plain SQL, up/down) - **PostgreSQL** via pgx/v5 + sqlc (type-safe query generation). Goose for migrations (plain SQL, up/down)
- **Admin UI**: htmx + Go html/template + chi router. No SPA, no React, no build step - **Dashboard**: SvelteKit (Svelte 5, adapter-static) + Tailwind CSS v4 + Bits UI. Built to static files, embedded into the Go binary via `go:embed`, served as catch-all at root
- **Lago** for billing (external service, not in this codebase) - **Lago** for billing (external service, not in this codebase)
## Coding Conventions ## Coding Conventions
@ -214,22 +232,184 @@ The main module (`go.mod`) and envd (`envd/go.mod`) are fully independent. `make
## Web UI Styling ## Web UI Styling
**Wrenn brand:** ### Identity
Warm earthy developer tool with crafted organic character.
**Color palette (light/dark):** Warm, confident developer tool with industrial precision and crafted organic character. The feel is sharp and data-forward — not cold or sterile, but not soft either. Think: an engineer's favorite tool, built with care.
Background scale: #f8f6f1#f1eeea#e8e5e0#dedbd5 (light); #090b0a#0f1211#151918#1b201e#222826 (dark). Text hierarchy: bright #2c2a26 / body #4a4740 / dim #7a766e / faint #a09b93 (light); #e8e5df / #c8c4bc / #8a867f / #5f5c57 (dark). Sage green brand accent: #5e8c58 (light) / #89a785 (dark), with glow variant rgba(94,140,88,0.08). Borders: #e2dfd9 (light) / #262c2a (dark). Semantic status colors: amber #9e7c2e (warning/building), red #b35544 (error/failed), blue #3d7aac (info/stopped) — each with a color-dim transparent bg variant for badge backgrounds. Destructive: #b35544 light / #c27b6d dark.
**Typography:** ---
Four fonts. Manrope (variable, weights 300700) for all UI labels, nav, body. Instrument Serif (400) for page titles, empty-state headings, large metric values. JetBrains Mono (400/500) for code, env var keys/values, deployment IDs, commit SHAs, log viewer, URL paths. Alice for the sidebar wordmark only. Base body size 14px. Headings: h1 24px serif, h2 20px, h3 18px, h4h6 11px sans-serif uppercase wide-tracked. Metric card values 34px serif at letter-spacing: -0.08em. Section labels at 0.060.07em tracking, weight 550600.
Spacing: 4px base unit (Tailwind scale). Page content p-8 (32px). Cards p-4p-5. Sidebar nav items 7px 10px. Consistent, moderate density — functional but not cramped.
**Borders & depth:** Flat aesthetic — --shadow-sm: 0 0 #0000, no drop shadows. Depth is achieved through background color stepping (bg → bg-3 → bg-4 → bg-5), not shadows. Borders 1px solid in warm muted tones. Corner radii: cards/surfaces 12px, inputs/small buttons 68px, avatars 8px, dots 50%. ### Color Palette (Dark Mode)
**Components:** Active sidebar nav items use a 3px left-border in sage green rather than filled backgrounds, with a sage glow bg (rgba(94,140,88,0.08)). Focus rings are double-ring: 0 0 0 2px background, 0 0 0 4px ring. Status system has four states (Live/sage, Building/amber+pulse, Failed/red, Stopped/faint) each with solid dot + transparent-bg badge pair. Buttons follow ghost → outline → filled hierarchy. Tables wrapped in rounded-xl border. Dialogs via native <dialog>. Toasts bottom-anchored. **Background scale (6 steps, near-black-green):**
`#0a0c0b` (bg-0, page base) → `#0f1211` (bg-1, sidebar/topbar) → `#141817` (bg-2, cards/surfaces) → `#1a1e1c` (bg-3, hover states/elevated) → `#212624` (bg-4, inputs/avatars) → `#2a302d` (bg-5, active controls)
**Animation:** Crisp 150ms transitions on all interactive elements. Sidebar width 250ms ease. Custom wrenn-pulse keyframe (2.5s ease infinite box-shadow bloom) on live/building status dots. Top-of-page loading bar (h-0.5, sage green) on navigation. **Text hierarchy (5 levels):**
- Bright `#eae7e2` — page titles, metric values, active states
- Primary `#d0cdc6` — body text, nav labels, readable content
- Secondary `#9b9790` — supporting text, inactive nav, descriptions
- Tertiary `#6b6862` — labels, section headers, timestamps
- Muted `#454340` — ghost text, disabled states, grid labels
**Dark mode:** Full support. Very dark near-black-green backgrounds with warm off-white text and desaturated sage accent. Flat (no card shadows). System preference detection + localStorage persistence. **Sage green brand accent (3 tiers + 2 glows):**
- Solid `#5e8c58` — primary accent, buttons, borders, active indicators
- Mid `#89a785` — badges, chart lines, secondary accent
- Bright `#a4c89f` — active nav text, live counts, chart dots
- Glow `rgba(94,140,88,0.07)` — active nav backgrounds, subtle highlights
- Glow Mid `rgba(94,140,88,0.14)` — live badges, status badge backgrounds
**Overall feel:** Warm, earthy, semi-flat. Avoids cold grays entirely — palette leans slightly warm/brown-tinted throughout. The serif + mono + geometric sans type stack gives a designed but unfussy developer-tool character. Organic and considered, not sterile. **Borders (2 levels):**
- Default `#1f2321` — card edges, dividers, sidebar borders
- Mid `#2a2f2c` — hover states, interactive borders, stronger separation
**Semantic status colors:**
- Amber `#d4a73c` — warning, building, countdown timers
- Red `#cf8172` — error, failed, destructive actions
- Blue `#5a9fd4` — info, stopped (use sparingly)
**Light mode:** (TBD — follow same warm-tinted approach. Background scale from `#f8f6f1``#dedbd5`. Text hierarchy inverts. Accent stays `#5e8c58` for solid.)
---
### Typography
Four fonts, each with a clear role:
| Font | Role | Weights | Where |
|------|------|---------|-------|
| **Manrope** (variable) | Body, UI | 400700 | All body text, nav labels, buttons, descriptions, section headers |
| **Instrument Serif** | Display, metrics | 400 | Page titles (h1), large metric values, empty-state headings only |
| **JetBrains Mono** | Code, data | 400600 | Status bar, time range buttons, search inputs, IDs, commit SHAs, countdown timers, log viewer, URL paths, code blocks |
| **Alice** | Brand wordmark | 400 | Sidebar wordmark only — never used elsewhere |
**Sizing:**
- Base body: `14px`
- Page title (h1): `24px` serif, `letter-spacing: -0.02em`
- Card metric values: `36px` serif, `letter-spacing: -0.04em`
- Chart inline metric: `30px` serif, `letter-spacing: -0.04em`
- Nav items: `13px` body, weight 500
- Section/group labels: `11px` body, uppercase, `letter-spacing: 0.06em`, weight 600
- Chart section labels: `12px` body, uppercase, `letter-spacing: 0.05em`, weight 600
- Stat cell labels: `11px` body, uppercase, `letter-spacing: 0.05em`, weight 600
- Badge text: `10px`, uppercase, `letter-spacing: 0.04em`, weight 600
- Status bar / footer links: `1112px` mono
- Table headers: `11px` body, uppercase, `letter-spacing: 0.05em`, weight 600, color muted
- Table body cells: `13px`
**Key rule:** Instrument Serif is reserved exclusively for page-level titles and large numeric values. It provides warmth and character without softness. Everything else uses Manrope (UI) or JetBrains Mono (data/code).
---
### Spacing
4px base unit (Tailwind scale). Moderate density — functional and confident, never cramped.
- Page content padding: `2428px`
- Card/surface internal padding: `1820px`
- Sidebar width: `230px`
- Sidebar nav item padding: `8px 10px`
- Sidebar brand area: `18px 16px 16px`
- Tab bar items: `10px 16px`
- Topbar: `16px 28px`
- Metric strip cell: `18px 20px`
- Chart header: `18px 20px`
- Chart canvas: `14px 20px 12px`
- Table header cells: `11px 16px`
- Table body cells: `12px 16px`
- Status bar: `6px 28px`
- Between sections (cards): `2024px` margin-bottom
---
### Borders & Depth
**Flat aesthetic — no drop shadows.** Depth comes from background color stepping (bg-0 → bg-1 → bg-2 → bg-3), not shadows. `--shadow-sm: 0 0 #0000`.
- All borders: `1px solid` in warm muted tones
- Corner radii: cards/surfaces `8px`, inputs/buttons `5px`, logo mark `6px`, avatars `5px`, dots `50%`
- Connected metric cells use shared border container with `border-left: 1px solid` between cells (no gap/grid trick) — creates the industrial panel look
- Tables wrapped in `border-radius: 8px` container with overflow hidden
---
### Components
**Sidebar navigation:**
- Active items use `3px left-border` in sage solid (`#5e8c58`) with accent glow background (`rgba(94,140,88,0.07)`)
- Active text color: accent-bright (`#a4c89f`)
- Icons at `16px`, opacity 0.5 default, 1.0 on active
- Group labels: `11px` uppercase with `0.06em` tracking, muted color
**Status chip (live indicator):**
- Rounded `8px` border, `bg-2` background, `border-mid` border
- Pulsing dot: `7px`, accent-solid fill, `box-shadow: 0 0 8px rgba(94,140,88,0.5)` with glow animation
- Count in mono at `14px` accent-bright, label in secondary text
**Live badges (inline):**
- `10px` text, uppercase, `3px` border-radius
- Background: accent-glow-mid (`rgba(94,140,88,0.14)`), text: accent mid
- Includes `5px` pulsing dot with box-shadow
**Metric strip:**
- 3-column grid, connected cells (single outer border, inner dividers)
- Hover: background steps from bg-2 to bg-3
- Value: `36px` serif, bright text
- Label: `11px` uppercase, tertiary
- Sub-metadata row with `1px` divider between items
**Chart cards:**
- `8px` border-radius, bg-2 background, default border
- Header: section label (12px uppercase) + large serif metric + live badge
- Range group: segmented buttons with `1px` borders, mono text, active state uses bg-5
- Chart area: SVG with `0.5px` grid lines in border color, `10px` mono axis labels in muted
- Data line: `1.5px` accent-solid stroke, `stroke-linejoin: round`
- Area fill: gradient from `rgba(94,140,88,0.28)` → transparent
- Data dot: accent-bright fill, `2.5px` bg-2 stroke, `4px` radius
**Buttons hierarchy:**
1. Ghost (icon-btn): transparent bg, default border, tertiary color → border-mid + secondary on hover
2. Outline: no bg, border-mid border → accent-solid border + primary text on hover
3. Tool: bg-2 background, default border → border-mid + primary on hover
4. Filled/CTA: accent-solid background, white text → lighter green on hover, subtle `translateY(-1px)` lift
**Tables:**
- Container: `8px` border-radius, border, overflow hidden
- Header: bg-3 background, `11px` uppercase muted text
- Body: default bg, `1px` border-bottom between rows
- Row hover: bg-3
**Empty states:**
- Centered, `72px` vertical padding
- Icon container: `56px` square, bg-3, border-mid border, `8px` radius
- Heading: `20px` serif, bright text
- Description: `13px` body, tertiary text
- CTA button below
**Inputs:**
- bg-2 background, default border, `5px` radius
- Mono font for search/filter inputs
- Focus: `border-color: accent-solid` (clean single ring, no double-ring)
- Placeholder: muted color
**Focus rings:** Single accent-solid border-color change on focus. Clean and minimal — no double-ring outlines.
---
### Animation
- **All interactive transitions:** `150ms ease`
- **Page load / section entrance:** `fadeUp``opacity: 0, translateY(6px)` → visible, `0.35s ease`, staggered with `6080ms` delays between elements
- **Chart data animation:** SVG `<animate>` on path `d`, polyline `points`, and circle `cy``0.50.6s` duration, `0.20.35s` begin delay, `fill: freeze`
- **Live status dot:** `glow` keyframe — `2.5s ease infinite` box-shadow bloom from `0 0 6px rgba(94,140,88,0.5)``0 0 14px rgba(94,140,88,0.2)`
- **CTA buttons:** subtle `translateY(-1px)` on hover for lift feel
---
### Dark Mode
Primary and default mode. Very dark near-black-green backgrounds (`#0a0c0b` base) with warm off-white text and desaturated sage accent. Completely flat — no card shadows anywhere. System preference detection + localStorage persistence.
---
### Overall Feel
Sharp, warm, industrial-confident. Avoids cold grays entirely — palette leans slightly warm/brown-tinted throughout. The serif display type provides organic character and warmth on titles and metrics, while Manrope handles readable UI text and JetBrains Mono anchors the data-forward, developer-tool identity. Connected metric panels, tight chart cards, and uppercase section labels create engineering density without sacrificing readability. The result is a tool that feels crafted and precise — designed by someone who uses developer tools daily.

View File

@ -9,10 +9,13 @@ LDFLAGS := -s -w
# ═══════════════════════════════════════════════════ # ═══════════════════════════════════════════════════
# Build # Build
# ═══════════════════════════════════════════════════ # ═══════════════════════════════════════════════════
.PHONY: build build-cp build-agent build-envd .PHONY: build build-cp build-agent build-envd build-frontend
build: build-cp build-agent build-envd build: build-cp build-agent build-envd
build-frontend:
cd frontend && pnpm install --frozen-lockfile && pnpm build
build-cp: build-cp:
go build -v -ldflags="$(LDFLAGS)" -o $(GOBIN)/wrenn-cp ./cmd/control-plane go build -v -ldflags="$(LDFLAGS)" -o $(GOBIN)/wrenn-cp ./cmd/control-plane
@ -28,7 +31,7 @@ build-envd:
# ═══════════════════════════════════════════════════ # ═══════════════════════════════════════════════════
# Development # Development
# ═══════════════════════════════════════════════════ # ═══════════════════════════════════════════════════
.PHONY: dev dev-cp dev-agent dev-envd dev-infra dev-down .PHONY: dev dev-cp dev-agent dev-envd dev-frontend dev-infra dev-down
## One command to start everything for local dev ## One command to start everything for local dev
dev: dev-infra migrate-up dev-cp dev: dev-infra migrate-up dev-cp
@ -49,6 +52,9 @@ dev-cp:
dev-agent: dev-agent:
sudo go run ./cmd/host-agent sudo go run ./cmd/host-agent
dev-frontend:
cd frontend && pnpm dev --port 5173
dev-envd: dev-envd:
cd $(ENVD_DIR) && go run . --debug --listen-tcp :3002 cd $(ENVD_DIR) && go run . --debug --listen-tcp :3002
@ -171,10 +177,12 @@ help:
@echo " make dev-infra Start PostgreSQL + Prometheus + Grafana" @echo " make dev-infra Start PostgreSQL + Prometheus + Grafana"
@echo " make dev-down Stop dev infra" @echo " make dev-down Stop dev infra"
@echo " make dev-cp Control plane (hot reload if air installed)" @echo " make dev-cp Control plane (hot reload if air installed)"
@echo " make dev-frontend Vite dev server with HMR (port 5173)"
@echo " make dev-agent Host agent (sudo required)" @echo " make dev-agent Host agent (sudo required)"
@echo " make dev-envd envd in TCP debug mode" @echo " make dev-envd envd in TCP debug mode"
@echo "" @echo ""
@echo " make build Build all binaries → builds/" @echo " make build Build all binaries → builds/"
@echo " make build-frontend Build SvelteKit dashboard → frontend/build/"
@echo " make build-envd Build envd static binary" @echo " make build-envd Build envd static binary"
@echo "" @echo ""
@echo " make migrate-up Apply migrations" @echo " make migrate-up Apply migrations"

View File

@ -75,7 +75,7 @@ Control plane listens on `CP_LISTEN_ADDR` (default `:8000`).
Hosts must be registered with the control plane before they can serve sandboxes. Hosts must be registered with the control plane before they can serve sandboxes.
1. **Create a host record** (via API or admin UI): 1. **Create a host record** (via API or dashboard):
```bash ```bash
# As an admin (JWT auth) # As an admin (JWT auth)
curl -X POST http://localhost:8000/v1/hosts \ curl -X POST http://localhost:8000/v1/hosts \

View File

@ -80,7 +80,7 @@ func main() {
slog.Error("CP_PUBLIC_URL must be set when OAuth providers are configured") slog.Error("CP_PUBLIC_URL must be set when OAuth providers are configured")
os.Exit(1) os.Exit(1)
} }
callbackURL := strings.TrimRight(cfg.CPPublicURL, "/") + "/v1/auth/oauth/github/callback" callbackURL := strings.TrimRight(cfg.CPPublicURL, "/") + "/auth/oauth/github/callback"
ghProvider := oauth.NewGitHubProvider(cfg.OAuthGitHubClientID, cfg.OAuthGitHubClientSecret, callbackURL) ghProvider := oauth.NewGitHubProvider(cfg.OAuthGitHubClientID, cfg.OAuthGitHubClientSecret, callbackURL)
oauthRegistry.Register(ghProvider) oauthRegistry.Register(ghProvider)
slog.Info("registered OAuth provider", "provider", "github") slog.Info("registered OAuth provider", "provider", "github")

View File

@ -9,6 +9,14 @@ SELECT * FROM team_api_keys WHERE key_hash = $1;
-- name: ListAPIKeysByTeam :many -- name: ListAPIKeysByTeam :many
SELECT * FROM team_api_keys WHERE team_id = $1 ORDER BY created_at DESC; SELECT * FROM team_api_keys WHERE team_id = $1 ORDER BY created_at DESC;
-- name: ListAPIKeysByTeamWithCreator :many
SELECT k.id, k.team_id, k.name, k.key_hash, k.key_prefix, k.created_by, k.created_at, k.last_used,
u.email AS creator_email
FROM team_api_keys k
JOIN users u ON u.id = k.created_by
WHERE k.team_id = $1
ORDER BY k.created_at DESC;
-- name: DeleteAPIKey :exec -- name: DeleteAPIKey :exec
DELETE FROM team_api_keys WHERE id = $1 AND team_id = $2; DELETE FROM team_api_keys WHERE id = $1 AND team_id = $2;

View File

@ -13,7 +13,9 @@ SELECT * FROM sandboxes WHERE id = $1 AND team_id = $2;
SELECT * FROM sandboxes ORDER BY created_at DESC; SELECT * FROM sandboxes ORDER BY created_at DESC;
-- name: ListSandboxesByTeam :many -- name: ListSandboxesByTeam :many
SELECT * FROM sandboxes WHERE team_id = $1 ORDER BY created_at DESC; SELECT * FROM sandboxes
WHERE team_id = $1 AND status NOT IN ('stopped', 'error')
ORDER BY created_at DESC;
-- name: ListSandboxesByHostAndStatus :many -- name: ListSandboxesByHostAndStatus :many
SELECT * FROM sandboxes SELECT * FROM sandboxes

23
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
node_modules
# Output
.output
.vercel
.netlify
.wrangler
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

1
frontend/.npmrc Normal file
View File

@ -0,0 +1 @@
engine-strict=true

30
frontend/package.json Normal file
View File

@ -0,0 +1,30 @@
{
"name": "frontend",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
},
"devDependencies": {
"@fontsource-variable/jetbrains-mono": "^5.2.8",
"@fontsource-variable/manrope": "^5.2.8",
"@fontsource/alice": "^5.2.8",
"@fontsource/instrument-serif": "^5.2.8",
"@sveltejs/adapter-static": "^3.0.10",
"@sveltejs/kit": "^2.50.2",
"@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/vite": "^4.2.1",
"bits-ui": "^2.16.3",
"svelte": "^5.51.0",
"svelte-check": "^4.4.2",
"tailwindcss": "^4.2.1",
"typescript": "^5.9.3",
"vite": "^7.3.1"
}
}

1491
frontend/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

121
frontend/src/app.css Normal file
View File

@ -0,0 +1,121 @@
@import 'tailwindcss';
@import '@fontsource-variable/manrope';
@import '@fontsource/instrument-serif/400.css';
@import '@fontsource-variable/jetbrains-mono';
@import '@fontsource/alice/400.css';
/*
* Wrenn Design Tokens
* Sharp, warm, industrial-confident. Dark-first.
*/
@theme {
/* Background scale (6 steps, near-black-green) */
--color-bg-0: #0a0c0b;
--color-bg-1: #0f1211;
--color-bg-2: #141817;
--color-bg-3: #1a1e1c;
--color-bg-4: #212624;
--color-bg-5: #2a302d;
/* Text hierarchy (5 levels) */
--color-text-bright: #eae7e2;
--color-text-primary: #d0cdc6;
--color-text-secondary: #9b9790;
--color-text-tertiary: #6b6862;
--color-text-muted: #454340;
/* Sage green brand accent (3 tiers + 2 glows) */
--color-accent: #5e8c58;
--color-accent-mid: #89a785;
--color-accent-bright: #a4c89f;
--color-accent-glow: rgba(94, 140, 88, 0.07);
--color-accent-glow-mid: rgba(94, 140, 88, 0.14);
/* Borders (2 levels) */
--color-border: #1f2321;
--color-border-mid: #2a2f2c;
/* Semantic status */
--color-amber: #d4a73c;
--color-red: #cf8172;
--color-blue: #5a9fd4;
/* Fonts */
--font-sans: 'Manrope Variable', system-ui, sans-serif;
--font-serif: 'Instrument Serif', serif;
--font-mono: 'JetBrains Mono Variable', monospace;
--font-brand: 'Alice', serif;
/* Radii */
--radius-card: 8px;
--radius-input: 5px;
--radius-button: 5px;
--radius-avatar: 5px;
--radius-logo: 6px;
/* Shadows — flat aesthetic */
--shadow-sm: 0 0 #0000;
}
/* Base styles */
html {
font-family: var(--font-sans);
font-size: 14px;
color: var(--color-text-primary);
background-color: var(--color-bg-0);
}
body {
margin: 0;
min-height: 100vh;
}
/* Selection */
::selection {
background: rgba(94, 140, 88, 0.25);
color: var(--color-text-bright);
}
/* Scrollbar — thin, matches dark theme */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--color-bg-4);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--color-bg-5);
}
/* Live status dot glow animation */
@keyframes wrenn-glow {
0%,
100% {
box-shadow: 0 0 6px rgba(94, 140, 88, 0.5);
}
50% {
box-shadow: 0 0 14px rgba(94, 140, 88, 0.2);
}
}
/* Fade-up entrance animation */
@keyframes fadeUp {
from {
opacity: 0;
transform: translateY(6px);
}
to {
opacity: 1;
transform: translateY(0);
}
}

13
frontend/src/app.d.ts vendored Normal file
View File

@ -0,0 +1,13 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

15
frontend/src/app.html Normal file
View File

@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#0a0c0b" />
<link rel="icon" href="/logo.svg" type="image/svg+xml" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>Wrenn</title>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View File

@ -0,0 +1,37 @@
export type AuthResponse = {
token: string;
user_id: string;
team_id: string;
email: string;
};
export type AuthResult = { ok: true; data: AuthResponse } | { ok: false; error: string };
export async function apiLogin(email: string, password: string): Promise<AuthResult> {
return authFetch('/api/v1/auth/login', { email, password });
}
export async function apiSignup(email: string, password: string): Promise<AuthResult> {
return authFetch('/api/v1/auth/signup', { email, password });
}
async function authFetch(url: string, body: Record<string, string>): Promise<AuthResult> {
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
const data = await res.json();
if (!res.ok) {
const message = data?.error?.message ?? 'Something went wrong';
return { ok: false, error: message };
}
return { ok: true, data: data as AuthResponse };
} catch {
return { ok: false, error: 'Unable to connect to the server' };
}
}

View File

@ -0,0 +1,66 @@
import { apiFetch, type ApiResult } from '$lib/api/client';
export type Capsule = {
id: string;
status: string;
template: string;
vcpus: number;
memory_mb: number;
timeout_sec: number;
guest_ip?: string;
host_ip?: string;
created_at: string;
started_at?: string;
last_active_at?: string;
last_updated: string;
};
export async function listCapsules(): Promise<ApiResult<Capsule[]>> {
return apiFetch('GET', '/api/v1/sandboxes');
}
export type CreateCapsuleParams = {
template?: string;
vcpus?: number;
memory_mb?: number;
timeout_sec?: number;
};
export async function createCapsule(params: CreateCapsuleParams): Promise<ApiResult<Capsule>> {
return apiFetch('POST', '/api/v1/sandboxes', params);
}
export async function pauseCapsule(id: string): Promise<ApiResult<Capsule>> {
return apiFetch('POST', `/api/v1/sandboxes/${id}/pause`);
}
export async function resumeCapsule(id: string): Promise<ApiResult<Capsule>> {
return apiFetch('POST', `/api/v1/sandboxes/${id}/resume`);
}
export async function destroyCapsule(id: string): Promise<ApiResult<void>> {
return apiFetch('DELETE', `/api/v1/sandboxes/${id}`);
}
export type Snapshot = {
name: string;
type: string;
vcpus?: number;
memory_mb?: number;
size_bytes: number;
created_at: string;
};
export async function createSnapshot(sandboxId: string, name?: string): Promise<ApiResult<Snapshot>> {
return apiFetch('POST', '/api/v1/snapshots', { sandbox_id: sandboxId, name });
}
export async function listSnapshots(typeFilter?: string): Promise<ApiResult<Snapshot[]>> {
const url = typeFilter ? `/api/v1/snapshots?type=${typeFilter}` : '/api/v1/snapshots';
return apiFetch('GET', url);
}
export async function deleteSnapshot(name: string): Promise<ApiResult<void>> {
return apiFetch('DELETE', `/api/v1/snapshots/${name}`);
}

View File

@ -0,0 +1,24 @@
import { auth } from '$lib/auth.svelte';
export type ApiResult<T> = { ok: true; data: T } | { ok: false; error: string };
export async function apiFetch<T>(method: string, path: string, body?: unknown): Promise<ApiResult<T>> {
try {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (auth.token) headers['Authorization'] = `Bearer ${auth.token}`;
const res = await fetch(path, {
method,
headers,
body: body ? JSON.stringify(body) : undefined
});
if (res.status === 204) return { ok: true, data: undefined as T };
const data = await res.json();
if (!res.ok) return { ok: false, error: data?.error?.message ?? 'Something went wrong' };
return { ok: true, data: data as T };
} catch {
return { ok: false, error: 'Unable to connect to the server' };
}
}

View File

@ -0,0 +1,26 @@
import { apiFetch, type ApiResult } from '$lib/api/client';
export type APIKey = {
id: string;
team_id: string;
name: string;
key_prefix: string;
created_by: string;
creator_email?: string;
created_at: string;
last_used?: string;
key?: string; // only present immediately after creation
};
export async function listKeys(): Promise<ApiResult<APIKey[]>> {
return apiFetch('GET', '/api/v1/api-keys');
}
export async function createKey(name: string): Promise<ApiResult<APIKey>> {
return apiFetch('POST', '/api/v1/api-keys', { name });
}
export async function revokeKey(id: string): Promise<ApiResult<void>> {
return apiFetch('DELETE', `/api/v1/api-keys/${id}`);
}

View File

@ -0,0 +1,94 @@
import { goto } from '$app/navigation';
const STORAGE_KEYS = {
token: 'wrenn_token',
userId: 'wrenn_user_id',
teamId: 'wrenn_team_id',
email: 'wrenn_email'
} as const;
function isTokenExpired(token: string): boolean {
try {
const payload = token.split('.')[1];
const decoded = atob(payload.replace(/-/g, '+').replace(/_/g, '/'));
const { exp } = JSON.parse(decoded);
return Date.now() / 1000 >= exp;
} catch {
return true;
}
}
function createAuth() {
let token = $state<string | null>(null);
let userId = $state<string | null>(null);
let teamId = $state<string | null>(null);
let email = $state<string | null>(null);
let initialized = $state(false);
// Initialize from localStorage synchronously at module load.
if (typeof window !== 'undefined') {
const stored = localStorage.getItem(STORAGE_KEYS.token);
if (stored && !isTokenExpired(stored)) {
token = stored;
userId = localStorage.getItem(STORAGE_KEYS.userId);
teamId = localStorage.getItem(STORAGE_KEYS.teamId);
email = localStorage.getItem(STORAGE_KEYS.email);
} else if (stored) {
// Expired — clean up.
for (const key of Object.values(STORAGE_KEYS)) {
localStorage.removeItem(key);
}
}
initialized = true;
}
const isAuthenticated = $derived(token !== null && !isTokenExpired(token));
return {
get token() {
return token;
},
get userId() {
return userId;
},
get teamId() {
return teamId;
},
get email() {
return email;
},
get isAuthenticated() {
return isAuthenticated;
},
get initialized() {
return initialized;
},
login(data: { token: string; user_id: string; team_id: string; email: string }) {
token = data.token;
userId = data.user_id;
teamId = data.team_id;
email = data.email;
localStorage.setItem(STORAGE_KEYS.token, data.token);
localStorage.setItem(STORAGE_KEYS.userId, data.user_id);
localStorage.setItem(STORAGE_KEYS.teamId, data.team_id);
localStorage.setItem(STORAGE_KEYS.email, data.email);
},
logout() {
token = null;
userId = null;
teamId = null;
email = null;
for (const key of Object.values(STORAGE_KEYS)) {
localStorage.removeItem(key);
}
goto('/login');
}
};
}
export const auth = createAuth();

View File

@ -0,0 +1,210 @@
<script lang="ts">
import { Dialog } from 'bits-ui';
import {
IconGithub,
IconMail,
IconLock,
IconUser,
IconX,
IconEye,
IconEyeOff
} from './icons';
let {
mode = $bindable('signin'),
open = $bindable(false),
onSwitchMode
}: {
mode: 'signin' | 'signup';
open: boolean;
onSwitchMode: () => void;
} = $props();
let email = $state('');
let password = $state('');
let name = $state('');
let showPassword = $state(false);
const title = $derived(mode === 'signin' ? 'Welcome back' : 'Create account');
const subtitle = $derived(
mode === 'signin' ? 'Sign in to your Wrenn account' : 'Get started with Wrenn'
);
const submitLabel = $derived(mode === 'signin' ? 'Sign in' : 'Create account');
const switchText = $derived(
mode === 'signin' ? "Don't have an account?" : 'Already have an account?'
);
const switchAction = $derived(mode === 'signin' ? 'Sign up' : 'Sign in');
function handleSubmit(e: Event) {
e.preventDefault();
}
</script>
<Dialog.Root bind:open>
<Dialog.Portal>
<Dialog.Overlay
class="fixed inset-0 z-50 bg-black/70 backdrop-blur-[3px]"
style="animation: overlayFadeIn 200ms ease"
/>
<Dialog.Content
class="fixed left-1/2 top-1/2 z-50 w-[calc(100%-2rem)] max-w-[400px] -translate-x-1/2 -translate-y-1/2 rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-0"
style="animation: contentSlideIn 250ms cubic-bezier(0.16, 1, 0.3, 1)"
>
<!-- Close button -->
<Dialog.Close
class="absolute right-3 top-3 flex h-7 w-7 items-center justify-center rounded-[var(--radius-button)] border border-transparent text-[var(--color-text-tertiary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:bg-[var(--color-bg-4)] hover:text-[var(--color-text-secondary)]"
>
<IconX size={14} />
</Dialog.Close>
<div class="px-7 pb-7 pt-8">
<!-- Header -->
<div class="mb-7">
<Dialog.Title
class="font-serif text-[24px] tracking-[-0.02em] text-[var(--color-text-bright)]"
>
{title}
</Dialog.Title>
<Dialog.Description
class="mt-1 text-[13px] text-[var(--color-text-secondary)]"
>
{subtitle}
</Dialog.Description>
</div>
<!-- GitHub OAuth -->
<button
type="button"
class="flex w-full items-center justify-center gap-2.5 rounded-[var(--radius-button)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] px-4 py-2.5 text-[13px] font-medium text-[var(--color-text-bright)] transition-all duration-150 hover:border-[var(--color-accent)] hover:text-[var(--color-text-bright)]"
>
<IconGithub size={16} />
Continue with GitHub
</button>
<!-- Divider -->
<div class="my-5 flex items-center gap-3">
<div class="h-px flex-1 bg-[var(--color-border)]"></div>
<span
class="font-mono text-[10px] uppercase tracking-[0.1em] text-[var(--color-text-muted)]"
>or</span
>
<div class="h-px flex-1 bg-[var(--color-border)]"></div>
</div>
<!-- Form -->
<form onsubmit={handleSubmit} class="space-y-3">
{#if mode === 'signup'}
<div class="group relative">
<div
class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] transition-colors duration-150 group-focus-within:text-[var(--color-accent)]"
>
<IconUser size={14} />
</div>
<input
type="text"
bind:value={name}
placeholder="Full name"
autocomplete="name"
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-2)] py-2.5 pl-9 pr-3 text-[13px] text-[var(--color-text-bright)] outline-none transition-all duration-150 placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-accent)]"
/>
</div>
{/if}
<div class="group relative">
<div
class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] transition-colors duration-150 group-focus-within:text-[var(--color-accent)]"
>
<IconMail size={14} />
</div>
<input
type="email"
bind:value={email}
placeholder="Email address"
autocomplete="email"
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-2)] py-2.5 pl-9 pr-3 text-[13px] text-[var(--color-text-bright)] outline-none transition-all duration-150 placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-accent)]"
/>
</div>
<div class="group relative">
<div
class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] transition-colors duration-150 group-focus-within:text-[var(--color-accent)]"
>
<IconLock size={14} />
</div>
<input
type={showPassword ? 'text' : 'password'}
bind:value={password}
placeholder="Password"
autocomplete={mode === 'signin' ? 'current-password' : 'new-password'}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-2)] py-2.5 pl-9 pr-10 text-[13px] text-[var(--color-text-bright)] outline-none transition-all duration-150 placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-accent)]"
/>
<button
type="button"
onclick={() => (showPassword = !showPassword)}
class="absolute right-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] transition-colors duration-150 hover:text-[var(--color-text-secondary)]"
tabindex={-1}
>
{#if showPassword}
<IconEyeOff size={14} />
{:else}
<IconEye size={14} />
{/if}
</button>
</div>
{#if mode === 'signin'}
<div class="flex justify-end">
<button
type="button"
class="text-[12px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:text-[var(--color-accent-mid)]"
>
Forgot password?
</button>
</div>
{/if}
<button
type="submit"
class="!mt-5 w-full rounded-[var(--radius-button)] bg-[var(--color-accent)] px-4 py-2.5 text-[13px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0"
>
{submitLabel}
</button>
</form>
<!-- Switch mode -->
<p class="mt-5 text-center text-[12px] text-[var(--color-text-secondary)]">
{switchText}
<button
type="button"
onclick={onSwitchMode}
class="font-medium text-[var(--color-text-primary)] transition-colors duration-150 hover:text-[var(--color-text-bright)]"
>
{switchAction}
</button>
</p>
</div>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
<style>
@keyframes overlayFadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes contentSlideIn {
from {
opacity: 0;
transform: translate(-50%, -48%) scale(0.96);
}
to {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}
}
</style>

View File

@ -0,0 +1,308 @@
<script lang="ts">
import { page } from '$app/stores';
import { Popover } from 'bits-ui';
import { auth } from '$lib/auth.svelte';
import {
IconMonitor,
IconBox,
IconKey,
IconMembers,
IconUsage,
IconBilling,
IconSettings,
IconLogout,
IconChevron,
IconPlus,
IconSidebar,
IconBell,
IconDocs,
IconAudit
} from './icons';
let { collapsed = $bindable(false) }: { collapsed: boolean } = $props();
let teamPopoverOpen = $state(false);
const currentTeam = 'default';
const userName = $derived(auth.email ?? '');
type NavItem = {
label: string;
icon: typeof IconMonitor;
href: string;
};
const platformItems: NavItem[] = [
{ label: 'Capsules', icon: IconMonitor, href: '/dashboard/capsules' },
{ label: 'Templates', icon: IconBox, href: '/dashboard/snapshots' }
];
const managementItems: NavItem[] = [
{ label: 'Keys', icon: IconKey, href: '/dashboard/keys' },
{ label: 'Members', icon: IconMembers, href: '/dashboard/members' },
{ label: 'Audit Logs', icon: IconAudit, href: '/dashboard/audit' }
];
const billingItems: NavItem[] = [
{ label: 'Usage', icon: IconUsage, href: '/dashboard/usage' },
{ label: 'Billing', icon: IconBilling, href: '/dashboard/billing' }
];
const teams = ['default', 'Wrenn Labs', 'Acme Corp'];
function isActive(href: string): boolean {
const p = $page.url.pathname;
return p === href || p.startsWith(href + '/');
}
function toggleCollapsed() {
collapsed = !collapsed;
localStorage.setItem('wrenn_sidebar_collapsed', String(collapsed));
}
</script>
<aside
class="flex h-screen shrink-0 flex-col overflow-hidden border-r border-[var(--color-border)] bg-[var(--color-bg-1)] transition-[width] duration-250 ease-in-out"
style="width: {collapsed ? '56px' : '230px'}"
>
<!-- Brand + collapse toggle -->
<div class="flex shrink-0 items-center px-4 pt-5 pb-4 {collapsed ? 'justify-center' : 'justify-between'}">
{#if !collapsed}
<div class="flex items-center gap-2.5">
<img
src="/logo.svg"
alt="Wrenn"
class="h-7 w-7 shrink-0 rounded-[var(--radius-logo)]"
/>
<span class="font-brand text-[15px] text-[var(--color-text-bright)]">Wrenn</span>
</div>
{/if}
<button
onclick={toggleCollapsed}
class="flex h-7 w-7 shrink-0 items-center justify-center rounded-[var(--radius-button)] text-[var(--color-text-tertiary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-secondary)]"
title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
>
<IconSidebar size={16} />
</button>
</div>
<!-- Team switcher -->
<div class="px-3 pb-0 {collapsed ? 'px-1.5' : ''}">
<Popover.Root bind:open={teamPopoverOpen}>
<Popover.Trigger
class="flex w-full items-center rounded-[var(--radius-input)] py-2 text-left transition-colors duration-150 hover:bg-[var(--color-bg-3)] {collapsed
? 'justify-center px-0'
: 'gap-2 px-2.5'}"
>
<div
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-[var(--radius-avatar)] bg-[var(--color-bg-4)] text-[10px] font-bold uppercase text-[var(--color-text-secondary)]"
>
{currentTeam[0]}
</div>
{#if !collapsed}
<div class="min-w-0 flex-1 overflow-hidden whitespace-nowrap">
<div
class="text-[11px] font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]"
>
Team
</div>
<div class="truncate text-[13px] text-[var(--color-text-primary)]">
{currentTeam}
</div>
</div>
<IconChevron
size={12}
direction="down"
class="shrink-0 text-[var(--color-text-tertiary)]"
/>
{/if}
</Popover.Trigger>
<Popover.Portal>
<Popover.Content
side="bottom"
align="start"
sideOffset={4}
class="z-50 w-[210px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-1.5"
style="animation: popoverSlideIn 150ms ease"
>
<div
class="mb-1 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]"
>
Teams
</div>
{#each teams as team}
<button
class="flex w-full items-center gap-2.5 rounded-[var(--radius-input)] px-2.5 py-2 text-[13px] transition-colors duration-150 hover:bg-[var(--color-bg-3)] {team ===
currentTeam
? 'bg-[var(--color-accent-glow)]'
: ''}"
onclick={() => (teamPopoverOpen = false)}
>
<div
class="flex h-5 w-5 items-center justify-center rounded-[var(--radius-avatar)] text-[9px] font-bold uppercase text-white {team ===
currentTeam
? 'bg-[var(--color-accent)]'
: 'bg-[var(--color-bg-5)]'}"
>
{team[0]}
</div>
<span
class={team === currentTeam
? 'font-medium text-[var(--color-text-bright)]'
: 'text-[var(--color-text-primary)]'}
>
{team}
</span>
</button>
{/each}
<div class="mt-0.5 border-t border-[var(--color-border)] pt-0.5">
<button
class="flex w-full items-center gap-2.5 rounded-[var(--radius-input)] px-2.5 py-2 text-[13px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)]"
>
<IconPlus size={14} />
Create team
</button>
</div>
</Popover.Content>
</Popover.Portal>
</Popover.Root>
</div>
<!-- Divider after team switcher -->
<div class="mx-4 mb-3 h-px bg-[var(--color-border)] {collapsed ? 'mx-3' : ''}"></div>
<!-- Navigation -->
<nav class="flex-1 overflow-y-auto px-3 {collapsed ? 'px-1.5' : ''}">
{@render navSection('Platform', platformItems)}
{@render navSection('Management', managementItems)}
{@render navSection('Billing', billingItems)}
</nav>
<!-- Bottom links -->
<div class="shrink-0 px-3 pb-1 {collapsed ? 'px-1.5' : ''}">
<a
href="/docs"
class="group flex items-center rounded-[var(--radius-input)] px-2.5 py-2.5 text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)] {collapsed ? 'justify-center px-2' : 'gap-3'}"
title={collapsed ? 'Docs' : undefined}
>
<IconDocs size={16} class="shrink-0 opacity-50 transition-opacity duration-150 group-hover:opacity-100" />
{#if !collapsed}<span class="text-[13px]">Docs</span>{/if}
</a>
<a
href="/dashboard/notifications"
class="group flex items-center rounded-[var(--radius-input)] px-2.5 py-2.5 text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)] {collapsed ? 'justify-center px-2' : 'gap-3'}"
title={collapsed ? 'Notifications' : undefined}
>
<IconBell size={16} class="shrink-0 opacity-50 transition-opacity duration-150 group-hover:opacity-100" />
{#if !collapsed}<span class="text-[13px]">Notifications</span>{/if}
</a>
<a
href="/dashboard/settings"
class="group flex items-center rounded-[var(--radius-input)] px-2.5 py-2.5 text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)] {collapsed ? 'justify-center px-2' : 'gap-3'}"
title={collapsed ? 'Settings' : undefined}
>
<IconSettings size={16} class="shrink-0 opacity-50 transition-opacity duration-150 group-hover:opacity-100" />
{#if !collapsed}<span class="text-[13px]">Settings</span>{/if}
</a>
</div>
<!-- User footer -->
<div
class="flex shrink-0 items-center border-t border-[var(--color-border)] px-3 py-2.5 {collapsed
? 'justify-center px-1.5'
: 'gap-2.5'}"
>
{#if !collapsed}
<div
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[var(--color-bg-4)] text-[10px] font-bold uppercase text-[var(--color-text-secondary)]"
>
{userName[0] ?? ''}
</div>
<span class="flex-1 truncate text-[13px] text-[var(--color-text-secondary)]">
{userName}
</span>
{/if}
<button
onclick={() => auth.logout()}
class="flex shrink-0 items-center justify-center rounded-[var(--radius-button)] transition-colors duration-150 hover:text-[var(--color-red)] {collapsed
? 'h-7 w-7 text-[var(--color-text-muted)] hover:bg-[var(--color-bg-3)]'
: 'h-6 w-6 text-[var(--color-text-tertiary)]'}"
title="Sign out"
>
<IconLogout size={collapsed ? 15 : 14} />
</button>
</div>
</aside>
{#snippet navSection(label: string, items: NavItem[])}
<div class="mb-3">
{#if collapsed}
{#if label !== 'Platform'}
<div class="mx-1 my-2 h-px bg-[var(--color-border)]"></div>
{/if}
{:else}
<div
class="mb-1 px-2.5 py-1.5 text-[11px] font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]"
>
{label}
</div>
{/if}
{#each items as item}
{#if isActive(item.href)}
<a
href={item.href}
class="group relative flex items-center rounded-[var(--radius-input)] bg-[var(--color-accent-glow-mid)] px-2.5 py-2.5 transition-colors duration-150 {collapsed
? 'justify-center px-2'
: 'gap-3'}"
title={collapsed ? item.label : undefined}
>
{#if !collapsed}
<div
class="absolute left-0 top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-[var(--color-accent)]"
></div>
{/if}
<item.icon size={16} class="shrink-0 text-[var(--color-accent-bright)]" />
{#if !collapsed}
<span class="text-[13px] font-medium text-[var(--color-accent-bright)]">
{item.label}
</span>
{/if}
</a>
{:else}
<a
href={item.href}
class="group flex items-center rounded-[var(--radius-input)] px-2.5 py-2.5 transition-colors duration-150 hover:bg-[var(--color-bg-3)] {collapsed
? 'justify-center px-2'
: 'gap-3'}"
title={collapsed ? item.label : undefined}
>
<item.icon
size={16}
class="shrink-0 opacity-50 transition-opacity duration-150 group-hover:opacity-100"
/>
{#if !collapsed}
<span
class="text-[13px] text-[var(--color-text-primary)] transition-colors duration-150 group-hover:text-[var(--color-text-bright)]"
>
{item.label}
</span>
{/if}
</a>
{/if}
{/each}
</div>
{/snippet}
<style>
@keyframes popoverSlideIn {
from {
opacity: 0;
transform: translateY(-4px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>

View File

@ -0,0 +1,24 @@
<script lang="ts">
import { toast } from '$lib/toast.svelte';
</script>
<div class="pointer-events-none fixed bottom-6 right-6 z-[100] flex flex-col-reverse gap-2">
{#each toast.list as t (t.id)}
<div
class="pointer-events-auto flex min-w-[280px] max-w-[400px] items-start gap-3 rounded-[var(--radius-card)] border bg-[var(--color-bg-2)] px-4 py-3 text-[13px] {t.type === 'error'
? 'border-[var(--color-red)]/30 text-[var(--color-red)]'
: 'border-[var(--color-accent)]/30 text-[var(--color-accent-bright)]'}"
style="animation: fadeUp 0.2s ease both"
>
<span class="flex-1 leading-relaxed">{t.message}</span>
<button
onclick={() => toast.dismiss(t.id)}
class="mt-0.5 shrink-0 opacity-50 transition-opacity hover:opacity-100"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
</div>
{/each}
</div>

View File

@ -0,0 +1,22 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
<line x1="16" y1="13" x2="8" y2="13" />
<line x1="16" y1="17" x2="8" y2="17" />
<polyline points="10 9 9 9 8 9" />
</svg>

View File

@ -0,0 +1,19 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" />
<path d="M13.73 21a2 2 0 0 1-3.46 0" />
</svg>

View File

@ -0,0 +1,19 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<rect x="1" y="4" width="22" height="16" rx="3" />
<path d="M1 10h22" />
</svg>

View File

@ -0,0 +1,20 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
<polyline points="3.27 6.96 12 12.01 20.73 6.96" />
<line x1="12" y1="22.08" x2="12" y2="12" />
</svg>

View File

@ -0,0 +1,21 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<rect x="4" y="2" width="16" height="20" rx="4" />
<path d="M4 12h16" />
<circle cx="8" cy="7" r="1" fill="currentColor" stroke="none" />
<circle cx="12" cy="7" r="1" fill="currentColor" stroke="none" />
</svg>

View File

@ -0,0 +1,30 @@
<script lang="ts">
let {
size = 18,
direction = 'down',
class: className = ''
}: { size?: number; direction?: 'up' | 'down' | 'left' | 'right'; class?: string } = $props();
const rotation = {
up: '180',
down: '0',
left: '90',
right: '-90'
};
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
style="transform: rotate({rotation[direction]}deg)"
aria-hidden="true"
>
<polyline points="6 9 12 15 18 9" />
</svg>

View File

@ -0,0 +1,19 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" />
<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z" />
</svg>

View File

@ -0,0 +1,19 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
<circle cx="12" cy="12" r="3" />
</svg>

View File

@ -0,0 +1,21 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path
d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"
/>
<line x1="1" y1="1" x2="23" y2="23" />
</svg>

View File

@ -0,0 +1,16 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="currentColor"
class={className}
aria-hidden="true"
>
<path
d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"
/>
</svg>

View File

@ -0,0 +1,20 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path
d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"
/>
</svg>

View File

@ -0,0 +1,19 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<rect x="3" y="11" width="18" height="11" rx="3" />
<path d="M7 11V7a5 5 0 0 1 10 0v4" />
</svg>

View File

@ -0,0 +1,20 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
<polyline points="16 17 21 12 16 7" />
<line x1="21" y1="12" x2="9" y2="12" />
</svg>

View File

@ -0,0 +1,19 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<rect x="2" y="4" width="20" height="16" rx="3" />
<polyline points="22,4 12,13 2,4" />
</svg>

View File

@ -0,0 +1,21 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
<circle cx="9" cy="7" r="4" />
<path d="M22 21v-2a4 4 0 0 0-3-3.87" />
<path d="M16 3.13a4 4 0 0 1 0 7.75" />
</svg>

View File

@ -0,0 +1,20 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<rect x="2" y="3" width="20" height="14" rx="2" />
<line x1="8" y1="21" x2="16" y2="21" />
<line x1="12" y1="17" x2="12" y2="21" />
</svg>

View File

@ -0,0 +1,19 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>

View File

@ -0,0 +1,21 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path
d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"
/>
<circle cx="12" cy="12" r="3" />
</svg>

View File

@ -0,0 +1,19 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<rect x="3" y="3" width="18" height="18" rx="3" />
<path d="M9 3v18" />
</svg>

View File

@ -0,0 +1,20 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<rect x="3" y="3" width="18" height="18" rx="3" />
<path d="M3 9h18" />
<path d="M9 9v12" />
</svg>

View File

@ -0,0 +1,20 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path
d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"
/>
</svg>

View File

@ -0,0 +1,18 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path d="M22 12h-4l-3 9L9 3l-3 9H2" />
</svg>

View File

@ -0,0 +1,19 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
<circle cx="12" cy="7" r="4" />
</svg>

View File

@ -0,0 +1,19 @@
<script lang="ts">
let { size = 18, class: className = '' }: { size?: number; class?: string } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
class={className}
aria-hidden="true"
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>

View File

@ -0,0 +1,25 @@
// Re-export all icon components
export { default as IconGithub } from './IconGithub.svelte';
export { default as IconCapsule } from './IconCapsule.svelte';
export { default as IconMonitor } from './IconMonitor.svelte';
export { default as IconTemplate } from './IconTemplate.svelte';
export { default as IconTool } from './IconTool.svelte';
export { default as IconKey } from './IconKey.svelte';
export { default as IconMembers } from './IconMembers.svelte';
export { default as IconUsage } from './IconUsage.svelte';
export { default as IconBilling } from './IconBilling.svelte';
export { default as IconSettings } from './IconSettings.svelte';
export { default as IconLogout } from './IconLogout.svelte';
export { default as IconChevron } from './IconChevron.svelte';
export { default as IconPlus } from './IconPlus.svelte';
export { default as IconSidebar } from './IconSidebar.svelte';
export { default as IconMail } from './IconMail.svelte';
export { default as IconLock } from './IconLock.svelte';
export { default as IconUser } from './IconUser.svelte';
export { default as IconX } from './IconX.svelte';
export { default as IconEye } from './IconEye.svelte';
export { default as IconEyeOff } from './IconEyeOff.svelte';
export { default as IconBell } from './IconBell.svelte';
export { default as IconDocs } from './IconDocs.svelte';
export { default as IconAudit } from './IconAudit.svelte';
export { default as IconBox } from './IconBox.svelte';

View File

@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.

View File

@ -0,0 +1,5 @@
export function getInitialCollapsed(): boolean {
return typeof window !== 'undefined'
? localStorage.getItem('wrenn_sidebar_collapsed') === 'true'
: false;
}

View File

@ -0,0 +1,22 @@
type Toast = { id: string; message: string; type: 'error' | 'success' };
let toasts = $state<Toast[]>([]);
export const toast = {
get list() {
return toasts;
},
error(message: string, duration = 4000) {
const id = Math.random().toString(36).slice(2);
toasts = [...toasts, { id, message, type: 'error' }];
setTimeout(() => this.dismiss(id), duration);
},
success(message: string, duration = 3000) {
const id = Math.random().toString(36).slice(2);
toasts = [...toasts, { id, message, type: 'success' }];
setTimeout(() => this.dismiss(id), duration);
},
dismiss(id: string) {
toasts = toasts.filter((t) => t.id !== id);
}
};

View File

@ -0,0 +1,8 @@
<script lang="ts">
import '../app.css';
import '$lib/auth.svelte';
let { children } = $props();
</script>
{@render children()}

View File

@ -0,0 +1,3 @@
// Static site generation — all pages prerendered
export const prerender = true;
export const ssr = false;

View File

@ -0,0 +1,11 @@
import { redirect } from '@sveltejs/kit';
import { browser } from '$app/environment';
import { auth } from '$lib/auth.svelte';
export function load() {
if (!browser) return;
if (auth.isAuthenticated) {
redirect(302, '/dashboard');
}
redirect(302, '/login');
}

View File

@ -0,0 +1,28 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import { auth } from '$lib/auth.svelte';
const params = $page.url.searchParams;
const error = params.get('error');
if (error) {
goto(`/login?error=${encodeURIComponent(error)}`);
} else {
const token = params.get('token');
const userId = params.get('user_id');
const teamId = params.get('team_id');
const email = params.get('email');
if (token && userId && teamId && email) {
auth.login({ token, user_id: userId, team_id: teamId, email });
goto('/dashboard');
} else {
goto('/login?error=missing_token');
}
}
</script>
<div class="flex min-h-screen items-center justify-center">
<p class="text-[13px] text-[var(--color-text-secondary)]">Signing you in...</p>
</div>

View File

@ -0,0 +1,7 @@
<script lang="ts">
import Toaster from '$lib/components/Toaster.svelte';
let { children } = $props();
</script>
{@render children()}
<Toaster />

View File

@ -0,0 +1,10 @@
import { redirect } from '@sveltejs/kit';
import { browser } from '$app/environment';
import { auth } from '$lib/auth.svelte';
export function load() {
if (!browser) return;
if (!auth.isAuthenticated) {
redirect(302, '/login');
}
}

View File

@ -0,0 +1,5 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { onMount } from 'svelte';
onMount(() => goto('/dashboard/capsules', { replaceState: true }));
</script>

View File

@ -0,0 +1,874 @@
<script lang="ts">
import Sidebar from '$lib/components/Sidebar.svelte';
import { onMount } from 'svelte';
import { toast } from '$lib/toast.svelte';
import {
listCapsules,
createCapsule,
pauseCapsule,
resumeCapsule,
destroyCapsule,
createSnapshot,
type Capsule,
type CreateCapsuleParams
} from '$lib/api/capsules';
const REFRESH_INTERVAL = 30;
const SPIN_DURATION = 600; // ms — minimum full rotation time
let collapsed = $state(
typeof window !== 'undefined'
? localStorage.getItem('wrenn_sidebar_collapsed') === 'true'
: false
);
let activeTab: 'list' | 'stats' = $state('list');
// Capsule list state
let capsules = $state<Capsule[]>([]);
let loading = $state(true);
let error = $state<string | null>(null);
let searchQuery = $state('');
let actionLoading = $state<string | null>(null);
let spinning = $state(false);
// Auto-refresh countdown state
let autoRefresh = $state(true);
let countdown = $state(REFRESH_INTERVAL);
let countdownInterval: ReturnType<typeof setInterval> | null = null;
let refreshInterval: ReturnType<typeof setInterval> | null = null;
// Sorting state
type SortKey = 'status' | 'vcpus' | 'memory_mb' | 'started_at' | 'timeout_sec';
let sortKey = $state<SortKey | null>(null);
let sortDir = $state<'asc' | 'desc'>('asc');
// Status menu state
let openMenuId = $state<string | null>(null);
let menuPos = $state<{ top: number; left: number }>({ top: 0, left: 0 });
// Create dialog state
let showCreateDialog = $state(false);
let createForm = $state<CreateCapsuleParams>({ template: 'minimal', vcpus: 1, memory_mb: 512, timeout_sec: 0 });
let creating = $state(false);
let createError = $state<string | null>(null);
// Destroy confirmation state
let destroyTarget = $state<Capsule | null>(null);
let destroying = $state(false);
let destroyError = $state<string | null>(null);
let filteredCapsules = $derived.by(() => {
let list = searchQuery
? capsules.filter((c) => c.id.toLowerCase().includes(searchQuery.toLowerCase()))
: [...capsules];
if (sortKey) {
const key = sortKey;
const dir = sortDir === 'asc' ? 1 : -1;
list.sort((a, b) => {
if (key === 'status') {
return a.status.localeCompare(b.status) * dir;
}
if (key === 'started_at') {
const ta = a.started_at ? new Date(a.started_at).getTime() : 0;
const tb = b.started_at ? new Date(b.started_at).getTime() : 0;
return (ta - tb) * dir;
}
const va = a[key] as number;
const vb = b[key] as number;
return (va - vb) * dir;
});
}
return list;
});
let runningCount = $derived(capsules.filter((c) => c.status === 'running').length);
function toggleSort(key: SortKey) {
if (sortKey === key) {
sortDir = sortDir === 'asc' ? 'desc' : 'asc';
} else {
sortKey = key;
sortDir = 'asc';
}
}
function startAutoRefresh() {
stopAutoRefresh();
countdown = REFRESH_INTERVAL;
countdownInterval = setInterval(() => {
countdown--;
if (countdown <= 0) {
countdown = REFRESH_INTERVAL;
}
}, 1000);
refreshInterval = setInterval(fetchCapsules, REFRESH_INTERVAL * 1000);
}
function stopAutoRefresh() {
if (countdownInterval) { clearInterval(countdownInterval); countdownInterval = null; }
if (refreshInterval) { clearInterval(refreshInterval); refreshInterval = null; }
}
function toggleAutoRefresh() {
autoRefresh = !autoRefresh;
if (autoRefresh) {
startAutoRefresh();
} else {
stopAutoRefresh();
}
}
async function fetchCapsules() {
const wasEmpty = capsules.length === 0;
if (wasEmpty) loading = true;
// Spin for at least SPIN_DURATION ms
spinning = true;
const spinTimer = new Promise<void>((resolve) => setTimeout(resolve, SPIN_DURATION));
error = null;
const result = await listCapsules();
if (result.ok) {
capsules = result.data;
} else {
error = result.error;
}
loading = false;
// Reset countdown on manual or auto refresh
if (autoRefresh) countdown = REFRESH_INTERVAL;
await spinTimer;
spinning = false;
}
async function handlePause(id: string) {
openMenuId = null;
actionLoading = id;
const result = await pauseCapsule(id);
if (result.ok) {
capsules = capsules.map((c) => (c.id === id ? result.data : c));
} else {
toast.error(result.error);
}
actionLoading = null;
}
async function handleResume(id: string) {
openMenuId = null;
actionLoading = id;
const result = await resumeCapsule(id);
if (result.ok) {
capsules = capsules.map((c) => (c.id === id ? result.data : c));
} else {
toast.error(result.error);
}
actionLoading = null;
}
async function handleSnapshot(id: string) {
openMenuId = null;
actionLoading = id;
const result = await createSnapshot(id);
if (result.ok) {
// Snapshot may have paused the capsule — refresh to get updated status
await fetchCapsules();
} else {
toast.error(result.error);
}
actionLoading = null;
}
async function handlePauseAndSnapshot(id: string) {
openMenuId = null;
actionLoading = id;
// Snapshot endpoint pauses automatically if running
const result = await createSnapshot(id);
if (result.ok) {
await fetchCapsules();
} else {
toast.error(result.error);
}
actionLoading = null;
}
async function handleDestroy() {
if (!destroyTarget) return;
destroying = true;
destroyError = null;
const id = destroyTarget.id;
const result = await destroyCapsule(id);
if (result.ok) {
capsules = capsules.filter((c) => c.id !== id);
destroyTarget = null;
} else {
destroyError = result.error;
}
destroying = false;
}
async function handleCreate() {
creating = true;
createError = null;
const result = await createCapsule(createForm);
if (result.ok) {
capsules = [result.data, ...capsules];
showCreateDialog = false;
createForm = { template: 'minimal', vcpus: 1, memory_mb: 512, timeout_sec: 0 };
} else {
createError = result.error;
}
creating = false;
}
function formatTime(iso: string | undefined): string {
if (!iso) return '—';
const d = new Date(iso);
return d.toLocaleString('en-US', {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
});
}
function timeAgo(iso: string | undefined): string {
if (!iso) return '';
const seconds = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
if (seconds < 60) return `${seconds}s ago`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
return `${Math.floor(seconds / 86400)}d ago`;
}
function handleClickOutside(event: MouseEvent) {
if (openMenuId && !(event.target as Element)?.closest('.status-menu-container')) {
openMenuId = null;
}
}
// Initial fetch + auto-refresh setup
onMount(() => {
fetchCapsules();
startAutoRefresh();
return () => stopAutoRefresh();
});
</script>
<style>
@keyframes spin-once {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.refresh-spin {
animation: spin-once 0.6s ease-in-out;
}
</style>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<svelte:window onclick={handleClickOutside} onkeydown={(e) => { if (e.key === 'Escape') openMenuId = null; }} />
<svelte:head>
<title>Wrenn - Capsules</title>
</svelte:head>
<div class="flex h-screen overflow-hidden">
<Sidebar bind:collapsed />
<div class="flex flex-1 flex-col overflow-hidden">
<main class="flex-1 overflow-y-auto bg-[var(--color-bg-0)]">
<!-- Header area -->
<div class="px-7 pt-6">
<!-- Top row: title + status chip -->
<div class="flex items-center justify-between">
<div>
<h1 class="font-serif text-[24px] tracking-[-0.02em] text-[var(--color-text-bright)]">
Capsules
</h1>
<p class="mt-1 text-[13px] text-[var(--color-text-tertiary)]">
Isolated VMs you can start, pause, and snapshot on demand.
</p>
</div>
<div class="flex items-center gap-3">
<!-- Status chip -->
<div
class="flex items-center gap-2.5 rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] px-3.5 py-2"
>
<span class="relative flex h-[7px] w-[7px]">
<span
class="absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]"
style="animation: wrenn-glow 2.5s ease-in-out infinite"
></span>
<span class="relative inline-flex h-[7px] w-[7px] rounded-full bg-[var(--color-accent)]"></span>
</span>
<span class="font-mono text-[14px] font-semibold text-[var(--color-accent-bright)]">{runningCount}</span>
<span class="text-[13px] text-[var(--color-text-secondary)]">concurrent capsules</span>
</div>
</div>
</div>
<!-- Tab bar -->
<div class="mt-4 flex gap-1 border-b border-[var(--color-border)]">
<button
onclick={() => (activeTab = 'list')}
class="flex items-center gap-2 border-b-2 px-4 py-2.5 text-[13px] font-medium transition-colors duration-150 {activeTab === 'list'
? 'border-[var(--color-accent)] text-[var(--color-accent-bright)]'
: 'border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]'}"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="8" y1="6" x2="21" y2="6" /><line x1="8" y1="12" x2="21" y2="12" /><line x1="8" y1="18" x2="21" y2="18" />
<line x1="3" y1="6" x2="3.01" y2="6" /><line x1="3" y1="12" x2="3.01" y2="12" /><line x1="3" y1="18" x2="3.01" y2="18" />
</svg>
List
</button>
<button
onclick={() => (activeTab = 'stats')}
class="flex items-center gap-2 border-b-2 px-4 py-2.5 text-[13px] font-medium transition-colors duration-150 {activeTab === 'stats'
? 'border-[var(--color-accent)] text-[var(--color-accent-bright)]'
: 'border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]'}"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="22 12 18 12 15 21 9 3 6 12 2 12" />
</svg>
Stats
</button>
</div>
</div>
<!-- Tab content -->
{#if activeTab === 'stats'}
<div class="p-7 space-y-5" style="animation: fadeUp 0.35s ease both">
<div class="flex overflow-hidden rounded-[var(--radius-card)] border border-[var(--color-border)]">
{@render metricCell('Concurrent Capsules', String(runningCount), '5-sec avg', 'limit: 20', true)}
{@render metricCell('Start Rate / Second', '0.000', '5-sec avg', null, true)}
{@render metricCell('Peak Concurrent', String(runningCount), '30-day max', 'limit: 20', false)}
</div>
{@render chartCard('Concurrent Capsules', String(runningCount), 'average')}
{@render chartCard('Start Rate Per Second', '0.000', 'average')}
</div>
{:else}
<div class="p-7" style="animation: fadeUp 0.35s ease both">
<!-- Search bar + controls -->
<div class="mb-4 flex items-center gap-3">
<div class="relative flex-1 max-w-[300px]">
<svg class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)]" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" />
</svg>
<input
type="text"
placeholder="Search by ID..."
bind:value={searchQuery}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-2)] py-2 pl-9 pr-3 font-mono text-[13px] text-[var(--color-text-bright)] outline-none placeholder:text-[var(--color-text-muted)] transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
</div>
<span class="text-[13px] text-[var(--color-text-secondary)]">{filteredCapsules.length} total</span>
<div class="flex-1"></div>
<!-- Refresh button -->
<button
onclick={fetchCapsules}
disabled={spinning}
class="flex h-8 w-8 items-center justify-center rounded-[var(--radius-button)] border border-[var(--color-border)] text-[var(--color-text-tertiary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-secondary)] disabled:opacity-50"
title="Refresh"
>
<svg
class={spinning ? 'refresh-spin' : ''}
width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
>
<polyline points="23 4 23 10 17 10" />
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />
</svg>
</button>
<!-- Auto-refresh countdown toggle -->
<button
onclick={toggleAutoRefresh}
class="flex items-center gap-1.5 rounded-[var(--radius-button)] border px-2.5 py-1.5 font-mono text-[11px] transition-colors duration-150
{autoRefresh
? 'border-[var(--color-accent)]/30 text-[var(--color-accent-mid)] hover:border-[var(--color-accent)]/50'
: 'border-[var(--color-border)] text-[var(--color-text-muted)] hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-secondary)]'}"
title={autoRefresh ? 'Click to disable auto-refresh' : 'Click to enable auto-refresh (30s)'}
>
{#if autoRefresh}
{countdown}s
{:else}
Off
{/if}
</button>
<button
onclick={() => { showCreateDialog = true; createError = null; }}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-4 py-2 text-[13px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
Launch Capsule
</button>
</div>
{#if error}
<div class="mb-4 rounded-[var(--radius-card)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-4 py-3 text-[13px] text-[var(--color-red)]">
{error}
</div>
{/if}
<!-- Table -->
<div class="rounded-[var(--radius-card)] border border-[var(--color-border)] overflow-hidden">
<!-- Table header -->
<div class="grid grid-cols-[1.6fr_0.8fr_0.5fr_0.5fr_0.6fr_1fr_0.9fr] rounded-t-[var(--radius-card)] border-b border-[var(--color-border)] bg-[var(--color-bg-3)]">
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">ID</div>
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Template</div>
{@render sortableHeader('CPU', 'vcpus')}
{@render sortableHeader('Memory', 'memory_mb')}
{@render sortableHeader('Idle Timeout', 'timeout_sec')}
{@render sortableHeader('Started', 'started_at')}
{@render sortableHeader('Status', 'status')}
</div>
{#if loading && capsules.length === 0}
<div class="flex items-center justify-center py-16">
<div class="flex items-center gap-3 text-[13px] text-[var(--color-text-secondary)]">
<svg class="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Loading capsules...
</div>
</div>
{:else if filteredCapsules.length === 0}
<div class="flex flex-col items-center justify-center py-[72px]">
<div class="mb-5 flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-3)]">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--color-text-secondary)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<rect x="2" y="3" width="20" height="14" rx="2" />
<line x1="8" y1="21" x2="16" y2="21" />
<line x1="12" y1="17" x2="12" y2="21" />
</svg>
</div>
<p class="font-serif text-[20px] tracking-[-0.02em] text-[var(--color-text-bright)]">
No capsules yet
</p>
<p class="mt-1.5 text-[13px] text-[var(--color-text-tertiary)]">
Active capsules will appear here.
</p>
<button
onclick={() => { showCreateDialog = true; createError = null; }}
class="mt-6 flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2.5 text-[13px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0"
>
Create a Capsule
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
</button>
</div>
{:else}
{#each filteredCapsules as capsule, i (capsule.id)}
<div
class="grid grid-cols-[1.6fr_0.8fr_0.5fr_0.5fr_0.6fr_1fr_0.9fr] items-center border-b border-[var(--color-border)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] last:border-b-0"
style="animation: fadeUp 0.35s ease both; animation-delay: {i * 40}ms"
>
<!-- ID with status dot -->
<div class="flex items-center gap-2.5 px-4 py-3">
{#if capsule.status === 'running'}
<span class="relative flex h-[6px] w-[6px] shrink-0">
<span class="absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]" style="animation: wrenn-glow 2.5s ease-in-out infinite"></span>
<span class="relative inline-flex h-[6px] w-[6px] rounded-full bg-[var(--color-accent)]"></span>
</span>
{:else if capsule.status === 'paused'}
<span class="inline-flex h-[6px] w-[6px] shrink-0 rounded-full bg-[var(--color-amber)]"></span>
{:else}
<span class="inline-flex h-[6px] w-[6px] shrink-0 rounded-full bg-[var(--color-text-muted)]"></span>
{/if}
<span class="font-mono text-[13px] text-[var(--color-text-bright)]">{capsule.id}</span>
</div>
<!-- Template -->
<div class="px-4 py-3">
<span class="text-[13px] text-[var(--color-text-secondary)]">{capsule.template}</span>
</div>
<!-- CPU -->
<div class="px-4 py-3">
<span class="font-mono text-[13px] text-[var(--color-text-secondary)]">{capsule.vcpus}</span>
</div>
<!-- Memory -->
<div class="px-4 py-3">
<span class="font-mono text-[13px] text-[var(--color-text-secondary)]">{capsule.memory_mb}MB</span>
</div>
<!-- Idle Timeout -->
<div class="px-4 py-3">
<span class="font-mono text-[13px] text-[var(--color-text-secondary)]">{capsule.timeout_sec ? `${capsule.timeout_sec}s` : '—'}</span>
</div>
<!-- Started -->
<div class="px-4 py-3">
<span class="text-[13px] text-[var(--color-text-secondary)]" title={capsule.started_at ?? ''}>{formatTime(capsule.started_at)}</span>
{#if capsule.last_active_at}
<span class="ml-1.5 text-[11px] text-[var(--color-text-muted)]">{timeAgo(capsule.last_active_at)}</span>
{/if}
</div>
<!-- Status button with popover -->
<div class="relative px-4 py-3 status-menu-container">
{#if actionLoading === capsule.id}
<span class="inline-flex items-center gap-1.5 text-[13px] text-[var(--color-text-secondary)]">
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
</span>
{:else}
<button
onclick={(e) => {
e.stopPropagation();
if (openMenuId === capsule.id) {
openMenuId = null;
} else {
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
menuPos = { top: rect.bottom + 4, left: rect.right - 180 };
openMenuId = capsule.id;
}
}}
class="inline-flex items-center gap-1.5 rounded-[var(--radius-button)] border border-[var(--color-border)] bg-[var(--color-bg-2)] px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.04em] text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)]"
>
{capsule.status}
<svg
class="transition-transform duration-150 {openMenuId === capsule.id ? 'rotate-180' : ''}"
width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"
>
<polyline points="6 9 12 15 18 9" />
</svg>
</button>
{/if}
</div>
</div>
{/each}
{/if}
</div>
</div>
{/if}
</main>
<!-- Status bar -->
<footer
class="flex h-7 shrink-0 items-center justify-end border-t border-[var(--color-border)] bg-[var(--color-bg-1)] px-7"
>
<div class="flex items-center gap-1.5">
<span class="inline-flex h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]"></span>
<span class="font-mono text-[11px] uppercase tracking-[0.04em] text-[var(--color-text-secondary)]">All systems operational</span>
</div>
</footer>
</div>
</div>
<!-- Fixed-position status popover menu -->
{#if openMenuId}
{@const openCapsule = capsules.find((c) => c.id === openMenuId)}
{#if openCapsule}
<div
class="fixed z-50 w-[180px] overflow-hidden rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] py-1"
style="top: {menuPos.top}px; left: {menuPos.left}px; animation: fadeUp 0.15s ease both"
>
{#if openCapsule.status === 'running'}
<button
onclick={() => handlePause(openCapsule.id)}
class="flex w-full items-center gap-2.5 px-3 py-2 text-[12px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)]"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" class="shrink-0">
<rect x="6" y="4" width="4" height="16" rx="1" />
<rect x="14" y="4" width="4" height="16" rx="1" />
</svg>
Pause
</button>
<button
onclick={() => handlePauseAndSnapshot(openCapsule.id)}
class="flex w-full items-center gap-2.5 px-3 py-2 text-[12px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)]"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0">
<path d="M14.5 4h-5L7 7H2v13a2 2 0 002 2h16a2 2 0 002-2V7h-5l-2.5-3z" />
<circle cx="12" cy="15" r="3" />
</svg>
Pause & Snapshot
</button>
{:else if openCapsule.status === 'paused'}
<button
onclick={() => handleResume(openCapsule.id)}
class="flex w-full items-center gap-2.5 px-3 py-2 text-[12px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)]"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" class="shrink-0">
<polygon points="5 3 19 12 5 21 5 3" />
</svg>
Resume
</button>
<button
onclick={() => handleSnapshot(openCapsule.id)}
class="flex w-full items-center gap-2.5 px-3 py-2 text-[12px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)]"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0">
<path d="M14.5 4h-5L7 7H2v13a2 2 0 002 2h16a2 2 0 002-2V7h-5l-2.5-3z" />
<circle cx="12" cy="15" r="3" />
</svg>
Snapshot
</button>
{/if}
<div class="my-1 border-t border-[var(--color-border)]"></div>
<button
onclick={() => { const target = openCapsule; openMenuId = null; destroyError = null; destroyTarget = target; }}
class="flex w-full items-center gap-2.5 px-3 py-2 text-[12px] text-[var(--color-red)] transition-colors duration-150 hover:bg-[var(--color-red)]/5"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0">
<polyline points="3 6 5 6 21 6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
</svg>
Destroy
</button>
</div>
{/if}
{/if}
<!-- Create Capsule Dialog -->
{#if showCreateDialog}
<div class="fixed inset-0 z-50 flex items-center justify-center">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute inset-0 bg-black/60"
onclick={() => { if (!creating) showCreateDialog = false; }}
onkeydown={(e) => { if (e.key === 'Escape' && !creating) showCreateDialog = false; }}
></div>
<div class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-6" style="animation: fadeUp 0.2s ease both">
<h2 class="font-serif text-[20px] tracking-[-0.02em] text-[var(--color-text-bright)]">Launch Capsule</h2>
<p class="mt-1 text-[13px] text-[var(--color-text-tertiary)]">Launch a new isolated VM.</p>
{#if createError}
<div class="mt-4 rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-[12px] text-[var(--color-red)]">
{createError}
</div>
{/if}
<div class="mt-5 space-y-4">
<div>
<label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="create-template">Template</label>
<input
id="create-template"
type="text"
bind:value={createForm.template}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-[13px] text-[var(--color-text-bright)] outline-none placeholder:text-[var(--color-text-muted)] transition-colors duration-150 focus:border-[var(--color-accent)]"
placeholder="minimal"
/>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="create-vcpus">vCPUs</label>
<input
id="create-vcpus"
type="number"
min="1"
max="8"
bind:value={createForm.vcpus}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-[13px] text-[var(--color-text-bright)] outline-none transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
</div>
<div>
<label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="create-memory">Memory (MB)</label>
<input
id="create-memory"
type="number"
min="128"
max="8192"
step="128"
bind:value={createForm.memory_mb}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-[13px] text-[var(--color-text-bright)] outline-none transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
</div>
</div>
<div>
<label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="create-timeout">Auto-pause timeout (seconds, 0 = never)</label>
<input
id="create-timeout"
type="number"
min="0"
bind:value={createForm.timeout_sec}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-[13px] text-[var(--color-text-bright)] outline-none transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
</div>
</div>
<div class="mt-6 flex justify-end gap-3">
<button
onclick={() => { showCreateDialog = false; }}
disabled={creating}
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-[13px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
>
Cancel
</button>
<button
onclick={handleCreate}
disabled={creating}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2 text-[13px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
>
{#if creating}
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Launching...
{:else}
Launch
{/if}
</button>
</div>
</div>
</div>
{/if}
<!-- Destroy Confirmation Dialog -->
{#if destroyTarget}
<div class="fixed inset-0 z-50 flex items-center justify-center">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute inset-0 bg-black/60"
onclick={() => { if (!destroying) destroyTarget = null; }}
onkeydown={(e) => { if (e.key === 'Escape' && !destroying) destroyTarget = null; }}
></div>
<div class="relative w-full max-w-[380px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-6" style="animation: fadeUp 0.2s ease both">
<h2 class="font-serif text-[20px] tracking-[-0.02em] text-[var(--color-text-bright)]">Destroy Capsule</h2>
<p class="mt-2 text-[13px] text-[var(--color-text-tertiary)]">
This will permanently destroy <span class="font-mono text-[var(--color-text-secondary)]">{destroyTarget.id}</span>. This action cannot be undone.
</p>
{#if destroyError}
<div class="mt-4 rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-[12px] text-[var(--color-red)]">
{destroyError}
</div>
{/if}
<div class="mt-6 flex justify-end gap-3">
<button
onclick={() => { destroyTarget = null; }}
disabled={destroying}
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-[13px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
>
Cancel
</button>
<button
onclick={handleDestroy}
disabled={destroying}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-red)] px-5 py-2 text-[13px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
>
{#if destroying}
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Destroying...
{:else}
Destroy
{/if}
</button>
</div>
</div>
</div>
{/if}
<!-- Sortable header snippet -->
{#snippet sortableHeader(label: string, key: SortKey)}
<button
onclick={() => toggleSort(key)}
class="flex items-center gap-1 px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)] transition-colors duration-150 hover:text-[var(--color-text-secondary)]"
>
{label}
{#if sortKey === key}
<svg
class="transition-transform duration-150 {sortDir === 'desc' ? 'rotate-180' : ''}"
width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"
>
<polyline points="18 15 12 9 6 15" />
</svg>
{/if}
</button>
{/snippet}
{#snippet metricCell(label: string, value: string, sublabel: string, extra: string | null, hasBorderRight: boolean)}
<div class="flex-1 bg-[var(--color-bg-2)] px-5 py-[18px] transition-colors duration-150 hover:bg-[var(--color-bg-3)] {hasBorderRight ? 'border-r border-[var(--color-border)]' : ''}">
<div class="flex items-center gap-2">
<span class="text-[12px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">{label}</span>
<span class="rounded-[3px] bg-[var(--color-accent-glow-mid)] px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.04em] text-[var(--color-accent-mid)]">
<span class="mr-0.5 inline-block h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]" style="animation: wrenn-glow 2.5s ease-in-out infinite"></span>
Live
</span>
</div>
<div class="mt-1 font-serif text-[36px] tracking-[-0.04em] text-[var(--color-text-bright)]">{value}</div>
<div class="mt-1 flex items-center gap-1.5 text-[11px] text-[var(--color-text-tertiary)]">
<span>{sublabel}</span>
{#if extra}
<span class="text-[var(--color-text-muted)]">|</span>
<span class="font-mono text-[var(--color-text-muted)]">{extra}</span>
{/if}
</div>
</div>
{/snippet}
{#snippet chartCard(label: string, value: string, sublabel: string)}
<div class="rounded-[var(--radius-card)] border border-[var(--color-border)] bg-[var(--color-bg-2)]">
<div class="flex items-center justify-between px-5 pt-[18px] pb-3">
<div>
<div class="text-[12px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">{label}</div>
<div class="mt-0.5 flex items-baseline gap-2">
<span class="font-serif text-[30px] tracking-[-0.04em] text-[var(--color-text-bright)]">{value}</span>
<span class="text-[13px] text-[var(--color-text-secondary)]">{sublabel}</span>
<span class="rounded-[3px] bg-[var(--color-accent-glow-mid)] px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.04em] text-[var(--color-accent-mid)]">
<span class="mr-0.5 inline-block h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]" style="animation: wrenn-glow 2.5s ease-in-out infinite"></span>
Live
</span>
</div>
</div>
<div class="flex overflow-hidden rounded-[var(--radius-button)] border border-[var(--color-border)]">
{#each ['5m', '1H', '6H', '24H', '30D'] as range, i}
<button
class="px-2.5 py-1 font-mono text-[11px] transition-colors duration-150 {range === '1H'
? 'bg-[var(--color-bg-5)] text-[var(--color-text-bright)]'
: 'text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]'} {i > 0
? 'border-l border-[var(--color-border)]'
: ''}"
>
{range}
</button>
{/each}
</div>
</div>
<div class="relative h-[200px] px-5 pb-3">
<div class="absolute left-0 top-0 flex h-full w-12 flex-col justify-between py-1 text-right">
<span class="font-mono text-[10px] text-[var(--color-text-muted)]">4</span>
<span class="font-mono text-[10px] text-[var(--color-text-muted)]">3</span>
<span class="font-mono text-[10px] text-[var(--color-text-muted)]">2</span>
<span class="font-mono text-[10px] text-[var(--color-text-muted)]">1</span>
<span class="font-mono text-[10px] text-[var(--color-text-muted)]">0</span>
</div>
<svg class="ml-8 h-full w-[calc(100%-2rem)]" viewBox="0 0 400 180" preserveAspectRatio="none">
{#each [0, 45, 90, 135, 180] as y}
<line x1="0" y1={y} x2="400" y2={y} stroke="var(--color-border)" stroke-width="0.5" stroke-dasharray="4 4" />
{/each}
<line x1="0" y1="180" x2="400" y2="180" stroke="var(--color-accent)" stroke-width="1.5" />
</svg>
<div class="ml-8 flex justify-between pt-2">
{#each ['03:01', '03:02', '03:03', '03:04', '03:05'] as t}
<span class="font-mono text-[10px] text-[var(--color-text-muted)]">{t}</span>
{/each}
</div>
</div>
</div>
{/snippet}

View File

@ -0,0 +1,440 @@
<script lang="ts">
import Sidebar from '$lib/components/Sidebar.svelte';
import { onMount } from 'svelte';
import { listKeys, createKey, revokeKey, type APIKey } from '$lib/api/keys';
let collapsed = $state(
typeof window !== 'undefined'
? localStorage.getItem('wrenn_sidebar_collapsed') === 'true'
: false
);
// List state
let keys = $state<APIKey[]>([]);
let loading = $state(true);
let error = $state<string | null>(null);
// Create dialog state
let showCreate = $state(false);
let createName = $state('');
let creating = $state(false);
let createError = $state<string | null>(null);
// Reveal state — shown immediately after creation
let newKey = $state<APIKey | null>(null);
let copied = $state(false);
// Revoke state
let revokeTarget = $state<APIKey | null>(null);
let revoking = $state(false);
let revokeError = $state<string | null>(null);
async function fetchKeys() {
loading = true;
error = null;
const result = await listKeys();
if (result.ok) {
keys = result.data;
} else {
error = result.error;
}
loading = false;
}
async function handleCreate() {
if (!createName.trim()) return;
creating = true;
createError = null;
const result = await createKey(createName.trim());
if (result.ok) {
keys = [result.data, ...keys];
newKey = result.data;
showCreate = false;
createName = '';
copied = false;
} else {
createError = result.error;
}
creating = false;
}
async function handleRevoke() {
if (!revokeTarget) return;
revoking = true;
revokeError = null;
const id = revokeTarget.id;
const result = await revokeKey(id);
if (result.ok) {
keys = keys.filter((k) => k.id !== id);
revokeTarget = null;
} else {
revokeError = result.error;
}
revoking = false;
}
async function copyKey() {
if (!newKey?.key) return;
await navigator.clipboard.writeText(newKey.key);
copied = true;
setTimeout(() => (copied = false), 2000);
}
function formatDate(iso: string | undefined): string {
if (!iso) return '—';
return new Date(iso).toLocaleString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false
});
}
function timeAgo(iso: string | undefined): string {
if (!iso) return '';
const seconds = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
if (seconds < 60) return `${seconds}s ago`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
return `${Math.floor(seconds / 86400)}d ago`;
}
onMount(fetchKeys);
</script>
<svelte:head>
<title>Wrenn - API Keys</title>
</svelte:head>
<div class="flex h-screen overflow-hidden">
<Sidebar bind:collapsed />
<div class="flex flex-1 flex-col overflow-hidden">
<main class="flex-1 overflow-y-auto bg-[var(--color-bg-0)]">
<!-- Header -->
<div class="px-7 pt-6">
<div class="flex items-center justify-between">
<div>
<h1 class="font-serif text-[24px] tracking-[-0.02em] text-[var(--color-text-bright)]">
API Keys
</h1>
<p class="mt-1 text-[13px] text-[var(--color-text-tertiary)]">
Keys authenticate SDK and direct API requests. Treat them like passwords.
</p>
</div>
<button
onclick={() => { showCreate = true; createError = null; createName = ''; }}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-4 py-2 text-[13px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
New Key
</button>
</div>
<div class="mt-5 border-b border-[var(--color-border)]"></div>
</div>
<!-- Content -->
<div class="p-7" style="animation: fadeUp 0.35s ease both">
{#if error}
<div class="mb-4 rounded-[var(--radius-card)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-4 py-3 text-[13px] text-[var(--color-red)]">
{error}
</div>
{/if}
{#if loading}
<div class="flex items-center justify-center py-24">
<div class="flex items-center gap-3 text-[13px] text-[var(--color-text-secondary)]">
<svg class="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Loading keys...
</div>
</div>
{:else if keys.length === 0}
<div class="flex flex-col items-center justify-center py-[72px]">
<div class="mb-5 flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-3)]">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--color-text-secondary)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4" />
</svg>
</div>
<p class="font-serif text-[20px] tracking-[-0.02em] text-[var(--color-text-bright)]">No API keys yet</p>
<p class="mt-1.5 text-[13px] text-[var(--color-text-tertiary)]">Create a key to authenticate SDK and API requests.</p>
<button
onclick={() => { showCreate = true; createError = null; createName = ''; }}
class="mt-6 flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2.5 text-[13px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0"
>
Create a Key
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
</button>
</div>
{:else}
<div class="rounded-[var(--radius-card)] border border-[var(--color-border)] overflow-hidden">
<!-- Table header -->
<div class="grid grid-cols-[2fr_1.2fr_1.4fr_1.4fr_80px] border-b border-[var(--color-border)] bg-[var(--color-bg-3)]">
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Name / Key</div>
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Created By</div>
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Created</div>
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Last Used</div>
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]"></div>
</div>
{#each keys as key, i (key.id)}
<div
class="grid grid-cols-[2fr_1.2fr_1.4fr_1.4fr_80px] items-center border-b border-[var(--color-border)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] last:border-b-0"
style="animation: fadeUp 0.35s ease both; animation-delay: {i * 40}ms"
>
<!-- Name + prefix -->
<div class="flex flex-col gap-0.5 px-4 py-3">
<span class="text-[13px] font-medium text-[var(--color-text-bright)]">{key.name || '—'}</span>
<span class="font-mono text-[12px] text-[var(--color-text-muted)]">{key.key_prefix}...</span>
</div>
<!-- Created by -->
<div class="px-4 py-3">
<span class="text-[13px] text-[var(--color-text-secondary)]">{key.creator_email ?? key.created_by}</span>
</div>
<!-- Created at -->
<div class="px-4 py-3">
<span class="text-[13px] text-[var(--color-text-secondary)]">{formatDate(key.created_at)}</span>
</div>
<!-- Last used -->
<div class="px-4 py-3">
{#if key.last_used}
<span class="text-[13px] text-[var(--color-text-secondary)]" title={formatDate(key.last_used)}>
{timeAgo(key.last_used)}
</span>
{:else}
<span class="text-[13px] text-[var(--color-text-muted)]">Never</span>
{/if}
</div>
<!-- Revoke -->
<div class="flex justify-end px-4 py-3">
<button
onclick={() => { revokeTarget = key; revokeError = null; }}
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.04em] text-[var(--color-text-tertiary)] transition-colors duration-150 hover:border-[var(--color-red)]/40 hover:text-[var(--color-red)]"
>
Revoke
</button>
</div>
</div>
{/each}
</div>
<p class="mt-3 text-[12px] text-[var(--color-text-muted)]">
{keys.length} {keys.length === 1 ? 'key' : 'keys'} total
</p>
{/if}
</div>
</main>
<!-- Status bar -->
<footer class="flex h-7 shrink-0 items-center justify-end border-t border-[var(--color-border)] bg-[var(--color-bg-1)] px-7">
<div class="flex items-center gap-1.5">
<span class="inline-flex h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]"></span>
<span class="font-mono text-[11px] uppercase tracking-[0.04em] text-[var(--color-text-secondary)]">All systems operational</span>
</div>
</footer>
</div>
</div>
<!-- Create Key Dialog -->
{#if showCreate}
<div class="fixed inset-0 z-50 flex items-center justify-center">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute inset-0 bg-black/60"
onclick={() => { if (!creating) showCreate = false; }}
onkeydown={(e) => { if (e.key === 'Escape' && !creating) showCreate = false; }}
></div>
<div class="relative w-full max-w-[400px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-6" style="animation: fadeUp 0.2s ease both">
<h2 class="font-serif text-[20px] tracking-[-0.02em] text-[var(--color-text-bright)]">New API Key</h2>
<p class="mt-1 text-[13px] text-[var(--color-text-tertiary)]">Give your key a name to identify it later.</p>
{#if createError}
<div class="mt-4 rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-[12px] text-[var(--color-red)]">
{createError}
</div>
{/if}
<div class="mt-5">
<label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="key-name">
Key name
</label>
<input
id="key-name"
type="text"
placeholder="e.g. Production SDK"
bind:value={createName}
onkeydown={(e) => { if (e.key === 'Enter' && !creating) handleCreate(); }}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 text-[13px] text-[var(--color-text-bright)] outline-none placeholder:text-[var(--color-text-muted)] transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
</div>
<div class="mt-6 flex justify-end gap-3">
<button
onclick={() => { showCreate = false; }}
disabled={creating}
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-[13px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
>
Cancel
</button>
<button
onclick={handleCreate}
disabled={creating || !createName.trim()}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2 text-[13px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
>
{#if creating}
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Creating...
{:else}
Create Key
{/if}
</button>
</div>
</div>
</div>
{/if}
<!-- Key Reveal Dialog — shown once after creation -->
{#if newKey}
<div class="fixed inset-0 z-50 flex items-center justify-center">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute inset-0 bg-black/60"
onclick={() => { newKey = null; }}
onkeydown={(e) => { if (e.key === 'Escape') newKey = null; }}
></div>
<div class="relative w-full max-w-[480px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-6" style="animation: fadeUp 0.2s ease both">
<!-- Success indicator -->
<div class="mb-4 flex items-center gap-2.5">
<span class="flex h-5 w-5 items-center justify-center rounded-full bg-[var(--color-accent-glow-mid)]">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="var(--color-accent-bright)" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<polyline points="20 6 9 17 4 12" />
</svg>
</span>
<span class="text-[12px] font-semibold text-[var(--color-accent-mid)]">Key created successfully</span>
</div>
<h2 class="font-serif text-[20px] tracking-[-0.02em] text-[var(--color-text-bright)]">{newKey.name || 'API Key'}</h2>
<p class="mt-1 text-[13px] text-[var(--color-text-tertiary)]">
Copy this key now — it won't be shown again.
</p>
<!-- Key display -->
<div class="mt-5 rounded-[var(--radius-input)] border border-[var(--color-border-mid)] bg-[var(--color-bg-0)] p-4">
<div class="flex items-center gap-3">
<span class="min-w-0 flex-1 break-all font-mono text-[13px] leading-relaxed text-[var(--color-text-bright)]">
{newKey.key ?? ''}
</span>
<button
onclick={copyKey}
class="shrink-0 flex items-center gap-1.5 rounded-[var(--radius-button)] border px-3 py-1.5 text-[12px] font-semibold transition-all duration-150
{copied
? 'border-[var(--color-accent)]/40 bg-[var(--color-accent-glow-mid)] text-[var(--color-accent-mid)]'
: 'border-[var(--color-border-mid)] text-[var(--color-text-secondary)] hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)]'}"
>
{#if copied}
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<polyline points="20 6 9 17 4 12" />
</svg>
Copied
{:else}
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
Copy
{/if}
</button>
</div>
</div>
<!-- Warning -->
<div class="mt-3 flex items-start gap-2 rounded-[var(--radius-input)] border border-[var(--color-amber)]/20 bg-[var(--color-amber)]/5 px-3 py-2.5">
<svg class="mt-0.5 shrink-0" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--color-amber)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
<line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" />
</svg>
<p class="text-[12px] leading-relaxed text-[var(--color-amber)]">
Store this key securely. For security reasons, we only show it once and cannot retrieve it later.
</p>
</div>
<div class="mt-6 flex justify-end">
<button
onclick={() => { newKey = null; }}
class="rounded-[var(--radius-button)] bg-[var(--color-bg-4)] border border-[var(--color-border-mid)] px-5 py-2 text-[13px] font-semibold text-[var(--color-text-primary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:bg-[var(--color-bg-5)]"
>
Done
</button>
</div>
</div>
</div>
{/if}
<!-- Revoke Confirmation Dialog -->
{#if revokeTarget}
<div class="fixed inset-0 z-50 flex items-center justify-center">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute inset-0 bg-black/60"
onclick={() => { if (!revoking) revokeTarget = null; }}
onkeydown={(e) => { if (e.key === 'Escape' && !revoking) revokeTarget = null; }}
></div>
<div class="relative w-full max-w-[380px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-6" style="animation: fadeUp 0.2s ease both">
<h2 class="font-serif text-[20px] tracking-[-0.02em] text-[var(--color-text-bright)]">Revoke Key</h2>
<p class="mt-2 text-[13px] text-[var(--color-text-tertiary)]">
Revoke <span class="font-medium text-[var(--color-text-secondary)]">{revokeTarget.name || revokeTarget.id}</span>?
Any request using it will stop working immediately.
</p>
<p class="mt-1.5 font-mono text-[12px] text-[var(--color-text-muted)]">{revokeTarget.key_prefix}...</p>
{#if revokeError}
<div class="mt-4 rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-[12px] text-[var(--color-red)]">
{revokeError}
</div>
{/if}
<div class="mt-6 flex justify-end gap-3">
<button
onclick={() => { revokeTarget = null; }}
disabled={revoking}
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-[13px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
>
Cancel
</button>
<button
onclick={handleRevoke}
disabled={revoking}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-red)] px-5 py-2 text-[13px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
>
{#if revoking}
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Revoking...
{:else}
Revoke Key
{/if}
</button>
</div>
</div>
</div>
{/if}

View File

@ -0,0 +1,629 @@
<script lang="ts">
import Sidebar from '$lib/components/Sidebar.svelte';
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import {
listSnapshots,
deleteSnapshot,
createCapsule,
type Snapshot
} from '$lib/api/capsules';
let collapsed = $state(
typeof window !== 'undefined'
? localStorage.getItem('wrenn_sidebar_collapsed') === 'true'
: false
);
// Page tab — Images is disabled/future
let pageTab = $state<'snapshots' | 'images'>('snapshots');
// Type filter within snapshots tab
type TypeFilter = 'all' | 'snapshot' | 'base';
let typeFilter = $state<TypeFilter>('all');
// List state
let snapshots = $state<Snapshot[]>([]);
let loading = $state(true);
let error = $state<string | null>(null);
// Delete state
let deleteTarget = $state<Snapshot | null>(null);
let deleting = $state(false);
let deleteError = $state<string | null>(null);
// Row dropdown (split button chevron)
let openDropdownName = $state<string | null>(null);
let dropdownPos = $state<{ top: number; left: number }>({ top: 0, left: 0 });
// Launch state
let launchTarget = $state<Snapshot | null>(null);
let launchVcpus = $state(1);
let launchMemoryMb = $state(512);
let launchTimeoutSec = $state(0);
let launching = $state(false);
let launchError = $state<string | null>(null);
let filteredSnapshots = $derived.by(() => {
if (typeFilter === 'all') return snapshots;
return snapshots.filter((s) => s.type === typeFilter);
});
async function fetchSnapshots() {
loading = true;
error = null;
const result = await listSnapshots();
if (result.ok) {
snapshots = result.data;
} else {
error = result.error;
}
loading = false;
}
async function handleDelete() {
if (!deleteTarget) return;
deleting = true;
deleteError = null;
const name = deleteTarget.name;
const result = await deleteSnapshot(name);
if (result.ok) {
snapshots = snapshots.filter((s) => s.name !== name);
deleteTarget = null;
} else {
deleteError = result.error;
}
deleting = false;
}
function openLaunch(snapshot: Snapshot) {
launchTarget = snapshot;
launchVcpus = snapshot.vcpus ?? 1;
launchMemoryMb = snapshot.memory_mb ?? 512;
launchTimeoutSec = 0;
launchError = null;
}
async function handleLaunch() {
if (!launchTarget) return;
launching = true;
launchError = null;
const result = await createCapsule({
template: launchTarget.name,
vcpus: launchVcpus,
memory_mb: launchMemoryMb,
timeout_sec: launchTimeoutSec
});
if (result.ok) {
launchTarget = null;
goto('/dashboard/capsules');
} else {
launchError = result.error;
}
launching = false;
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
return `${(bytes / 1024 ** 3).toFixed(2)} GB`;
}
function formatDate(iso: string): string {
return new Date(iso).toLocaleString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false
});
}
function timeAgo(iso: string): string {
const seconds = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
if (seconds < 60) return `${seconds}s ago`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
return `${Math.floor(seconds / 86400)}d ago`;
}
function emptyHeading(f: TypeFilter): string {
if (f === 'snapshot') return 'No snapshots';
if (f === 'base') return 'No images';
return 'No snapshots yet';
}
function emptyDescription(f: TypeFilter): string {
if (f === 'snapshot') return 'Capture a running capsule to create a snapshot.';
if (f === 'base') return 'Images appear here once added to your account.';
return 'Snapshots are created from the Capsules page. Pause or snapshot a running capsule to get started.';
}
onMount(fetchSnapshots);
</script>
<svelte:head>
<title>Wrenn - Templates</title>
</svelte:head>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<svelte:window
onkeydown={(e) => {
if (e.key === 'Escape') {
if (openDropdownName) { openDropdownName = null; return; }
if (deleting || launching) return;
deleteTarget = null;
launchTarget = null;
}
}}
onclick={(e) => {
if (openDropdownName && !(e.target as Element)?.closest('.split-btn-container')) {
openDropdownName = null;
}
}}
/>
<div class="flex h-screen overflow-hidden">
<Sidebar bind:collapsed />
<div class="flex flex-1 flex-col overflow-hidden">
<main class="flex-1 overflow-y-auto bg-[var(--color-bg-0)]">
<!-- Header -->
<div class="px-7 pt-6">
<div class="flex items-start justify-between">
<div>
<h1 class="font-serif text-[24px] tracking-[-0.02em] text-[var(--color-text-bright)]">
Templates
</h1>
<p class="mt-1 text-[13px] text-[var(--color-text-tertiary)]">
Point-in-time captures and base environments for launching capsules.
</p>
</div>
</div>
<!-- Page-level tabs -->
<div class="mt-5 flex gap-0 border-b border-[var(--color-border)]">
<!-- Snapshots tab (active) -->
<button
onclick={() => (pageTab = 'snapshots')}
class="flex items-center gap-2 border-b-2 px-4 py-2.5 text-[13px] font-medium transition-colors duration-150 {pageTab === 'snapshots'
? 'border-[var(--color-accent)] text-[var(--color-accent-bright)]'
: 'border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]'}"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="8" y1="6" x2="21" y2="6" /><line x1="8" y1="12" x2="21" y2="12" /><line x1="8" y1="18" x2="21" y2="18" />
<line x1="3" y1="6" x2="3.01" y2="6" /><line x1="3" y1="12" x2="3.01" y2="12" /><line x1="3" y1="18" x2="3.01" y2="18" />
</svg>
List
</button>
<!-- Images tab (disabled, coming soon) -->
<button
disabled
title="Coming soon"
class="flex cursor-not-allowed items-center gap-2 border-b-2 border-transparent px-4 py-2.5 text-[13px] font-medium opacity-40"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
<circle cx="8.5" cy="8.5" r="1.5" />
<polyline points="21 15 16 10 5 21" />
</svg>
Images
<span class="rounded-[3px] bg-[var(--color-bg-4)] px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.06em] text-[var(--color-text-muted)]">
Soon
</span>
</button>
</div>
</div>
<!-- Snapshots tab content -->
{#if pageTab === 'snapshots'}
<div class="p-7" style="animation: fadeUp 0.35s ease both">
{#if error}
<div class="mb-4 rounded-[var(--radius-card)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-4 py-3 text-[13px] text-[var(--color-red)]">
{error}
</div>
{/if}
{#if loading}
<div class="flex items-center justify-center py-24">
<div class="flex items-center gap-3 text-[13px] text-[var(--color-text-secondary)]">
<svg class="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Loading snapshots...
</div>
</div>
{:else}
<!-- Filter row -->
<div class="mb-4 flex items-center justify-between">
<div class="flex gap-1.5">
{#each ([['all', 'All'], ['snapshot', 'Snapshots'], ['base', 'Images']] as const) as [val, label]}
<button
onclick={() => (typeFilter = val)}
class="rounded-full border px-3 py-1 text-[12px] font-medium transition-colors duration-150 {typeFilter === val
? 'border-[var(--color-border-mid)] bg-[var(--color-bg-5)] text-[var(--color-text-bright)]'
: 'border-[var(--color-border)] bg-[var(--color-bg-3)] text-[var(--color-text-secondary)] hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)]'}"
>
{label}
</button>
{/each}
</div>
<span class="text-[12px] text-[var(--color-text-muted)]">
{filteredSnapshots.length}
{filteredSnapshots.length === 1 ? 'snapshot' : 'snapshots'}
</span>
</div>
{#if filteredSnapshots.length === 0}
<!-- Empty state -->
<div class="flex flex-col items-center justify-center py-[72px]">
<div class="mb-5 flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-3)]">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--color-text-secondary)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
<polyline points="3.27 6.96 12 12.01 20.73 6.96" /><line x1="12" y1="22.08" x2="12" y2="12" />
</svg>
</div>
<p class="font-serif text-[20px] tracking-[-0.02em] text-[var(--color-text-bright)]">
{emptyHeading(typeFilter)}
</p>
<p class="mt-1.5 max-w-[340px] text-center text-[13px] text-[var(--color-text-tertiary)]">
{emptyDescription(typeFilter)}
</p>
{#if typeFilter === 'all' || typeFilter === 'snapshot'}
<a
href="/dashboard/capsules"
class="mt-6 flex items-center gap-2 rounded-[var(--radius-button)] border border-[var(--color-border-mid)] bg-[var(--color-bg-3)] px-4 py-2 text-[13px] font-medium text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:bg-[var(--color-bg-4)] hover:text-[var(--color-text-primary)]"
>
Go to Capsules
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<line x1="5" y1="12" x2="19" y2="12" />
<polyline points="12 5 19 12 12 19" />
</svg>
</a>
{/if}
</div>
{:else}
<!-- Table -->
<div class="overflow-hidden rounded-[var(--radius-card)] border border-[var(--color-border)]">
<!-- Header -->
<div class="grid border-b border-[var(--color-border)] bg-[var(--color-bg-3)]" style="grid-template-columns: 2fr 1fr 0.7fr 0.9fr 0.8fr 1.3fr 140px">
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Name</div>
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Type</div>
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">vCPUs</div>
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Memory</div>
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Size</div>
<div class="px-4 py-[11px] text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Created</div>
<div class="px-4 py-[11px] text-right text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Actions</div>
</div>
<!-- Rows -->
{#each filteredSnapshots as snapshot, i (snapshot.name)}
<div
class="grid items-center border-b border-[var(--color-border)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] last:border-b-0"
style="grid-template-columns: 2fr 1fr 0.7fr 0.9fr 0.8fr 1.3fr 140px; animation: fadeUp 0.35s ease both; animation-delay: {i * 40}ms"
>
<!-- Name -->
<div class="px-4 py-3">
<span class="font-mono text-[13px] text-[var(--color-text-bright)]">{snapshot.name}</span>
</div>
<!-- Type badge -->
<div class="px-4 py-3">
{#if snapshot.type === 'snapshot'}
<span class="inline-flex items-center gap-1.5 rounded-[3px] border border-[var(--color-accent)]/20 bg-[var(--color-accent-glow-mid)] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.04em] text-[var(--color-accent-mid)]">
<span class="inline-block h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]" style="box-shadow: 0 0 6px rgba(94,140,88,0.5)"></span>
Snapshot
</span>
{:else}
<span class="inline-flex items-center gap-1.5 rounded-[3px] border border-[var(--color-blue)]/20 bg-[var(--color-blue)]/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.04em] text-[var(--color-blue)]">
<span class="inline-block h-[5px] w-[5px] rounded-full bg-[var(--color-blue)]"></span>
Image
</span>
{/if}
</div>
<!-- vCPUs -->
<div class="px-4 py-3">
{#if snapshot.type === 'snapshot' && snapshot.vcpus != null}
<span class="font-mono text-[13px] text-[var(--color-text-secondary)]">{snapshot.vcpus}</span>
{:else}
<span class="text-[13px] text-[var(--color-text-muted)]"></span>
{/if}
</div>
<!-- Memory -->
<div class="px-4 py-3">
{#if snapshot.type === 'snapshot' && snapshot.memory_mb != null}
<span class="font-mono text-[13px] text-[var(--color-text-secondary)]">{snapshot.memory_mb} MB</span>
{:else}
<span class="text-[13px] text-[var(--color-text-muted)]"></span>
{/if}
</div>
<!-- Size -->
<div class="px-4 py-3">
<span class="font-mono text-[13px] text-[var(--color-text-muted)]">{formatBytes(snapshot.size_bytes)}</span>
</div>
<!-- Created -->
<div class="px-4 py-3" title={formatDate(snapshot.created_at)}>
<span class="text-[13px] text-[var(--color-text-secondary)]">{timeAgo(snapshot.created_at)}</span>
</div>
<!-- Actions: split button -->
<div class="flex items-center justify-end px-3 py-3">
<div class="split-btn-container relative flex items-stretch overflow-hidden rounded-[var(--radius-button)] border border-[var(--color-border-mid)] bg-[var(--color-bg-3)]">
<!-- Launch part -->
<button
onclick={() => openLaunch(snapshot)}
class="flex items-center px-3 py-1.5 text-[12px] font-medium text-[var(--color-text-primary)] transition-colors duration-150 hover:bg-[var(--color-bg-4)] hover:text-[var(--color-text-bright)]"
>
Launch
</button>
<!-- Divider -->
<div class="w-px shrink-0 bg-[var(--color-border-mid)]"></div>
<!-- Chevron / dropdown trigger -->
<button
onclick={(e) => {
e.stopPropagation();
if (openDropdownName === snapshot.name) {
openDropdownName = null;
} else {
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
dropdownPos = { top: rect.bottom + 4, left: rect.right - 128 };
openDropdownName = snapshot.name;
}
}}
class="flex items-center px-2 py-1.5 text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-4)] hover:text-[var(--color-text-bright)]"
>
<svg
class="transition-transform duration-150 {openDropdownName === snapshot.name ? 'rotate-180' : ''}"
width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"
>
<polyline points="6 9 12 15 18 9" />
</svg>
</button>
</div>
</div>
</div>
{/each}
</div>
<p class="mt-3 text-[12px] text-[var(--color-text-muted)]">
{filteredSnapshots.length} {filteredSnapshots.length === 1 ? 'snapshot' : 'snapshots'}
{typeFilter !== 'all' ? `· filtered` : '· total'}
</p>
{/if}
{/if}
</div>
{/if}
</main>
<!-- Status bar -->
<footer class="flex h-7 shrink-0 items-center justify-end border-t border-[var(--color-border)] bg-[var(--color-bg-1)] px-7">
<div class="flex items-center gap-1.5">
<span class="inline-flex h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]"></span>
<span class="font-mono text-[11px] uppercase tracking-[0.04em] text-[var(--color-text-secondary)]">All systems operational</span>
</div>
</footer>
</div>
</div>
<!-- Split button dropdown -->
{#if openDropdownName}
{@const dropdownSnapshot = snapshots.find((s) => s.name === openDropdownName)}
{#if dropdownSnapshot}
<div
class="fixed z-50 w-32 overflow-hidden rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] py-1"
style="top: {dropdownPos.top}px; left: {dropdownPos.left}px; animation: fadeUp 0.15s ease both"
>
<button
onclick={(e) => {
e.stopPropagation();
const target = snapshots.find((s) => s.name === openDropdownName);
openDropdownName = null;
if (target) { deleteTarget = target; deleteError = null; }
}}
class="flex w-full items-center gap-2 px-3 py-2 text-[12px] text-[var(--color-red)] transition-colors duration-150 hover:bg-[var(--color-red)]/5"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0">
<polyline points="3 6 5 6 21 6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
</svg>
Delete
</button>
</div>
{/if}
{/if}
<!-- Delete Confirmation Dialog -->
{#if deleteTarget}
<div class="fixed inset-0 z-50 flex items-center justify-center">
<div
class="absolute inset-0 bg-black/60"
onclick={() => { if (!deleting) deleteTarget = null; }}
onkeydown={(e) => { if (e.key === 'Escape' && !deleting) deleteTarget = null; }}
></div>
<div
class="relative w-full max-w-[380px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-6"
style="animation: fadeUp 0.2s ease both"
>
<h2 class="font-serif text-[20px] tracking-[-0.02em] text-[var(--color-text-bright)]">Delete Snapshot</h2>
<p class="mt-2 text-[13px] text-[var(--color-text-tertiary)]">
Delete <span class="font-mono font-medium text-[var(--color-text-secondary)]">{deleteTarget.name}</span>?
This action cannot be undone.
</p>
{#if deleteTarget.type === 'snapshot'}
<div class="mt-3 flex items-start gap-2 rounded-[var(--radius-input)] border border-[var(--color-amber)]/20 bg-[var(--color-amber)]/5 px-3 py-2.5">
<svg class="mt-0.5 shrink-0" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--color-amber)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
<line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" />
</svg>
<p class="text-[12px] leading-relaxed text-[var(--color-amber)]">
This live capture includes saved memory state. Any capsule relying on it will be unable to resume.
</p>
</div>
{/if}
{#if deleteError}
<div class="mt-4 rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-[12px] text-[var(--color-red)]">
{deleteError}
</div>
{/if}
<div class="mt-6 flex justify-end gap-3">
<button
onclick={() => (deleteTarget = null)}
disabled={deleting}
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-[13px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
>
Cancel
</button>
<button
onclick={handleDelete}
disabled={deleting}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-red)] px-5 py-2 text-[13px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
>
{#if deleting}
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Deleting...
{:else}
Delete Snapshot
{/if}
</button>
</div>
</div>
</div>
{/if}
<!-- Launch Dialog -->
{#if launchTarget}
<div class="fixed inset-0 z-50 flex items-center justify-center">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute inset-0 bg-black/60"
onclick={() => { if (!launching) launchTarget = null; }}
onkeydown={(e) => { if (e.key === 'Escape' && !launching) launchTarget = null; }}
></div>
<div
class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-6"
style="animation: fadeUp 0.2s ease both"
>
<h2 class="font-serif text-[20px] tracking-[-0.02em] text-[var(--color-text-bright)]">Launch Capsule</h2>
<p class="mt-1 text-[13px] text-[var(--color-text-tertiary)]">
Start a new capsule from this template.
</p>
{#if launchError}
<div class="mt-4 rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-[12px] text-[var(--color-red)]">
{launchError}
</div>
{/if}
<!-- Template name (readonly) -->
<div class="mt-5">
<label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">
Template
</label>
<div class="flex items-center gap-2 rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-0)] px-3 py-2">
{#if launchTarget.type === 'snapshot'}
<span class="inline-block h-[6px] w-[6px] shrink-0 rounded-full bg-[var(--color-accent)]" style="box-shadow: 0 0 6px rgba(94,140,88,0.5)"></span>
{:else}
<span class="inline-block h-[6px] w-[6px] shrink-0 rounded-full bg-[var(--color-blue)]"></span>
{/if}
<span class="flex-1 font-mono text-[13px] text-[var(--color-text-bright)]">{launchTarget.name}</span>
<span class="text-[11px] text-[var(--color-text-muted)]">
{launchTarget.type === 'snapshot' ? 'Snapshot' : 'Image'}
</span>
</div>
</div>
<!-- vCPUs + Memory -->
<div class="mt-4 grid grid-cols-2 gap-3">
<div>
<label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="launch-vcpus">
vCPUs
</label>
{#if launchTarget.type === 'snapshot'}
<div class="rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-0)] px-3 py-2 font-mono text-[13px] text-[var(--color-text-muted)]">
{launchTarget.vcpus ?? 1}
</div>
{:else}
<input
id="launch-vcpus"
type="number"
min="1"
max="32"
bind:value={launchVcpus}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-[13px] text-[var(--color-text-bright)] outline-none transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
{/if}
</div>
<div>
<label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="launch-memory">
Memory (MB)
</label>
{#if launchTarget.type === 'snapshot'}
<div class="rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-0)] px-3 py-2 font-mono text-[13px] text-[var(--color-text-muted)]">
{launchTarget.memory_mb ?? 512}
</div>
{:else}
<input
id="launch-memory"
type="number"
min="128"
step="128"
bind:value={launchMemoryMb}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-[13px] text-[var(--color-text-bright)] outline-none transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
{/if}
</div>
</div>
<!-- Timeout -->
<div class="mt-4">
<label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="launch-timeout">Auto-pause timeout (seconds, 0 = never)</label>
<input
id="launch-timeout"
type="number"
min="0"
bind:value={launchTimeoutSec}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-[13px] text-[var(--color-text-bright)] outline-none transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
</div>
<div class="mt-6 flex justify-end gap-3">
<button
onclick={() => (launchTarget = null)}
disabled={launching}
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-[13px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
>
Cancel
</button>
<button
onclick={handleLaunch}
disabled={launching}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2 text-[13px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
>
{#if launching}
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Launching...
{:else}
Launch
{/if}
</button>
</div>
</div>
</div>
{/if}

View File

@ -0,0 +1,287 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { auth } from '$lib/auth.svelte';
import { apiLogin, apiSignup } from '$lib/api/auth';
import {
IconGithub,
IconMail,
IconLock,
IconEye,
IconEyeOff
} from '$lib/components/icons';
let mode: 'signin' | 'signup' = $state('signin');
let email = $state('');
let password = $state('');
let showPassword = $state(false);
let error = $state('');
let loading = $state(false);
// Mouse-reactive glow — moves opposite to cursor with viscous drag
let glowX = $state(50);
let glowY = $state(50);
let targetX = 50;
let targetY = 50;
let rafId: number | null = null;
const LERP_FACTOR = 0.04; // lower = more drag
function lerpLoop() {
const dx = targetX - glowX;
const dy = targetY - glowY;
if (Math.abs(dx) > 0.01 || Math.abs(dy) > 0.01) {
glowX += dx * LERP_FACTOR;
glowY += dy * LERP_FACTOR;
rafId = requestAnimationFrame(lerpLoop);
} else {
glowX = targetX;
glowY = targetY;
rafId = null;
}
}
function handleMouseMove(e: MouseEvent) {
const target = e.currentTarget as HTMLElement;
const rect = target.getBoundingClientRect();
const normX = (e.clientX - rect.left) / rect.width;
const normY = (e.clientY - rect.top) / rect.height;
// Invert: mouse goes right → glow goes left
targetX = 55 - normX * 10;
targetY = 55 - normY * 10;
if (rafId === null) {
rafId = requestAnimationFrame(lerpLoop);
}
}
const title = $derived(mode === 'signin' ? 'Welcome back' : 'Create account');
const subtitle = $derived(
mode === 'signin' ? 'Sign in to your Wrenn account' : 'Get started with Wrenn'
);
const submitLabel = $derived(mode === 'signin' ? 'Sign in' : 'Create account');
const switchText = $derived(
mode === 'signin' ? "Don't have an account?" : 'Already have an account?'
);
const switchAction = $derived(mode === 'signin' ? 'Sign up' : 'Sign in');
function switchMode() {
mode = mode === 'signin' ? 'signup' : 'signin';
error = '';
}
async function handleSubmit(e: Event) {
e.preventDefault();
error = '';
loading = true;
const result =
mode === 'signin'
? await apiLogin(email, password)
: await apiSignup(email, password);
loading = false;
if (!result.ok) {
error = result.error;
return;
}
auth.login(result.data);
goto('/dashboard');
}
</script>
<svelte:head>
<title>Wrenn — {mode === 'signin' ? 'Sign in' : 'Sign up'}</title>
</svelte:head>
<div class="flex min-h-screen">
<!-- Left panel — branding -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="relative hidden w-1/2 flex-col items-center justify-center overflow-hidden bg-[var(--color-bg-1)] lg:flex"
onmousemove={handleMouseMove}
>
<!-- Mouse-reactive radial glow -->
<div
class="pointer-events-none absolute inset-0"
style="background: radial-gradient(ellipse 55% 45% at {glowX}% {glowY}%, rgba(94, 140, 88, 0.09) 0%, transparent 70%)"
aria-hidden="true"
></div>
<!-- Centered logo + wordmark -->
<div
class="relative z-10 flex flex-col items-center"
style="animation: fadeUp 0.35s ease both"
>
<img src="/logo.svg" alt="Wrenn" class="h-20 w-20 rounded-[var(--radius-card)]" />
<span
class="mt-5 font-brand text-[44px] tracking-[-0.01em] text-[var(--color-text-bright)]"
>
Wrenn
</span>
</div>
<!-- Tagline below logo -->
<div
class="relative z-10 mt-10 text-center"
style="animation: fadeUp 0.35s ease 0.1s both"
>
<h1
class="font-serif text-[42px] leading-[1.15] tracking-[-0.03em] text-[var(--color-text-bright)]"
>
Scale Up. Spin Out.
</h1>
</div>
<!-- Sub-tagline -->
<p
class="relative z-10 mt-6 font-mono text-[13px] uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]"
style="animation: fadeUp 0.35s ease 0.2s both"
>
Run Anything. Worry about Nothing.
</p>
</div>
<!-- Right panel — auth form -->
<div
class="flex w-full flex-col items-center justify-center bg-[var(--color-bg-0)] px-6 lg:w-1/2"
>
<!-- Mobile logo (shown only on small screens) -->
<div
class="mb-10 flex flex-col items-center lg:hidden"
style="animation: fadeUp 0.35s ease both"
>
<img src="/logo.svg" alt="Wrenn" class="h-12 w-12 rounded-[var(--radius-card)]" />
<span
class="mt-2 font-brand text-[24px] tracking-[-0.01em] text-[var(--color-text-bright)]"
>
Wrenn
</span>
</div>
<div class="w-full max-w-[400px]" style="animation: fadeUp 0.35s ease 0.1s both">
<!-- Header -->
<div class="mb-8">
<h2
class="font-serif text-[34px] tracking-[-0.02em] text-[var(--color-text-bright)]"
>
{title}
</h2>
<p class="mt-2 text-[14px] text-[var(--color-text-secondary)]">
{subtitle}
</p>
</div>
<!-- GitHub OAuth -->
<a
href="/api/auth/oauth/github"
class="flex w-full items-center justify-center gap-2.5 rounded-[var(--radius-button)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] px-4 py-3 text-[14px] font-medium text-[var(--color-text-bright)] no-underline transition-all duration-150 hover:border-[var(--color-accent)] hover:text-[var(--color-text-bright)]"
>
<IconGithub size={16} />
Continue with GitHub
</a>
<!-- Divider -->
<div class="my-6 flex items-center gap-3">
<div class="h-px flex-1 bg-[var(--color-border)]"></div>
<span
class="font-mono text-[10px] uppercase tracking-[0.1em] text-[var(--color-text-muted)]"
>or</span
>
<div class="h-px flex-1 bg-[var(--color-border)]"></div>
</div>
<!-- Form -->
<form onsubmit={handleSubmit} class="space-y-3">
<div class="group relative">
<div
class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] transition-colors duration-150 group-focus-within:text-[var(--color-accent)]"
>
<IconMail size={14} />
</div>
<input
type="email"
bind:value={email}
placeholder="Email address"
autocomplete="email"
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-2)] py-3 pl-9 pr-3 text-[14px] text-[var(--color-text-bright)] outline-none transition-all duration-150 placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-accent)]"
/>
</div>
<div class="group relative">
<div
class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] transition-colors duration-150 group-focus-within:text-[var(--color-accent)]"
>
<IconLock size={14} />
</div>
<input
type={showPassword ? 'text' : 'password'}
bind:value={password}
placeholder="Password"
autocomplete={mode === 'signin' ? 'current-password' : 'new-password'}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-2)] py-3 pl-9 pr-10 text-[14px] text-[var(--color-text-bright)] outline-none transition-all duration-150 placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-accent)]"
/>
<button
type="button"
onclick={() => (showPassword = !showPassword)}
class="absolute right-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] transition-colors duration-150 hover:text-[var(--color-text-secondary)]"
tabindex={-1}
>
{#if showPassword}
<IconEyeOff size={14} />
{:else}
<IconEye size={14} />
{/if}
</button>
</div>
{#if mode === 'signin'}
<div class="flex justify-end">
<button
type="button"
class="text-[13px] text-[var(--color-text-secondary)] transition-colors duration-150 hover:text-[var(--color-accent-mid)]"
>
Forgot password?
</button>
</div>
{/if}
{#if error}
<p class="text-[13px] text-[var(--color-red)]">{error}</p>
{/if}
<button
type="submit"
disabled={loading}
class="!mt-5 w-full rounded-[var(--radius-button)] bg-[var(--color-accent)] px-4 py-3 text-[14px] font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:pointer-events-none disabled:opacity-50"
>
{#if loading}
<span class="inline-flex items-center gap-2">
<span
class="inline-block h-3.5 w-3.5 animate-spin rounded-full border-2 border-white/30 border-t-white"
></span>
{submitLabel}
</span>
{:else}
{submitLabel}
{/if}
</button>
</form>
<!-- Switch mode -->
<p class="mt-6 text-center text-[13px] text-[var(--color-text-secondary)]">
{switchText}
<button
type="button"
onclick={switchMode}
class="font-medium text-[var(--color-text-primary)] transition-colors duration-150 hover:text-[var(--color-text-bright)]"
>
{switchAction}
</button>
</p>
</div>
</div>
</div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

1
frontend/static/logo.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 221 KiB

View File

@ -0,0 +1,3 @@
# allow crawling everything by default
User-agent: *
Disallow:

19
frontend/svelte.config.js Normal file
View File

@ -0,0 +1,19 @@
import adapter from '@sveltejs/adapter-static';
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
adapter: adapter({
pages: 'build',
assets: 'build',
fallback: 'index.html',
precompress: false
})
},
vitePlugin: {
dynamicCompileOptions: ({ filename }) =>
filename.includes('node_modules') ? undefined : { runes: true }
}
};
export default config;

20
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,20 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"rewriteRelativeImportExtensions": true,
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// To make changes to top-level options such as include and exclude, we recommend extending
// the generated config; see https://svelte.dev/docs/kit/configuration#typescript
}

15
frontend/vite.config.ts Normal file
View File

@ -0,0 +1,15 @@
import { sveltekit } from '@sveltejs/kit/vite';
import tailwindcss from '@tailwindcss/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [tailwindcss(), sveltekit()],
server: {
proxy: {
'/api': {
target: 'http://localhost:8000',
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
});

View File

@ -28,6 +28,8 @@ type apiKeyResponse struct {
TeamID string `json:"team_id"` TeamID string `json:"team_id"`
Name string `json:"name"` Name string `json:"name"`
KeyPrefix string `json:"key_prefix"` KeyPrefix string `json:"key_prefix"`
CreatedBy string `json:"created_by"`
CreatorEmail string `json:"creator_email,omitempty"`
CreatedAt string `json:"created_at"` CreatedAt string `json:"created_at"`
LastUsed *string `json:"last_used,omitempty"` LastUsed *string `json:"last_used,omitempty"`
Key *string `json:"key,omitempty"` // only populated on Create Key *string `json:"key,omitempty"` // only populated on Create
@ -39,6 +41,26 @@ func apiKeyToResponse(k db.TeamApiKey) apiKeyResponse {
TeamID: k.TeamID, TeamID: k.TeamID,
Name: k.Name, Name: k.Name,
KeyPrefix: k.KeyPrefix, KeyPrefix: k.KeyPrefix,
CreatedBy: k.CreatedBy,
}
if k.CreatedAt.Valid {
resp.CreatedAt = k.CreatedAt.Time.Format(time.RFC3339)
}
if k.LastUsed.Valid {
s := k.LastUsed.Time.Format(time.RFC3339)
resp.LastUsed = &s
}
return resp
}
func apiKeyWithCreatorToResponse(k db.ListAPIKeysByTeamWithCreatorRow) apiKeyResponse {
resp := apiKeyResponse{
ID: k.ID,
TeamID: k.TeamID,
Name: k.Name,
KeyPrefix: k.KeyPrefix,
CreatedBy: k.CreatedBy,
CreatorEmail: k.CreatorEmail,
} }
if k.CreatedAt.Valid { if k.CreatedAt.Valid {
resp.CreatedAt = k.CreatedAt.Time.Format(time.RFC3339) resp.CreatedAt = k.CreatedAt.Time.Format(time.RFC3339)
@ -76,7 +98,7 @@ func (h *apiKeyHandler) Create(w http.ResponseWriter, r *http.Request) {
func (h *apiKeyHandler) List(w http.ResponseWriter, r *http.Request) { func (h *apiKeyHandler) List(w http.ResponseWriter, r *http.Request) {
ac := auth.MustFromContext(r.Context()) ac := auth.MustFromContext(r.Context())
keys, err := h.svc.List(r.Context(), ac.TeamID) keys, err := h.svc.ListWithCreator(r.Context(), ac.TeamID)
if err != nil { if err != nil {
writeError(w, http.StatusInternalServerError, "db_error", "failed to list API keys") writeError(w, http.StatusInternalServerError, "db_error", "failed to list API keys")
return return
@ -84,7 +106,7 @@ func (h *apiKeyHandler) List(w http.ResponseWriter, r *http.Request) {
resp := make([]apiKeyResponse, len(keys)) resp := make([]apiKeyResponse, len(keys))
for i, k := range keys { for i, k := range keys {
resp[i] = apiKeyToResponse(k) resp[i] = apiKeyWithCreatorToResponse(k)
} }
writeJSON(w, http.StatusOK, resp) writeJSON(w, http.StatusOK, resp)

View File

@ -1,625 +0,0 @@
package api
import (
"fmt"
"net/http"
)
func serveTestUI(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, testUIHTML)
}
const testUIHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wrenn Sandbox — Test Console</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Menlo', 'Consolas', 'JetBrains Mono', monospace;
font-size: 13px;
background: #0f1211;
color: #c8c4bc;
padding: 16px;
}
h1 { font-size: 18px; color: #e8e5df; margin-bottom: 12px; }
h2 { font-size: 14px; color: #89a785; margin: 16px 0 8px; border-bottom: 1px solid #262c2a; padding-bottom: 4px; }
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.panel {
background: #151918;
border: 1px solid #262c2a;
border-radius: 8px;
padding: 12px;
}
.full { grid-column: 1 / -1; }
label { display: block; color: #8a867f; margin: 6px 0 2px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; }
input, select {
width: 100%;
background: #1b201e;
border: 1px solid #262c2a;
color: #e8e5df;
padding: 6px 8px;
border-radius: 4px;
font-family: inherit;
font-size: 13px;
}
input:focus, select:focus { outline: none; border-color: #5e8c58; }
.btn-row { display: flex; gap: 6px; margin-top: 8px; flex-wrap: wrap; }
button {
padding: 6px 14px;
border: 1px solid #262c2a;
border-radius: 4px;
font-family: inherit;
font-size: 12px;
cursor: pointer;
background: #1b201e;
color: #c8c4bc;
transition: all 0.15s;
}
button:hover { border-color: #5e8c58; color: #e8e5df; }
.btn-green { background: #2a3d28; border-color: #5e8c58; color: #89a785; }
.btn-green:hover { background: #3a5035; }
.btn-red { background: #3d2828; border-color: #b35544; color: #c27b6d; }
.btn-red:hover { background: #4d3030; }
.btn-amber { background: #3d3428; border-color: #9e7c2e; color: #c8a84e; }
.btn-amber:hover { background: #4d4030; }
.btn-blue { background: #28343d; border-color: #3d7aac; color: #6da0cc; }
.btn-blue:hover { background: #304050; }
table { width: 100%; border-collapse: collapse; margin-top: 8px; }
th { text-align: left; font-size: 11px; color: #8a867f; text-transform: uppercase; letter-spacing: 0.05em; padding: 4px 8px; border-bottom: 1px solid #262c2a; }
td { padding: 6px 8px; border-bottom: 1px solid #1b201e; }
tr:hover td { background: #1b201e; }
.status { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 11px; font-weight: 600; }
.status-running { background: rgba(94,140,88,0.15); color: #89a785; }
.status-paused { background: rgba(158,124,46,0.15); color: #c8a84e; }
.status-pending { background: rgba(61,122,172,0.15); color: #6da0cc; }
.status-stopped { background: rgba(138,134,127,0.15); color: #8a867f; }
.status-error { background: rgba(179,85,68,0.15); color: #c27b6d; }
.status-hibernated { background: rgba(61,122,172,0.15); color: #6da0cc; }
.log {
background: #0f1211;
border: 1px solid #262c2a;
border-radius: 4px;
padding: 8px;
max-height: 300px;
overflow-y: auto;
margin-top: 8px;
font-size: 12px;
white-space: pre-wrap;
word-break: break-all;
}
.log-entry { margin-bottom: 4px; }
.log-time { color: #5f5c57; }
.log-ok { color: #89a785; }
.log-err { color: #c27b6d; }
.log-info { color: #6da0cc; }
.exec-output {
background: #0f1211;
border: 1px solid #262c2a;
border-radius: 4px;
padding: 8px;
max-height: 200px;
overflow-y: auto;
margin-top: 8px;
font-size: 12px;
white-space: pre-wrap;
}
.clickable { cursor: pointer; color: #89a785; text-decoration: underline; }
.clickable:hover { color: #aacdaa; }
.auth-badge {
display: inline-block;
padding: 2px 8px;
border-radius: 10px;
font-size: 11px;
font-weight: 600;
margin-left: 8px;
}
.auth-badge.authed { background: rgba(94,140,88,0.15); color: #89a785; }
.auth-badge.unauthed { background: rgba(179,85,68,0.15); color: #c27b6d; }
.key-display {
background: #1b201e;
border: 1px solid #5e8c58;
border-radius: 4px;
padding: 8px;
margin-top: 8px;
font-size: 12px;
word-break: break-all;
color: #89a785;
}
</style>
</head>
<body>
<h1>Wrenn Sandbox Test Console <span id="auth-status" class="auth-badge unauthed">not authenticated</span></h1>
<div class="grid">
<!-- Auth Panel -->
<div class="panel">
<h2>Authentication</h2>
<label>Email</label>
<input type="email" id="auth-email" value="" placeholder="user@example.com">
<label>Password</label>
<input type="password" id="auth-password" value="" placeholder="min 8 characters">
<div class="btn-row">
<button class="btn-green" onclick="signup()">Sign Up</button>
<button class="btn-blue" onclick="login()">Log In</button>
<button class="btn-red" onclick="logout()">Log Out</button>
</div>
<div id="auth-info" style="margin-top:8px;font-size:12px;color:#5f5c57"></div>
</div>
<!-- API Keys Panel -->
<div class="panel">
<h2>API Keys</h2>
<label>Key Name</label>
<input type="text" id="key-name" value="" placeholder="my-api-key">
<div class="btn-row">
<button class="btn-green" onclick="createAPIKey()">Create Key</button>
<button onclick="listAPIKeys()">Refresh</button>
</div>
<div id="new-key-display" style="display:none" class="key-display"></div>
<div id="api-keys-table"></div>
<label style="margin-top:12px">Active API Key</label>
<input type="text" id="active-api-key" value="" placeholder="wrn_...">
</div>
<!-- Create Sandbox -->
<div class="panel">
<h2>Create Sandbox</h2>
<label>Template</label>
<input type="text" id="create-template" value="minimal" placeholder="minimal or snapshot name">
<label>vCPUs</label>
<input type="number" id="create-vcpus" value="1" min="1" max="8">
<label>Memory (MB)</label>
<input type="number" id="create-memory" value="512" min="128" max="8192">
<label>Timeout (sec, 0 = no auto-pause)</label>
<input type="number" id="create-timeout" value="0" min="0">
<div class="btn-row">
<button class="btn-green" onclick="createSandbox()">Create</button>
</div>
</div>
<!-- Snapshot Management -->
<div class="panel">
<h2>Create Snapshot</h2>
<label>Sandbox ID</label>
<input type="text" id="snap-sandbox-id" placeholder="sb-xxxxxxxx">
<label>Snapshot Name (optional)</label>
<input type="text" id="snap-name" placeholder="auto-generated if empty">
<div class="btn-row">
<button class="btn-amber" onclick="createSnapshot()">Create Snapshot</button>
<label style="display:inline-flex;align-items:center;margin:0;font-size:12px;text-transform:none;letter-spacing:0">
<input type="checkbox" id="snap-overwrite" style="width:auto;margin-right:4px"> Overwrite
</label>
</div>
<h2>Snapshots / Templates</h2>
<div class="btn-row">
<button onclick="listSnapshots()">Refresh</button>
</div>
<div id="snapshots-table"></div>
</div>
<!-- Execute Command -->
<div class="panel">
<h2>Execute Command</h2>
<label>Sandbox ID</label>
<input type="text" id="exec-sandbox-id" placeholder="sb-xxxxxxxx">
<label>Command</label>
<input type="text" id="exec-cmd" value="/bin/sh" placeholder="/bin/sh">
<label>Args (comma separated)</label>
<input type="text" id="exec-args" value="-c,uname -a" placeholder="-c,echo hello">
<div class="btn-row">
<button class="btn-green" onclick="execCmd()">Run</button>
</div>
<div id="exec-output" class="exec-output" style="display:none"></div>
</div>
<!-- Activity Log -->
<div class="panel">
<h2>Activity Log</h2>
<div id="log" class="log"></div>
</div>
<!-- Sandboxes List -->
<div class="panel full">
<h2>Sandboxes</h2>
<div class="btn-row">
<button onclick="listSandboxes()">Refresh</button>
<label style="display:inline-flex;align-items:center;margin:0;font-size:12px;text-transform:none;letter-spacing:0">
<input type="checkbox" id="auto-refresh" style="width:auto;margin-right:4px"> Auto-refresh (5s)
</label>
</div>
<div id="sandboxes-table"></div>
</div>
</div>
<script>
const API = '';
let jwtToken = '';
let activeAPIKey = '';
function log(msg, level) {
const el = document.getElementById('log');
const t = new Date().toLocaleTimeString();
const cls = level === 'ok' ? 'log-ok' : level === 'err' ? 'log-err' : 'log-info';
el.innerHTML = '<div class="log-entry"><span class="log-time">' + t + '</span> <span class="' + cls + '">' + esc(msg) + '</span></div>' + el.innerHTML;
}
function esc(s) {
const d = document.createElement('div');
d.textContent = s;
return d.innerHTML;
}
function updateAuthStatus() {
const badge = document.getElementById('auth-status');
const info = document.getElementById('auth-info');
if (jwtToken) {
badge.textContent = 'authenticated';
badge.className = 'auth-badge authed';
try {
const payload = JSON.parse(atob(jwtToken.split('.')[1]));
info.textContent = 'User: ' + payload.email + ' | Team: ' + payload.team_id;
} catch(e) {
info.textContent = 'Token set';
}
} else {
badge.textContent = 'not authenticated';
badge.className = 'auth-badge unauthed';
info.textContent = '';
}
}
// API call with appropriate auth headers.
async function api(method, path, body, authType) {
const opts = { method, headers: {} };
if (authType === 'jwt' && jwtToken) {
opts.headers['Authorization'] = 'Bearer ' + jwtToken;
} else if (authType === 'apikey') {
const key = document.getElementById('active-api-key').value;
if (!key) {
throw new Error('No API key set. Create one first and paste it in the Active API Key field.');
}
opts.headers['X-API-Key'] = key;
}
if (body) {
opts.headers['Content-Type'] = 'application/json';
opts.body = JSON.stringify(body);
}
const resp = await fetch(API + path, opts);
if (resp.status === 204) return null;
const data = await resp.json();
if (resp.status >= 300) {
throw new Error(data.error ? data.error.message : resp.statusText);
}
return data;
}
function statusBadge(s) {
return '<span class="status status-' + s + '">' + s + '</span>';
}
// --- Auth ---
async function signup() {
const email = document.getElementById('auth-email').value;
const password = document.getElementById('auth-password').value;
if (!email || !password) { log('Email and password required', 'err'); return; }
log('Signing up as ' + email + '...', 'info');
try {
const data = await api('POST', '/v1/auth/signup', { email, password });
jwtToken = data.token;
updateAuthStatus();
log('Signed up! User: ' + data.user_id + ', Team: ' + data.team_id, 'ok');
} catch (e) {
log('Signup failed: ' + e.message, 'err');
}
}
async function login() {
const email = document.getElementById('auth-email').value;
const password = document.getElementById('auth-password').value;
if (!email || !password) { log('Email and password required', 'err'); return; }
log('Logging in as ' + email + '...', 'info');
try {
const data = await api('POST', '/v1/auth/login', { email, password });
jwtToken = data.token;
updateAuthStatus();
log('Logged in! User: ' + data.user_id + ', Team: ' + data.team_id, 'ok');
listAPIKeys();
} catch (e) {
log('Login failed: ' + e.message, 'err');
}
}
function logout() {
jwtToken = '';
updateAuthStatus();
log('Logged out', 'info');
}
// --- API Keys ---
async function createAPIKey() {
if (!jwtToken) { log('Log in first to create API keys', 'err'); return; }
const name = document.getElementById('key-name').value || 'Unnamed API Key';
log('Creating API key "' + name + '"...', 'info');
try {
const data = await api('POST', '/v1/api-keys', { name }, 'jwt');
const display = document.getElementById('new-key-display');
display.style.display = 'block';
display.textContent = 'New key (copy now — shown only once): ' + data.key;
document.getElementById('active-api-key').value = data.key;
log('API key created: ' + data.key_prefix, 'ok');
listAPIKeys();
} catch (e) {
log('Create API key failed: ' + e.message, 'err');
}
}
async function listAPIKeys() {
if (!jwtToken) return;
try {
const data = await api('GET', '/v1/api-keys', null, 'jwt');
renderAPIKeys(data);
} catch (e) {
log('List API keys failed: ' + e.message, 'err');
}
}
function renderAPIKeys(keys) {
if (!keys || keys.length === 0) {
document.getElementById('api-keys-table').innerHTML = '<p style="color:#5f5c57;margin-top:8px">No API keys</p>';
return;
}
let html = '<table><thead><tr><th>Name</th><th>Prefix</th><th>Created</th><th>Last Used</th><th>Actions</th></tr></thead><tbody>';
for (const k of keys) {
html += '<tr>';
html += '<td>' + esc(k.name) + '</td>';
html += '<td style="font-size:11px">' + esc(k.key_prefix) + '</td>';
html += '<td>' + new Date(k.created_at).toLocaleString() + '</td>';
html += '<td>' + (k.last_used ? new Date(k.last_used).toLocaleString() : '-') + '</td>';
html += '<td><button class="btn-red" onclick="deleteAPIKey(\'' + k.id + '\')">Delete</button></td>';
html += '</tr>';
}
html += '</tbody></table>';
document.getElementById('api-keys-table').innerHTML = html;
}
async function deleteAPIKey(id) {
log('Deleting API key ' + id + '...', 'info');
try {
await api('DELETE', '/v1/api-keys/' + id, null, 'jwt');
log('Deleted API key ' + id, 'ok');
listAPIKeys();
} catch (e) {
log('Delete API key failed: ' + e.message, 'err');
}
}
// --- Sandboxes ---
async function listSandboxes() {
try {
const data = await api('GET', '/v1/sandboxes', null, 'apikey');
renderSandboxes(data);
} catch (e) {
log('List sandboxes failed: ' + e.message, 'err');
}
}
function renderSandboxes(sandboxes) {
if (!sandboxes || sandboxes.length === 0) {
document.getElementById('sandboxes-table').innerHTML = '<p style="color:#5f5c57;margin-top:8px">No sandboxes</p>';
return;
}
let html = '<table><thead><tr><th>ID</th><th>Status</th><th>Template</th><th>vCPUs</th><th>Mem</th><th>TTL</th><th>Host IP</th><th>Created</th><th>Actions</th></tr></thead><tbody>';
for (const sb of sandboxes) {
html += '<tr>';
html += '<td class="clickable" onclick="useSandbox(\'' + sb.id + '\')">' + sb.id + '</td>';
html += '<td>' + statusBadge(sb.status) + '</td>';
html += '<td>' + esc(sb.template) + '</td>';
html += '<td>' + sb.vcpus + '</td>';
html += '<td>' + sb.memory_mb + 'MB</td>';
html += '<td>' + (sb.timeout_sec ? sb.timeout_sec + 's' : '-') + '</td>';
html += '<td>' + (sb.host_ip || '-') + '</td>';
html += '<td>' + new Date(sb.created_at).toLocaleTimeString() + '</td>';
html += '<td><div class="btn-row">';
if (sb.status === 'running') {
html += '<button class="btn-blue" onclick="pingSandbox(\'' + sb.id + '\')">Ping</button>';
html += '<button class="btn-amber" onclick="pauseSandbox(\'' + sb.id + '\')">Pause</button>';
html += '<button class="btn-red" onclick="destroySandbox(\'' + sb.id + '\')">Destroy</button>';
} else if (sb.status === 'paused') {
html += '<button class="btn-green" onclick="resumeSandbox(\'' + sb.id + '\')">Resume</button>';
html += '<button class="btn-red" onclick="destroySandbox(\'' + sb.id + '\')">Destroy</button>';
} else {
html += '<button class="btn-red" onclick="destroySandbox(\'' + sb.id + '\')">Destroy</button>';
}
html += '</div></td>';
html += '</tr>';
}
html += '</tbody></table>';
document.getElementById('sandboxes-table').innerHTML = html;
}
function useSandbox(id) {
document.getElementById('exec-sandbox-id').value = id;
document.getElementById('snap-sandbox-id').value = id;
}
async function createSandbox() {
const template = document.getElementById('create-template').value;
const vcpus = parseInt(document.getElementById('create-vcpus').value);
const memory_mb = parseInt(document.getElementById('create-memory').value);
const timeout_sec = parseInt(document.getElementById('create-timeout').value);
log('Creating sandbox (template=' + template + ', vcpus=' + vcpus + ', mem=' + memory_mb + 'MB)...', 'info');
try {
const data = await api('POST', '/v1/sandboxes', { template, vcpus, memory_mb, timeout_sec }, 'apikey');
log('Created sandbox ' + data.id + ' [' + data.status + ']', 'ok');
listSandboxes();
} catch (e) {
log('Create failed: ' + e.message, 'err');
}
}
async function pauseSandbox(id) {
log('Pausing ' + id + '...', 'info');
try {
await api('POST', '/v1/sandboxes/' + id + '/pause', null, 'apikey');
log('Paused ' + id, 'ok');
listSandboxes();
} catch (e) {
log('Pause failed: ' + e.message, 'err');
}
}
async function resumeSandbox(id) {
log('Resuming ' + id + '...', 'info');
try {
await api('POST', '/v1/sandboxes/' + id + '/resume', null, 'apikey');
log('Resumed ' + id, 'ok');
listSandboxes();
} catch (e) {
log('Resume failed: ' + e.message, 'err');
}
}
async function destroySandbox(id) {
log('Destroying ' + id + '...', 'info');
try {
await api('DELETE', '/v1/sandboxes/' + id, null, 'apikey');
log('Destroyed ' + id, 'ok');
listSandboxes();
} catch (e) {
log('Destroy failed: ' + e.message, 'err');
}
}
async function pingSandbox(id) {
log('Pinging ' + id + '...', 'info');
try {
await api('POST', '/v1/sandboxes/' + id + '/ping', null, 'apikey');
log('Pinged ' + id + ' — inactivity timer reset', 'ok');
} catch (e) {
log('Ping failed: ' + e.message, 'err');
}
}
// --- Exec ---
async function execCmd() {
const sandboxId = document.getElementById('exec-sandbox-id').value;
const cmd = document.getElementById('exec-cmd').value;
const argsStr = document.getElementById('exec-args').value;
const args = argsStr ? argsStr.split(',').map(s => s.trim()) : [];
if (!sandboxId) { log('No sandbox ID for exec', 'err'); return; }
const out = document.getElementById('exec-output');
out.style.display = 'block';
out.textContent = 'Running...';
log('Exec on ' + sandboxId + ': ' + cmd + ' ' + args.join(' '), 'info');
try {
const data = await api('POST', '/v1/sandboxes/' + sandboxId + '/exec', { cmd, args }, 'apikey');
let text = '';
if (data.stdout) text += data.stdout;
if (data.stderr) text += '\n[stderr]\n' + data.stderr;
text += '\n[exit_code=' + data.exit_code + ', duration=' + data.duration_ms + 'ms]';
out.textContent = text;
log('Exec completed (exit=' + data.exit_code + ')', data.exit_code === 0 ? 'ok' : 'err');
} catch (e) {
out.textContent = 'Error: ' + e.message;
log('Exec failed: ' + e.message, 'err');
}
}
// --- Snapshots ---
async function createSnapshot() {
const sandbox_id = document.getElementById('snap-sandbox-id').value;
const name = document.getElementById('snap-name').value;
const overwrite = document.getElementById('snap-overwrite').checked;
if (!sandbox_id) { log('No sandbox ID for snapshot', 'err'); return; }
const body = { sandbox_id };
if (name) body.name = name;
const qs = overwrite ? '?overwrite=true' : '';
log('Creating snapshot from ' + sandbox_id + (name ? ' as "' + name + '"' : '') + '...', 'info');
try {
const data = await api('POST', '/v1/snapshots' + qs, body, 'apikey');
log('Snapshot created: ' + data.name + ' (' + (data.size_bytes / 1024 / 1024).toFixed(1) + 'MB)', 'ok');
listSnapshots();
listSandboxes();
} catch (e) {
log('Snapshot failed: ' + e.message, 'err');
}
}
async function listSnapshots() {
try {
const data = await api('GET', '/v1/snapshots', null, 'apikey');
renderSnapshots(data);
} catch (e) {
log('List snapshots failed: ' + e.message, 'err');
}
}
function renderSnapshots(snapshots) {
if (!snapshots || snapshots.length === 0) {
document.getElementById('snapshots-table').innerHTML = '<p style="color:#5f5c57;margin-top:8px">No snapshots</p>';
return;
}
let html = '<table><thead><tr><th>Name</th><th>Type</th><th>vCPUs</th><th>Mem</th><th>Size</th><th>Actions</th></tr></thead><tbody>';
for (const s of snapshots) {
html += '<tr>';
html += '<td class="clickable" onclick="useTemplate(\'' + esc(s.name) + '\')">' + esc(s.name) + '</td>';
html += '<td>' + s.type + '</td>';
html += '<td>' + (s.vcpus || '-') + '</td>';
html += '<td>' + (s.memory_mb ? s.memory_mb + 'MB' : '-') + '</td>';
html += '<td>' + (s.size_bytes / 1024 / 1024).toFixed(1) + 'MB</td>';
html += '<td><button class="btn-red" onclick="deleteSnapshot(\'' + esc(s.name) + '\')">Delete</button></td>';
html += '</tr>';
}
html += '</tbody></table>';
document.getElementById('snapshots-table').innerHTML = html;
}
function useTemplate(name) {
document.getElementById('create-template').value = name;
log('Template set to "' + name + '" — click Create to launch from this snapshot', 'info');
}
async function deleteSnapshot(name) {
log('Deleting snapshot "' + name + '"...', 'info');
try {
await api('DELETE', '/v1/snapshots/' + encodeURIComponent(name), null, 'apikey');
log('Deleted snapshot "' + name + '"', 'ok');
listSnapshots();
} catch (e) {
log('Delete snapshot failed: ' + e.message, 'err');
}
}
// --- Auto-refresh ---
let refreshInterval = null;
document.getElementById('auto-refresh').addEventListener('change', function() {
if (this.checked) {
refreshInterval = setInterval(listSandboxes, 5000);
} else {
clearInterval(refreshInterval);
refreshInterval = null;
}
});
// --- Init ---
updateAuthStatus();
</script>
</body>
</html>`

View File

@ -0,0 +1,56 @@
package api
import (
"log/slog"
"net/http"
"strings"
"git.omukk.dev/wrenn/sandbox/internal/auth"
"git.omukk.dev/wrenn/sandbox/internal/db"
)
// requireAPIKeyOrJWT accepts either X-API-Key header or Authorization: Bearer JWT.
// Both stamp TeamID into the request context via auth.AuthContext.
func requireAPIKeyOrJWT(queries *db.Queries, jwtSecret []byte) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Try API key first.
if key := r.Header.Get("X-API-Key"); key != "" {
hash := auth.HashAPIKey(key)
row, err := queries.GetAPIKeyByHash(r.Context(), hash)
if err != nil {
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid API key")
return
}
if err := queries.UpdateAPIKeyLastUsed(r.Context(), row.ID); err != nil {
slog.Warn("failed to update api key last_used", "key_id", row.ID, "error", err)
}
ctx := auth.WithAuthContext(r.Context(), auth.AuthContext{TeamID: row.TeamID})
next.ServeHTTP(w, r.WithContext(ctx))
return
}
// Try JWT bearer token.
if header := r.Header.Get("Authorization"); strings.HasPrefix(header, "Bearer ") {
tokenStr := strings.TrimPrefix(header, "Bearer ")
claims, err := auth.VerifyJWT(jwtSecret, tokenStr)
if err != nil {
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired token")
return
}
ctx := auth.WithAuthContext(r.Context(), auth.AuthContext{
TeamID: claims.TeamID,
UserID: claims.Subject,
Email: claims.Email,
})
next.ServeHTTP(w, r.WithContext(ctx))
return
}
writeError(w, http.StatusUnauthorized, "unauthorized", "X-API-Key or Authorization: Bearer <token> required")
})
}
}

View File

@ -49,14 +49,11 @@ func New(queries *db.Queries, agent hostagentv1connect.HostAgentServiceClient, p
r.Get("/openapi.yaml", serveOpenAPI) r.Get("/openapi.yaml", serveOpenAPI)
r.Get("/docs", serveDocs) r.Get("/docs", serveDocs)
// Test UI for sandbox lifecycle management.
r.Get("/test", serveTestUI)
// Unauthenticated auth endpoints. // Unauthenticated auth endpoints.
r.Post("/v1/auth/signup", authH.Signup) r.Post("/v1/auth/signup", authH.Signup)
r.Post("/v1/auth/login", authH.Login) r.Post("/v1/auth/login", authH.Login)
r.Get("/v1/auth/oauth/{provider}", oauthH.Redirect) r.Get("/auth/oauth/{provider}", oauthH.Redirect)
r.Get("/v1/auth/oauth/{provider}/callback", oauthH.Callback) r.Get("/auth/oauth/{provider}/callback", oauthH.Callback)
// JWT-authenticated: API key management. // JWT-authenticated: API key management.
r.Route("/v1/api-keys", func(r chi.Router) { r.Route("/v1/api-keys", func(r chi.Router) {
@ -66,9 +63,9 @@ func New(queries *db.Queries, agent hostagentv1connect.HostAgentServiceClient, p
r.Delete("/{id}", apiKeys.Delete) r.Delete("/{id}", apiKeys.Delete)
}) })
// API-key-authenticated: sandbox lifecycle. // Sandbox lifecycle: accepts API key or JWT bearer token.
r.Route("/v1/sandboxes", func(r chi.Router) { r.Route("/v1/sandboxes", func(r chi.Router) {
r.Use(requireAPIKey(queries)) r.Use(requireAPIKeyOrJWT(queries, jwtSecret))
r.Post("/", sandbox.Create) r.Post("/", sandbox.Create)
r.Get("/", sandbox.List) r.Get("/", sandbox.List)
@ -87,9 +84,9 @@ func New(queries *db.Queries, agent hostagentv1connect.HostAgentServiceClient, p
}) })
}) })
// API-key-authenticated: snapshot / template management. // Snapshot / template management: accepts API key or JWT bearer token.
r.Route("/v1/snapshots", func(r chi.Router) { r.Route("/v1/snapshots", func(r chi.Router) {
r.Use(requireAPIKey(queries)) r.Use(requireAPIKeyOrJWT(queries, jwtSecret))
r.Post("/", snapshots.Create) r.Post("/", snapshots.Create)
r.Get("/", snapshots.List) r.Get("/", snapshots.List)
r.Delete("/{name}", snapshots.Delete) r.Delete("/{name}", snapshots.Delete)
@ -127,12 +124,6 @@ func (s *Server) Handler() http.Handler {
return s.router return s.router
} }
// Router returns the underlying chi router so additional routes (e.g. dashboard)
// can be mounted on it.
func (s *Server) Router() chi.Router {
return s.router
}
func serveOpenAPI(w http.ResponseWriter, r *http.Request) { func serveOpenAPI(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/yaml") w.Header().Set("Content-Type", "application/yaml")
_, _ = w.Write(openapiYAML) _, _ = w.Write(openapiYAML)

View File

@ -26,10 +26,10 @@ func HashAPIKey(plaintext string) string {
return hex.EncodeToString(sum[:]) return hex.EncodeToString(sum[:])
} }
// APIKeyPrefix returns the displayable prefix of an API key (e.g. "wrn_ab12..."). // APIKeyPrefix returns the first 8 characters of a plaintext API key (e.g. "wrn_ab12").
func APIKeyPrefix(plaintext string) string { func APIKeyPrefix(plaintext string) string {
if len(plaintext) > 12 { if len(plaintext) > 10 {
return plaintext[:12] + "..." return plaintext[:10]
} }
return plaintext return plaintext
} }

View File

@ -7,6 +7,8 @@ package db
import ( import (
"context" "context"
"github.com/jackc/pgx/v5/pgtype"
) )
const deleteAPIKey = `-- name: DeleteAPIKey :exec const deleteAPIKey = `-- name: DeleteAPIKey :exec
@ -114,6 +116,57 @@ func (q *Queries) ListAPIKeysByTeam(ctx context.Context, teamID string) ([]TeamA
return items, nil return items, nil
} }
const listAPIKeysByTeamWithCreator = `-- name: ListAPIKeysByTeamWithCreator :many
SELECT k.id, k.team_id, k.name, k.key_hash, k.key_prefix, k.created_by, k.created_at, k.last_used,
u.email AS creator_email
FROM team_api_keys k
JOIN users u ON u.id = k.created_by
WHERE k.team_id = $1
ORDER BY k.created_at DESC
`
type ListAPIKeysByTeamWithCreatorRow struct {
ID string `json:"id"`
TeamID string `json:"team_id"`
Name string `json:"name"`
KeyHash string `json:"key_hash"`
KeyPrefix string `json:"key_prefix"`
CreatedBy string `json:"created_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
LastUsed pgtype.Timestamptz `json:"last_used"`
CreatorEmail string `json:"creator_email"`
}
func (q *Queries) ListAPIKeysByTeamWithCreator(ctx context.Context, teamID string) ([]ListAPIKeysByTeamWithCreatorRow, error) {
rows, err := q.db.Query(ctx, listAPIKeysByTeamWithCreator, teamID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAPIKeysByTeamWithCreatorRow
for rows.Next() {
var i ListAPIKeysByTeamWithCreatorRow
if err := rows.Scan(
&i.ID,
&i.TeamID,
&i.Name,
&i.KeyHash,
&i.KeyPrefix,
&i.CreatedBy,
&i.CreatedAt,
&i.LastUsed,
&i.CreatorEmail,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const updateAPIKeyLastUsed = `-- name: UpdateAPIKeyLastUsed :exec const updateAPIKeyLastUsed = `-- name: UpdateAPIKeyLastUsed :exec
UPDATE team_api_keys SET last_used = NOW() WHERE id = $1 UPDATE team_api_keys SET last_used = NOW() WHERE id = $1
` `

View File

@ -219,7 +219,9 @@ func (q *Queries) ListSandboxesByHostAndStatus(ctx context.Context, arg ListSand
} }
const listSandboxesByTeam = `-- name: ListSandboxesByTeam :many const listSandboxesByTeam = `-- name: ListSandboxesByTeam :many
SELECT id, host_id, template, status, vcpus, memory_mb, timeout_sec, guest_ip, host_ip, created_at, started_at, last_active_at, last_updated, team_id FROM sandboxes WHERE team_id = $1 ORDER BY created_at DESC SELECT id, host_id, template, status, vcpus, memory_mb, timeout_sec, guest_ip, host_ip, created_at, started_at, last_active_at, last_updated, team_id FROM sandboxes
WHERE team_id = $1 AND status NOT IN ('stopped', 'error')
ORDER BY created_at DESC
` `
func (q *Queries) ListSandboxesByTeam(ctx context.Context, teamID string) ([]Sandbox, error) { func (q *Queries) ListSandboxesByTeam(ctx context.Context, teamID string) ([]Sandbox, error) {

View File

@ -52,6 +52,11 @@ func (s *APIKeyService) List(ctx context.Context, teamID string) ([]db.TeamApiKe
return s.DB.ListAPIKeysByTeam(ctx, teamID) return s.DB.ListAPIKeysByTeam(ctx, teamID)
} }
// ListWithCreator returns all API keys for the team, joined with the creator's email.
func (s *APIKeyService) ListWithCreator(ctx context.Context, teamID string) ([]db.ListAPIKeysByTeamWithCreatorRow, error) {
return s.DB.ListAPIKeysByTeamWithCreator(ctx, teamID)
}
// Delete removes an API key by ID, scoped to the given team. // Delete removes an API key by ID, scoped to the given team.
func (s *APIKeyService) Delete(ctx context.Context, keyID, teamID string) error { func (s *APIKeyService) Delete(ctx context.Context, keyID, teamID string) error {
return s.DB.DeleteAPIKey(ctx, db.DeleteAPIKeyParams{ID: keyID, TeamID: teamID}) return s.DB.DeleteAPIKey(ctx, db.DeleteAPIKeyParams{ID: keyID, TeamID: teamID})

View File

@ -106,7 +106,7 @@ func (s *SandboxService) Create(ctx context.Context, p SandboxCreateParams) (db.
return sb, nil return sb, nil
} }
// List returns all sandboxes belonging to the given team. // List returns active sandboxes (excludes stopped/error) belonging to the given team.
func (s *SandboxService) List(ctx context.Context, teamID string) ([]db.Sandbox, error) { func (s *SandboxService) List(ctx context.Context, teamID string) ([]db.Sandbox, error) {
return s.DB.ListSandboxesByTeam(ctx, teamID) return s.DB.ListSandboxesByTeam(ctx, teamID)
} }