diff --git a/.agents/skills/README.md b/.agents/skills/README.md new file mode 100644 index 000000000..e80b3e107 --- /dev/null +++ b/.agents/skills/README.md @@ -0,0 +1,24 @@ +# Skills + +Skills live here as real directories. `.claude/skills/` holds symlinks to them +(`.claude/skills/ -> ../../.agents/skills/`), which is the only path +Claude Code reads; that directory stays untracked. Most entries are personal +installs via `npx skills add` and stay gitignored; the ones re-included in +`.gitignore` ship with the repo. A fresh clone (a teammate, a cloud session) +needs the symlinks once: + +```sh +mkdir -p .claude/skills && for d in .agents/skills/*/; do n=$(basename "$d"); ln -sfn "../../.agents/skills/$n" ".claude/skills/$n"; done +``` + +| Skill | Source | License | +|---|---|---| +| `screenshot` | this repo, wraps `scripts/screenshot.mjs` | AGPL-3.0 (repo) | +| `grill-me`, `codebase-design` | github.com/mattpocock/skills | MIT | + +To ship another one: install it, add `!.agents/skills//` to +`.gitignore`, and a row here with its license. Only self-contained skills +qualify: one that invokes another skill by name (`/grilling`, +`/domain-modeling`) breaks in a clone that lacks it. Update a vendored skill +by re-installing and committing the diff; do not edit vendored text, raise it +upstream. diff --git a/.agents/skills/codebase-design/DEEPENING.md b/.agents/skills/codebase-design/DEEPENING.md new file mode 100644 index 000000000..3938457b8 --- /dev/null +++ b/.agents/skills/codebase-design/DEEPENING.md @@ -0,0 +1,37 @@ +# Deepening + +How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md) — **module**, **interface**, **seam**, **adapter**. + +## Dependency categories + +When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam. + +### 1. In-process + +Pure computation, in-memory state, no I/O. Always deepenable — merge the modules and test through the new interface directly. No adapter needed. + +### 2. Local-substitutable + +Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface. + +### 3. Remote but owned (Ports & Adapters) + +Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter. + +Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."* + +### 4. True external (Mock) + +Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter. + +## Seam discipline + +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection. +- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them. + +## Testing strategy: replace, don't layer + +- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist — delete them. +- Write new tests at the deepened module's interface. The **interface is the test surface**. +- Tests assert on observable outcomes through the interface, not internal state. +- Tests should survive internal refactors — they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. diff --git a/.agents/skills/codebase-design/DESIGN-IT-TWICE.md b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md new file mode 100644 index 000000000..49a7c42a2 --- /dev/null +++ b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md @@ -0,0 +1,44 @@ +# Design It Twice + +When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout) — your first idea is unlikely to be the best. + +Uses the vocabulary in [SKILL.md](SKILL.md) — **module**, **interface**, **seam**, **adapter**, **leverage**. + +## Process + +### 1. Frame the problem space + +Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate: + +- The constraints any new interface would need to satisfy +- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md)) +- A rough illustrative code sketch to ground the constraints — not a proposal, just a way to make the constraints concrete + +Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel. + +### 2. Spawn sub-agents + +Spawn 3+ sub-agents in parallel using the Agent tool. Each must produce a **radically different** interface for the deepened module. + +Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint: + +- Agent 1: "Minimize the interface — aim for 1–3 entry points max. Maximise leverage per entry point." +- Agent 2: "Maximise flexibility — support many use cases and extension." +- Agent 3: "Optimise for the most common caller — make the default case trivial." +- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies." + +Include both [SKILL.md](SKILL.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. + +Each sub-agent outputs: + +1. Interface (types, methods, params — plus invariants, ordering, error modes) +2. Usage example showing how callers use it +3. What the implementation hides behind the seam +4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md)) +5. Trade-offs — where leverage is high, where it's thin + +### 3. Present and compare + +Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**. + +After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated — the user wants a strong read, not a menu. diff --git a/.agents/skills/codebase-design/SKILL.md b/.agents/skills/codebase-design/SKILL.md new file mode 100644 index 000000000..16620c245 --- /dev/null +++ b/.agents/skills/codebase-design/SKILL.md @@ -0,0 +1,114 @@ +--- +name: codebase-design +description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary. +--- + +# Codebase Design + +Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone. + +## Glossary + +Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. + +**Module** — anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service. + +**Interface** — everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow — they refer only to the type-level surface). + +**Implementation** — what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. + +**Depth** — leverage at the interface: the amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation. + +**Seam** _(Michael Feathers)_ — a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context). + +**Adapter** — a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). + +**Leverage** — what callers get from depth: more capability per unit of interface they learn. One implementation pays back across N call sites and M tests. + +**Locality** — what maintainers get from depth: change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere. + +## Deep vs shallow + +**Deep module** = small interface + lots of implementation: + +``` +┌─────────────────────┐ +│ Small Interface │ ← Few methods, simple params +├─────────────────────┤ +│ │ +│ Deep Implementation│ ← Complex logic hidden +│ │ +└─────────────────────┘ +``` + +**Shallow module** = large interface + little implementation (avoid): + +``` +┌─────────────────────────────────┐ +│ Large Interface │ ← Many methods, complex params +├─────────────────────────────────┤ +│ Thin Implementation │ ← Just passes through +└─────────────────────────────────┘ +``` + +When designing an interface, ask: + +- Can I reduce the number of methods? +- Can I simplify the parameters? +- Can I hide more complexity inside? + +## Principles + +- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts — they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. +- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. +- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape. +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. + +## Designing for testability + +Good interfaces make testing natural: + +1. **Accept dependencies, don't create them.** + + ```typescript + // Testable + function processOrder(order, paymentGateway) {} + + // Hard to test + function processOrder(order) { + const gateway = new StripeGateway(); + } + ``` + +2. **Return results, don't produce side effects.** + + ```typescript + // Testable + function calculateDiscount(cart): Discount {} + + // Hard to test + function applyDiscount(cart): void { + cart.total -= discount; + } + ``` + +3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup. + +## Relationships + +- A **Module** has exactly one **Interface** (the surface it presents to callers and tests). +- **Depth** is a property of a **Module**, measured against its **Interface**. +- A **Seam** is where a **Module**'s **Interface** lives. +- An **Adapter** sits at a **Seam** and satisfies the **Interface**. +- **Depth** produces **Leverage** for callers and **Locality** for maintainers. + +## Rejected framings + +- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. +- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow — interface here includes every fact a caller must know. +- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. + +## Going deeper + +- **Deepening a cluster given its dependencies** — see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing. +- **Exploring alternative interfaces** — see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement. diff --git a/.agents/skills/grill-me/SKILL.md b/.agents/skills/grill-me/SKILL.md new file mode 100644 index 000000000..f1543a911 --- /dev/null +++ b/.agents/skills/grill-me/SKILL.md @@ -0,0 +1,8 @@ +--- +name: grill-me +description: Interview the user relentlessly about a plan or design until reaching shared understanding, resolving each branch of the decision tree. Use when user wants to stress-test a plan, get grilled on their design, or mentions "grill me". +--- + +Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer. + +If a question can be answered by exploring the codebase, explore the codebase instead. diff --git a/.agents/skills/grill-me/plan-readonly-mcp.md b/.agents/skills/grill-me/plan-readonly-mcp.md new file mode 100644 index 000000000..5c7a7c305 --- /dev/null +++ b/.agents/skills/grill-me/plan-readonly-mcp.md @@ -0,0 +1,54 @@ +# Read-Only Turso MCP for Claude + +## Goal + +Connect Claude to a read-only replica of the prod database via Turso MCP, so Claude can answer product analytics and debugging questions without any risk to prod. + +## Architecture + +``` +Prod Turso DB → (one-shot sync) → ~/.openstatus/replica.db → Turso MCP → Claude + (chmod 444, scrubbed) (execute_query only) +``` + +## Steps + +### 1. Sync script — `packages/db/src/sync-replica.mts` + +- Loads `DATABASE_URL` + `DATABASE_AUTH_TOKEN` from `packages/db/.env` +- Creates `~/.openstatus/` directory if needed +- Uses `@libsql/client` embedded replica: `file:///Users//.openstatus/replica.db` with `syncUrl` pointing to prod +- Calls `.sync()` once, then: + - Scrubs sensitive tables: `DELETE FROM apiKey; DELETE FROM session;` + - Sets file permissions to `chmod 444` (read-only) +- Exits + +### 2. Package.json script + +- Add `"sync-replica"` to `packages/db/package.json` so it can be run with `pnpm sync-replica` + +### 3. MCP registration + +```bash +claude mcp add turso --tool execute_query -- turso mcp ~/.openstatus/replica.db +``` + +- `--tool execute_query` restricts Claude to read-only SELECT queries only +- Exact `turso mcp` args to be confirmed via `turso mcp --help` + +### 4. Gitignore + +- Ensure `replica.db` is not committable (should already be covered by `*.db` patterns, verify) + +## Usage + +1. Run `cd packages/db && pnpm sync-replica` to get a fresh snapshot +2. Claude can now query the replica via the MCP tool +3. Re-run the sync script whenever you need fresher data + +## Safety layers + +1. **Network isolation** — local `.db` file, no network path back to prod +2. **Tool filtering** — Claude only sees `execute_query` (SELECT-only), not insert/update/delete/schema tools +3. **File permissions** — `chmod 444` prevents writes at the OS level +4. **Credential scrub** — `apiKey` and `session` tables are deleted after sync diff --git a/.agents/skills/screenshot/SKILL.md b/.agents/skills/screenshot/SKILL.md new file mode 100644 index 000000000..90e57a416 --- /dev/null +++ b/.agents/skills/screenshot/SKILL.md @@ -0,0 +1,111 @@ +--- +name: screenshot +description: Screenshot pages of the local dev server of any Next.js app here (dashboard, marketing web, status page) in light and dark, logged in where needed. Use after any visible change, when asked to "take a screenshot", "show me", or to verify a layout before reporting it done. +--- + +# Screenshots + +One script does the loop: find Playwright, use system Chrome (or the bundled +Chromium on a machine without it), log in if the app needs it, set the theme, +shoot an element or the page. + +```sh +node scripts/screenshot.mjs --app dashboard /incidents/1 --selector "[data-slot=timeline]" +node scripts/screenshot.mjs --app web /pricing --full-page +node scripts/screenshot.mjs --app status-page /acme +``` + +It prints the PNG paths. Read them with the Read tool and judge against +`DESIGN.md`. Both themes by default; `--theme light` for one. + +## Before running + +1. Find the dev server: `lsof -nP -iTCP:3000 -iTCP:3001 -iTCP:3002 -sTCP:LISTEN`. + Defaults are dashboard `:3001`, web and status page `:3000`, but `apps/web` + is often started on `:3001` here, so check `lsof -a -p -d cwd` or + just run the script: it refuses a base whose probe path is a 404. Reuse a + running server, HMR picks up edits. Nothing running: + `pnpm -w dev:dashboard`, `dev:web` or `dev:status-page` (each also starts + sqld on :8080), logged to a file, stopped when done. If the default port is + taken, start the app alone on another port and pass `--base`: + `PORT=3002 pnpm --filter @openstatus/dashboard dev`. +2. Database, dashboard only: the script reads live sessions from sqld over + HTTP, default `--db http://127.0.0.1:8080`. A second sqld on :8099 is the + throwaway seeded one; pass `--db http://127.0.0.1:8099` and point the + dashboard at it with `DATABASE_URL`. +3. Auth, dashboard only. The seed (`pnpm --filter @openstatus/db seed`, + through `devbox run --` because of the deno pin) creates two maintainers + with sessions that expire in 2099: `max@openstatus.dev` (token + `seed-session-max`, owner of workspace 1 `love-openstatus`) and + `thibault@openstatus.dev` (token `seed-session-thibault`, admin of 1). + Pass `--user max@openstatus.dev` and the script finds the row, or skip the + DB with `--token seed-session-max --workspace love-openstatus`. Without + `--user` it takes any live session, and the two seeded ones tie, so name + the user when identity matters. No session at all: + `--login --log ` submits the email form, follows the + `>>> Magic Link:` line the dev server prints and saves a storage state next + to the output. A database that predates the seed change has no `max@` + session: re-seed or `--login`. + +## Flags + +| Flag | Default | Note | +|---|---|---| +| `--app` | `dashboard` | `dashboard`, `web` or `status-page`; sets base and whether to log in | +| ` …` | required | one or more paths; on the status page the slug is the first segment in dev | +| `--selector` | page | CSS selector; every visible match is shot | +| `--theme` | `both` | `light` or `dark` | +| `--out` | `.screenshots` | gitignored | +| `--width` | `1400` | viewport width, 2× device scale | +| `--full-page` | off | full-page capture when no selector | +| `--base` | per app | override the dev server URL | +| `--db` | `http://127.0.0.1:8080` | sqld HTTP endpoint for the session lookup | +| `--user` | | pick the session of this email | +| `--workspace` | first membership | slug for the `workspace-slug` cookie | +| `--token` | | explicit session token, skips the lookup | +| `--login`, `--log` | | magic-link login fallback | + +## Selectors worth knowing + +- dashboard: `[data-slot=timeline]` activity timelines, `[data-slot=input-group]` + composers, `[data-slot=detail-header]` page headers, `[data-slot=property-list]` + the aside +- web: `main`, or a section by its heading id +- status page: `[data-slot=status-bar]` and the other block slots from + `packages/ui/src/components/blocks/` + +## Fixtures + +Seeded, workspace 1 `love-openstatus`: incident #1 (`/incidents/1`, declared +by Thibault, commander Max, eight events covering declare, Slack bind, linked +report #2, a Slack note, a commander change, a mitigation with a note, a +plain note and a Slack unbind), status reports #1 (resolved) and #2 (linked), maintenances, status pages +`/status` (page 1, with components) and `/acme` (page 2). Safe to mutate; +re-seed to reset. + +## Rules + +- Shoot the element, not the viewport, unless layout is the question. +- Shoot before and after, both themes, and compare. +- Do not post, edit or delete on the fixtures unless the screenshot needs + that state; say so when you do. +- A redirect to `/login` means auth failed. Fix auth; do not screenshot the + login page and call it done. +- Stop any dev server you started. Match by port, never by process name, + so the user's own servers survive. + +## Sharing + +The PNGs are gitignored, so where the user sees them depends on where the +session runs. + +- **Local machine (terminal or desktop app):** leave them in `.screenshots/` + and name the files in the final message. The user opens them directly. +- **Cloud session:** nothing leaves the sandbox except git, so the files + vanish with the VM. Publish them with the Artifact tool: one page, the + shots side by side with "before" and "after" captions, uploaded as assets, + and put the link in the final message. Never commit screenshots to make + them visible. +- **Review evidence for a PR:** when a reviewer needs the image, publish it + as an artifact and link it from the PR description; the PR text is the + one place a screenshot link belongs in the repo. diff --git a/.gitignore b/.gitignore index b7ed4bfe4..a83d9198f 100644 --- a/.gitignore +++ b/.gitignore @@ -82,9 +82,17 @@ plan.md *.tsbuildinfo -.claude/skills/** -.agents/skills/** +# Skills live in .agents/skills; .claude/skills holds personal symlinks to them and stays untracked. +# Most are personal installs (skills-lock.json); the ones re-included below ship with the repo, +# see .agents/skills/README.md. +.agents/skills/* +.claude/skills/ +!.agents/skills/README.md +!.agents/skills/screenshot/ +!.agents/skills/grill-me/ +!.agents/skills/codebase-design/ skills-lock.json +.screenshots/ .mcp.json diff --git a/AGENTS.md b/AGENTS.md index 229300d06..feae67c92 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,6 +77,7 @@ boundaries with external SDKs or at registry-style dispatch. When you need one: ## Package context +- `DESIGN.md` — what good UI looks like: hierarchy, compound kits, tokens, motion, a11y - `packages/services/AGENTS.md` — service verbs, audit log, scope enforcement - `packages/ui/AGENTS.md` — stock shadcn vs. the published blocks registry - `apps/dashboard/AGENTS.md` — Next.js runtimes, client boundary, UI verification diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 000000000..f7989e5fd --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,283 @@ +# DESIGN.md + +How openstatus UI should look, feel and be built. `AGENTS.md` says where code +lives and what breaks; this file says what good looks like. Read both before +touching anything a user sees. Rules are short on purpose: the reason is the +rule, and the exception is in review. + +## Principles + +- **Hierarchy over decoration.** A page has one loud level and one quiet + level. Authored content (a note, an update, a postmortem) is loud. State + changes and system events are quiet. If everything is emphasized, nothing + is. +- **Quiet by default.** Start from `text-muted-foreground` and lift only the + word that matters to `text-foreground`. Borders, fills and color are earned. +- **Compose, don't invent.** A new screen is existing primitives in a new + arrangement. A new primitive is a reviewed decision, not a side effect of a + feature. +- **Unseen details compound.** Nobody notices a 160ms press or a + dashed-underline hover on its own. Together they are why the product feels + right. +- **Learnable by repetition.** The same shape on every incident, report and + maintenance teaches the workflow without a tour. Consistency across pages + beats a better idea on one page. + +## Components + +### Where things live + +| Layer | Path | Rule | +|---|---|---| +| shadcn primitives | `packages/ui/src/components/ui/` | Stock. Edited only as a documented last resort, see `packages/ui/AGENTS.md`. | +| Public blocks | `packages/ui/src/components/blocks/` | Published registry. Imports nothing from an app; apps import them freely. | +| Shared custom | `packages/ui/src/components/custom/` | Ours, used by more than one app. | +| App kits | `apps/*/src/components/content/`, `common/` | Compound kits a whole app composes from. | +| Feature rows | `apps/*/src/components//` | What a feature renders with the kits. | + +A repeated visual is a new part in a kit, never a copied class stack. A +feature-specific row (an incident event, a report update) lives in the feature +folder and imports the kit; it does not add exports to the kit. + +### Compound components + +One kit per concept, small export list, every part a plain element wrapper: + +```tsx +export function TimelineItem({ children, className, ...props }: React.ComponentProps<"li">) { + return ( +
  • + {children} +
  • + ); +} +``` + +- Props are `React.ComponentProps<"tag">` plus the few the part owns. Spread + the rest, merge `className` with `cn`, always set `data-slot`. +- Parent context is expressed in CSS, not props: + `in-data-[slot=timeline-card]:text-foreground` lets an actor render muted in a + row and bold in a card without a `variant` prop. +- State is expressed through attributes the browser already sets: + `aria-pressed:`, `data-[state=open]:`, `aria-invalid:`, `disabled:`. Style + the attribute, never a parallel boolean class. +- Keep the kit at the number of exports it needs. `Timeline` has eleven. If + a feature needs a twelfth, first ask whether it is a row in the feature file. +- Children, not render props, for layout. Slot props (`renderMessage`, + `asChild`) only where a block must stay free of app dependencies. + +### Variants + +- `cva` for the visual axes of a part, `VariantProps` for the type. Status + variants are `default | success | warning | destructive | info`, pinned with + `satisfies Record` so a missing one fails typecheck. +- `className` is for layout (margin, width, grid placement). It is not for + restyling a part's colors or type; add a variant instead. +- Prefer a boolean switch (`dot`, `plain`) over a new variant when it only + removes chrome. +- `gap-*` on flex and grid, never `space-x-*` / `space-y-*`. `size-*` when + width equals height. `truncate` plus `min-w-0` on the flex child. + +### Primitives + +When a shadcn primitive is not enough, in order: pass `className`, wrap it in +a kit part, add a variant to the wrapper. Editing `ui/` is a last resort with a +comment saying why. Shared UI comes from `@openstatus/ui`; an app never forks a +primitive (`docs/adr/0003`). + +## Hierarchy and layout + +- **Two row kinds, one rail.** A list of events has a compact sentence row + (icon, muted sentence, time) and a card (avatar, header, body, optional + footer, actions top-right). The rule for which: an authored message is a + card, everything else is a row. The rail runs between every item, including + card to card and composer to first item. +- **Sentences, not labels.** A row reads "Thibault marked Resolved", not + "Status changed · Thibault". The actor and the lifted value carry the only + emphasis. +- **Composer first, newest first.** On anything time-ordered the input sits + on top and the latest item is directly below it. During an incident you want + to know what just happened. +- **Content left, properties right.** Detail pages are a main column + (header, composer, timeline, postmortem) and an aside of label/value + properties. The aside is reference; it never competes with the timeline. A + linked entity is one row with its actions behind a menu, not a card with a + primary button. +- **Section title plus count.** `Activity 10`, `Updates 3`. The count is mono + and muted. +- **Spacing.** Lists `gap-4`, cards `px-4`, inside a row `gap-2.5`, stacked + compact rows pull up with a short rail. Pages cap at `max-w-6xl`. Padding + is symmetric unless the asymmetry is explained in a comment. +- **Empty states** use the dashed `EmptyStateContainer` with a title and one + sentence that says what to do next. Never a bare "No data". +- **Inline editing.** Title and summary are borderless inputs that show their + edge on hover and focus. Save on blur or explicit action; never on every + keystroke. +- **Hover affordance** is a dashed, muted underline (`decoration-dashed + decoration-muted-foreground/50 underline-offset-2`). Not a color change, not + a chevron, not a dot. + +## Color + +- Tokens only: `background`, `foreground`, `muted`, `muted-foreground`, + `border`, `ring`, `success`, `warning`, `info`, `destructive`. They are OKLCH in + `packages/ui/src/globals.css`. Never a raw palette class (`text-emerald-600`). +- Dark mode comes from the tokens. No `dark:` color overrides in components. + Images in content pages get a `.dark` sibling file. +- Status color sits on the smallest element that can carry it: a `StatusDot`, + the word in a sentence, the icon in a disc. Chrome stays neutral. +- Tinted chrome is one recipe: `border-{token}/20 bg-{token}/10 text-{token}`. + Inside a sentence use `StatusBadge plain` (dot and mono text, no border). + Bordered badges belong in cards and tables. +- Impact and status labels on the status page are colored text only. +- A new token goes into `registry.json` `cssVars` too, or it is undefined for + everyone who installs a block. +- Contrast: 4.5:1 for text, 3:1 for icons, focus rings and borders that + carry meaning. Muted text on a muted fill is the usual offender; check it in + both themes. + +## Typography + +- Sans for prose, labels and buttons. Mono for values: ids, counts, dates, + durations, statuses, anything a user might copy or compare. +- `tabular-nums` on any number that updates in place so columns do not jitter. +- No font sizes beyond the scale. Hierarchy comes from weight and color + before size: `font-medium text-foreground` for the lifted word, size only + for the page title. +- Relative time in the row (`2d ago`), absolute time with timezone in a hover + card. Both from `HoverCardTimestamp`; never format a date inline. +- Wrapped sentences are allowed. Icons top-align (`items-start`) so a two-line + row still reads. +- Sentence case everywhere. Brand is `openstatus`, lowercase, except at the + start of a sentence. Click paths use `>`: `Settings > Integrations`. + +## Radius + +The scale is proportional to the themed `--radius` (`xs` 0.2, `sm` 0.6, `md` +0.8, `lg` 1.0, `xl` 1.4). Prefer `rounded-lg`. Never hard-code a pixel radius. +`rounded-full` only wraps a glyph. The status page and the marketing site set +`--radius` to 0, so a radius in a demo is dead code. Details in +`packages/ui/AGENTS.md`. + +## Motion + +CSS transitions only. There is no animation library in this repo and none is +planned. + +- **Ask first whether it should move.** Something seen a hundred times a day + (command menu, keyboard shortcuts, list navigation) does not animate. + Hover and press get feedback, not motion. Modals, drawers and toasts get a + standard transition. Only rare moments may delight. +- **Durations.** Press feedback 100–160ms. Tooltips 125–200ms. Dropdowns and + selects 150–250ms. Modals and drawers 200–300ms. Nothing in the UI over + 300ms. +- **Easing.** `ease-out` for anything entering or leaving. `ease-in-out` for + movement on screen. `ease` for color and hover. Never `ease-in`. +- **Transition named properties**, never `transition-all`. Prefer + `transform` and `opacity`; they do not trigger layout. +- **Press feedback** on pressables we own (kit parts, blocks, custom): + `active:scale-[0.97]` with the press duration above, on press rather than + release. The stock `ui/button` stays untouched; add it through a wrapper + class, not by editing `ui/`. +- **Never enter from `scale(0)`.** Start at 0.95 or higher with opacity. +- **Popovers scale from their trigger** + (`origin-(--radix-popover-content-transform-origin)`). Modals stay centered. +- **Second tooltip opens instantly.** The delay guards the first hover only. +- **`motion-reduce:`** on every transition that moves or scales. Fades may + stay. +- `@starting-style` for enter animations when support allows, the + `data-mounted` pattern otherwise. No `useEffect` just to animate. + +## Interaction and accessibility + +- **Native elements.** A `button` acts, a link navigates. No `div` with + `role="button"`. Space and Enter both work on a button because it is one. +- **Every icon-only control has a label**: `aria-label` plus a tooltip that + shows the same text and the shortcut if there is one. Decorative glyphs + (`StatusDot`, rail icons) are `aria-hidden`. +- **Focus is visible.** Never remove the `focus-visible` ring; override it + with the token ring if a layout needs it. Keep focus inside overlays and + return it to the trigger on close. The shadcn primitives already do this; a + custom popover must too. +- **Overlays have a title.** Dialog, Sheet, Drawer always get a title; + `sr-only` when the design hides it. +- **Forms.** Every control has a connected label. Placeholder text is not a + label. Validation sets `aria-invalid` on the control and `data-invalid` on + the field. Errors read next to the field, not only in a toast. +- **Keyboard.** `⌘↵` submits a composer, `Escape` leaves it, a single letter + toggles a mode (`E` for preview). Shortcuts ignore key repeat, ignore + typing inside inputs, textareas and open overlays, and show in the tooltip. +- **Targets.** 24×24px minimum on desktop, 44×44px where touch is likely. + Pad the hit area, not the icon. +- **Loading.** `Skeleton` for layouts, `Spinner` with `disabled` on a button. + No `isLoading` prop on a primitive; compose it. +- **Destructive actions confirm** with a dialog that names the thing being + removed. The last item in a required list cannot be deleted; hide the + action rather than erroring. +- **Toasts** carry an error the user can act on. A failed background call is + never silent. + +## Responsive and mobile + +- Mobile first. Breakpoints follow the content, not devices. `sm:` for two + columns, `md:` for the full layout. A four-column grid steps through two. +- No horizontal page scroll at 320px. Tables overflow in their own scroller + (`overscroll-behavior: contain`); pages never do. +- `hover:` styles apply only where hover exists. Tailwind v4 compiles `hover:` + to `(hover: hover)`; do not reintroduce ungated hover with raw CSS. Touch + users get `:active` feedback instead. +- `touch-action: manipulation` on tappable elements removes the double-tap + delay. `-webkit-tap-highlight-color: transparent` globally, then every + tappable has its own `:active` state. +- Inputs are 16px on touch so iOS does not zoom. Never disable zoom. +- `100dvh` for app shells, drawers and bottom-pinned UI; `100svh` for heroes. + Fixed bars pad with `env(safe-area-inset-*)` and the viewport meta sets + `viewport-fit=cover`. +- Swap structure with `useIsMobile` only when CSS cannot: Dialog becomes + Drawer, a row of actions becomes a menu. Everything else is a breakpoint. +- Gate on capability (`(pointer: coarse)`, `(hover: hover)`), never on the + user agent. +- Test on a phone, not only in the emulator. Sticky hover, the keyboard and + safe areas do not reproduce. + +## HTML + +- Semantic first: `ol` for ordered timelines, `time` with `dateTime` for + every timestamp, `header`/`section`/`aside` where the page has those parts, + one `h1`, headings in order. +- Interactive inside interactive is a bug: no button in a link, no link in a + button. A card that is clickable has one link, overlaid, and the rest is + inert to the click. +- Images declare `width` and `height` or `fill`; no layout shift on load. +- `color-scheme: light dark` on the root; `theme-color` once per scheme. +- No manual `z-index` on overlays; the primitives own the stack. +- `inert` on background content while an overlay is open comes from the + primitive. Do not reimplement focus trapping. + +## Worst cases + +Before calling a view done, render it with: + +- a 255-character title, an email with no break opportunity, a one-letter + name, a name with emoji +- no avatar, no author (legacy rows), no description +- 0, 1 and 1,000 items; a count of 1 that must not say "1 updates" +- 320px wide, the widest layout, 200% zoom +- both themes + +Flex failures look like squished avatars (`shrink-0`), text that overflows +instead of wrapping (`min-w-0`), actions pushed off-screen, badges on two +lines, and a last row clipped mid-glyph. + +## Verify by looking + +An agent cannot judge rendering from a diff. For any visible change, +`scripts/screenshot.mjs` (the `screenshot` skill) shoots the element, not the +viewport, in both themes on the local dev server of the dashboard, the +marketing site or the status page, logging in with a seeded session where +needed. Selectors differ per app: `[data-slot=timeline]` and the other +dashboard slots, `main` or a section on the marketing site, the block slots +from `packages/ui/src/components/blocks/` on the status page. Compare against the previous state. Feedback +goes back the same way: a screenshot with the problem boxed and one sentence. +Marketing and docs pages render every component on `/kitchen-sink` so drift +is visible there first. diff --git a/apps/dashboard/AGENTS.md b/apps/dashboard/AGENTS.md index b5839e252..1e0aca814 100644 --- a/apps/dashboard/AGENTS.md +++ b/apps/dashboard/AGENTS.md @@ -1,11 +1,23 @@ # AGENTS.md — apps/dashboard -## Visual changes need a human +## Visual changes need a screenshot -An agent cannot verify rendering. If a change alters layout, styling or any -visible behaviour, say so and ask for confirmation rather than reporting it as -done. Prefer taking on work in `packages/services`, `packages/api` and the route -handlers, where `pnpm verify` and the test suites are real evidence. +A diff does not show rendering. If a change alters layout, styling or any +visible behaviour, screenshot it before reporting it done: + +```sh +node scripts/screenshot.mjs --app dashboard /incidents/1 --selector "[data-slot=timeline]" +``` + +It runs system Chrome (or Playwright's bundled Chromium where there is none) +against the local dev server, logs in +with a seeded session (`--user max@openstatus.dev` or +`thibault@openstatus.dev`), shoots light and dark, and prints the PNG paths. +Look at them. The `screenshot` skill has the flags, ports and fixtures; the +root `DESIGN.md` says what to judge against. Taste calls (spacing, hierarchy, +whether something should exist) still go to a human, with the screenshot +attached. `pnpm verify` and the test suites remain the evidence for everything +that is not visual. ## Runtimes @@ -31,3 +43,13 @@ Reuse the dashboard's own primitives — `TableCell*`, `ResultTable`, Persisted chat messages are validated on write, which is what makes the `asUIMessages` cast in `apps/dashboard/src/components/chat/use-chat-session.ts` safe. Keep casts of that kind in one named helper. + + + +# This is NOT the Next.js you know + +This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. + +This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean. + + diff --git a/apps/dashboard/package.json b/apps/dashboard/package.json index a3c5a88e5..030f4355a 100644 --- a/apps/dashboard/package.json +++ b/apps/dashboard/package.json @@ -3,7 +3,7 @@ "version": "1.0.0", "private": true, "scripts": { - "dev": "PORT=3001 next dev --turbopack", + "dev": "PORT=${PORT:-3001} next dev --turbopack", "build": "next build", "start": "next start", "lint": "next lint", diff --git a/apps/status-page/AGENTS.md b/apps/status-page/AGENTS.md index 75e975d15..6ca14ba3d 100644 --- a/apps/status-page/AGENTS.md +++ b/apps/status-page/AGENTS.md @@ -58,6 +58,12 @@ no `page` row ends up. The proxy rewrites those to a 404 (`resolveUnresolvedHostAction`) so an unknown slug or a custom domain missing from the DB never answers with the explorer or its OG image. Only `themes.openstatus.dev` is indexable — see `lib/theme-explorer-host.ts`. +## Screenshots + +For any visible change, shoot it before reporting it done: +`node scripts/screenshot.mjs --app status-page /acme` (in dev the slug is the +first path segment; the `screenshot` skill has the flags). Judge against the +root `DESIGN.md`. diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index 7d0b8adcb..10fd133d2 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -59,3 +59,19 @@ component once so drift is visible. - Every capitalised tag must be registered in `mdx-components/index.tsx`. - No new colours beyond tokens, no font sizes beyond the prose scale, no radius. Dark mode comes from tokens only; images get a `.dark` sibling. + +## Screenshots + +For any visible change, shoot it before reporting it done: +`node scripts/screenshot.mjs --app web /pricing` (the `screenshot` skill has the +flags). Judge against the root `DESIGN.md`. + + + +# This is NOT the Next.js you know + +This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. + +This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean. + + diff --git a/packages/db/src/seed.mts b/packages/db/src/seed.mts index 4a17e08de..82e5a25cc 100644 --- a/packages/db/src/seed.mts +++ b/packages/db/src/seed.mts @@ -17,6 +17,7 @@ import { pageComponent, privateLocation, privateLocationToMonitors, + session, statusReport, statusReportUpdate, statusReportsToPageComponents, @@ -209,6 +210,55 @@ async function main() { .onConflictDoNothing() .run(); + // The two maintainers, with sessions that outlive any local database, so + // the dashboard and scripts/screenshot.mjs log in without a magic link. Tokens are fixed on purpose: this seed only runs against + // localhost. + await db + .insert(user) + .values([ + { + id: 2, + tenantId: "2", + name: "Maximilian Kaske", + firstName: "Maximilian", + lastName: "Kaske", + email: "max@openstatus.dev", + emailVerified: new Date(), + photoUrl: "https://github.com/mxkaske.png", + }, + { + id: 3, + tenantId: "3", + name: "Thibault Le Ouay Ducasse", + firstName: "Thibault", + lastName: "Le Ouay Ducasse", + email: "thibault@openstatus.dev", + emailVerified: new Date(), + photoUrl: "https://github.com/thibaultleouay.png", + }, + ]) + .onConflictDoNothing() + .run(); + await db + .insert(usersToWorkspaces) + .values([ + { workspaceId: 1, userId: 2, role: "owner" }, + { workspaceId: 1, userId: 3, role: "admin" }, + { workspaceId: 2, userId: 2, role: "owner" }, + { workspaceId: 3, userId: 3, role: "owner" }, + ]) + .onConflictDoNothing() + .run(); + const farFuture = new Date("2099-01-01T00:00:00Z"); + await db + .insert(session) + .values([ + { sessionToken: "seed-session-max", userId: 2, expires: farFuture }, + { sessionToken: "seed-session-thibault", userId: 3, expires: farFuture }, + ]) + .onConflictDoNothing() + .run(); + // Page Components - representing monitors on the status page await db .insert(pageComponent) @@ -507,8 +557,8 @@ async function main() { severity: "major", status: "mitigated", summary: "Increased 5xx responses on the public API.", - commanderId: 1, - declaredBy: 1, + commanderId: 2, + declaredBy: 3, declaredAt: twoHoursAgo, startedAt: new Date(twoHoursAgo.getTime() - 10 * 60 * 1000), mitigatedAt: new Date(twoHoursAgo.getTime() + 45 * 60 * 1000), @@ -516,29 +566,72 @@ async function main() { }) .onConflictDoNothing() .run(); + // Messages follow the service formats so the timeline parses them into + // sentences; one row of every kind the incident page renders. + const minutesAfterDeclare = (m: number) => + new Date(twoHoursAgo.getTime() + m * 60 * 1000); await db .insert(incidentEvent) .values([ { incidentId: 1, type: "declared", - message: "Incident declared", - createdBy: 1, + message: "Declared as major: Elevated API error rates", + createdBy: 3, createdAt: twoHoursAgo, }, + { + incidentId: 1, + type: "slack_channel_bound", + message: "Slack channel <#C0C7Y4CG6F2> bound", + createdBy: null, + createdAt: minutesAfterDeclare(1), + }, + { + incidentId: 1, + type: "status_report_linked", + message: "Linked status report #2", + createdBy: 3, + createdAt: minutesAfterDeclare(2), + }, { incidentId: 1, type: "note", - message: "Rolling back the latest API deploy.", - createdBy: 1, - createdAt: new Date(twoHoursAgo.getTime() + 20 * 60 * 1000), + message: + "Rolling back the latest API deploy, 5xx started right after it went out.\n\n[From Slack](https://openstatus.slack.com/archives/C0C7Y4CG6F2/p1700000000000100)", + createdBy: 2, + createdAt: minutesAfterDeclare(12), + }, + { + incidentId: 1, + type: "commander_changed", + message: "Commander set to Maximilian Kaske", + createdBy: 3, + createdAt: minutesAfterDeclare(15), + }, + { + incidentId: 1, + type: "status_changed", + message: + "Status changed from open to mitigated\n\nRollback done, error rate back to baseline.", + createdBy: 2, + createdAt: minutesAfterDeclare(45), + }, + { + incidentId: 1, + type: "note", + message: + "Baseline for 30 minutes now. Keeping the incident open until p99 latency recovers too.", + createdBy: 2, + createdAt: minutesAfterDeclare(75), }, + // Unbound again so the timeline and the incident's (empty) Slack binding agree. { incidentId: 1, - type: "mitigated", - message: "Rollback done, error rate back to baseline.", - createdBy: 1, - createdAt: new Date(twoHoursAgo.getTime() + 45 * 60 * 1000), + type: "slack_channel_unbound", + message: "Slack channel <#C0C7Y4CG6F2> unbound", + createdBy: null, + createdAt: minutesAfterDeclare(80), }, ]) .run(); diff --git a/scripts/screenshot.mjs b/scripts/screenshot.mjs new file mode 100644 index 000000000..451a97a0d --- /dev/null +++ b/scripts/screenshot.mjs @@ -0,0 +1,260 @@ +#!/usr/bin/env node +// Screenshot pages of a local Next.js dev server, in light and dark. +// +// node scripts/screenshot.mjs --app dashboard /incidents/1 --selector "[data-slot=timeline]" +// node scripts/screenshot.mjs --app web /pricing --full-page +// node scripts/screenshot.mjs --app status-page /acme +// +// Flags: --app dashboard|web|status-page (default dashboard), --base , +// --selector , --theme both|light|dark, --out , --width , +// --full-page, --user , --workspace , --token , +// --db , --login --log . +// +// The dashboard needs a login. In order: --token, a live row in the `session` +// table (the seed creates seed-session-max and seed-session-thibault; narrow +// with --user), a saved storage state, or --login, which submits the email +// form and follows the `>>> Magic Link:` line the dev server prints to --log. +// Playwright is borrowed from apps/screenshot-service so the version follows +// that package; the browser is the system Chrome, or Playwright's bundled +// Chromium where there is none. + +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const repo = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const { chromium } = createRequire( + join(repo, "apps/screenshot-service/package.json"), +)("playwright"); + +const APPS = { + dashboard: { base: "http://localhost:3001", auth: true, probe: "/login" }, + web: { base: "http://localhost:3000", auth: false }, + // In dev the page slug is the first path segment: /acme, not acme.localhost. + "status-page": { base: "http://localhost:3000", auth: false }, +}; + +const BOOLEAN_FLAGS = new Set(["full-page"]); +const args = process.argv.slice(2); +const flags = {}; +const paths = []; +for (let i = 0; i < args.length; i++) { + const a = args[i]; + if (a.startsWith("--")) { + const key = a.slice(2); + const next = args[i + 1]; + if (BOOLEAN_FLAGS.has(key) || next === undefined || next.startsWith("--")) + flags[key] = true; + else flags[key] = args[++i]; + } else paths.push(a); +} +const app = APPS[flags.app ?? "dashboard"]; +if (!app || paths.length === 0) { + console.error( + "usage: screenshot.mjs --app dashboard|web|status-page [...] [--selector css] [--theme both|light|dark]", + ); + process.exit(2); +} + +const base = (flags.base ?? app.base).replace(/\/$/, ""); +const db = flags.db ?? "http://127.0.0.1:8080"; +const out = resolve(flags.out ?? ".screenshots"); +const themes = + flags.theme === "light" || flags.theme === "dark" + ? [flags.theme] + : ["light", "dark"]; +const width = Number(flags.width ?? 1400); +const stateFile = resolve(flags.state ?? join(out, "state.json")); +const wantsAuth = app.auth || Boolean(flags.token || flags.login); +mkdirSync(out, { recursive: true }); + +async function sql(statements) { + const res = await fetch(db, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ statements }), + }); + if (!res.ok) throw new Error(`sqld ${res.status} at ${db}`); + const body = await res.json(); + return body.map((r) => { + if (r.error) throw new Error(r.error.message); + const { columns, rows } = r.results; + return rows.map((row) => + Object.fromEntries(columns.map((c, i) => [c, row[i]])), + ); + }); +} + +// Session rows carry user_id only; the workspace cookie needs a slug the user +// belongs to, so both come from the same lookup. +async function sessionCookies() { + const where = flags.user ? "and u.email = ?" : ""; + const params = flags.user ? [flags.user] : []; + const [rows] = await sql([ + { + q: `select s.session_token as token, u.id as user_id, u.email as email + from session s join user u on u.id = s.user_id + where s.expires > unixepoch() * 1000 ${where} + order by s.expires desc limit 1`, + params, + }, + ]); + if (rows.length === 0) return null; + const { token, user_id, email } = rows[0]; + let slug = flags.workspace; + if (!slug) { + const [ws] = await sql([ + { + q: `select w.slug as slug from users_to_workspaces m join workspace w on w.id = m.workspace_id + where m.user_id = ? order by m.workspace_id limit 1`, + params: [user_id], + }, + ]); + slug = ws[0]?.slug; + } + console.error(`auth: session of ${email}${slug ? ` in ${slug}` : ""}`); + return cookies(token, slug); +} + +function cookies(token, slug) { + const host = new URL(base).hostname; + const list = [ + { name: "authjs.session-token", value: token, domain: host, path: "/" }, + ]; + if (slug) + list.push({ name: "workspace-slug", value: slug, domain: host, path: "/" }); + return list; +} + +async function magicLinkLogin(context) { + if (!flags.log) throw new Error("--login needs --log "); + const page = await context.newPage(); + await page.goto(`${base}/login`); + // The form opens closed; the email input appears after the mode button. + const input = page.locator('input[name="email"]'); + if (!(await input.isVisible())) + await page.getByRole("button", { name: "Continue with email" }).click(); + await input.fill(flags.login); + const seen = readFileSync(flags.log, "utf8").length; + await input.press("Enter"); + let url; + for (let i = 0; i < 40 && !url; i++) { + await page.waitForTimeout(500); + url = readFileSync(flags.log, "utf8") + .slice(seen) + .match(/Magic Link: (http\S+)/)?.[1]; + } + if (!url) throw new Error("no `>>> Magic Link:` line appeared in the log"); + await page.goto(url, { waitUntil: "networkidle" }); + await page.close(); + await context.storageState({ path: stateFile }); + console.error( + `auth: magic link for ${flags.login}, state saved to ${stateFile}`, + ); +} + +// apps/web and the dashboard both default to :3001 on this machine; the +// dashboard's /login is a form, everything else answers 404 there. +const probe = await fetch(base + (app.probe ?? paths[0])).catch(() => null); +if (!probe || probe.status === 404 || probe.status >= 500) { + console.error( + `nothing usable at ${base}${app.probe ?? paths[0]} (${probe?.status ?? "unreachable"}); start the ${flags.app ?? "dashboard"} dev server or pass --base`, + ); + process.exit(1); +} + +// System Chrome locally; a remote VM has none, so fall back to Playwright's +// bundled Chromium (`cd apps/screenshot-service && npx playwright install chromium`). +const browser = await chromium + .launch({ channel: "chrome" }) + .catch(async (e) => { + console.error( + `chrome: ${e.message.split("\n")[0]}; trying bundled chromium`, + ); + return chromium.launch().catch((e2) => { + console.error( + `chromium: ${e2.message.split("\n")[0]}\nrun: cd apps/screenshot-service && npx playwright install chromium`, + ); + process.exit(1); + }); + }); +let auth = null; +if (flags.token) auth = cookies(flags.token, flags.workspace); +else if (wantsAuth && !flags.login) + auth = await sessionCookies().catch( + (e) => (console.error(`auth: ${e.message}`), null), + ); +// One login for all themes: the dashboard rate-limits magic-link emails. +if (flags.login) { + const context = await browser.newContext(); + await magicLinkLogin(context); + await context.close(); +} +const useState = wantsAuth && !auth && existsSync(stateFile); +if (wantsAuth && !auth && !useState) { + console.error( + "auth: no session found; seed the database, pass --token, or --login --log ", + ); +} + +const written = []; +process.on("uncaughtException", async (e) => { + console.error(e.message); + await browser.close().catch(() => {}); + process.exit(1); +}); +for (const theme of themes) { + const context = await browser.newContext({ + viewport: { width, height: 1000 }, + deviceScaleFactor: 2, + colorScheme: theme, + ...(useState ? { storageState: stateFile } : {}), + }); + if (auth) await context.addCookies(auth); + // Every app uses next-themes with the default storage key. + await context.addInitScript((t) => localStorage.setItem("theme", t), theme); + + const page = await context.newPage(); + for (const path of paths) { + await page.goto(base + path, { waitUntil: "networkidle" }); + // Only the dashboard has a login page, so landing there means auth + // failed or --base points at the dashboard for another app. + if (page.url().includes("/login")) + throw new Error( + app.auth + ? `redirected to login for ${path}; auth failed` + : `${base} serves the dashboard, not ${flags.app}; pass --base`, + ); + const name = + path.replace(/^\/+/, "").replace(/[^a-z0-9]+/gi, "-") || "root"; + if (flags.selector) { + const all = page.locator(flags.selector); + const n = await all.count(); + let k = 0; + for (let i = 0; i < n; i++) { + const el = all.nth(i); + if (!(await el.isVisible())) continue; + await el.scrollIntoViewIfNeeded(); + const file = join(out, `${name}-${theme}${n > 1 ? `-${k}` : ""}.png`); + await el.screenshot({ path: file }); + written.push(file); + k++; + } + if (k === 0) { + console.error(`no visible match for ${flags.selector} on ${path}`); + process.exitCode = 1; + } + } else { + const file = join(out, `${name}-${theme}.png`); + await page.screenshot({ + path: file, + fullPage: Boolean(flags["full-page"]), + }); + written.push(file); + } + } + await context.close(); +} +await browser.close(); +for (const f of written) console.log(f);