diff --git a/packages/api/src/router/stripe/index.ts b/packages/api/src/router/stripe/index.ts index e9c34e430..c09b23b19 100644 --- a/packages/api/src/router/stripe/index.ts +++ b/packages/api/src/router/stripe/index.ts @@ -28,6 +28,7 @@ import { z } from "zod"; import { createTRPCRouter, protectedProcedure } from "../../trpc"; import { buildFromSubscriptionOrThrow, + canAutomateTax, getCurrentPeriodEnd, getCurrentSubscription, hasPaymentMethod, @@ -104,6 +105,9 @@ async function createPaymentMethodSetupSession(args: { mode: "setup", payment_method_types: ["card"], customer: args.customer, + // The address lets Stripe Tax place the customer once the trial converts. + billing_address_collection: "required", + customer_update: { name: "auto", address: "auto" }, setup_intent_data: { metadata: { subscriptionId: args.subscriptionId } }, success_url: args.successUrl, cancel_url: args.cancelUrl, @@ -262,6 +266,9 @@ export const stripeRouter = createTRPCRouter({ items, proration_behavior: "create_prorations", cancel_at_period_end: false, + ...((await canAutomateTax(stripeId)) && { + automatic_tax: { enabled: true }, + }), ...(isTrialing && { trial_end: "now", payment_behavior: "error_if_incomplete", @@ -305,6 +312,8 @@ export const stripeRouter = createTRPCRouter({ name: "auto", address: "auto", }, + billing_address_collection: "required", + automatic_tax: { enabled: true }, line_items: [ { price: priceId, diff --git a/packages/api/src/router/stripe/shared.ts b/packages/api/src/router/stripe/shared.ts index fe325152e..e6ccf88bf 100644 --- a/packages/api/src/router/stripe/shared.ts +++ b/packages/api/src/router/stripe/shared.ts @@ -194,6 +194,18 @@ export async function hasPaymentMethod(subscription: Stripe.Subscription) { ); } +// Stripe rejects automatic tax on a subscription whose customer it cannot +// place (no address yet, e.g. a card-less trial), so only opt in once it can. +// `not_collecting` is a valid location where we are not registered: no tax. +export async function canAutomateTax(customerId: string) { + const customer = await stripe.customers.retrieve(customerId, { + expand: ["tax"], + }); + if (customer.deleted) return false; + const status = customer.tax?.automatic_tax; + return status === "supported" || status === "not_collecting"; +} + export function trialEndsAtOf(subscription: Stripe.Subscription) { return subscription.status === "trialing" && subscription.trial_end ? new Date(subscription.trial_end * 1000) diff --git a/packages/api/src/router/stripe/trial-lifecycle.test.ts b/packages/api/src/router/stripe/trial-lifecycle.test.ts index e919d2fbf..f5a9b82b5 100644 --- a/packages/api/src/router/stripe/trial-lifecycle.test.ts +++ b/packages/api/src/router/stripe/trial-lifecycle.test.ts @@ -454,6 +454,68 @@ describe("trial lifecycle", () => { ]); }); + function stubSetup() { + stubs.push( + stub(stripe.setupIntents, "retrieve", () => + Promise.resolve({ + payment_method: "pm_new", + metadata: { subscriptionId: "sub_setup" }, + } as unknown as Stripe.Response), + ), + stub(stripe.subscriptions, "retrieve", () => + Promise.resolve( + subscription("cus_setup", { + id: "sub_setup", + }) as Stripe.Response, + ), + ), + stub(stripe.customers, "update", () => + Promise.resolve({} as Stripe.Response), + ), + ); + } + + const setupCompleted = () => + event("checkout.session.completed", { + mode: "setup", + customer: "cus_setup", + setup_intent: "seti_1", + } as Stripe.Checkout.Session); + + test("setup checkout completed → automatic tax on after the card", async () => { + stubSetup(); + + await caller().sessionCompleted(setupCompleted()); + + expect(updateSubscription.calls.map((c) => c.args)).toEqual([ + ["sub_setup", { default_payment_method: "pm_new" }], + ["sub_setup", { automatic_tax: { enabled: true } }], + ]); + }); + + test("Stripe rejecting the tax location still keeps the card", async () => { + stubSetup(); + stubs = stubs.filter((s) => s !== updateSubscription); + updateSubscription.restore(); + const update = stub( + stripe.subscriptions, + "update", + (_id: string, params?: Stripe.SubscriptionUpdateParams) => + params?.automatic_tax + ? Promise.reject(new Error("customer_tax_location_invalid")) + : Promise.resolve({} as Stripe.Response), + ); + stubs.push(update); + + await caller().sessionCompleted(setupCompleted()); + + expect(update.calls[0]?.args).toEqual([ + "sub_setup", + { default_payment_method: "pm_new" }, + ]); + assertSpyCalls(update, 2); + }); + test("trialing → active clears trialEndsAt", async () => { const s = await seedTrial(); const sub = subscription(s.stripeId, { status: "active" }); diff --git a/packages/api/src/router/stripe/webhook.ts b/packages/api/src/router/stripe/webhook.ts index 7ffe3b095..486f39716 100644 --- a/packages/api/src/router/stripe/webhook.ts +++ b/packages/api/src/router/stripe/webhook.ts @@ -224,6 +224,22 @@ async function attachSetupPaymentMethod(session: Stripe.Checkout.Session) { await stripe.subscriptions.update(subscriptionId, { default_payment_method: paymentMethod, }); + + // The card now carries the billing address the setup session required, and + // Stripe Tax falls back to it. Just try: Stripe rejects a location it cannot + // place, and that must not undo the card we already attached. + if (!subscription.automatic_tax?.enabled) { + try { + await stripe.subscriptions.update(subscriptionId, { + automatic_tax: { enabled: true }, + }); + } catch (err) { + console.error( + `Failed to enable automatic tax on ${subscriptionId}:`, + err, + ); + } + } return subscription; } -- 2.51.2 From 32527be753c192206efed04729dc2d7accb515de Mon Sep 17 00:00:00 2001 From: Thibault Le Ouay Date: Mon, 12 Oct 2026 17:44:12 +0200 Subject: [PATCH 2/6] invitation: lowercase email (#2896) --- .../invitation/__tests__/invitation.test.ts | 45 +++++++++++++++++++ packages/services/src/invitation/accept.ts | 5 ++- packages/services/src/invitation/list.ts | 5 ++- packages/services/src/invitation/schemas.ts | 12 +++-- 4 files changed, 60 insertions(+), 7 deletions(-) diff --git a/packages/services/src/invitation/__tests__/invitation.test.ts b/packages/services/src/invitation/__tests__/invitation.test.ts index 02127565a..8dcbe71a4 100644 --- a/packages/services/src/invitation/__tests__/invitation.test.ts +++ b/packages/services/src/invitation/__tests__/invitation.test.ts @@ -74,6 +74,18 @@ describe("createInvitation", () => { }); }); + test("stores the email trimmed and lowercased", async () => { + await withTestTransaction(async (tx) => { + const email = `${TEST_PREFIX}-case-${Date.now()}@example.com`; + const row = await createInvitation({ + ctx: { ...teamCtx, db: tx }, + input: { email: ` ${email.toUpperCase()} ` }, + }); + + expect(row.email).toBe(email); + }); + }); + test("rejects read-only actor", async () => { await withTestTransaction(async (tx) => { const readOnlyCtx = { @@ -146,6 +158,39 @@ describe("getInvitationByToken", () => { }); }); + test("matches a legacy mixed-case invitation case-insensitively", async () => { + await withTestTransaction(async (tx) => { + const ctx = { ...teamCtx, db: tx }; + const email = `${TEST_PREFIX}-legacy-${Date.now()}@example.com`; + const token = crypto.randomUUID(); + const legacy = await tx + .insert(invitation) + .values({ + email: email.toUpperCase(), + workspaceId: teamCtx.workspace.id, + token, + expiresAt: new Date(Date.now() + 60_000), + }) + .returning() + .get(); + + const row = await getInvitationByToken({ + ctx, + input: { token, email }, + }); + expect(row.id).toBe(legacy.id); + + const workspaceRow = await acceptInvitation({ + ctx: { + ...makeUserCtx(teamCtx.workspace, { userId: acceptingUserId }), + db: tx, + }, + input: { id: legacy.id, email }, + }); + expect(workspaceRow.id).toBe(teamCtx.workspace.id); + }); + }); + test("rejects a valid token for the wrong email", async () => { await withTestTransaction(async (tx) => { const ctx = { ...teamCtx, db: tx }; diff --git a/packages/services/src/invitation/accept.ts b/packages/services/src/invitation/accept.ts index d8f7c0aad..ea7e4c158 100644 --- a/packages/services/src/invitation/accept.ts +++ b/packages/services/src/invitation/accept.ts @@ -1,4 +1,4 @@ -import { and, eq, gte, isNull } from "@openstatus/db"; +import { and, eq, gte, isNull, sql } from "@openstatus/db"; import { invitation, selectWorkspaceSchema, @@ -58,7 +58,8 @@ export async function acceptInvitation(args: { const existing = await tx.query.invitation.findFirst({ where: and( eq(invitation.id, input.id), - eq(invitation.email, input.email), + // Rows created before emails were normalized keep their original casing. + sql`lower(${invitation.email}) = ${input.email}`, isNull(invitation.acceptedAt), gte(invitation.expiresAt, new Date()), ), diff --git a/packages/services/src/invitation/list.ts b/packages/services/src/invitation/list.ts index ae607b670..3c1ed2514 100644 --- a/packages/services/src/invitation/list.ts +++ b/packages/services/src/invitation/list.ts @@ -1,4 +1,4 @@ -import { and, db as defaultDb, eq, gte, isNull } from "@openstatus/db"; +import { and, db as defaultDb, eq, gte, isNull, sql } from "@openstatus/db"; import { invitation, selectInvitationSchema, @@ -59,7 +59,8 @@ export async function getInvitationByToken(args: { eq(invitation.token, input.token), isNull(invitation.acceptedAt), gte(invitation.expiresAt, new Date()), - eq(invitation.email, input.email), + // Rows created before emails were normalized keep their original casing. + sql`lower(${invitation.email}) = ${input.email}`, ), with: { workspace: true }, }); diff --git a/packages/services/src/invitation/schemas.ts b/packages/services/src/invitation/schemas.ts index 85dac2ef0..bd163ebcc 100644 --- a/packages/services/src/invitation/schemas.ts +++ b/packages/services/src/invitation/schemas.ts @@ -1,7 +1,13 @@ import { z } from "zod"; +/** + * Invitation emails are stored and compared lowercase. Trim + lowercase run + * before the format check so `" Foo@Bar.com "` normalizes instead of failing. + */ +const InvitationEmail = z.string().trim().toLowerCase().pipe(z.email()); + export const CreateInvitationInput = z.object({ - email: z.email(), + email: InvitationEmail, }); export type CreateInvitationInput = z.infer; @@ -13,7 +19,7 @@ export type ListInvitationsInput = z.infer; export const GetInvitationByTokenInput = z.object({ token: z.string().min(1), - email: z.email(), + email: InvitationEmail, }); export type GetInvitationByTokenInput = z.infer< typeof GetInvitationByTokenInput @@ -21,6 +27,6 @@ export type GetInvitationByTokenInput = z.infer< export const AcceptInvitationInput = z.object({ id: z.number().int(), - email: z.email(), + email: InvitationEmail, }); export type AcceptInvitationInput = z.infer; -- 2.51.2 From aa7b8e2ff0f30a1f67d3ad03f4327fec1dd4bcb1 Mon Sep 17 00:00:00 2001 From: Maximilian Kaske <56969857+mxkaske@users.noreply.github.com> Date: Tue, 13 Oct 2026 23:03:01 +0200 Subject: [PATCH 3/6] chore: design doc, screenshot script, seeded sessions and repo skills (#2901) * docs: add DESIGN.md with the UI conventions and principles Hierarchy, compound kits, cva variants, tokens, typography, motion, a11y, responsive and worst-case rules in one place; AGENTS.md says where code lives, this says what good looks like. Root AGENTS.md points at it. * chore: ship repo skills for cloud sessions Skills live as real directories in .agents/skills with symlinks in .claude/skills, the only path Claude Code reads. Both stay gitignored by default; the ones re-included by name ship with the repo so remote and teammate sessions have them: screenshot, grill-me, codebase-design, improve-codebase-architecture. Sources and licenses are listed in .agents/skills/README.md. * chore: screenshot script for the local dev servers scripts/screenshot.mjs shoots a page or element of the dashboard, web or status-page dev server in light and dark, logging into the dashboard with a seeded session (or a magic link read from the dev log). It borrows Playwright from apps/screenshot-service, uses system Chrome with a bundled-Chromium fallback, and refuses a base that serves the wrong app. The dashboard AGENTS.md now asks for a screenshot instead of a human for visible changes; web and status-page get the same pointer. The Next.js agent-rules block is committed in every app so next dev stops re-adding it. * chore(dashboard): let PORT override the dev port PORT=3001 in the dev script beat the environment, so a second instance needed next dev -p. The default stays 3001. * chore(db): seed the maintainers with sessions and a full incident timeline max@openstatus.dev and thibault@openstatus.dev with workspace roles and sessions valid for a year (fixed tokens, local only), so the dashboard and scripts/screenshot.mjs log in without a magic link. Incident 1 now carries seven events in the service message formats, one of every row kind the timeline renders. * chore(skills): say how screenshots reach the user from local and cloud sessions * chore: address review findings on the screenshot script, seed and docs screenshot.mjs: open the email form before filling it, log in once for all themes (the dashboard rate-limits magic links), treat --full-page as a valueless flag, fail on a login redirect for every app, exit non-zero when a selector matches nothing, print one line on an uncaught error. seed: sessions expire in 2099 instead of a year, the stale script path in the comment, and a slack_channel_unbound event so the timeline and the incident's empty Slack binding agree. DESIGN.md: stock primitives may be edited as a documented last resort, blocks import nothing from an app (apps import blocks), ring joins the token list, selectors are named per app. Drop improve-codebase-architecture from the shipped skills: it invokes /grilling and /domain-modeling, which a clone does not have, and proposes ADRs, which this repo forbids. README: the screenshot skill is AGPL-3.0 like the repo, and only self-contained skills ship. --- .agents/skills/README.md | 24 ++ .agents/skills/codebase-design/DEEPENING.md | 37 +++ .../skills/codebase-design/DESIGN-IT-TWICE.md | 44 +++ .agents/skills/codebase-design/SKILL.md | 114 +++++++ .agents/skills/grill-me/SKILL.md | 8 + .agents/skills/grill-me/plan-readonly-mcp.md | 54 ++++ .agents/skills/screenshot/SKILL.md | 111 +++++++ .gitignore | 12 +- AGENTS.md | 1 + DESIGN.md | 283 ++++++++++++++++++ apps/dashboard/AGENTS.md | 32 +- apps/dashboard/package.json | 2 +- apps/status-page/AGENTS.md | 6 + apps/web/AGENTS.md | 16 + packages/db/src/seed.mts | 115 ++++++- scripts/screenshot.mjs | 260 ++++++++++++++++ 16 files changed, 1100 insertions(+), 19 deletions(-) create mode 100644 .agents/skills/README.md create mode 100644 .agents/skills/codebase-design/DEEPENING.md create mode 100644 .agents/skills/codebase-design/DESIGN-IT-TWICE.md create mode 100644 .agents/skills/codebase-design/SKILL.md create mode 100644 .agents/skills/grill-me/SKILL.md create mode 100644 .agents/skills/grill-me/plan-readonly-mcp.md create mode 100644 .agents/skills/screenshot/SKILL.md create mode 100644 DESIGN.md create mode 100644 scripts/screenshot.mjs 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); -- 2.51.2 From 03a965ca50a3db443be3ee8e20a7cccfd406163c Mon Sep 17 00:00:00 2001 From: Maximilian Kaske Date: Tue, 13 Oct 2026 23:06:24 +0200 Subject: [PATCH 4/6] chore: second review pass on the screenshot script - login guard: exact /login path, dashboard only, and not when /login itself is requested, so status-page password pages and the login screen can be shot - explicit --user or --token never fall back to a saved state; the chosen auth source is logged; --login is skipped once auth is resolved - deterministic session and workspace pick (user_id, created_at tiebreakers) - the non-dashboard probe detects a dashboard on --base up front - --width is validated; the header points at the skill instead of repeating it - turbo passes PORT through, so pnpm dev:dashboard honours it too; the skill says to use the --filter form when DATABASE_URL must differ - seed comment back to two lines --- .agents/skills/screenshot/SKILL.md | 5 ++- packages/db/src/seed.mts | 5 +-- scripts/screenshot.mjs | 65 +++++++++++++++++------------- turbo.json | 4 +- 4 files changed, 46 insertions(+), 33 deletions(-) diff --git a/.agents/skills/screenshot/SKILL.md b/.agents/skills/screenshot/SKILL.md index 90e57a416..823af0400 100644 --- a/.agents/skills/screenshot/SKILL.md +++ b/.agents/skills/screenshot/SKILL.md @@ -28,7 +28,10 @@ It prints the PNG paths. Read them with the Read tool and judge against `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`. + `PORT=3002 pnpm --filter @openstatus/dashboard dev`. Use that direct form + whenever you also need a different `DATABASE_URL`: the root `pnpm -w + dev:dashboard` runs through turbo, which passes `PORT` through but drops + other variables, so the app reads its `.env` database. 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 diff --git a/packages/db/src/seed.mts b/packages/db/src/seed.mts index 82e5a25cc..c8a1644aa 100644 --- a/packages/db/src/seed.mts +++ b/packages/db/src/seed.mts @@ -210,9 +210,8 @@ 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. + // Fixed tokens so the dashboard and scripts/screenshot.mjs log in without a + // magic link; main() refuses non-local databases. await db .insert(user) .values([ diff --git a/scripts/screenshot.mjs b/scripts/screenshot.mjs index 451a97a0d..eb97fa41b 100644 --- a/scripts/screenshot.mjs +++ b/scripts/screenshot.mjs @@ -5,18 +5,7 @@ // 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. +// Flags, auth order and fixtures: .agents/skills/screenshot/SKILL.md. import { existsSync, mkdirSync, readFileSync } from "node:fs"; import { createRequire } from "node:module"; @@ -65,6 +54,10 @@ const themes = ? [flags.theme] : ["light", "dark"]; const width = Number(flags.width ?? 1400); +if (!Number.isFinite(width) || width <= 0) { + console.error(`--width must be a positive number, got ${flags.width}`); + process.exit(2); +} const stateFile = resolve(flags.state ?? join(out, "state.json")); const wantsAuth = app.auth || Boolean(flags.token || flags.login); mkdirSync(out, { recursive: true }); @@ -96,7 +89,7 @@ async function sessionCookies() { 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`, + order by s.expires desc, s.user_id limit 1`, params, }, ]); @@ -107,7 +100,7 @@ async function sessionCookies() { 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`, + where m.user_id = ? order by m.created_at, m.workspace_id limit 1`, params: [user_id], }, ]); @@ -154,8 +147,8 @@ async function magicLinkLogin(context) { ); } -// apps/web and the dashboard both default to :3001 on this machine; the -// dashboard's /login is a form, everything else answers 404 there. +// Three apps, two default ports, and on this machine any of them may sit on +// :3001. Only the dashboard serves a form at /login; use that to tell them apart. const probe = await fetch(base + (app.probe ?? paths[0])).catch(() => null); if (!probe || probe.status === 404 || probe.status >= 500) { console.error( @@ -163,6 +156,17 @@ if (!probe || probe.status === 404 || probe.status >= 500) { ); process.exit(1); } +if (!app.auth) { + const login = await fetch(`${base}/login`, { redirect: "manual" }).catch( + () => null, + ); + if (login?.status === 200) { + console.error( + `${base} serves the dashboard, not ${flags.app}; 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`). @@ -180,18 +184,25 @@ const browser = await chromium }); }); let auth = null; -if (flags.token) auth = cookies(flags.token, flags.workspace); -else if (wantsAuth && !flags.login) +if (flags.token) { + auth = cookies(flags.token, flags.workspace); + console.error("auth: --token"); +} 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) { +if (flags.login && !auth) { const context = await browser.newContext(); await magicLinkLogin(context); await context.close(); } -const useState = wantsAuth && !auth && existsSync(stateFile); +// A saved state is only a fallback; an explicit identity must not silently +// become whoever logged in last. +const useState = + wantsAuth && !auth && !flags.user && !flags.token && existsSync(stateFile); +if (useState) console.error(`auth: saved state ${stateFile}`); if (wantsAuth && !auth && !useState) { console.error( "auth: no session found; seed the database, pass --token, or --login --log ", @@ -218,14 +229,12 @@ for (const theme of themes) { 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`, - ); + if ( + app.auth && + new URL(page.url()).pathname === "/login" && + !path.startsWith("/login") + ) + throw new Error(`redirected to login for ${path}; auth failed`); const name = path.replace(/^\/+/, "").replace(/[^a-z0-9]+/gi, "-") || "root"; if (flags.selector) { diff --git a/turbo.json b/turbo.json index 72795002b..b3cd23ec2 100644 --- a/turbo.json +++ b/turbo.json @@ -4,7 +4,9 @@ // Vercel disables corepack unless it can confirm turbo >= 2.1.3 or sees this // passthrough; without corepack it falls back to pnpm 9, which can't read // `overrides` from pnpm-workspace.yaml and fails the frozen install. - "globalPassThroughEnv": ["COREPACK_HOME"], + // PORT: strict env mode would strip it, and `pnpm dev:dashboard` could never + // move off :3001. + "globalPassThroughEnv": ["COREPACK_HOME", "PORT"], "tasks": { "registry:build": { "outputs": ["public/r/**"] -- 2.51.2 From d23190af9c57983c3da3c659dd96e28ef0c860b7 Mon Sep 17 00:00:00 2001 From: Maximilian Kaske <56969857+mxkaske@users.noreply.github.com> Date: Wed, 14 Oct 2026 12:28:19 +0200 Subject: [PATCH 5/6] chore: one-command dev stack for screenshots in cloud sessions (#2902) * chore: one-command dev stack for screenshots in cloud sessions Taking a dashboard screenshot from a bare clone meant hunting for a toolchain (deno and sqld are not on the sandbox image and their download hosts are blocked), hand-running env copy, sqld, migrate, seed and the dev server, aliasing Playwright's pinned Chromium build, and hand-writing a gallery page to share the PNGs. - scripts/dev-stack.mjs: `up` fetches the devbox-pinned deno and sqld from npm when missing, creates the .env files, starts sqld, migrates, seeds once, starts the dashboard, warms routes and records PIDs; `down` stops only what it started; `status` and `tools` for the hook. - scripts/screenshot.mjs: falls back to a preinstalled Chromium (PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH or /opt/pw-browsers/chromium), warms each route with the session cookies before navigating and allows 120s for the first compile, hides the dev-only Tailwind badge and Next indicator, and writes .screenshots/index.html as a publishable gallery. - Tailwind breakpoint indicator gets data-slot="tailwind-indicator" in the three apps so the script can hide it. - .claude/hooks/session-start.sh (cloud only): links .claude/skills, pnpm install, prefetches the tools, and compiles the dashboard once so the cached container starts warm. - Docs: screenshot skill, dashboard AGENTS.md and README, skills README. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0181yZ69zwxbheB2q2C7Zoo9 * chore: capture screenshots with agent-browser scripts/screenshot.mjs drove Playwright borrowed from apps/screenshot-service and carried browser-path fallbacks for the cloud sandbox. It now drives agent-browser (vercel-labs) over its CLI with the same flags and conventions: seeded-session cookies, light and dark at 2x, dev chrome hidden, element shots, the gallery. Element shots pin the match to the viewport's top-left at its own size since agent-browser shoots viewports. `--state` (an agent-browser state file) replaces the magic-link `--login` flow. dev-stack `tools` fetches the pinned agent-browser alongside deno, from one package.json in the cache so installs stay additive. The session-start hook exports AGENT_BROWSER_EXECUTABLE_PATH for the sandbox's Chromium. The screenshot skill is rewritten around agent-browser, with a recipe for interactive states the script cannot reach. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0181yZ69zwxbheB2q2C7Zoo9 * fix: address review findings on the dev stack and screenshot script - `up` seeds only a database it created; a reused server with no seeded session gets a hint to pass --reseed instead of being wiped. - `down` decides by the recorded process group's members (pgrep -g), so an orphaned next-server is still stopped and a reused pid is never signalled. A reusing `up` keeps the pid only when the group is still ours. - `up` also fetches agent-browser, so a clean session can shoot right after. - `--selector` skips visibility:hidden matches, which the isolation style would otherwise reveal. - Gallery heading is neutral and names the app in its facts. - README documents the stack database path and how to reset it. - Hook command quotes CLAUDE_PROJECT_DIR. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0181yZ69zwxbheB2q2C7Zoo9 * fix: fail `down` when pgrep cannot answer; keep the commit in the gallery title A missing or broken pgrep read as "no group members", so `down` stopped nothing and dropped the state while the stack kept running. Only exit 1 (no match) is an empty group now; anything else aborts before the state is removed. The gallery title read the facts by index and picked up the branch once the App row was added. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0181yZ69zwxbheB2q2C7Zoo9 --------- Co-authored-by: Claude --- .agents/skills/README.md | 5 +- .agents/skills/screenshot/SKILL.md | 111 ++++- .claude/hooks/session-start.sh | 43 ++ .claude/settings.json | 14 + apps/dashboard/AGENTS.md | 9 +- apps/dashboard/README.md | 1 + .../src/components/tailwind-indicator.tsx | 5 +- .../src/components/tailwind-indicator.tsx | 5 +- .../web/src/components/tailwind-indicator.tsx | 5 +- scripts/dev-stack.mjs | 388 ++++++++++++++++++ scripts/screenshot.mjs | 380 +++++++++++------ 11 files changed, 816 insertions(+), 150 deletions(-) create mode 100755 .claude/hooks/session-start.sh create mode 100644 .claude/settings.json create mode 100644 scripts/dev-stack.mjs diff --git a/.agents/skills/README.md b/.agents/skills/README.md index e80b3e107..2d05304bc 100644 --- a/.agents/skills/README.md +++ b/.agents/skills/README.md @@ -4,8 +4,9 @@ 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: +`.gitignore` ship with the repo. A fresh clone needs the symlinks once; the +session-start hook in `.claude/hooks/session-start.sh` creates them in cloud +sessions, a teammate runs: ```sh mkdir -p .claude/skills && for d in .agents/skills/*/; do n=$(basename "$d"); ln -sfn "../../.agents/skills/$n" ".claude/skills/$n"; done diff --git a/.agents/skills/screenshot/SKILL.md b/.agents/skills/screenshot/SKILL.md index 823af0400..d49c2350b 100644 --- a/.agents/skills/screenshot/SKILL.md +++ b/.agents/skills/screenshot/SKILL.md @@ -5,9 +5,14 @@ description: Screenshot pages of the local dev server of any Next.js app here (d # 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. +The engine is [agent-browser](https://github.com/vercel-labs/agent-browser), +a CLI that drives Chrome over CDP. Two ways in: + +- `scripts/screenshot.mjs` for the standard evidence shots. It logs in with + a seeded session, shoots light and dark at 2×, hides dev-only chrome, + takes the element or the page, and writes a gallery. +- `agent-browser` directly for a state the script cannot reach: a dropdown + open, a dialog, a filled composer. See **Interactive shots**. ```sh node scripts/screenshot.mjs --app dashboard /incidents/1 --selector "[data-slot=timeline]" @@ -15,10 +20,36 @@ 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. +It prints the PNG paths and writes `.screenshots/index.html`, a gallery of +every shot in the output directory. Read the PNGs with the Read tool and +judge against `DESIGN.md`. Both themes by default; `--theme light` for one. + +## Cloud session (nothing installed, nothing running) + +One command brings up everything the dashboard needs, then shoot: + +```sh +node scripts/dev-stack.mjs up --warm /incidents/1 +node scripts/screenshot.mjs --app dashboard /incidents/1 --user max@openstatus.dev +node scripts/dev-stack.mjs down # when finished; stops only what `up` started +``` + +`up` fetches pinned deno, sqld and agent-browser from npm when they are not +on PATH (the official download hosts are blocked in the sandbox; npm is +not), creates the two `.env` files from their examples, starts sqld on +:8080, migrates, seeds once (`--reseed` wipes and reseeds), starts the +dashboard on :3001 and warms the given routes. Servers already answering +are reused and left alone by `down`. The session-start hook has usually +already fetched the tools and compiled the dashboard, so `up` takes about +15 seconds. `status` shows what is up; logs are in `.screenshots/stack/`. +`--port` and `--db-port` move the two servers. + +`pnpm -w dev:dashboard` does not work there: it runs `turso dev`, which the +sandbox lacks. agent-browser uses the sandbox's Chromium through +`AGENT_BROWSER_EXECUTABLE_PATH=/opt/pw-browsers/chromium`; the hook exports +it and the script sets it itself when unset. No `agent-browser install`. -## Before running +## Before running (local machine) 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` @@ -44,11 +75,14 @@ It prints the PNG paths. Read them with the Read tool and judge against 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`. + the user when identity matters. No seeded session: log in once with + agent-browser (`open http://localhost:3001/login`, submit the email, follow + the `>>> Magic Link:` line from the dev server log with `open`), run + `agent-browser state save .screenshots/auth.json`, and pass + `--state .screenshots/auth.json`. +4. agent-browser: `npm i -g agent-browser` (it wants node 24, the devbox + pin), or let `node scripts/dev-stack.mjs tools` fetch the pinned copy + into `node_modules/.cache`. It finds Chrome on its own locally. ## Flags @@ -56,7 +90,7 @@ It prints the PNG paths. Read them with the Read tool and judge against |---|---|---| | `--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 | +| `--selector` | page | CSS selector; every visible match is shot on its own | | `--theme` | `both` | `light` or `dark` | | `--out` | `.screenshots` | gitignored | | `--width` | `1400` | viewport width, 2× device scale | @@ -66,7 +100,35 @@ It prints the PNG paths. Read them with the Read tool and judge against | `--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 | +| `--state` | | agent-browser state file (cookies + storage) instead of a seeded session | + +## Interactive shots + +For a state the script cannot reach, drive agent-browser yourself. The +sequence below is what the script does, minus the gallery; `agent-browser +skills get core` has the full command set. + +```sh +agent-browser set viewport 1400 1000 2 # 2× like the script +agent-browser set media dark # or light; next-themes follows it +agent-browser cookies set authjs.session-token seed-session-max --url http://localhost:3001 +agent-browser cookies set workspace-slug love-openstatus --url http://localhost:3001 +agent-browser open http://localhost:3001/incidents/1 +agent-browser wait --fn "document.fonts.status === 'loaded'" +agent-browser eval "document.head.insertAdjacentHTML('beforeend','')" +agent-browser snapshot -i # refs for the interactive elements +agent-browser click @e12 # e.g. the severity select +agent-browser screenshot .screenshots/incidents-1-severity-dark.png +agent-browser close # sessions outlive the shell +``` + +- `wait --load networkidle` times out against the dev server (the HMR + socket never goes idle). Wait for fonts, an element (`wait @ref`) or text. +- `--session ` isolates a browser; the script uses one per theme and + closes it. Close the ones you open. +- agent-browser shoots viewports, not elements. The script's `--selector` + pins the match to the viewport's top-left at its own size and hides the + rest; for an ad-hoc element shot, `scrollintoview` and shoot the viewport. ## Selectors worth knowing @@ -86,6 +148,15 @@ plain note and a Slack unbind), status reports #1 (resolved) and #2 (linked), ma `/status` (page 1, with components) and `/acme` (page 2). Safe to mutate; re-seed to reset. +## What the script already handles + +- Each route is fetched once with the session cookies before the browser + opens it, so a cold Turbopack compile (10s+) never trips a timeout. +- The dev-only Tailwind breakpoint badge (`[data-slot=tailwind-indicator]`) + and the Next.js dev indicator are hidden before the capture. +- Not handled: avatar images from blocked hosts render as initials or alt + text in the sandbox. Say so when it shows; do not chase it. + ## Rules - Shoot the element, not the viewport, unless layout is the question. @@ -94,8 +165,8 @@ re-seed to reset. 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. +- Stop any dev server you started (`dev-stack down`, or by port, never by + process name) and close any agent-browser session you opened. ## Sharing @@ -105,10 +176,12 @@ 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. + vanish with the VM. Publish the generated gallery with the Artifact tool: + `file_path` `.screenshots/index.html`, `root` `.screenshots`, and every PNG + it shows passed in `files` under its own name (`{"incidents-1-light.png": + "incidents-1-light.png", ...}`). The gallery is written as a page fragment + (title, style, body) for exactly that. 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/.claude/hooks/session-start.sh b/.claude/hooks/session-start.sh new file mode 100755 index 000000000..d3bd6fc69 --- /dev/null +++ b/.claude/hooks/session-start.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Cloud sessions start from a bare clone: no node_modules, no deno, no sqld, +# and no .claude/skills symlinks. Prepare all of it once; the container state +# is cached afterwards, so later sessions start with it in place. +set -euo pipefail + +if [ "${CLAUDE_CODE_REMOTE:-}" != "true" ]; then + exit 0 +fi + +cd "$CLAUDE_PROJECT_DIR" + +# Claude Code reads skills from .claude/skills only; see .agents/skills/README.md. +mkdir -p .claude/skills +for d in .agents/skills/*/; do + n=$(basename "$d") + ln -sfn "../../.agents/skills/$n" ".claude/skills/$n" +done + +pnpm install + +# deno (pnpm verify, migrations, seed), sqld (local libSQL) and agent-browser +# (screenshots) are not on the image; dev-stack fetches pinned versions from +# npm into node_modules/.cache and prints their paths. +node scripts/dev-stack.mjs tools + +# Seed the database and compile the dashboard once, so the cached container +# carries a warm .next and the first screenshot starts in seconds instead of +# a minute. Skipped on resume (cache present); a failure must not block the +# session. +if [ ! -d apps/dashboard/.next/dev ]; then + node scripts/dev-stack.mjs up --warm /overview /incidents/1 || true + node scripts/dev-stack.mjs down || true +fi + +tools="$CLAUDE_PROJECT_DIR/node_modules/.cache/openstatus-tools" +if [ -n "${CLAUDE_ENV_FILE:-}" ]; then + echo "export PATH=\"$tools/node_modules/.bin:$tools/sqld:\$PATH\"" >> "$CLAUDE_ENV_FILE" + # The sandbox's Chromium; agent-browser does not look there on its own. + if [ -x /opt/pw-browsers/chromium ]; then + echo 'export AGENT_BROWSER_EXECUTABLE_PATH=/opt/pw-browsers/chromium' >> "$CLAUDE_ENV_FILE" + fi +fi diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 000000000..d0d6eb355 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,14 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/session-start.sh" + } + ] + } + ] + } +} diff --git a/apps/dashboard/AGENTS.md b/apps/dashboard/AGENTS.md index 1e0aca814..8d55adcae 100644 --- a/apps/dashboard/AGENTS.md +++ b/apps/dashboard/AGENTS.md @@ -6,15 +6,16 @@ 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/dev-stack.mjs up --warm /incidents/1 # only when nothing is running 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 +It drives agent-browser 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, +Look at them. `dev-stack.mjs` provisions the database and dashboard from a +bare clone, which a cloud session is. 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. diff --git a/apps/dashboard/README.md b/apps/dashboard/README.md index 9d0c3757c..15c7e40e5 100644 --- a/apps/dashboard/README.md +++ b/apps/dashboard/README.md @@ -82,6 +82,7 @@ To log in: - **Port 8080 already in use** — a leftover libSQL server from step 2. Kill that terminal and re-run `pnpm -w dev:dashboard`. - **Magic link doesn't arrive** — it isn't emailed in dev. Look in the dashboard terminal stdout for `>>> Magic Link: ...`. - **Reset the dev DB** — stop the libSQL server, delete `openstatus-dev.db` at the repo root, restart libSQL, re-run `pnpm -w dx`. +- **No Turso CLI or Deno on the machine** (a cloud sandbox) — `node scripts/dev-stack.mjs up` does steps 2 to 5 with sqld and deno fetched from npm; `down` stops them. Its database is `.screenshots/stack/openstatus-dev.db`: `up --reseed` resets the fixtures, or delete the directory while the stack is down. ## Related services (optional for dashboard development) diff --git a/apps/dashboard/src/components/tailwind-indicator.tsx b/apps/dashboard/src/components/tailwind-indicator.tsx index a9967cb30..28c6eed30 100644 --- a/apps/dashboard/src/components/tailwind-indicator.tsx +++ b/apps/dashboard/src/components/tailwind-indicator.tsx @@ -2,7 +2,10 @@ export function TailwindIndicator() { if (process.env.NODE_ENV === "production") return null; return ( -
    +
    xs
    sm
    md
    diff --git a/apps/status-page/src/components/tailwind-indicator.tsx b/apps/status-page/src/components/tailwind-indicator.tsx index a9967cb30..28c6eed30 100644 --- a/apps/status-page/src/components/tailwind-indicator.tsx +++ b/apps/status-page/src/components/tailwind-indicator.tsx @@ -2,7 +2,10 @@ export function TailwindIndicator() { if (process.env.NODE_ENV === "production") return null; return ( -
    +
    xs
    sm
    md
    diff --git a/apps/web/src/components/tailwind-indicator.tsx b/apps/web/src/components/tailwind-indicator.tsx index b2ada3c52..3e67729b0 100644 --- a/apps/web/src/components/tailwind-indicator.tsx +++ b/apps/web/src/components/tailwind-indicator.tsx @@ -2,7 +2,10 @@ export function TailwindIndicator() { if (process.env.NODE_ENV === "production") return null; return ( -
    +
    xs
    sm
    md
    diff --git a/scripts/dev-stack.mjs b/scripts/dev-stack.mjs new file mode 100644 index 000000000..56153235b --- /dev/null +++ b/scripts/dev-stack.mjs @@ -0,0 +1,388 @@ +#!/usr/bin/env node +// Bring up (or tear down) what a dashboard screenshot needs: deno and sqld, +// the env files, a seeded libSQL on :8080 and the dashboard on :3001. +// +// node scripts/dev-stack.mjs up [--reseed] [--warm /incidents/1 ...] +// node scripts/dev-stack.mjs down +// node scripts/dev-stack.mjs status +// node scripts/dev-stack.mjs tools # only fetch deno, sqld, agent-browser +// +// Servers already answering on their port are reused and left alone by `down`; +// only processes this script started are stopped. Flags, ports and fixtures: +// .agents/skills/screenshot/SKILL.md. + +import { execFileSync, spawn, spawnSync } from "node:child_process"; +import { + copyFileSync, + existsSync, + mkdirSync, + mkdtempSync, + openSync, + readFileSync, + renameSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { delimiter, dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const repo = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const stackDir = join(repo, ".screenshots", "stack"); +const stateFile = join(stackDir, "state.json"); +const toolsDir = join(repo, "node_modules", ".cache", "openstatus-tools"); + +// The sqld npm wrapper's postinstall is broken, so the platform tarball is +// unpacked by hand. Its binary reports the devbox-pinned sqld version. +const SQLD_NPM_VERSION = "0.24.1-pre.42"; +// Capture engine of scripts/screenshot.mjs; not in devbox.json, pinned here. +const AGENT_BROWSER_VERSION = "0.39.1"; + +const args = process.argv.slice(2); +const command = args.shift(); +const flags = { warm: [] }; +for (let i = 0; i < args.length; i++) { + const a = args[i]; + if (a === "--warm") { + while (args[i + 1] && !args[i + 1].startsWith("--")) + flags.warm.push(args[++i]); + } else if (a.startsWith("--")) { + const next = args[i + 1]; + flags[a.slice(2)] = + next === undefined || next.startsWith("--") ? true : args[++i]; + } +} +if (!["up", "down", "status", "tools"].includes(command)) { + console.error( + "usage: dev-stack.mjs up [--reseed] [--warm ...] [--port 3001] [--db-port 8080] | down | status | tools", + ); + process.exit(2); +} + +const port = Number(flags.port ?? 3001); +const dbPort = Number(flags["db-port"] ?? 8080); +const base = `http://localhost:${port}`; +const dbUrl = `http://127.0.0.1:${dbPort}`; + +const log = (msg) => console.error(`dev-stack: ${msg}`); +const since = (t) => `${((Date.now() - t) / 1000).toFixed(1)}s`; + +function pinnedVersion(name) { + const devbox = JSON.parse(readFileSync(join(repo, "devbox.json"), "utf8")); + const entry = devbox.packages.find((p) => p.startsWith(`${name}@`)); + if (!entry) throw new Error(`${name} is not pinned in devbox.json`); + return entry.slice(name.length + 1); +} + +function onPath(bin) { + const r = spawnSync(process.platform === "win32" ? "where" : "which", [bin], { + encoding: "utf8", + }); + return r.status === 0 ? r.stdout.trim().split("\n")[0] : null; +} + +// The cache has one package.json for every npm-installed tool, so a later +// install never prunes an earlier one. +function ensureNpmTool(name, version) { + const found = onPath(name); + if (found) return found; + const bin = join(toolsDir, "node_modules", ".bin", name); + if (existsSync(bin)) return bin; + mkdirSync(toolsDir, { recursive: true }); + const manifest = join(toolsDir, "package.json"); + const pkg = existsSync(manifest) + ? JSON.parse(readFileSync(manifest, "utf8")) + : { name: "openstatus-tools", private: true, dependencies: {} }; + pkg.dependencies[name] = version; + writeFileSync(manifest, JSON.stringify(pkg, null, 2)); + log(`fetching ${name} ${version} from npm into ${toolsDir}`); + execFileSync( + "npm", + ["install", "--prefix", toolsDir, "--no-audit", "--no-fund"], + { stdio: "inherit" }, + ); + return bin; +} + +const ensureDeno = () => ensureNpmTool("deno", pinnedVersion("deno")); +const ensureAgentBrowser = () => + ensureNpmTool("agent-browser", AGENT_BROWSER_VERSION); + +function ensureSqld() { + const found = onPath("sqld"); + if (found) return found; + const bin = join(toolsDir, "sqld", "sqld"); + if (existsSync(bin)) return bin; + const os = { linux: "linux", darwin: "darwin" }[process.platform]; + const arch = { x64: "x64", arm64: "arm64" }[process.arch]; + if (!os || !arch) + throw new Error( + `no sqld npm build for ${process.platform}-${process.arch}; install sqld ${pinnedVersion("sqld")} yourself`, + ); + log( + `fetching sqld ${pinnedVersion("sqld")} (npm @sqld/${os}-${arch}@${SQLD_NPM_VERSION})`, + ); + const tmp = mkdtempSync(join(tmpdir(), "sqld-")); + const tarball = execFileSync( + "npm", + [ + "pack", + `@sqld/${os}-${arch}@${SQLD_NPM_VERSION}`, + "--pack-destination", + tmp, + "--silent", + ], + { encoding: "utf8" }, + ).trim(); + execFileSync("tar", ["xzf", join(tmp, tarball), "-C", tmp, "package/sqld"]); + mkdirSync(dirname(bin), { recursive: true }); + renameSync(join(tmp, "package", "sqld"), bin); + rmSync(tmp, { recursive: true, force: true }); + return bin; +} + +function ensureEnvFiles() { + for (const dir of ["apps/dashboard", "packages/db"]) { + const target = join(repo, dir, ".env"); + if (!existsSync(target)) { + copyFileSync(join(repo, dir, ".env.example"), target); + log(`created ${dir}/.env from .env.example`); + } + } +} + +async function sql(statements) { + const res = await fetch(dbUrl, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ statements }), + signal: AbortSignal.timeout(5000), + }).catch(() => null); + if (!res?.ok) return null; + const body = await res.json(); + return body.map((r) => { + if (r.error) throw new Error(r.error.message); + return r.results.rows; + }); +} + +async function dashboardUp() { + const res = await fetch(`${base}/login`, { + redirect: "manual", + signal: AbortSignal.timeout(5000), + }).catch(() => null); + return res?.status === 200; +} + +async function waitFor(check, what, ms) { + const until = Date.now() + ms; + while (Date.now() < until) { + if (await check()) return; + await new Promise((r) => setTimeout(r, 500)); + } + throw new Error(`${what} did not come up within ${ms / 1000}s`); +} + +function readState() { + return existsSync(stateFile) + ? JSON.parse(readFileSync(stateFile, "utf8")) + : {}; +} + +function writeState(state) { + mkdirSync(stackDir, { recursive: true }); + writeFileSync(stateFile, JSON.stringify(state, null, 2)); +} + +// Detached with its own process group, so `down` can stop pnpm, next and its +// workers together via the negative pid. +function launch(name, cmd, cmdArgs, opts) { + const out = openSync(join(stackDir, `${name}.log`), "a"); + const child = spawn(cmd, cmdArgs, { + ...opts, + detached: true, + stdio: ["ignore", out, out], + }); + child.unref(); + log(`started ${name} (pid ${child.pid}, log .screenshots/stack/${name}.log)`); + return child.pid; +} + +function alive(pid) { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +// The recorded pid leads a process group. The launcher (pnpm) can exit before +// next does, and after a reboot the pid can belong to something else, so the +// group's members decide, not the leader. +function groupMembers(pgid) { + const r = spawnSync("pgrep", ["-l", "-g", String(pgid)], { + encoding: "utf8", + }); + // pgrep exits 1 for "no match"; anything else means it could not answer, + // and guessing "empty" would make `down` drop the state while the stack runs. + if (r.error || (r.status !== 0 && r.status !== 1)) + throw new Error( + `pgrep is needed to stop the stack: ${r.error?.message ?? r.stderr.trim()}`, + ); + return r.status === 0 ? r.stdout.trim().split("\n").filter(Boolean) : []; +} + +const SQLD_GROUP = /\bsqld\b/; +const DASHBOARD_GROUP = /\b(pnpm|node|next-server)\b/; +const ours = (pid, expected) => + Boolean(pid) && groupMembers(pid).some((m) => expected.test(m)); + +function stop(name, pid, expected) { + if (!pid) return; + const members = groupMembers(pid); + if (members.length === 0) return; + if (!members.some((m) => expected.test(m))) { + log(`not stopping ${name}: pid ${pid} now belongs to "${members[0]}"`); + return; + } + for (const signal of ["SIGTERM", "SIGKILL"]) { + try { + process.kill(-pid, signal); + } catch { + return; + } + const until = Date.now() + 5000; + while (groupMembers(pid).length && Date.now() < until) + spawnSync("sleep", ["0.2"]); + if (groupMembers(pid).length === 0) break; + } + log(`stopped ${name} (pid ${pid})`); +} + +async function up() { + const started = Date.now(); + mkdirSync(stackDir, { recursive: true }); + const deno = ensureDeno(); + const sqld = ensureSqld(); + ensureAgentBrowser(); + ensureEnvFiles(); + const toolPath = [dirname(deno), dirname(sqld), process.env.PATH].join( + delimiter, + ); + const state = readState(); + + // The seed wipes every table, so only a database this run created is seeded + // without being asked; a reused server may hold someone's real data. + let fresh = false; + if (await sql(["select 1"])) { + log(`reusing sqld at ${dbUrl}`); + if (!ours(state.sqld, SQLD_GROUP)) delete state.sqld; + } else { + const dbPath = join(stackDir, "openstatus-dev.db"); + fresh = !existsSync(dbPath); + state.sqld = launch("sqld", sqld, [ + "--db-path", + dbPath, + "--http-listen-addr", + `127.0.0.1:${dbPort}`, + ]); + writeState(state); + await waitFor(() => sql(["select 1"]), "sqld", 20000); + log(`sqld answering after ${since(started)}`); + } + + const env = { + ...process.env, + PATH: toolPath, + DATABASE_URL: dbUrl, + DATABASE_AUTH_TOKEN: process.env.DATABASE_AUTH_TOKEN ?? "any-token", + }; + const run = (script) => { + const t = Date.now(); + const r = spawnSync("pnpm", ["--filter", "@openstatus/db", script], { + cwd: repo, + env, + stdio: "inherit", + }); + if (r.status !== 0) + throw new Error(`pnpm --filter @openstatus/db ${script} failed`); + log(`${script}: ${since(t)}`); + }; + run("migrate"); + const [sessions] = (await sql([ + "select count(*) from session where session_token = 'seed-session-max'", + ])) ?? [[[0]]]; + const seeded = sessions[0][0] > 0; + if (flags.reseed || (fresh && !seeded)) run("seed"); + else if (!seeded) + log( + `no seeded session in the existing database at ${dbUrl}; pass --reseed to wipe and seed it`, + ); + else + log("seed present (seed-session-max); pass --reseed to reset the fixtures"); + + if (await dashboardUp()) { + log(`reusing dashboard at ${base}`); + if (!ours(state.dashboard, DASHBOARD_GROUP)) delete state.dashboard; + } else { + state.dashboard = launch( + "dashboard", + "pnpm", + ["--filter", "@openstatus/dashboard", "dev"], + { cwd: repo, env: { ...env, PORT: String(port) } }, + ); + writeState(state); + const t = Date.now(); + await waitFor(dashboardUp, "dashboard", 180000); + log(`dashboard answering after ${since(t)}`); + } + + // The first request to a route pays the Turbopack compile (10s+); do it here + // so the screenshot's navigation never races a timeout. + for (const path of flags.warm) { + const t = Date.now(); + const res = await fetch(base + path, { + headers: { + cookie: + "authjs.session-token=seed-session-max; workspace-slug=love-openstatus", + }, + redirect: "manual", + }).catch(() => null); + log(`warmed ${path}: ${res?.status ?? "unreachable"} in ${since(t)}`); + } + writeState(state); + log(`ready in ${since(started)}: dashboard ${base}, sqld ${dbUrl}`); +} + +async function down() { + const state = readState(); + stop("dashboard", state.dashboard, DASHBOARD_GROUP); + stop("sqld", state.sqld, SQLD_GROUP); + if (!state.dashboard && !state.sqld) + log("nothing started by this script is running"); + rmSync(stateFile, { force: true }); +} + +async function status() { + const state = readState(); + console.log( + `dashboard ${base}: ${(await dashboardUp()) ? "up" : "down"}${state.dashboard ? ` (pid ${state.dashboard}${alive(state.dashboard) ? "" : ", gone"})` : ""}`, + ); + console.log( + `sqld ${dbUrl}: ${(await sql(["select 1"])) ? "up" : "down"}${state.sqld ? ` (pid ${state.sqld}${alive(state.sqld) ? "" : ", gone"})` : ""}`, + ); +} + +function tools() { + console.log(`deno: ${ensureDeno()}`); + console.log(`sqld: ${ensureSqld()}`); + console.log(`agent-browser: ${ensureAgentBrowser()}`); +} + +try { + await { up, down, status, tools }[command](); +} catch (e) { + console.error(`dev-stack: ${e.message}`); + process.exit(1); +} diff --git a/scripts/screenshot.mjs b/scripts/screenshot.mjs index eb97fa41b..8e6a5812d 100644 --- a/scripts/screenshot.mjs +++ b/scripts/screenshot.mjs @@ -1,5 +1,6 @@ #!/usr/bin/env node -// Screenshot pages of a local Next.js dev server, in light and dark. +// Screenshot pages of a local Next.js dev server, in light and dark, through +// agent-browser (https://github.com/vercel-labs/agent-browser). // // node scripts/screenshot.mjs --app dashboard /incidents/1 --selector "[data-slot=timeline]" // node scripts/screenshot.mjs --app web /pricing --full-page @@ -7,15 +8,18 @@ // // Flags, auth order and fixtures: .agents/skills/screenshot/SKILL.md. -import { existsSync, mkdirSync, readFileSync } from "node:fs"; -import { createRequire } from "node:module"; +import { execFileSync, spawnSync } from "node:child_process"; +import { + existsSync, + mkdirSync, + readdirSync, + statSync, + writeFileSync, +} from "node:fs"; 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" }, @@ -58,10 +62,48 @@ if (!Number.isFinite(width) || width <= 0) { console.error(`--width must be a positive number, got ${flags.width}`); process.exit(2); } -const stateFile = resolve(flags.state ?? join(out, "state.json")); -const wantsAuth = app.auth || Boolean(flags.token || flags.login); +const wantsAuth = app.auth || Boolean(flags.token || flags.state); mkdirSync(out, { recursive: true }); +// agent-browser from PATH, else the copy `dev-stack.mjs tools` fetched. +const bin = (() => { + const which = spawnSync("which", ["agent-browser"], { encoding: "utf8" }); + if (which.status === 0) return which.stdout.trim(); + const cached = join( + repo, + "node_modules/.cache/openstatus-tools/node_modules/.bin/agent-browser", + ); + if (existsSync(cached)) return cached; + console.error( + "agent-browser not found: node scripts/dev-stack.mjs tools, or npm i -g agent-browser", + ); + process.exit(1); +})(); +const env = { ...process.env, AGENT_BROWSER_DEFAULT_TIMEOUT: "120000" }; +// The cloud sandbox ships a Chromium that agent-browser does not find by itself. +if ( + !env.AGENT_BROWSER_EXECUTABLE_PATH && + existsSync("/opt/pw-browsers/chromium") +) + env.AGENT_BROWSER_EXECUTABLE_PATH = "/opt/pw-browsers/chromium"; + +function ab(session, ...cmd) { + const r = spawnSync(bin, ["--session", session, ...cmd], { + encoding: "utf8", + env, + }); + if (r.status !== 0) + throw new Error( + `agent-browser ${cmd.join(" ")}: ${(r.stderr || r.stdout).trim()}`, + ); + return r.stdout.trim(); +} +// `eval` prints the result as JSON; page code returns JSON strings for objects. +function evalJs(session, js) { + const v = JSON.parse(ab(session, "eval", js)); + return typeof v === "string" && v.startsWith("{") ? JSON.parse(v) : v; +} + async function sql(statements) { const res = await fetch(db, { method: "POST", @@ -111,42 +153,11 @@ async function sessionCookies() { } 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: "/" }); + const list = [{ name: "authjs.session-token", value: token }]; + if (slug) list.push({ name: "workspace-slug", value: slug }); 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}`, - ); -} - // Three apps, two default ports, and on this machine any of them may sit on // :3001. Only the dashboard serves a form at /login; use that to tell them apart. const probe = await fetch(base + (app.probe ?? paths[0])).catch(() => null); @@ -168,102 +179,227 @@ if (!app.auth) { } } -// 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); console.error("auth: --token"); -} else if (wantsAuth && !flags.login) { +} else if (flags.state) { + console.error(`auth: agent-browser state ${flags.state}`); +} else if (wantsAuth) { auth = await sessionCookies().catch( (e) => (console.error(`auth: ${e.message}`), null), ); + if (!auth) + console.error( + "auth: no session found; seed the database, pass --token, or --state ", + ); } -// One login for all themes: the dashboard rate-limits magic-link emails. -if (flags.login && !auth) { - const context = await browser.newContext(); - await magicLinkLogin(context); - await context.close(); -} -// A saved state is only a fallback; an explicit identity must not silently -// become whoever logged in last. -const useState = - wantsAuth && !auth && !flags.user && !flags.token && existsSync(stateFile); -if (useState) console.error(`auth: saved state ${stateFile}`); -if (wantsAuth && !auth && !useState) { - console.error( - "auth: no session found; seed the database, pass --token, or --login --log ", - ); + +// The first request to a route pays the dev server's compile (10s+ on a cold +// Turbopack cache); take it here so no browser command waits on it. +if (auth) { + const headers = { + cookie: auth.map((c) => `${c.name}=${c.value}`).join("; "), + }; + for (const path of paths) { + const t = Date.now(); + const res = await fetch(base + path, { headers, redirect: "manual" }).catch( + () => null, + ); + console.error( + `warm ${path}: ${res?.status ?? "unreachable"} in ${((Date.now() - t) / 1000).toFixed(1)}s`, + ); + } } +// Dev-only chrome floats over the bottom-left corner: the apps' Tailwind +// breakpoint badge and the Next.js dev indicator. +const HIDE_DEV_CHROME = `(() => { + const st = document.createElement("style"); + st.textContent = "[data-slot=tailwind-indicator],nextjs-portal{display:none!important}"; + document.head.appendChild(st); + return "ok"; +})()`; + +// agent-browser shoots viewports, not elements. Pin the k-th match to the +// viewport's top-left at its own size, hide everything else, and let the +// caller size the viewport to it. +const isolate = (selector, k) => `(() => { + const els = [...document.querySelectorAll(${JSON.stringify(selector)})].filter((e) => e.getClientRects().length && getComputedStyle(e).visibility !== "hidden"); + const el = els[${k}]; + if (!el) return JSON.stringify({ count: els.length }); + const r = el.getBoundingClientRect(); + const w = Math.ceil(r.width), h = Math.ceil(r.height); + const st = document.createElement("style"); + st.id = "__shot"; + st.textContent = "html{background:" + getComputedStyle(document.body).backgroundColor + "!important}" + + "body{visibility:hidden!important;overflow:hidden!important}" + + "[data-shot-target]{visibility:visible!important;position:fixed!important;top:0!important;left:0!important;margin:0!important;width:" + w + "px!important;height:" + h + "px!important;z-index:2147483647!important}"; + el.setAttribute("data-shot-target", ""); + document.head.appendChild(st); + return JSON.stringify({ count: els.length, w, h }); +})()`; +const RESTORE = `(() => { + document.getElementById("__shot")?.remove(); + document.querySelector("[data-shot-target]")?.removeAttribute("data-shot-target"); + return "ok"; +})()`; + +// next-themes follows prefers-color-scheme until the user picks a theme; a +// saved choice (from --state) would win, so pin the storage key too. +const pinTheme = (theme) => `(() => { + localStorage.setItem("theme", ${JSON.stringify(theme)}); + return document.documentElement.classList.contains(${JSON.stringify(theme)}) ? "ok" : "reload"; +})()`; + +const LOADED = `document.readyState === "complete" && document.fonts.status === "loaded"`; + 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" }); - if ( - app.auth && - new URL(page.url()).pathname === "/login" && - !path.startsWith("/login") - ) - throw new Error(`redirected to login for ${path}; auth failed`); - 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++; + // One isolated browser per theme; sessions survive this process, so close it. + const session = `openstatus-shot-${theme}-${process.pid}`; + try { + ab(session, "set", "viewport", String(width), "1000", "2"); + ab(session, "set", "media", theme); + for (const c of auth ?? []) + ab(session, "cookies", "set", c.name, c.value, "--url", base); + for (const path of paths) { + const open = flags.state ? ["--state", flags.state] : []; + ab(session, ...open, "open", base + path); + ab(session, "wait", "--fn", LOADED); + const url = ab(session, "get", "url"); + if ( + app.auth && + new URL(url).pathname === "/login" && + !path.startsWith("/login") + ) + throw new Error(`redirected to login for ${path}; auth failed`); + if (evalJs(session, pinTheme(theme)) === "reload") { + ab(session, "reload"); + ab(session, "wait", "--fn", LOADED); } - if (k === 0) { - console.error(`no visible match for ${flags.selector} on ${path}`); - process.exitCode = 1; + evalJs(session, HIDE_DEV_CHROME); + const name = + path.replace(/^\/+/, "").replace(/[^a-z0-9]+/gi, "-") || "root"; + if (flags.selector) { + let k = 0; + for (;;) { + const box = evalJs(session, isolate(flags.selector, k)); + if (!box.w) break; + ab(session, "set", "viewport", String(box.w), String(box.h), "2"); + const file = join( + out, + `${name}-${theme}${box.count > 1 ? `-${k}` : ""}.png`, + ); + ab(session, "screenshot", file); + written.push(file); + evalJs(session, RESTORE); + ab(session, "set", "viewport", String(width), "1000", "2"); + if (++k >= box.count) break; + } + if (k === 0) { + console.error(`no visible match for ${flags.selector} on ${path}`); + process.exitCode = 1; + } + } else { + const file = join(out, `${name}-${theme}.png`); + ab( + session, + "screenshot", + file, + ...(flags["full-page"] ? ["--full"] : []), + ); + written.push(file); } - } else { - const file = join(out, `${name}-${theme}.png`); - await page.screenshot({ - path: file, - fullPage: Boolean(flags["full-page"]), - }); - written.push(file); } + } catch (e) { + console.error(e.message); + process.exitCode = 1; + break; + } finally { + spawnSync(bin, ["--session", session, "close"], { env }); } - await context.close(); } -await browser.close(); +writeGallery(); for (const f of written) console.log(f); + +// A gallery of every PNG in the output directory, written as a page fragment +// (title + style + body) so the Artifact tool can publish it as is, with the +// PNGs passed as `files`. Browsers render the fragment fine locally too. +function writeGallery() { + const shots = readdirSync(out) + .filter((f) => f.endsWith(".png")) + .map((f) => ({ file: f, mtime: statSync(join(out, f)).mtimeMs })); + if (shots.length === 0) return; + const groups = new Map(); + for (const s of shots) { + const m = s.file.match(/^(.*?)-(light|dark)(-\d+)?\.png$/); + const key = m ? `${m[1]}${m[3] ?? ""}` : s.file; + const g = groups.get(key) ?? { key, shots: [], mtime: 0 }; + g.shots.push({ ...s, theme: m?.[2] ?? "" }); + g.mtime = Math.max(g.mtime, s.mtime); + groups.set(key, g); + } + const git = (...a) => + execFileSync("git", a, { cwd: repo, encoding: "utf8" }).trim(); + const commit = git("rev-parse", "--short", "HEAD"); + const facts = [ + ["App", flags.app ?? "dashboard"], + ["Branch", git("rev-parse", "--abbrev-ref", "HEAD")], + ["Commit", commit], + ["Taken", new Date().toISOString().slice(0, 16).replace("T", " ") + " UTC"], + [ + "Viewport", + `${width} px wide, 2× scale${flags["full-page"] ? ", full page" : ""}`, + ], + ]; + const esc = (s) => + s.replace( + /[&<>"]/g, + (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c], + ); + const html = `Screenshots ${esc(commit)} + +
    +

    Screenshots

    +
    ${facts.map(([k, v]) => `
    ${esc(k)}
    ${esc(v)}
    `).join("")}
    +${[...groups.values()] + .sort((a, b) => b.mtime - a.mtime) + .map( + (g) => `
    +

    ${esc(g.key)}

    +${g.shots + .sort((a, b) => a.theme.localeCompare(b.theme) * -1) + .map( + (s) => `
    +
    ${esc(s.theme || s.file)}
    +
    ${esc(g.key)} ${esc(s.theme)}
    +
    `, + ) + .join("\n")} +
    `, + ) + .join("\n")} +
    +`; + const index = join(out, "index.html"); + writeFileSync(index, html); + console.error(`gallery: ${index}`); +} -- 2.51.2 From 500dbdf09f316d284390de26f7fec5f3771657f3 Mon Sep 17 00:00:00 2001 From: Maximilian Kaske <56969857+mxkaske@users.noreply.github.com> Date: Thu, 15 Oct 2026 08:28:27 +0200 Subject: [PATCH 6/6] feat: opt-in Starter trial through Stripe Checkout (#2904) * feat: opt-in Starter trial through Stripe Checkout No trial starts at signup anymore. The owner of a free workspace who signed in with GitHub or Google starts a 14-day Starter trial from a Stripe Checkout page (no card required), from the billing page, the plan table or the upgrade dialog, with an optional "what do you want to test?" note. - getCheckoutSession({ trial, surface, intent }) runs the eligibility guards before creating a Stripe customer - sessionCompleted marks the trial: audit reason trial_started, customer metadata trialed, user.trialed_at, trial_started event - new user.trialed_at column; the trialEligibility query reads only the database, the Checkout mutation adds the Stripe guards - welcome email and marketing copy no longer promise an automatic trial * feat: trial marker on the workspace, eligibility on workspace.get, upgrade intent dialog - move trialed_at from user to workspace, next to trial_ends_at; the webhook sets it through markWorkspaceTrialed - workspace.get returns `trial` (eligibility without Stripe), checked against the workspace row first; drop stripeRouter.trialEligibility and its prefetch - after ?success or ?trial on billing, ask "What are you building?" once per user, stored as upgrade-intent feedback; feedback.hasSubmitted * style(dashboard): taller textarea and ghost skip in the upgrade intent dialog * feat: workspace.trialed_at migration, drop intent field from billing trial card The post-checkout "What are you building?" dialog asks instead. * fix: trial detection from checkout metadata, dedupe trial_started, upgrade_dialog surface - classify opt-in trials by subscription.metadata.source, not live status - track trial_started only when the workspace marker is first set - show the plan-table trial caption only when Starter is listed - index account.user_id for the provider lookup - no credit card needed hint in the billing card and nav banner * style(dashboard): ask what openstatus is used for in the upgrade intent dialog * ci: apply automated fixes * fix: share trial config, toast only once the trial is live - TRIAL_DAYS and TrialSurface move to an import-free trial-config module - the billing page polls workspace.get before the trial-started toast - tailor wording in the upgrade intent dialog - oxfmt * ci: apply automated fixes * fix(db): regenerate 0093 with account_user_id_idx * chore(db): drop trialedAt comment --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> --- .../(dashboard)/settings/billing/client.tsx | 102 +- .../settings/billing/search-params.ts | 1 + .../data-table/billing/data-table.tsx | 47 +- .../src/components/dialogs/upgrade-intent.tsx | 88 + .../src/components/dialogs/upgrade.tsx | 17 +- .../src/components/nav/nav-banner-upgrade.tsx | 14 +- apps/dashboard/src/lib/auth/index.ts | 35 +- apps/web/src/content/pages/home.mdx | 4 +- .../pages/product/incident-management.mdx | 4 +- .../src/content/pages/product/status-page.mdx | 4 +- .../pages/product/uptime-monitoring.mdx | 4 +- .../src/content/pages/unrelated/pricing.mdx | 6 +- packages/api/src/router/feedback.test.ts | 44 + packages/api/src/router/feedback.ts | 18 + packages/api/src/router/stripe/index.ts | 68 +- .../api/src/router/stripe/trial-config.ts | 4 + .../src/router/stripe/trial-lifecycle.test.ts | 95 + packages/api/src/router/stripe/trial.test.ts | 497 +- packages/api/src/router/stripe/trial.ts | 223 +- packages/api/src/router/stripe/webhook.ts | 42 +- packages/api/src/router/workspace.ts | 10 +- .../db/drizzle/0093_wonderful_red_skull.sql | 2 + packages/db/drizzle/meta/0093_snapshot.json | 6907 +++++++++++++++++ packages/db/drizzle/meta/_journal.json | 7 + packages/db/src/schema/feedbacks/constants.ts | 1 + packages/db/src/schema/users/user.ts | 1 + .../db/src/schema/workspaces/workspace.ts | 1 + packages/emails/emails/welcome.tsx | 17 +- packages/emails/src/templates.test.tsx | 14 +- .../src/user/__tests__/providers.test.ts | 29 + packages/services/src/user/index.ts | 7 +- packages/services/src/user/providers.ts | 22 + packages/services/src/user/schemas.ts | 3 + .../src/workspace/__tests__/trial.test.ts | 136 +- packages/services/src/workspace/index.ts | 3 +- packages/services/src/workspace/trial.ts | 52 +- 36 files changed, 8075 insertions(+), 454 deletions(-) create mode 100644 apps/dashboard/src/components/dialogs/upgrade-intent.tsx create mode 100644 packages/api/src/router/feedback.test.ts create mode 100644 packages/api/src/router/stripe/trial-config.ts create mode 100644 packages/db/drizzle/0093_wonderful_red_skull.sql create mode 100644 packages/db/drizzle/meta/0093_snapshot.json create mode 100644 packages/services/src/user/__tests__/providers.test.ts create mode 100644 packages/services/src/user/providers.ts diff --git a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx index e93b194f2..ea00748da 100644 --- a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx +++ b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx @@ -1,12 +1,14 @@ "use client"; +import { TRIAL_DAYS } from "@openstatus/api/src/router/stripe/trial-config"; import { allPlans } from "@openstatus/db/src/schema/plan/config"; import type { Limits } from "@openstatus/db/src/schema/plan/schema"; import { Button } from "@openstatus/ui/components/ui/button"; +import { useCookieState } from "@openstatus/ui/hooks/use-cookie-state"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useRouter } from "next/navigation"; import { useQueryStates } from "nuqs"; -import { useEffect, useMemo, useTransition } from "react"; +import { useEffect, useMemo, useState, useTransition } from "react"; import { toast } from "sonner"; import { BillingAddons } from "@/components/content/billing-addons"; @@ -23,6 +25,7 @@ import { SectionTitle, } from "@/components/content/section"; import { DataTable } from "@/components/data-table/billing/data-table"; +import { UpgradeIntentDialog } from "@/components/dialogs/upgrade-intent"; import { FormCard, FormCardContent, @@ -76,9 +79,26 @@ export function Client() { const router = useRouter(); const [isPending, startTransition] = useTransition(); const queryClient = useQueryClient(); - const [{ success, setup }, setSearchParams] = + const [{ success, setup, trial }, setSearchParams] = useQueryStates(searchParamsParsers); const { data: workspace } = useQuery(trpc.workspace.get.queryOptions()); + // Captured on mount: the toasts clear the params while the dialog is open. + const [askIntent, setAskIntent] = useState(Boolean(success || trial)); + const { data: hasIntent } = useQuery({ + ...trpc.feedback.hasSubmitted.queryOptions({ source: "upgrade-intent" }), + enabled: askIntent, + }); + const [currency] = useCookieState("x-currency", "USD"); + const trialCheckoutMutation = useMutation( + trpc.stripeRouter.getCheckoutSession.mutationOptions({ + onSuccess: (data) => { + if (data?.type === "checkout" && data.session.url) { + window.location.assign(data.session.url); + } + }, + onError: (error) => toast.error(error.message), + }), + ); const { data: usage } = useQuery(trpc.workspace.usage.queryOptions()); const paymentMethodSetupMutation = useMutation( trpc.stripeRouter.getPaymentMethodSetupSession.mutationOptions({ @@ -122,6 +142,38 @@ export function Client() { } }, [success, setSearchParams]); + useEffect(() => { + if (!trial) return; + let cancelled = false; + queryClient.invalidateQueries({ + queryKey: trpc.stripeRouter.getBillingInterval.queryKey(), + }); + // The webhook can land after the redirect, and anyone can open + // `?trial=true`, so only toast once the workspace is actually trialing. + (async () => { + for (let attempt = 0; attempt < 5 && !cancelled; attempt++) { + const ws = await queryClient.fetchQuery({ + ...trpc.workspace.get.queryOptions(), + staleTime: 0, + }); + if (cancelled) return; + if (ws.trialDaysLeft !== null) { + toast.success(`Your ${TRIAL_DAYS}-day Starter trial has started`, { + duration: 5_000, + onAutoClose: () => setSearchParams({ trial: null }), + onDismiss: () => setSearchParams({ trial: null }), + }); + return; + } + await new Promise((resolve) => setTimeout(resolve, 1_000)); + } + if (!cancelled) setSearchParams({ trial: null }); + })(); + return () => { + cancelled = true; + }; + }, [trial, setSearchParams, queryClient, trpc]); + useEffect(() => { if (setup) { queryClient.invalidateQueries({ @@ -157,6 +209,10 @@ export function Client() { return ( +
    Billing @@ -165,6 +221,48 @@ export function Client() { + {workspace?.trial.eligible ? ( + + + + Try Starter free for {TRIAL_DAYS} days + + + 1 min checks, more monitors, custom domain, Slack and on-call + integrations. + + + + + + No credit card needed. + {" "} + The workspace returns to Hobby after {TRIAL_DAYS} days unless + you add a card. + + + + + ) : null} {workspace.trialEndsAt && trialDaysLeft ? ( diff --git a/apps/dashboard/src/app/(dashboard)/settings/billing/search-params.ts b/apps/dashboard/src/app/(dashboard)/settings/billing/search-params.ts index 0e6b7e14c..84e66c386 100644 --- a/apps/dashboard/src/app/(dashboard)/settings/billing/search-params.ts +++ b/apps/dashboard/src/app/(dashboard)/settings/billing/search-params.ts @@ -3,6 +3,7 @@ import { createSearchParamsCache, parseAsBoolean } from "nuqs/server"; export const searchParamsParsers = { success: parseAsBoolean, setup: parseAsBoolean, + trial: parseAsBoolean, }; export const searchParamsCache = createSearchParamsCache(searchParamsParsers); diff --git a/apps/dashboard/src/components/data-table/billing/data-table.tsx b/apps/dashboard/src/components/data-table/billing/data-table.tsx index 326b19966..26453ac01 100644 --- a/apps/dashboard/src/components/data-table/billing/data-table.tsx +++ b/apps/dashboard/src/components/data-table/billing/data-table.tsx @@ -1,5 +1,9 @@ "use client"; +import { + TRIAL_DAYS, + type TrialSurface, +} from "@openstatus/api/src/router/stripe/trial-config"; import type { WorkspacePlan } from "@openstatus/db/src/schema"; import type { Addons, @@ -49,7 +53,13 @@ function getQuantitySuffix(addon: keyof Addons, interval: BillingInterval) { return packSize > 1 ? `${period}/${packSize}` : `${period}/each`; } -export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) { +export function DataTable({ + restrictTo, + surface = "plan_table", +}: { + restrictTo?: WorkspacePlan[]; + surface?: TrialSurface; +}) { const [interval, setInterval] = useState("monthly"); const [currency] = useCookieState("x-currency", "USD"); const trpc = useTRPC(); @@ -61,6 +71,7 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) { trpc.stripeRouter.getBillingInterval.queryOptions(), ); const currentInterval = intervalQuery.data; + const canTrial = workspace?.trial.eligible === true; const checkoutSessionMutation = useMutation( trpc.stripeRouter.getCheckoutSession.mutationOptions({ @@ -128,7 +139,11 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) { {isTrialing ? "Upgrading ends your trial and charges your card today." - : "A list to compare the different features by plan."} + : canTrial && + interval === "monthly" && + filteredPlans.some(({ id }) => id === "starter") + ? `Starter can be tried free for ${TRIAL_DAYS} days, no credit card needed.` + : "A list to compare the different features by plan."} @@ -157,6 +172,8 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) { currentInterval !== null && currentInterval !== interval; const price = getPriceConfig(id, currency, interval); + const isTrialOffer = + canTrial && id === "starter" && interval === "monthly"; return ( {plan.description}

    + {isTrialOffer ? ( +

    + Free for {TRIAL_DAYS} days. No credit card needed. +

    + ) : null}
    {isFreePlan ? ( @@ -196,6 +218,19 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) { onClick={() => { startTransition(async () => { try { + if (isTrialOffer) { + await checkoutSessionMutation.mutateAsync({ + trial: true, + plan: "starter", + interval: "monthly", + surface, + currency: currency || "USD", + workspaceSlug: workspace.slug, + successUrl: `${BASE_URL}/settings/billing?trial=true`, + cancelUrl: `${BASE_URL}/settings/billing`, + }); + return; + } if (id === "free") { await customerPortalMutation.mutateAsync({ workspaceSlug: workspace.slug, @@ -232,9 +267,11 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) { ? "Choosing..." : isIntervalSwitch ? `Switch to ${interval}` - : isTrialing && !isFreePlan - ? "Upgrade now" - : "Choose"} + : isTrialOffer + ? `Start ${TRIAL_DAYS}-day trial` + : isTrialing && !isFreePlan + ? "Upgrade now" + : "Choose"}
    diff --git a/apps/dashboard/src/components/dialogs/upgrade-intent.tsx b/apps/dashboard/src/components/dialogs/upgrade-intent.tsx new file mode 100644 index 000000000..b2b424c7b --- /dev/null +++ b/apps/dashboard/src/components/dialogs/upgrade-intent.tsx @@ -0,0 +1,88 @@ +"use client"; + +import { Button } from "@openstatus/ui/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@openstatus/ui/components/ui/dialog"; +import { Label } from "@openstatus/ui/components/ui/label"; +import { Textarea } from "@openstatus/ui/components/ui/textarea"; +import type { DialogProps } from "@radix-ui/react-dialog"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useId, useState } from "react"; +import { toast } from "sonner"; + +import { useTRPC } from "@/lib/trpc/client"; + +/** Asked after an upgrade or trial start; stored as `upgrade-intent` feedback. */ +export function UpgradeIntentDialog(props: DialogProps) { + const trpc = useTRPC(); + const queryClient = useQueryClient(); + const id = useId(); + const [message, setMessage] = useState(""); + const feedbackMutation = useMutation( + trpc.feedback.submit.mutationOptions({ + onSuccess: () => { + queryClient.invalidateQueries({ + queryKey: trpc.feedback.hasSubmitted.queryKey({ + source: "upgrade-intent", + }), + }); + toast.success("Thanks for sharing"); + props.onOpenChange?.(false); + }, + onError: (error) => toast.error(error.message), + }), + ); + + return ( + + + + What are you using openstatus for? + + A sentence or two helps us tailor openstatus to you. + + +
    + +