chore(studio): improve AGENTS.md and skills from PR review data (#54467)

This commit is contained in:
Alaister Young authored and GitHub committed 2026-12-03 18:30:27 +08:00
1 parent 5a506a54dd
commit 2eb00165c3
49 files changed
+1280 -6645

No files matched your search

+22 -24
View File
@@ -1,14 +1,11 @@
---
name: clickhouse-logs-queries
description: >-
Write, review, and migrate Supabase logs queries against the ClickHouse-backed
`logs` table (the `logs.all.otel` analytics endpoint). Use this whenever a task
involves Logs Explorer SQL, the `log_attributes` map, querying a log `source`
(edge_logs, postgres_logs, auth_logs, etc.), translating an old BigQuery
`cross join unnest(metadata)` logs query to ClickHouse, or wiring analytics log
SQL in `apps/studio/data/logs` and `apps/studio/components/interfaces/Settings/Logs`.
Reach for it even when the user just says "logs query", "Logs Explorer", or
pastes a BigQuery logs query to convert, not only when they name ClickHouse.
Write, review, and migrate Supabase logs queries against the ClickHouse
`logs` table (`logs.all.otel`). Reach for it on any "logs query", "Logs
Explorer", `log_attributes`, `source` filtering (`edge_logs`, `postgres_logs`,
`auth_logs`), BigQuery `unnest(metadata)` conversion, or Studio analytics log
SQL task — even without naming ClickHouse.
---
# Querying Supabase logs (ClickHouse)
@@ -36,21 +33,21 @@ translation table.
Each row has a small set of real columns. Everything specific to a service lives
in `log_attributes`.
| Column | Type | Notes |
| ---------------- | --------------------- | ----------------------------------------------------- |
| `id` | `String` | Unique log identifier. |
| `timestamp` | `DateTime64` (UTC) | When the log was produced. Order/compare it directly. |
| `event_message` | `String` | The raw log line. |
| `severity_text` | `String` | Log level, when the source sets one. |
| `source` | `String` | The service the log came from. Always filter on this. |
| `log_attributes` | `Map(String, String)` | Structured per-source fields, keyed by a dotted path. |
| Column | Type | Notes |
| ---------------- | --------------------- | -------------------------------------------------------------------- |
| `id` | `String` | Unique log identifier. |
| `timestamp` | `DateTime64` (UTC) | When the log was produced. Order/compare it directly. |
| `event_message` | `String` | The raw log line. |
| `severity_text` | `String` | Log level, when the source sets one. |
| `source` | `String` | The service the log came from. Filter on this to scope to a service. |
| `log_attributes` | `Map(String, String)` | Structured per-source fields, keyed by a dotted path. |
`timestamp` is formatted like `2026-06-22T09:34:06.215000` (ISO 8601, microsecond
precision, no trailing `Z`). In the Logs Explorer the selected time range is
applied for you, so you rarely need to write a `timestamp` filter by hand.
A minimal, well-formed query. Lead with a comment naming the query, filter by
`source`, and always `limit`:
`source`, always `limit`, and omit trailing semicolons:
```sql
-- recent edge requests
@@ -58,7 +55,7 @@ select timestamp, event_message
from logs
where source = 'edge_logs'
order by timestamp desc
limit 100;
limit 100
```
## Sources
@@ -128,7 +125,7 @@ from logs
where source = 'postgres_logs'
group by key
order by n desc
limit 100;
limit 100
```
`arrayJoin(mapKeys(...))` flattens the map keys into one row per key so you can
@@ -157,9 +154,9 @@ rejects `count(*)` and `select *` — use `count()` and list the columns you nee
These keep queries correct and cheap. Log tables are large; an unbounded scan
reads far more data than you need.
- **Start every query with an identifying comment** (e.g. `-- errors since last deploy`). It labels the query in logs and review, and makes each of several queries in a file easy to tell apart.
- **Always include a `LIMIT`.** Even for aggregates while you iterate.
- **Always query `from logs where source = '...'`.** There is no per-service table (no `edge_logs`, `postgres_logs`, etc. table) — there is one `logs` table, and `source` scopes it to a service. Filtering by `source` is required, not just an optimization.
- **Start saved or production queries with an identifying comment** (e.g. `-- errors since last deploy`). It labels the query in logs and review, and makes multiple queries in a file easy to tell apart.
- **Always include a `LIMIT`** (even for aggregates while iterating) and omit trailing semicolons (Studio's ClickHouse surface expects no trailing `;`).
- **Scope to a service with `from logs where source = '...'`.** There is no per-service table (no `edge_logs`, `postgres_logs`, etc. table) — filtering by `source` is required for service-scoped correctness, not just performance (omit `source` only for cross-service or single-ID lookups).
- **Keep the time range tight.** A smaller window returns results faster.
- **Filter on the real columns** (`source`, `timestamp`) before reaching into
`log_attributes`.
@@ -222,5 +219,6 @@ per-service table for `from logs where source = ...`, remove every
`cross join unnest(...)`, rewrite unnest-alias columns as `log_attributes['...']`
lookups, swap the functions above) are spelled out with a full before/after in
[references/bigquery-migration.md](references/bigquery-migration.md). The Logs
Explorer also has a built-in **Rewrite to ClickHouse** action that does this with
AI; point users to it for one-off conversions in the dashboard.
Explorer also has a built-in **Rewrite query to ClickHouse SQL** toolbar button
(and **Rewrite with Assistant** banner action) that does this with AI; point
users to it for one-off conversions in the dashboard.
@@ -1,91 +1,55 @@
# Wiring a logs query in the Studio codebase
This covers writing analytics log SQL inside `apps/studio` so it is safe, routed
to the right endpoint, and consistent with the existing OTEL builders. Read this
when you are editing TypeScript that builds or runs a logs query, not when you are
just writing a query in the Logs Explorer UI.
This covers wiring analytics log SQL inside `apps/studio` so it is branded,
routed to the right endpoint, and consistent with existing OTEL builders. Read
this when editing TypeScript that builds or runs a logs query, not when writing
a standalone query in the Logs Explorer UI.
## Branded SQL: never concatenate user input
## Branded SQL & execution boundary
All analytics log SQL must be a `SafeLogSqlFragment`, built with the helpers in
`apps/studio/data/logs/safe-analytics-sql.ts`. Two things enforce this: the
`sql` parameter of `executeAnalyticsSql` (`apps/studio/data/logs/execute-analytics-sql.ts`)
is typed `SafeLogSqlFragment`, and an eslint `no-restricted-syntax` rule in
`apps/studio/eslint.config.cjs` blocks direct `post()`/`get()` calls to the
`logs.all` / `logs.all.otel` endpoints from any file other than
`execute-analytics-sql.ts`. The branding is what keeps interpolated values from
becoming injection. The key
exports:
- `safeSql\`...\``— a tagged template that only accepts`SafeLogSqlFragment`interpolations. Plain strings (and Postgres-branded`SafeSqlFragment`) are
rejected at compile time, so you cannot accidentally drop a raw value in.
- `analyticsLiteral(value)` — turns a string/number/boolean into a safely escaped
literal fragment (single quotes and backslashes are escaped). Use it for every
dynamic value, especially the `source`.
- `joinSqlFragments(fragments, separator)` — joins already-safe fragments with a
fixed structural separator (`' and '`, `', '`, etc.).
- `keyword(value, allowed)` — resolves a value against a compile-time allow-list of
fragments (e.g. an `AND`/`OR` operator). Returns the allow-listed fragment, never
the raw input.
- `quotedIdent(value)` — backtick-quotes a dotted identifier path after validating
each segment.
Compose with `safeSql` plus these helpers. The only way to run SQL that was not
built from them is the user-authored path: `untrustedLogSql(text)` marks editor
text as `UntrustedLogSqlFragment` (displayable, storable, never executable), and
`acceptUntrustedLogsSql(fragment)` promotes it to `SafeLogSqlFragment`. That
promotion is a security boundary — call it only from a run gesture (Run
button click, Cmd+Enter) or an approval-gated tool call (the AI notebook
tools). Never from render, `useEffect`, or any automatic path. The notebook
persist path also promotes cells because the writable notebook type requires
`SafeLogSqlFragment`; that is storage typing, not execution approval, and is
not precedent for promoting anywhere else.
```ts
import { analyticsLiteral, safeSql } from '@/data/logs/safe-analytics-sql'
const source = 'edge_logs'
const sql = safeSql`
select timestamp, event_message
from logs
where source = ${analyticsLiteral(source)}
order by timestamp desc
limit 100
`
```
All analytics log SQL must be a `SafeLogSqlFragment` built with
`apps/studio/data/logs/safe-analytics-sql.ts` and executed through
`executeAnalyticsSql` (`apps/studio/data/logs/execute-analytics-sql.ts`). See
[safe-sql-execution](../../safe-sql-execution/SKILL.md) (Analytics SQL section)
for the complete helper reference (`safeSql`, `analyticsLiteral`, `quotedIdent`,
`keyword`, `joinSqlFragments`), ESLint checks, and `acceptUntrustedLogsSql`
security rules.
## Pick the endpoint and builder by flag
The ClickHouse path is gated by the `otelLegacyLogs` ConfigCat flag
(`useFlag('otelLegacyLogs')` from `common` — ConfigCat, not PostHog). Keep the BigQuery path working when
the flag is off. Two helpers in `apps/studio/data/logs/logs-endpoint.ts` express
the split:
The ClickHouse path is gated by a ConfigCat flag (`useFlag(...)` from `'common'`
— ConfigCat, not PostHog) depending on the surface:
- `logsAllEndpointUrl(useOtel)` — returns the `logs.all.otel` endpoint when
`useOtel`, otherwise the legacy `logs.all` endpoint.
- `pickLogsQueryBuilder(useOtel, otel, bq)` — picks between an OTEL builder and a
BigQuery builder while preserving the type.
- `useFlag('otelLegacyLogs')` — Logs Explorer, Logs Previewer, Single Log, Auth
Logs, SQL Editor Logs, Edge Functions stats
- `useFlag('otelReports')` — report charts under `data/reports/**` and
`routes/project/$ref/observability/**`
- `useUnifiedLogsBackend()` (`otelUnifiedLogs`, defaults `true`) — Unified Logs
Keep the BigQuery path working when the flag is off. Two helpers in
`apps/studio/data/logs/logs-endpoint.ts` keep the endpoint and SQL dialect
paired:
- `logsAllEndpointUrl(useOtel)` — returns `logs.all.otel` when `useOtel`,
otherwise legacy `logs.all`.
- `pickLogsQueryBuilder(useOtel, otel, bq)` — selects the OTEL or BigQuery
builder while preserving the type.
```ts
const useOtel = useFlag('otelLegacyLogs')
import { useFlag } from 'common'
import { LogsTableName } from '@/components/interfaces/Settings/Logs/Logs.constants'
import { genDefaultQuery } from '@/components/interfaces/Settings/Logs/Logs.utils'
import { genDefaultQueryOtel } from '@/components/interfaces/Settings/Logs/Logs.utils.otel'
import { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'
import { logsAllEndpointUrl, pickLogsQueryBuilder } from '@/data/logs/logs-endpoint'
const useOtel = useFlag('otelLegacyLogs') // or 'otelReports' for report charts
const builder = pickLogsQueryBuilder(useOtel, genDefaultQueryOtel, genDefaultQuery)
const endpoint = logsAllEndpointUrl(useOtel)
// include { otel: useOtel } in the React Query key so the two paths cache separately
```
// Include { otel: useOtel } in the React Query key so the two paths cache separately
Run the fragment through `executeAnalyticsSql` (`apps/studio/data/logs/execute-analytics-sql.ts`)
against that endpoint:
```ts
import { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'
import { analyticsLiteral, quotedIdent, safeSql } from '@/data/logs/safe-analytics-sql'
// ✅ GOOD: every interpolation is sanitized.
const sql = safeSql`
SELECT timestamp, event_message
FROM ${quotedIdent(table)}
WHERE id = ${analyticsLiteral(id)}
`
const sql = builder(LogsTableName.EDGE, filters, 100)
await executeAnalyticsSql({
projectRef,
@@ -96,42 +60,40 @@ await executeAnalyticsSql({
})
```
```ts
// 🛑 BAD: raw string interpolation. This fails to type-check at the
// executeAnalyticsSql boundary because the result is `string`, not
// `SafeLogSqlFragment`.
const sql = `SELECT * FROM ${table} WHERE id = '${id}'`
await executeAnalyticsSql({ projectRef, endpoint, sql, iso_timestamp_start, iso_timestamp_end })
```
For OTEL-only queries that intentionally run ClickHouse SQL directly (no
BigQuery fallback), pin `endpoint: logsAllEndpointUrl(true)` (see
`apps/studio/data/logs/otel-log-keys-query.ts`).
## Follow the existing OTEL builders
## Follow the existing OTEL builders & chart migrations
When you need a new query shape, mirror the generators in
`apps/studio/components/interfaces/Settings/Logs/Logs.utils.otel.ts` rather than
inventing a parallel style. They already encode the conventions:
inventing a parallel style:
- `genDefaultQueryOtel`, `genCountQueryOtel`, `genChartQueryOtel`,
`genSingleLogQueryOtel` — the row/count/chart/single-log builders. They select
the real columns plus source-specific `log_attributes[...]` lookups aliased to
the leaf names the renderers expect.
- `mapOtelPreviewRow`, `mapOtelSingleLogToLegacy`, `otelTimestampToMicros` — the
JS normalization layer. `timestamp` must end up a microsecond number for the
pagination cursor and the renderers, so reuse `otelTimestampToMicros` rather
than parsing the ISO string yourself.
`genSingleLogQueryOtel` — row/count/chart/single-log builders selecting real
columns plus source-specific `log_attributes[...]` lookups aliased to the leaf
names renderers expect.
- `mapOtelPreviewRow`, `mapOtelSingleLogToLegacy`, `otelTimestampToMicros` — JS
normalization layer. `timestamp` must end up as a microsecond number for the
pagination cursor and renderers, so reuse `otelTimestampToMicros` rather than
parsing ISO strings by hand.
- **Migrating report charts**: gate report queries with `useFlag('otelReports')`
and verify timestamp units on chart axes. Select companion "Open in Logs
Explorer" deep-link SQL with `useFlag('otelLegacyLogs')` (keeping BigQuery SQL
when `otelLegacyLogs` is off) so reports and Logs Explorer never send the
wrong dialect when the two flags differ.
The map-key discovery hook (`apps/studio/data/logs/otel-log-keys-query.ts`,
`fetchOtelLogKeys` / `useOtelLogKeysQuery`) is the canonical example of a small,
correctly-branded OTEL query — read it before writing a new one.
Read `apps/studio/data/logs/otel-log-keys-query.ts` (`fetchOtelLogKeys` /
`useOtelLogKeysQuery`) as the canonical example of a small, correctly branded
OTEL query.
## Checklist
- [ ] Every dynamic value goes through `analyticsLiteral` (or another sanitizer),
never string concatenation.
- [ ] The query filters by `source` and includes a `LIMIT`.
- [ ] Every dynamic value goes through `safe-analytics-sql.ts` sanitizers (see `safe-sql-execution`), never string concatenation.
- [ ] The query filters by `source` (when scoping to a service) and includes a `LIMIT`.
- [ ] Numeric `log_attributes` values are wrapped in `toInt32OrZero`.
- [ ] The endpoint and builder are chosen with `logsAllEndpointUrl` /
`pickLogsQueryBuilder` off `useFlag('otelLegacyLogs')`.
- [ ] The React Query key distinguishes the OTEL and BigQuery paths.
- [ ] `timestamp` is normalized to micros for any row consumed by the table/cursor.
- [ ] There is a unit test asserting the generated SQL string (see
`Logs.utils.otel.test.ts` and `safe-analytics-sql.test.ts` for the pattern).
- [ ] Endpoint and builder stay paired via `logsAllEndpointUrl` / `pickLogsQueryBuilder` off the surface's ConfigCat flag (`otelLegacyLogs` or `otelReports`), or `logsAllEndpointUrl(true)` for OTEL-only queries.
- [ ] The React Query key distinguishes OTEL and BigQuery paths.
- [ ] `timestamp` is normalized to micros for table/cursor rows, and migrated report charts verify axis timestamp units plus companion "Open in Logs Explorer" SQL gated on `useFlag('otelLegacyLogs')`.
- [ ] Unit tests assert the generated SQL string (see `Logs.utils.otel.test.ts` and `safe-analytics-sql.test.ts`).
+5 -3
View File
@@ -31,19 +31,21 @@ Flag scattered special cases, duplicate domain contracts, pass-through abstracti
Keep transformations and business rules independently understandable without extracting every expression from a component. Follow domain-specific composition conventions where they apply.
Prefer self-explanatory names and structure. Avoid comments that restate the code or narrate change history; history belongs in commits and PRs. Preserve domain-required annotations and semantic tooling directives.
Prefer self-explanatory names and structure. Avoid comments that restate the code, narrate change/mock history, contain LLM scratchpad reasoning, or reference private repository paths/symbols or internal teammate names; history belongs in commits and PRs. Preserve domain-required annotations, brief comments explaining non-obvious invariants, and semantic tooling directives.
## Meaningful coverage
For Studio, follow [studio-testing](../studio-testing/SKILL.md) for test selection and location, [studio-mock-api-tests](../studio-mock-api-tests/SKILL.md) for network-backed component tests, and [studio-e2e-tests](../studio-e2e-tests/SKILL.md) for E2E execution. Use [vitest](../vitest/SKILL.md) for runner details. For docs, follow [review-the-docs](../review-the-docs/SKILL.md) and use [test-the-docs](../test-the-docs/SKILL.md) when runnable snippets need verification.
For Studio, follow [studio-testing](../studio-testing/SKILL.md) for test selection, quality gates, location, and MSW component tests, and [studio-e2e-tests](../studio-e2e-tests/SKILL.md) for E2E execution. For docs, follow [review-the-docs](../review-the-docs/SKILL.md) and use [test-the-docs](../test-the-docs/SKILL.md) when runnable snippets need verification.
Each new test should protect a meaningful behavior or plausible regression. Prefer observable outcomes and representative failures over private state, DOM structure, class names, or whole-tree snapshots. Reuse real definitions and existing fixtures when suitable, while keeping expected outcomes independent of the implementation's calculation.
Actively recommend deleting low-value filler tests rather than keeping them for coverage. Flag any added test that fails these kill criteria: (1) **Static-Analysis** — `typecheck`, ESLint, Knip, or OpenAPI types already enforce it; (2) **Concrete-Regression** — cannot name a realistic runtime bug that would ship unnoticed; (3) **Mirror/Tautology** — restates literals/schemas, echoes configured mocks, or asserts a test-hardcoded flag like `enabled: false`; (4) **No-Deformation** — adds unused production props, parameters, or exports solely as test seams.
Inspect changed tests and nearby coverage for duplicates, assertions that cannot fail, unawaited async checks, and mocks that replace the integration being verified. Preserve distinct boundary, error, historical-data, and safety cases. Rewrite brittle coverage around the meaningful contract before removing its only assertion. Do not add tests solely for static configuration, type guarantees, framework internals, or coverage percentages.
## Verification evidence
Choose formatting, lint, typecheck, build, and test commands from the affected package's actual scripts and CI configuration. Check changed files with the repository's Prettier configuration. Do not assume an unscoped root `tsc` validates every package. Record commands, scope, and outcomes; distinguish checks run personally from CI results and author claims.
Choose formatting, lint, typecheck, build, and test commands from the affected package's actual scripts and CI configuration. Check changed files with the repository's formatter (`pnpm format:check`, powered by oxfmt, which covers `{apps,packages,blocks,i18n}/**/*.{js,jsx,ts,tsx,css,md,mdx,json}`); for changed files outside that glob (such as `.agents/**`, `e2e/**`, `.github/**`, or root files), run `pnpm exec oxfmt --check <paths...>` explicitly. Do not assume an unscoped root `tsc` validates every package. Record commands, scope, and outcomes; distinguish checks run personally from CI results and author claims.
In readiness mode for executable behavior:
+18 -2
View File
@@ -1,8 +1,24 @@
---
name: copywriting
description: Write or audit UI copy (buttons, labels, empty states, error messages, tooltips, form text) anywhere in the monorepo. Load it before shipping or reviewing any user-facing text — including when copy is incidental to the task, like a new feature that adds buttons, toasts, dialogs, or validation messages.
description: Write or audit UI copy (buttons, labels, empty states, error messages, tooltips, form text) anywhere in the monorepo. Load before shipping or reviewing any user-facing text, including incidental buttons, toasts, dialogs, or validation messages.
---
# Copywriting
Source of truth: `apps/design-system/content/docs/copywriting.mdx`. Read it before writing or auditing any UI copy — it covers voice and tone, buttons, error messages, empty states, and confirmation dialogs with good/bad examples.
Source of truth: `apps/design-system/content/docs/copywriting.mdx`. Read it before writing or auditing UI copy. It covers voice and tone, buttons, error messages, empty states, confirmation dialogs, and capitalization (sentence case, title case, proper nouns).
## Microcopy principles
Apply these four checks to every string you ship:
1. **Situated to the current screen and known state**: Omit words already provided by surrounding headers, labels, or dialog context. When the current state is known, write the single direct statement instead of branching (`"If running: X. If stopped: Y."`). Avoid device- or layout-bound references (`"Hover over…"`, `"above"`).
2. **Plain user product language**: Describe outcomes in the user's terms. Never expose backend parameter names, HTTP status codes, implementation-history framing (`"Legacy behavior"`), or robotic status phrasing (`"Start requested"` → `"Starting…"`).
3. **Actionable self-serve next steps**: Give every warning, error, gated, or unavailable state a concrete next step or link. Avoid dead ends and do not make `"contact support"` the primary CTA when a self-serve action exists.
4. **Cross-surface lexical consistency**: Use identical action verbs across triggers, tooltips, confirmation dialogs, empty states, and toasts. Gate copy behind the same feature flags as the UI so disabled capabilities are never mentioned.
## Studio house rules
- **No solo em dashes (`—`)**: Split into separate sentences with a period.
- **Drop the `"Supabase"` prefix inside Studio**: Write `"Storage"`, `"Auth"`, or `"Pipelines"`, not `"Supabase Storage"`.
- **Surface naming**: Lowercase `"dashboard"`. Use `"branch"` instead of `"project"` on settings pages when viewing a branch.
- **E2E check**: When changing visible copy, grep `e2e/studio/` for the old string.
+7 -8
View File
@@ -17,12 +17,12 @@ allows feature flag overrides in local and staging environments only.
PRs modifying any of these paths need growth eng review:
- `packages/dev-tools/**` (owned by `@supabase/growth-eng` in CODEOWNERS)
- `packages/common/posthog-client.ts` (flag override reads, event subscription)
- `packages/common/posthog-client.ts` (owned by `@supabase/growth-eng` in CODEOWNERS; flag override reads, event subscription)
- `packages/common/feature-flags.tsx` (flag override merge logic)
- App-level mounting: `DevToolbarProvider`/`DevToolbar`/`DevToolbarTrigger` in `apps/studio/`, `apps/www/`, `apps/docs/`
Note: `posthog-client.ts` and `feature-flags.tsx` are NOT in CODEOWNERS for growth-eng,
so PRs touching only those files won't auto-request review. Watch for these in the PR feed.
Note: `packages/common/feature-flags.tsx` is NOT in CODEOWNERS for `@supabase/growth-eng`,
so PRs touching only that file won't auto-request review. Watch for these in the PR feed.
## Review Checklist
@@ -58,8 +58,8 @@ These are read by:
**Check for:**
- Cookie name changes (must stay in sync across writer and all readers)
- Changes to the merge/precedence logic in `feature-flags.tsx` (currently: `vercel-flag-overrides` first, then `x-cc-flag-overrides` takes precedence in local dev)
- Override cookies being read outside the `IS_LOCAL_DEV` / `isLocalDev` guard — overrides must never affect production flag evaluation
- Changes to the merge/precedence logic in `feature-flags.tsx` (currently: `vercel-flag-overrides` first, then `x-cc-flag-overrides` takes precedence when `isDevToolsEnabled` is true in `local` or `staging`)
- Override cookies being read outside their environment guards (`isDevToolsEnabled` in `feature-flags.tsx` for `local`/`staging`; `process.env.NODE_ENV === 'development'` in `posthog-client.ts:getFeatureFlag()`) — overrides must never affect production flag evaluation
- Changes to `parseOverrideValue` or `valuesAreEqual` in `packages/dev-tools/utils.ts` that could cause type coercion bugs
### 3. Telemetry Event Subscription
@@ -94,13 +94,12 @@ server-side telemetry. Uses exponential backoff on connection errors.
**Provider + toolbar panel** (`DevToolbarProvider`, `DevToolbar`):
- `apps/studio/routes/__root.tsx`
- `apps/studio/routes/__root.tsx` (also mounts `DevToolbarTrigger`)
- `apps/www/pages/_app.tsx`, `apps/www/app/providers.tsx`
- `apps/docs/features/app.providers.tsx`
**Trigger button** (`DevToolbarTrigger`) — rendered separately in nav/header components:
**Trigger button** (`DevToolbarTrigger`) — rendered separately in nav/header components for `www` and `docs`:
- `apps/studio/components/layouts/Navigation/LayoutHeader/LayoutHeader.tsx`
- `apps/www/components/Nav/index.tsx`
- `apps/docs/components/Navigation/NavigationMenu/TopNavBar.tsx`
+53 -185
View File
@@ -1,33 +1,21 @@
---
name: react-hook-form
description: Correct React Hook Form usage anywhere in the monorepo — data flow, subscriptions,
reset, dirty state, number inputs, and controlled-input rules. Load this BEFORE
writing or modifying ANY form code, adding a field to an existing form, touching
watch/useWatch/formState/getValues/setValue/reset, wiring a form into a dialog or
sheet, or building a submit/cancel footer — even when the change looks trivial.
The codebase contains widespread RHF anti-patterns; without this skill you will
copy them. For form layout and which components to use, also load
description: Correct React Hook Form usage across the monorepo — data flow, subscriptions,
reset, dirty state, number inputs, and controlled-input rules. Load before writing or
editing any form, field, watch/useWatch/formState/getValues/setValue/reset, or
submit/cancel footer; older files contain anti-patterns. For layout and components, see
studio-ui-patterns.
---
# React Hook Form
How to write forms that stay correct as they grow. The existing codebase is **not**
a safe reference: `form.watch()` off prop-drilled form objects, subscription-only
watches, unguarded `valueAsNumber`, and `?? undefined` controlled values are all
common in older code and all wrong. Follow this skill, not the neighboring file.
The existing codebase is **not** a safe reference: `form.watch()` off prop-drilled form objects, subscription-only watches, unguarded `valueAsNumber`, and `?? undefined` controlled values are common in older code and all wrong. Follow this skill, not the neighboring file.
**Policy — fix what you touch.** New code must follow these rules. When you modify
existing form code, upgrade the specific fields/hooks/components you're editing to
match (e.g. a component you touch that calls `form.watch` gets converted to
`useWatch`). Leave untouched code alone, but tell the user about anti-patterns you
noticed and didn't fix. Never add new violations: `react-hook-form/no-use-watch`
is ratcheted in Studio CI — any increase in the warning count fails the build.
**Policy — fix what you touch.** New code must follow these rules. When modifying existing form code, upgrade the specific fields/hooks/components you touch (e.g. convert `form.watch` to `useWatch`). Leave untouched code alone, but mention anti-patterns you noticed. Never add new violations: `react-hook-form/no-use-watch` is an ESLint `error` in Studio CI.
## Mental model: subscriptions decide who re-renders
RHF is uncontrolled at heart. Values live in refs; nothing re-renders unless a
subscription says so. Every read API is a subscription decision:
RHF is uncontrolled at heart. Values live in refs; nothing re-renders unless a subscription says so. Every read API is a subscription decision:
| API | Subscribes | Re-renders | Use for |
| ----------------------------- | ---------- | -------------------------- | ---------------------------------------------- |
@@ -38,69 +26,38 @@ subscription says so. Every read API is a subscription decision:
| `getValues()` | no | never | event handlers and `onSubmit` only |
| `subscribe()` | callback | none | side effects outside render |
Two facts explain most of the bugs we've shipped:
Two facts explain most form bugs:
1. **`form.watch()` and `form.formState` hoist their subscription to the `useForm`
owner**, no matter which component calls them. A child that reads
`form.watch('x')` off a prop works today only because the whole tree re-renders
on every change — it silently goes stale the moment anyone adds `React.memo`
between owner and child, and until then it re-renders every sibling on every
keystroke. A no-arg `form.watch()` sets `watchAll` and re-renders the tree on
every field change for the life of the form.
2. **`formState` is a Proxy** — reading a property is what arms the subscription.
Destructure it (`const { isDirty } = form.formState`), never pass the object
around or read it conditionally (`a && formState.isValid` may never subscribe).
Enforced by `react-hook-form/destructuring-formstate` (error).
1. **`form.watch()` and `form.formState` hoist their subscription to the `useForm` owner**, no matter where they are called. A child calling `form.watch('x')` off a prop works only by re-rendering the entire tree on every keystroke and silently goes stale behind `React.memo`. A no-arg `form.watch()` re-renders the whole tree on every field change.
2. **`formState` is a Proxy** — reading a property arms the subscription. Destructure it (`const { isDirty } = form.formState`), never pass the object around or read it conditionally (`a && formState.isValid` may never subscribe). Enforced by `react-hook-form/destructuring-formstate` (error).
### Reading values, by location
- **In the component that owns `useForm`:** destructure `formState`; prefer
`useWatch` over `form.watch` even here (the `no-use-watch` rule flags every
`watch`, and `useWatch` scopes the re-render if the JSX is later extracted).
- **In any child component or custom hook:** accept `control` (not the whole
`form`) and use `useWatch({ control, name })` / `useFormState({ control })`.
Inside `<Form {...form}>` (which _is_ `FormProvider`), `useFormContext()` +
`useWatch({ name })` also works and avoids prop-drilling entirely.
- **Consume the return value.** Never call a watch for its subscription side
effect and then read via `getValues()` — the watch list and the read list will
drift apart (it has already happened; fields silently lost reactivity). The
value you render must _be_ the value you subscribed to.
- **One read path per value per render.** Mixing `useWatch('x')` on one line and
`getValues('x')` a few lines later lets the two disagree within a single render.
- **Name what you watch.** `useWatch({ control })` with no `name` re-renders on
every keystroke in every field. Subscribe to the specific names you use.
- `watch(callback)` is deprecated — use `subscribe()` for render-free listeners,
and always return its cleanup from `useEffect`.
- **In the `useForm` owner:** destructure `formState`; use `useWatch` over `form.watch` (`no-use-watch` flags every `watch`, and `useWatch` scopes re-renders if extracted later).
- **In any child component or custom hook:** pass `control` (not `form`) and use `useWatch({ control, name })` / `useFormState({ control })`, or read via `useFormContext()` + `useWatch({ name })` inside `<Form {...form}>`.
- **Consume the return value & use one read path per render:** never call a watch only for its subscription and read via `getValues()` — the two lists drift and disagree within a render. Always pass `name` to `useWatch` so you don't subscribe to every field.
- **`watch(callback)` is deprecated:** use `subscribe()` for render-free listeners and return its cleanup from `useEffect`.
```tsx
// ❌ common in the codebase — all three subscriptions hoist to the form owner
// ❌ subscriptions hoist to the form owner and read paths drift
function Fields({ form }: { form: UseFormReturn<FormValues> }) {
form.watch(['storageType', 'totalSize']) // return value discarded
const { errors } = form.formState // prop-form formState
const size = form.getValues('totalSize') // non-reactive read in render
...
form.watch(['storageType', 'totalSize'])
const { errors } = form.formState
const size = form.getValues('totalSize')
}
// ✅ child subscribes for itself and consumes what it watches
function Fields({ control }: { control: Control<FormValues> }) {
const [storageType, totalSize] = useWatch({ control, name: ['storageType', 'totalSize'] })
const { errors } = useFormState({ control })
...
}
```
## The canonical form
zod schema → `z.infer` type → `useForm` with `zodResolver` and **complete**
`defaultValues` → `<Form {...form}>` → `FormField` render-prop per field →
`FormItemLayout` → `FormControl` → primitive from `ui`. Layout/container choices
(Card vs Sheet, `layout=` variants) are covered by the `studio-ui-patterns` skill
and the demos in `apps/design-system/registry/default/example/`
(`form-patterns-pagelayout.tsx`, `form-patterns-sidepanel.tsx`) — check them
before inventing structure.
zod schema → `z.infer` type → `useForm` with `zodResolver` and **complete** `defaultValues` → `<Form {...form}>` → `FormField` → `FormItemLayout` → `FormControl` → primitive from `'ui'`. For Card vs Sheet layout and demos, see `studio-ui-patterns`.
```tsx
// Module level — static references, not recreated on every render
const FORM_ID = 'pool-config-form'
const FormSchema = z.object({
@@ -110,14 +67,10 @@ const FormSchema = z.object({
.refine((v) => v !== '', 'Max connections is required'),
})
type FormValues = z.infer<typeof FormSchema>
const defaultValues: FormValues = { name: '', maxConnections: '' }
// Inside the component
const form = useForm<FormValues>({
resolver: zodResolver(FormSchema),
defaultValues,
})
const form = useForm<FormValues>({ resolver: zodResolver(FormSchema), defaultValues })
<Form {...form}>
<form id={FORM_ID} onSubmit={form.handleSubmit(onSubmit)}>
@@ -136,90 +89,34 @@ const form = useForm<FormValues>({
</Form>
```
Define the schema, `type`, static `defaultValues`, and the form's id at module
level, outside the component. Rebuilding them per render is wasted work and
unstable references — RHF reads `defaultValues` only on the first render, but
anything else comparing against these objects sees a fresh identity each time.
When they genuinely depend on runtime data, build the schema with `useMemo` and
feed server-driven defaults through the `values` option (next section) instead
of hoisting.
- **Module-level statics:** define the schema, `type`, static `defaultValues`, and singleton `FORM_ID` at module level so references stay stable. Only build a schema in `useMemo` when validation rules genuinely depend on runtime data; feed server-driven defaults via `values` (next section). Put input validation in the Zod schema so every input path (typing, paste, drag-and-drop) shares one contract.
- **External submit buttons:** use `form={FORM_ID}` for singleton forms; if the form can mount multiple instances at once, mint a per-instance id with `useId()` and share it between `<form>` and its buttons.
- **`FormItemLayout` + `<FormControl>` auto-ID contract:**
- Never pass manual `id` props to `<FormItemLayout>` or its child input — `FormItem`/`FormLabel`/`FormControl` auto-bind `formItemId`.
- Wrap the single input control directly in `<FormControl>` (no layout `<div>` inside, which steals `id` and breaks label association). When a `FormItemLayout` renders multiple controls, give each additional control its own accessible label/`aria-label`.
- Do not add redundant `aria-label` to controls already bound through `<FormItemLayout>` + `<FormControl>`.
Submit buttons living outside the `<form>` (sheet/dialog footers) use the same
module-level `FORM_ID` via `form={FORM_ID}` on the button. A module-level id is
only safe for singleton forms — if the component can mount more than once at a
time, duplicate ids make external buttons submit the first matching form, so
mint a per-instance id with `useId()` and share it between the `<form>` and its
buttons.
## `defaultValues`, server data, and `reset`
## defaultValues, server data, and reset
- **Provide a complete `defaultValues` object — every field, no `undefined`.**
`isDirty`, `dirtyFields`, and Cancel-reset all compare against it; a missing or
`undefined` default breaks all three, and `undefined` also makes React treat the
input as uncontrolled (see below).
- **Form populated from an API? Use the `values` option, not a hand-rolled
effect.** `values` reacts to the query resolving and resets the form for you;
computing `defaultValues` from a query that may not have loaded freezes whatever
happened to be in cache at mount. Add
`resetOptions: { keepDirtyValues: true }` when a background refetch must not
clobber the user's in-progress edits. `keepDirtyValues` preserves whatever is
in `formState.dirtyFields`; typed edits and `setValue(…, { shouldDirty: true })`
populate it regardless of subscriptions, but `useFieldArray` operations
(append/remove/move) only mark fields dirty while `dirtyFields` or `isDirty`
is subscribed — so a form that combines `keepDirtyValues` with a field array
must read one of them in the owner, or the next refetch will discard array
edits. (Good examples:
`components/interfaces/Settings/Database/ConnectionLogging.tsx`,
`components/interfaces/Storage/FilesBuckets/EditBucketModal.tsx`.)
- **After a successful mutation, re-baseline the form** in `onSuccess` so the
saved state becomes the new baseline (`isDirty` returns to false, Cancel now
reverts to the saved values). Prefer what the server actually persisted: if the
form uses `values` and the mutation invalidates the query, the refetch handles
this for you; if the mutation returns the updated resource, `reset(response)`.
`reset(submittedValues)` is the fallback for APIs that store exactly what was
sent — if the server normalizes or fills values, it baselines the form to data
that was never saved. A bare `reset()` reverts to the _previous_ defaults —
wrong after a save.
- Cancel buttons call `form.reset()`. This only visually restores fields whose
values round-trip through defined, controlled values — which is why the null
rules below matter.
- **Provide complete `defaultValues` (every field, no `undefined`).** `isDirty`, `dirtyFields`, and Cancel-reset all compare against it; missing or `undefined` defaults break all three and make React treat inputs as uncontrolled.
- **Server-populated forms: use `values`, not a `useEffect`.** `values` reacts when the query resolves; computing `defaultValues` from an unloaded query freezes whatever was cached at mount. Add `resetOptions: { keepDirtyValues: true }` when background refetches must not clobber edits — **note that `resetOptions` is inherited by every `reset()` call** (including `values` updates, `reset(response)`, and bare `form.reset()`), so any intentional reset that must replace or discard dirty edits (post-save or Cancel) must explicitly pass `{ keepDirtyValues: false }`. For `useFieldArray`, destructure `dirtyFields` from `form.formState` in the owner (`isDirty` alone does not populate `dirtyFields`). (Example: `components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx`.)
- **Re-baseline after a successful mutation** in `onSuccess` so `isDirty` clears and Cancel reverts to saved values. Disable edits while saving ([Disabling and gating](#disabling-and-gating)), then call `form.reset(response, { keepDirtyValues: false })` using persisted server data (falling back to `submittedValues` only when the server stores values verbatim — a bare `reset()` reverts to _previous_ defaults). Don't rely on `values` query invalidation alone: if the server normalizes input back to the previously loaded value (e.g. `" A "` → `"A"`), RHF deep-compares `values` and skips the reset.
- **Cancel & modal hygiene:** Cancel calls `form.reset()` — or `form.reset(undefined, { keepDirtyValues: false })` when `keepDirtyValues: true` is configured (the explicit `undefined` 1st argument is required when passing options). Never stack multiple `useEffect`s calling `form.reset()`, and reset form state cleanly when dialogs/sheets close or reopen so previous submissions don't leak.
## Controlled inputs: never let `value` flip to `undefined`
React decides controlled vs uncontrolled per render from whether `value` is
defined. A field whose value can be `undefined` (or becomes `undefined` on reset)
flips modes: console warnings, and — worse — `reset()` stops clearing the visible
text because React abandoned the DOM value. `value={field.value ?? undefined}` is
a bug, not a fix.
React decides controlled vs uncontrolled per render from whether `value` is defined. Letting `value` become `undefined` (including on `reset()`) triggers console warnings and stops `reset()` from clearing DOM text. `value={field.value ?? undefined}` is a bug, not a fix.
- Text fields: default to `''`, never `null`/`undefined`.
- **Normalize `null` from the API at the form boundary** (`growthPercent ?? ''`
when building defaults) and convert back on submit (`'' → null`). Do not paper
over a `null` default with a `placeholder` that looks like a value: the user
sees "50", the form holds `null`, and every downstream comparison
(`defaultValues.growthPercent !== watched` → `null !== 50`) reports a permanent
phantom change while Cancel silently fails to reset the field.
- Selects/radios: default to `''` or a real option value; checkboxes/switches to
`false`.
- Default text fields to `''`, selects/radios to `''` or a real option, and checkboxes/switches to `false`.
- **Normalize `null` at the form boundary** (`growthPercent ?? ''` inbound, `'' → null` on submit). Never paper over a `null` default with a value-like `placeholder` — it causes permanent phantom diffs and broken Cancel resets.
## Number inputs
The blessed pattern keeps `''` as the "empty" sentinel so the input stays
controlled, and lets zod coerce on validation (see `maxConnections` above):
`z.union([z.literal(''), z.coerce.number()...]).refine((v) => v !== '', '…')`
with a plain `<Input {...field} type="number" />`.
Keep `''` as the empty sentinel so the input stays controlled and let zod coerce on validation (`z.union([z.literal(''), z.coerce.number()...]).refine((v) => v !== '', '…')` with `<Input {...field} type="number" />`).
If you instead wire `onChange` through `e.target.valueAsNumber` (or
`valueAsNumber: true`), an empty or partially-typed input produces `NaN`, which
lands in form state and propagates into every calculation, price preview, and
`value` attribute downstream. Guard it with the **same empty sentinel the
field's schema declares** — with the `''`-union schema above:
`field.onChange(Number.isNaN(e.target.valueAsNumber) ? '' : e.target.valueAsNumber)`.
Never let `NaN` into form state.
Avoid `register(name, { valueAsNumber: true })` (RHF converts `''` to `NaN` internally and cannot be guarded inline) — use `setValueAs` on `register`, or guard `e.target.valueAsNumber` inside controlled `field.onChange`: `field.onChange(Number.isNaN(e.target.valueAsNumber) ? '' : e.target.valueAsNumber)`.
A nullable API field (`null` = "unset", e.g. a platform default applies)
doesn't change the in-form sentinel — keep `''` inside the form and convert at
the boundaries:
For nullable API fields (`null` = unset), keep `''` inside the form and convert at the boundaries:
```tsx
// inbound: null → '' when building defaults/values
@@ -230,61 +127,32 @@ growthPercent: z.union([z.literal(''), z.coerce.number().gte(10).lte(100)]),
mutate({ growth_percent: values.growthPercent === '' ? null : values.growthPercent })
```
If `null` does end up in form state (some existing forms hold it), keep it out
of both the input and the coercion: render via `value={field.value ?? ''}`, and
don't pass the value through `z.coerce.number()` — `Number(null)` is `0`, so a
nullable field fed into the coercing union silently validates empty as `0`.
Either way it's one sentinel per field, used consistently across defaults,
schema, `onChange`, rendering, and the submit mapping.
If legacy form state holds `null`, render via `value={field.value ?? ''}` and never pass it through `z.coerce.number()` (`Number(null)` silently validates as `0`). Use one consistent sentinel per field across defaults, schema, `onChange`, rendering, and submit.
## Dirty state and change detection
- Gate Save on `isDirty`; show Cancel only when dirty. In the owner, destructure
from `form.formState`; anywhere else, `useFormState({ control })`.
- When the form lives in a Sheet or Dialog, also wire dirty dismissal:
`useConfirmOnClose` + `DiscardChangesConfirmationDialog`. Route Cancel,
Escape, and backdrop through the guard; call the raw `onClose` on successful
submit so you do not prompt after save. Details:
`apps/design-system/content/docs/ui-patterns/modality.mdx` (Dirty form
dismissal) and the studio-ui-patterns skill Sheets section.
- To show _which_ fields changed (review/summary dialogs), read `dirtyFields`
from the same subscription instead of hand-comparing
`defaultValues.x !== watchedX`. RHF already does that comparison correctly;
hand-rolled versions break on the null-vs-placeholder mismatch and must be
kept in sync with the watch list by hand.
- `setValue` outside user input needs explicit flags:
`setValue('x', v, { shouldDirty: true, shouldValidate: true })` — otherwise the
change is invisible to `isDirty` and validation.
- Gate Save on `isDirty` and show Cancel only when dirty (destructured from `form.formState` in the owner, or via `useFormState({ control })` elsewhere).
- For forms in a Sheet or Dialog, wire dirty dismissal via `useConfirmOnClose` + `DiscardChangesConfirmationDialog` and call raw `onClose` on save (see `studio-ui-patterns` and `apps/design-system/content/docs/ui-patterns/modality.mdx`).
- Read `dirtyFields` from the same subscription to show _which_ fields changed instead of hand-comparing `defaultValues.x !== watchedX`.
- Pass explicit flags to programmatic `setValue`: `setValue('x', v, { shouldDirty: true, shouldValidate: true })`.
## Disabling and gating
If a field must not be edited (plan tier, permissions, cooldown), disable the
field itself — a notice next to an editable input gates nothing. Wire the same
condition into both the notice and the control. Permission checks come from
`useAsyncCheckPermissions`; disabled buttons that need an explanation use
`ButtonTooltip`.
When a field cannot be edited (plan tier, permissions via `useAsyncCheckPermissions`, cooldown) or while submitting/saving (`isSaving = isSubmitting || isPending`, covering both async validation and mutations), disable the control (and any related add/remove/cancel actions) with the same condition as the notice; use `ButtonTooltip` for disabled buttons needing explanation. Combine conditions on each control (`disabled={!canEdit || isSaving}`), or wrap native form controls in `<fieldset disabled={isSaving}>` (gating external footer buttons separately) so per-control disabled states stay intact.
Caution: `register`/`useController` `disabled: true` removes the field's value
from submission data. For "visible but locked" fields whose value must survive
submit, use the input's own `disabled`/`readOnly` prop (as `FormField` +
primitive props do) rather than RHF-level disabling, or the form-level
`disabled` option to freeze everything during async work.
Caution: `register`/`useController` `disabled: true` omits the field's value from submission data, so pass `disabled` to the input primitive (or `readOnly` on text inputs) whenever a locked value must survive submit. Avoid `useForm({ disabled })` when any control relies on a primitive-only `disabled` prop — RHF writes `ref.disabled = field._f.disabled || formDisabled` onto registered refs (and sets `field.disabled` in `FormField`), so `disabled: false` can re-enable a permission-locked input.
## Submit and mutations
`onSubmit` receives validated, typed data — trust it; don't re-read via
`getValues()`. Mutations follow Studio conventions: `onSuccess` → `toast.success`
- `reset(values)` (or query invalidation when using `values:`), `onError` →
`toast.error`; pass the mutation's `isPending` to the button's `loading` prop.
Default validation `mode: 'onSubmit'` is right for most forms — pick another mode
deliberately, not by copying.
- Use `type="submit"` on submit buttons (never `onClick={() => onSubmit()}`) so native submission and Enter-key behavior work, and ensure every validation failure surfaces a visible error.
- Trust the validated, typed data passed to `onSubmit` (don't re-read via `getValues()`). Follow Studio mutation conventions: `onSuccess` → `toast.success` + re-baseline `form.reset(...)` (above), and pass `isSubmitting || isPending` to the submit button's `loading` prop. Studio mutation hooks already emit a default `toast.error` when `onError` is omitted — keep error handling in a single layer: omit `onError` to use the default toast, or pass a hook-level `onError` whenever the call site owns error handling itself (inline or via `mutateAsync` + `catch`, see `studio-queries`).
- Keep default `mode: 'onSubmit'` unless you have a deliberate reason to validate earlier.
## Lint rules in force (Studio)
| Rule | Level | Meaning |
| ------------------------------------------- | ---------------- | ------------------------------------------------ |
| `react-hook-form/destructuring-formstate` | error | destructure `formState`, never hold the object |
| `react-hook-form/no-access-control` | error | don't reach into `control` internals |
| `react-hook-form/no-nested-object-setvalue` | error | `setValue('a.b', v)`, not `setValue('a', {b:v})` |
| `react-hook-form/no-use-watch` | warn (ratcheted) | use `useWatch`, not `watch` |
| Rule | Level | Meaning |
| ------------------------------------------- | ----- | ------------------------------------------------ |
| `react-hook-form/destructuring-formstate` | error | destructure `formState`, never hold the object |
| `react-hook-form/no-access-control` | error | don't reach into `control` internals |
| `react-hook-form/no-nested-object-setvalue` | error | `setValue('a.b', v)`, not `setValue('a', {b:v})` |
| `react-hook-form/no-use-watch` | error | use `useWatch`, not `watch` |
+113 -389
View File
@@ -1,462 +1,186 @@
---
name: safe-sql-execution
description: >-
Use whenever code will build, return, fetch, or execute SQL that runs against
a user's real Postgres database — even when the request reads like an ordinary
feature or bug fix and never says "security," "injection," or
"SafeSqlFragment." This covers: writing or editing any pg-meta function, query
builder, or endpoint that builds/returns SQL for database objects (tables,
views, functions, DB triggers, indexes, RLS policies); interpolating a
schema/table/column/search/route-param value into SQL text; storing, fetching,
or re-running SQL that round-trips from the database (a policy's definition, a
function/view definition, a snippet's saved content); and any
"Run"/"Apply"/"Execute" action that sends SQL to a project's database (SQL
editor run-selection, policy editor apply, snippet runner). Load this BEFORE
writing such code, not only when reviewing a finished diff. Skip only for
changes that never touch SQL text or execution — styling, unrelated data
hooks, non-SQL form validation, or UI layout work.
Provenance-tracked SQL execution rules for Postgres (SafeSqlFragment via
pg-meta) and Analytics/Logs (SafeLogSqlFragment via safe-analytics-sql). Load
BEFORE writing or editing any SQL query builder, pg-meta helper, tables/views/
functions/triggers/indexes/RLS policy SQL, interpolated schema/table/column/
search/route params, round-tripped DB/snippet SQL, or Run/Apply/Execute SQL
action (executeSql / executeAnalyticsSql) — even when the task never mentions
security or SafeSqlFragment.
---
# Safe SQL execution
# Safe SQL Execution
Supabase Studio executes SQL statements directly against the user's database.
Because this is the authenticated user's own database, our security model is
different from most frontend applications: a user should be able to execute any
SQL statement, as long as it is proven that they themselves authored it. What
we SHOULD NOT ALLOW is execution of SQL statements that can be influenced by an
attacker, such as through URL parameters.
Studio runs SQL directly against the authenticated user's Postgres database and analytics logs. Our security model is **proven authorship**: users may run any SQL they explicitly authored or that is hardcoded in the app, but SQL influenced by external input (URL params, LLM output, auto-saved snippets) must never execute without sanitization or an explicit user run gesture.
## Security model
Two intentionally **disjoint** branded type systems enforce this at compile time:
The security model for SQL execution in Supabase Studio is based on the
principle of "proven authorship". This means that a user should only be able to
execute SQL statements that they have explicitly authored, and not statements
that can be influenced by external input.
- **Postgres SQL**: `SafeSqlFragment` from `@supabase/pg-meta` → `executeSql` (`apps/studio/data/sql/execute-sql-mutation.ts`)
- **Analytics / Logs SQL**: `SafeLogSqlFragment` from `apps/studio/data/logs/safe-analytics-sql.ts` → `executeAnalyticsSql` (`apps/studio/data/logs/execute-analytics-sql.ts`)
There are three classes of SQL fragments:
---
1. Hardcoded within the application code. These are safe to execute because
they cannot be influenced by an attacker. They can be marked with the
`safeSql` utility with `pg-meta`:
## Postgres SQL (`@supabase/pg-meta`)
```ts
import { safeSql } from '@supabase/pg-meta'
### Branded types & provenance rules
const sql = safeSql`
SELECT *
FROM users
WHERE id = 1
`
```
- `SafeSqlFragment`: safe to execute (hardcoded via `safeSql`, sanitized via `ident`/`literal`/`keyword`, or user-authored via `SafeSqlInput` / `acceptUntrustedSql`). `executeSql` rejects plain `string` and `UntrustedSqlFragment` at compile time.
- `WriteSqlFragment` (`asWriteSql`): subtype of `SafeSqlFragment` propagated through `safeSql` and `joinSqlFragments`; `executeSql` requires a write grant (or `Unguarded`) to run it.
- `UntrustedSqlFragment`: externally influenceable SQL (URL params, LLM output, saved snippets), marked with `untrustedSql(raw)`.
- `DisplayableSqlFragment`: union `SafeSqlFragment | UntrustedSqlFragment` — safe to display in the UI, not to execute.
- **Never cast `as SafeSqlFragment`** — even redundantly on a `safeSql` template literal (which already returns `SafeSqlFragment`). Assertions bypass provenance tracking; the sole narrow exception is promoting catalog definitions directly inside a data fetcher (below).
`safeSql` automatically creates a string of the branded type
`SafeSqlFragment`. (See Provenance Tracking below.)
### Building safe fragments
2. Third-party influenceable. These are SQL fragments that can be influenced
by an attacker, such as through URL parameters or LLM output. These should
be marked with the `untrustedSql` utility with `pg-meta`:
Compose hardcoded SQL with `safeSql` and sanitize every dynamic value using `@supabase/pg-meta` helpers:
```ts
import { untrustedSql } from '@supabase/pg-meta'
const unsafeQuery = searchParams.get('query')
const querySql = untrustedSql(unsafeQuery)
```
`untrustedSql` creates a string of the branded type `UntrustedSqlFragment`.
(See Provenance Tracking below.)
3. User-authored. These are SQL fragments that are authored by the user
themselves within the UI, for example in a text input field. Because the
user is the author, these should be considered safe to execute.
However, there is a caveat, where third-party and user-authored code can
mix, contaminating the user-authored code (for example, if an input is
prefilled from an unsanitized URL parameter). Provenance tracking helps us
track these cases.
For example, a safe input component could be implemented as follows by requiring that its placeholder and controlled value are of type `SafeSqlFragment`. In this case we can use its onChange to promote the user input to `SafeSqlFragment` type, because we know that the user is the author of the input. An implementation of this is in
@apps/studio/components/ui/SafeSqlInput.tsx:
```ts
import { rawSql, type SafeSqlFragment } from '@supabase/pg-meta'
import type { ChangeEvent, ComponentProps } from 'react'
import { Input } from 'ui-patterns/DataInputs/Input'
type InputProps = ComponentProps<typeof Input>
export type SafeSqlInputProps = Omit<
InputProps, 'placeholder' | 'value' | 'onChange'
> & {
placeholder?: SafeSqlFragment
value: SafeSqlFragment
onChange?:
(event: ChangeEvent<HTMLInputElement>, value: SafeSqlFragment) => void
}
export const SafeSqlInput = ({ onChange, ...props }: SafeSqlInputProps) => (
<Input
{...props}
onChange={(event) => onChange?.(event, rawSql(event.target.value))}
/>
)
```
This is pretty much the ONLY VALID USE CASE of the rawSql export from
pg-meta, and it should be used with caution.
## Provenance tracking
Branded types are used to track the provenance of SQL fragments. The types,
exported from `pg-meta`, are:
- `SafeSqlFragment`: represents SQL fragments that are safe to execute, because
they are either hardcoded in the application or authored by the user
themselves.
- `UntrustedSqlFragment`: represents SQL fragments that can be influenced by an
attacker, such as through URL parameters or LLM output.
These are valid ways to generate a `SafeSqlFragment`:
- Using the `safeSql` utility from `pg-meta` to create hardcoded SQL fragments.
- Using the sanitization utilities from `pg-meta` to sanitize untrusted input
and promote it to a `SafeSqlFragment`:
- `ident`
- `literal`
- `keyword`
- Using the safe SQL manipulation utilities:
- `joinSqlFragments` (from `pg-meta`)
- `trimSafeSqlFragment` (from `apps/studio/lib/sql.ts`)
`UntrustedSqlFragments` can be generated from raw strings using
`untrustedSql()`.
There is also a union type, `DisplayableSqlFragment`, which represents SQL fragments that can be safely displayed in the UI, but not necessarily executed. This includes both `SafeSqlFragment` and `UntrustedSqlFragment`.
## Security of SQL round-tripped from the user's database
SQL derived directly from catalog tables (e.g., function definitions, RLS
expressions, etc.) is considered safe, and it is promoted AT THE POINT OF
BEING QUERIED from the database. In most cases, this is in an
apps/studio/data/\*_/_.ts file, in the utility function that makes the API or
database fetch.
A critical exception to the safety of SQL round-tripped from the database is
user snippets. These must NEVER BE CONSIDERED SAFE because they are both (a)
externally influenceable and (b) auto-saved. The snippet type uses the
`unchecked_sql` property, which is an `UntrustedSqlFragment`, to enforce this.
## Promoting SQL fragments to `SafeSqlFragment` type
Given an insecure string or `UntrustedSqlFragment`, how do we promote it safely
to a `SafeSqlFragment`?
### Sanitization utilities
This is the preferred method when the input is sanitizable, e.g., it is a
relation name, a column name, will be compared as a literal, etc.
The pg-meta library provides the following sanitization utilities that can be
used to safely promote untrusted input to `SafeSqlFragment`:
- `ident`: for sanitizing identifiers such as table names or column names.
- `literal`: for sanitizing literal values that will be used in SQL statements.
- `keyword`: for sanitizing SQL keywords.
### `acceptUntrustedSql`
Some untrusted SQL fragments cannot be sanitized with the above utilities. For
example, the `USING` expression in the RLS policy editor is an arbitrary SQL
expression.
In these cases, we can promote the SQL fragment _upon explicit user action_.
User action indicates that the user has seen the SQL and is OK with running it.
For example, an explicit user action could be clicking a "Run" button.
The promotion happens with the `acceptUntrustedSql` utility from `pg-meta`,
which takes an `UntrustedSqlFragment` and returns a `SafeSqlFragment`.
This utility MUST ONLY BE USED IN event handlers. It should NEVER be used in
a useQuery, direct in the render body of a component, in a useEffect, or
anywhere it could auto-run without explicit user action.
This is safe:
- `safeSql` — tagged template accepting only `SafeSqlFragment` interpolations
- `ident` — sanitizes identifiers (schema, table, column names)
- `literal` — sanitizes literal values
- `keyword` — sanitizes SQL keywords
- `joinSqlFragments` (`@supabase/pg-meta`) & `trimSafeSqlFragment` (`apps/studio/lib/sql.ts`) — safe fragment manipulation
```ts
import { acceptUntrustedSql } from '@supabase/pg-meta'
import { ident, literal, safeSql } from '@supabase/pg-meta'
function SafeComponent() {
const { mutate: execute } = useExecuteSqlMutation()
const handleRun = () => {
// ✅ GOOD: Safe because it is in an event handler which requires a user
// click
execute({ sql: acceptUntrustedSql(/* sql */) })
}
return (
<button onClick={handleRun}>Run</button>
)
}
```
This is unsafe:
```ts
import { acceptUntrustedSql } from '@supabase/pg-meta'
function UnsafeComponent() {
const { data } = useQuery({
queryKey: ['execute-sql', sql],
queryFn: () => {
// 🛑 BAD: Unsafe because it is in a query which could auto-run without
// explicit user action
return execute({ sql: acceptUntrustedSql(/* sql */) })
},
})
}
```
## Type guarantees
SQL run against the user's Postgres database runs through the `executeSql`
function, which only takes arguments of type `SafeSqlFragment` for the SQL
parameter. Raw strings or `UntrustedSqlFragment`s will error at compile time.
## Examples
### Hard-coded SQL
```ts
// ✅ GOOD: Automatically safe with `safeSql` utility
const selectStatement = safeSql`select 1`
```
### SQL with sanitizable interpolations
```ts
// ✅ GOOD: `pg-meta` utilities sanitize the input
const tableName = ident(userInputTableName)
const searchString = literal(userInputSearchString)
const sqlStatement = safeSql`
// ✅ GOOD: hardcoded SQL + sanitized interpolations
const sql = safeSql`
SELECT *
FROM ${tableName}
WHERE search_column = ${searchString}
FROM ${ident(userInputTableName)}
WHERE search_column = ${literal(userInputSearchString)}
`
// 🛑 BAD: raw string interpolation fails to typecheck
const bad = safeSql`SELECT * FROM ${'my_table'}`
```
```ts
// 🛑 BAD: Passing raw strings will type error
const tableName = 'my_table'
const sqlStatement = safeSql`
SELECT *
FROM ${tableName}
`
```
### User-authored input (`SafeSqlInput`)
### Non-sanitizable SQL from a user input
Third-party values can contaminate user inputs if a raw `<Input>` is prefilled from URL params or plain strings. Use `SafeSqlInput` (`apps/studio/components/ui/SafeSqlInput.tsx`), which requires `SafeSqlFragment` for `value` and `placeholder` and promotes user keystrokes via `rawSql`. `SafeSqlInput` is essentially the **only** valid use of `rawSql`.
```ts
// ✅ GOOD: SafeSqlInput only allows a value that is a SafeSqlFragment
import { SafeSqlInput } from '@apps/studio/components/ui/SafeSqlInput'
```tsx
import { safeSql, type SafeSqlFragment } from '@supabase/pg-meta'
import { SafeSqlInput } from '@/components/ui/SafeSqlInput'
function MyComponent() {
// ✅ GOOD: value and placeholder are SafeSqlFragment; onChange yields SafeSqlFragment
function SafeExpressionField() {
const [sql, setSql] = useState<SafeSqlFragment>(safeSql``)
return (
<SafeSqlInput
placeholder={safeSql`Enter your SQL query here...`}
placeholder={safeSql`Enter your SQL expression...`}
value={sql}
onChange={(event, value) => setSql(value)}
onChange={(_event, value) => setSql(value)}
/>
)
}
// 🛑 BAD: raw <Input> mixes plain strings with SafeSqlFragment
// <Input placeholder="Enter SQL..." value={sql} onChange={(e) => setSql(e.target.value)} />
```
### Round-tripped database SQL vs user snippets
- **Catalog definitions** (function definitions, RLS expressions, views) returned directly from the database may be promoted **only at the fetch boundary** inside `apps/studio/data/**/*.ts` — never in shared `utils.ts` or components where provenance cannot be verified.
- **User snippets are ALWAYS UNSAFE**: snippets are auto-persisted and externally influenceable (e.g. prefilled from URL params). Their `unchecked_sql` field is typed `UntrustedSqlFragment` — never cast it and never auto-run it.
```ts
// 🛑 BAD: This input mixes SafeSqlFragments and unsafe strings
function MyBadComponent() {
const [sql, setSql] = useState<SafeSqlFragment>(safeSql``)
return (
<Input
// 🛑 BAD: This is unsafe because the placeholder is a raw string
placeholder="Enter your SQL query here..."
value={sql}
onChange={(event) => setSql(event.target.value)}
/>
)
// ✅ GOOD (see apps/studio/data/database-functions/database-functions-query.ts):
// promote catalog SQL directly at the fetch boundary
export async function getDatabaseFunctions(...) {
const { result } = await executeSql(...)
return result as SavedDatabaseFunction[]
}
// 🛑 BAD: promoting in a shared utils.ts or component hides where the string came from
```
### Round-tripping SQL from the database (NOT snippet content)
### Promoting non-sanitizable SQL (`acceptUntrustedSql`)
```ts
// ✅ GOOD: SQL from the database is promoted to SafeSqlFragment at the point
// of fetching
Arbitrary SQL that cannot be sanitized with `ident`/`literal`/`keyword` (such as snippet `unchecked_sql` or an RLS `USING` expression) can be promoted with `acceptUntrustedSql` (`@supabase/pg-meta`) **only inside an explicit user-action event handler** (e.g. clicking Run). Never call `acceptUntrustedSql` in `useQuery`, `useEffect`, render, or any automatic path.
// data/function-definitions.ts
function markFunctionDefinitionSafe(
functionDefinition: FunctionDefinition
): SafeFunctionDefinition {
return {
...functionDefinition,
definition: functionDefinition.definition as SafeSqlFragment,
}
}
// data/function-definitions.ts
function getFunctionDefinitions() {
return GET(`/function-definitions`).then((functionDefinitions) =>
functionDefinitions.map(markFunctionDefinitionSafe)
)
}
```
```ts
// 🛑 BAD: Strings are promoted to SafeSqlFragment in a utility function, where
// it is impossible to easily determine the safety of the input
// utils.ts
function markFunctionDefinitionSafe(
functionDefinition: FunctionDefinition
): SafeFunctionDefinition {
return {
...functionDefinition,
definition: functionDefinition.definition as SafeSqlFragment,
}
}
// Component.ts
function MyComponent() {
const { data: functionDefinitions } = useFunctionDefinitions()
const safeFunctionDefinitions = functionDefinitions.map(markFunctionDefinitionSafe)
}
```
### Snippet content is ALWAYS UNSAFE
Snippets are auto-persisted to the database and can be created or modified
through externally influenceable channels (e.g., prefilled from URL params).
The `unchecked_sql` property is typed as `UntrustedSqlFragment` to enforce this
— it must only be promoted to `SafeSqlFragment` via `acceptUntrustedSql` in an
event handler that requires explicit user action.
```ts
// 🛑 BAD: Snippet content is executed automatically via useQuery, with no
// explicit user action confirming that the user has reviewed the SQL.
```tsx
import { acceptUntrustedSql } from '@supabase/pg-meta'
function UnsafeSnippetPreview({ snippet }: { snippet: Snippet }) {
const { data } = useExecuteSqlQuery({
sql: acceptUntrustedSql(snippet.content.unchecked_sql),
})
import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'
import { useGrant } from '@/lib/grants'
import type { SqlSnippets, UserContent } from '@/types/userContent'
return <Results data={data} />
}
```
```ts
// 🛑 BAD: Casting bypasses the type system entirely. The snippet's
// `unchecked_sql` is `UntrustedSqlFragment` for a reason — never cast it.
function UnsafeSnippetRunner({ snippet }: { snippet: Snippet }) {
const { mutate: execute } = useExecuteSqlMutation()
useEffect(() => {
execute({ sql: snippet.content.unchecked_sql as SafeSqlFragment })
}, [snippet])
}
```
```ts
// ✅ GOOD: Snippet content is only promoted to SafeSqlFragment inside an event
// handler, after the user clicks Run. The user has seen the SQL in the editor
// and explicitly chosen to execute it.
import { acceptUntrustedSql } from '@supabase/pg-meta'
function SnippetRunner({ snippet }: { snippet: Snippet }) {
function SnippetRunner({
projectRef,
connectionString,
snippet,
}: {
projectRef: string
connectionString?: string | null
snippet: UserContent<SqlSnippets.Content>
}) {
const writeGrant = useGrant(
'POST /platform/pg-meta/{ref}/query',
{ projectRef },
{ variant: 'write' }
)
const { mutate: execute } = useExecuteSqlMutation()
// ✅ GOOD: promoted inside a click handler after the user sees and chooses to run the SQL
const handleRun = () => {
execute({ sql: acceptUntrustedSql(snippet.content.unchecked_sql) })
if (!writeGrant.grant) return
execute({
projectRef,
connectionString,
sql: acceptUntrustedSql(snippet.content.unchecked_sql),
sqlOrigin: 'user',
grant: writeGrant.grant,
})
}
return (
<>
<SnippetEditor snippet={snippet} />
<button onClick={handleRun}>Run</button>
</>
<button disabled={!writeGrant.grant} onClick={handleRun}>
Run
</button>
)
}
// 🛑 BAD: auto-running in useQuery/useEffect or casting bypasses user confirmation
// useQuery({ queryKey: [...], queryFn: () => executeSql({ projectRef, connectionString, sql: acceptUntrustedSql(sql), sqlOrigin: 'user', grant }) })
// useEffect(() => { execute({ projectRef, connectionString, sql: snippet.content.unchecked_sql as SafeSqlFragment, sqlOrigin: 'user', grant }) }, [snippet])
```
---
## Analytics SQL (BigQuery / ClickHouse)
The same security model applies to analytics queries, which target BigQuery
or ClickHouse via the
`/platform/projects/{ref}/analytics/endpoints/logs.all{,.otel}` endpoints.
Filter keys and values from URL parameters and UI inputs are spliced into SQL
that runs against the project's logs, so the same injection risk exists.
The same provenance model applies to analytics queries targeting `/platform/projects/{ref}/analytics/endpoints/logs.all{,.otel}`.
Analytics SQL uses its own `SafeLogSqlFragment` brand
(`apps/studio/data/logs/safe-analytics-sql.ts`), intentionally **disjoint**
from the pg-meta `SafeSqlFragment` brand. The brands are kept separate because
escape semantics differ — Postgres-safe `E'…'` strings, `::jsonb` casts, and
double-quoted identifiers are unsafe for BigQuery and/or ClickHouse, and vice
versa. Crossing the brands would silently emit unsafe SQL.
- **Disjoint brand**: `SafeLogSqlFragment` (`apps/studio/data/logs/safe-analytics-sql.ts`) is separate from pg-meta's `SafeSqlFragment` because escape semantics differ (`E'…'`, `::jsonb`, and double-quoted identifiers are unsafe in BigQuery/ClickHouse, and vice versa). Crossing brands fails at compile time. Never cast `as SafeLogSqlFragment`.
- **Wire boundary**: `executeAnalyticsSql` (`apps/studio/data/logs/execute-analytics-sql.ts`) accepts only `SafeLogSqlFragment`. An ESLint `no-restricted-syntax` rule in `apps/studio/eslint.config.cjs` catches direct `post()`/`get()` calls with string-literal `logs.all` / `logs.all.otel` URLs outside `execute-analytics-sql.ts` (indirect calls via `logsAllEndpointUrl(...)` are not caught by lint, so always route through `executeAnalyticsSql`).
The wire boundary is `executeAnalyticsSql` in
`apps/studio/data/logs/execute-analytics-sql.ts`, analogous to pg-meta's
`executeSql`; it accepts only `SafeLogSqlFragment`, and an eslint
`no-restricted-syntax` rule in `apps/studio/eslint.config.cjs` blocks direct
`post()`/`get()` calls to the `logs.all` endpoints from any other file.
### Helpers (`apps/studio/data/logs/safe-analytics-sql.ts`)
Build fragments with the helpers in `safe-analytics-sql.ts`:
- `safeSql` — template tag that only accepts `SafeLogSqlFragment`
interpolations; plain strings and Postgres `SafeSqlFragment`s are rejected at
compile time.
- `analyticsLiteral(value)` — sanitizes string/number/boolean literals.
- `quotedIdent(name)` — validates and backtick-quotes dotted identifiers.
- `keyword(value, allowed)` — resolves a value against an allow-list of
fragments (e.g. `AND`/`OR`); never returns the raw input.
- `joinSqlFragments(fragments, separator)` — composes already-branded
fragments.
- `safeSql` — tagged template accepting only `SafeLogSqlFragment` interpolations (rejects plain strings and Postgres `SafeSqlFragment`)
- `analyticsLiteral(value)` — escapes string (`''`, `\\`), number, or boolean literals
- `quotedIdent(value)` — validates `[A-Za-z_][A-Za-z0-9_]*` segments and backtick-quotes dotted identifiers
- `keyword(value, allowed)` — resolves against an allow-list of pre-branded fragments (e.g. `AND`/`OR`); never returns raw input
- `joinSqlFragments(fragments, separator)` — composes branded fragments with fixed structural separators
```ts
import { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'
import { analyticsLiteral, quotedIdent, safeSql } from '@/data/logs/safe-analytics-sql'
// ✅ GOOD: every interpolation is sanitized.
// ✅ GOOD: every dynamic interpolation is sanitized
const sql = safeSql`
SELECT timestamp, event_message
FROM ${quotedIdent(table)}
WHERE id = ${analyticsLiteral(id)}
`
await executeAnalyticsSql({ projectRef, endpoint, sql, iso_timestamp_start, iso_timestamp_end })
// 🛑 BAD: raw string fails to typecheck at executeAnalyticsSql
// const sql = `SELECT * FROM ${table} WHERE id = '${id}'`
```
```ts
// 🛑 BAD: raw string interpolation. This fails to type-check at the
// executeAnalyticsSql boundary because the result is `string`, not
// `SafeLogSqlFragment`.
const sql = `SELECT * FROM ${table} WHERE id = '${id}'`
await executeAnalyticsSql({ projectRef, endpoint, sql, iso_timestamp_start, iso_timestamp_end })
```
### Untrusted editor SQL (`acceptUntrustedLogsSql`)
The only path that runs SQL not built from these helpers is user-authored
editor text: `untrustedLogSql(text)` marks it `UntrustedLogSqlFragment`
(displayable and storable, never executable), and `acceptUntrustedLogsSql`
promotes it to `SafeLogSqlFragment`. That promotion is a **security boundary**
— call it only from a run gesture (Run button click, Cmd+Enter) or an
approval-gated tool call (the AI notebook tools). Never from render,
`useEffect`, or any automatic path. The notebook persist path also promotes
cells because the writable notebook type requires the safe brand; that is
storage typing, not execution approval, and is not precedent for promoting
anywhere else. The same rule as `acceptUntrustedSql` on the Postgres side.
Mark user-authored editor text with `untrustedLogSql(text)` (`UntrustedLogSqlFragment`: displayable and storable, never executable). Promote to `SafeLogSqlFragment` with `acceptUntrustedLogsSql(fragment)` **only** from an explicit run gesture (Run click, Cmd+Enter) or an approval-gated AI notebook tool call — never from render, `useEffect`, or any automatic path. (In `apps/studio/lib/ai/tools/*.server.ts`, ESLint `no-restricted-imports` blocks direct imports of `acceptUntrustedSql`/`acceptUntrustedLogsSql` — receive the promotion gate via `approvalGatedToolFromContract`. The notebook persist path promotes cells solely to satisfy writable storage typing, not as execution approval or precedent for promoting elsewhere.)
Endpoint selection, the OTEL query builders, and the rest of the Studio
wiring live in the `clickhouse-logs-queries` skill
(`references/codebase-integration.md`).
For ClickHouse query syntax, endpoint/flag selection, and OTEL builders, see [clickhouse-logs-queries](../clickhouse-logs-queries/references/codebase-integration.md).
+136 -392
View File
@@ -1,429 +1,173 @@
---
name: studio-e2e-tests
description: Write and run Playwright E2E tests for Supabase Studio (e2e/studio).
Use when asked to run e2e tests, write new E2E tests, or debug flaky or failing
Playwright tests. Covers running commands, avoiding race conditions, waiting
strategies, selectors, helper functions, and CI vs local differences.
description: Write, run, and debug Playwright E2E tests for Supabase Studio
(e2e/studio). Use for running E2E suites, avoiding race conditions, using
Studio fixtures/waiters/cleanup helpers, updating E2E selectors, or debugging
CI cold-start vs local dev differences.
---
# E2E Studio Tests
# Studio Playwright E2E Tests
Run Playwright end-to-end tests for the Studio application.
End-to-end tests live in `e2e/studio/features/*.spec.ts` and cover critical user
journeys (covering both mouse and keyboard interactions where each protects the
journey) or platform vs self-hosted differences that unit/MSW tests cannot
prove.
## Running Tests
Tests must be run from the `e2e/studio` directory:
Always run from `e2e/studio` (omit `--` so pnpm 12 forwards flags directly to
Playwright):
```bash
cd e2e/studio && pnpm run e2e
cd e2e/studio && pnpm run e2e # full suite (auto-starts local containers, 3 workers)
cd e2e/studio && pnpm run e2e features/cron-jobs.spec.ts # single file
cd e2e/studio && pnpm run e2e --grep "test name pattern" # grep filter
cd e2e/studio && pnpm run e2e:ui # interactive UI mode
```
### Run specific file
Self-hosted mode (`IS_PLATFORM=false`, `CI` unset) auto-starts local Supabase
containers via Playwright's web server config once browsers are installed
(`cd e2e/studio && pnpm exec playwright install`), provided nothing is already
listening on port `8082`.
```bash
cd e2e/studio && pnpm run e2e -- features/cron-jobs.spec.ts
```
## Fixtures & File Setup
### Run with grep filter
```bash
cd e2e/studio && pnpm run e2e -- --grep "test name pattern"
```
### UI mode for debugging
```bash
cd e2e/studio && pnpm run e2e -- --ui
```
## Environment Setup
- Tests auto-start Supabase local containers via web server config
- Self-hosted mode (`IS_PLATFORM=false`) runs tests in parallel (3 workers)
- No manual setup needed for self-hosted tests
## Test File Structure
- Tests are in `e2e/studio/features/*.spec.ts`
- Use custom test utility: `import { test } from '../utils/test.js'`
- Test fixtures provide `page`, `ref`, and other helpers
## Common Patterns
Wait for elements with generous timeouts:
```typescript
await expect(locator).toBeVisible({ timeout: 30000 })
```
Use serial mode for tests sharing database state:
```typescript
test.describe.configure({ mode: 'serial' })
```
## Writing Robust Selectors
### Selector priority (best to worst)
1. **`getByRole` with accessible name** - Most robust, tests accessibility
```typescript
page.getByRole('button', { name: 'Save' })
page.getByRole('button', { name: 'Configure API privileges' })
```
2. **`getByTestId`** - Stable, explicit test hooks
```typescript
page.getByTestId('table-editor-side-panel')
```
3. **`getByText` with exact match** - Good for unique text
```typescript
page.getByText('Data API access', { exact: true })
```
4. **`locator` with CSS** - Use sparingly, more fragile
```typescript
page.locator('[data-state="open"]')
```
### Patterns to avoid
- **XPath selectors** - Fragile to DOM changes
```typescript
// BAD
locator('xpath=ancestor::div[contains(@class, "space-y")]')
```
- **Parent traversal with `locator('..')`** - Breaks when structure changes
```typescript
// BAD
element.locator('..').getByRole('button')
```
- **Broad `filter({ hasText })` on generic elements** - May match multiple elements
```typescript
// BAD - popover may have more than one combobox
// Could consider scoping down the container or filtering the combobox more specifically
popover.getByRole('combobox')
```
### Add accessible labels to components
When a component lacks a good accessible name, add one in the source code:
```tsx
// In the React component
<Button aria-label="Configure API privileges">
<Settings />
</Button>
```
Then use it in tests:
```typescript
page.getByRole('button', { name: 'Configure API privileges' })
```
### Narrowing search scope
Scope selectors to specific containers to avoid matching wrong elements:
```typescript
// Good - scoped to side panel
const sidePanel = page.getByTestId('table-editor-side-panel')
const toggle = sidePanel.getByRole('switch')
// Good - find unique element, then scope from there
const popover = page.locator('[data-radix-popper-content-wrapper]')
const roleSection = popover.getByText('Anonymous (anon)', { exact: true })
```
## Avoiding Race Conditions
**Set up API waiters BEFORE triggering actions.** This is the most common source of flaky tests.
Always import `test` (providing `page`, `ref`, and Studio fixtures) from the
custom harness:
```ts
// ❌ Race condition — response may complete before waiter is set up
await page.getByRole('button', { name: 'Save' }).click()
await waitForApiResponse(page, 'pg-meta', ref, 'query?key=table-create')
// ✅ Waiter is ready before the action
const apiPromise = waitForApiResponse(page, 'pg-meta', ref, 'query?key=table-create')
await page.getByRole('button', { name: 'Save' }).click()
await apiPromise
import { test, withSetupCleanup } from '../utils/test.js'
import { withFileOnceSetup, releaseFileOnceCleanup } from '../utils/once-per-file.js'
```
Same rule applies before navigation:
- Use `test.describe.configure({ mode: 'serial' })` when tests in a file share
database state.
- Use `withFileOnceSetup(import.meta.url, fn)` /
`releaseFileOnceCleanup(import.meta.url)` in `beforeAll` / `afterAll` for
expensive one-time file setup (passing `import.meta.url` is required — an
arbitrary string throws at runtime).
- Dismiss toasts before clicking elements they can overlay:
```ts
import { dismissToastsIfAny } from '../utils/dismiss-toast.js'
await dismissToastsIfAny(page)
```
## Selectors & Accessibility Sync
Prefer `getByRole` (with accessible name) -> `getByTestId` -> exact `getByText`
over CSS/XPath/parent traversal (`locator('..')`), and scope to containers such
as `[data-radix-popper-content-wrapper]` or a specific side panel test ID.
- When an icon-only control lacks an accessible name, add one in the component:
```tsx
<Button aria-label="Configure API privileges">
<SettingsIcon />
</Button>
```
- When improving accessible names on repeated row buttons (e.g.
`${item.name} actions` instead of `"More options"`) or changing visible copy,
update matching selectors in `e2e/studio/` in the same PR.
- Never bypass hidden controls with `click({ force: true })` — hover or open the
owning container first, assert visibility, then click.
## Avoiding Race Conditions & Waits
**Register API waiters BEFORE triggering the action or navigation.** Setting up
a waiter after `.click()` or `.goto()` is the primary cause of E2E flakes:
```ts
import { toUrl } from '../utils/to-url.js'
import { waitForApiResponse, waitForTableToLoad } from '../utils/wait-for-response.js'
// ✅ Single waiter registered before action
const createPromise = waitForApiResponse(page, 'pg-meta', ref, 'query?key=table-create')
await page.getByRole('button', { name: 'Save' }).click()
await createPromise
// ✅ Multiple required requests from one action — register BOTH strict waiters before clicking
const savePromise = waitForApiResponse(page, 'pg-meta', ref, 'query?key=table-create')
const tablesPromise = waitForApiResponse(page, 'pg-meta', ref, 'tables?include_columns=true')
await page.getByRole('button', { name: 'Save' }).click()
await Promise.all([savePromise, tablesPromise])
// ✅ Navigation
const loadPromise = waitForTableToLoad(page, ref)
await page.goto(toUrl(`/project/${ref}/editor?schema=public`))
await loadPromise
```
When an action triggers multiple API calls, wait for all of them:
- Use strict `waitForApiResponse` for required responses; reserve
`{ soft: true, fallbackWaitMs: 1000 }` or `waitForApiResponseWithTimeout`
(from `../utils/wait-for-response-with-timeout.js`, which resolves `null` on
timeout) strictly for optional calls.
- Avoid `waitForLoadState('networkidle')` and avoid `waitForTimeout` for UI or
network waits (use explicit API waiters, `expect(locator).toBeVisible()`,
`waitForSelector(..., { state: 'detached' })`, or `expect.poll`). The **sole**
exception for `waitForTimeout` is waiting out a known client-side input
debounce (e.g. `300ms`).
- Include descriptive messages on `expect(locator, 'reason')` and generous
explicit timeouts (`{ timeout: 30000 }` / `{ timeout: 50000 }`) on slow DB/DDL
operations.
```ts
const createTablePromise = waitForApiResponseWithTimeout(page, (r) =>
r.url().includes('query?key=table-create')
)
const tablesPromise = waitForApiResponseWithTimeout(page, (r) =>
r.url().includes('tables?include_columns=true')
)
## Studio Utilities & Mocking
await page.getByRole('button', { name: 'Save' }).click()
await Promise.all([createTablePromise, tablesPromise])
```
## Waiting Strategies
Playwright auto-waits for elements to be actionable — prefer this over manual timeouts.
Use `expect.poll` for dynamic state changes:
```ts
await expect.poll(async () => await page.getByLabel(`View ${tableName}`).count()).toBe(0)
```
Use `waitForSelector` with state for element lifecycle:
```ts
await page.waitForSelector('[data-testid="side-panel"]', { state: 'detached' })
```
Avoid `networkidle` — use specific API waits instead:
```ts
// ❌ Unreliable and slow
await page.waitForLoadState('networkidle')
// ✅ Specific API response
await waitForApiResponse(page, 'pg-meta', ref, 'tables')
```
The only acceptable use of `waitForTimeout` is a client-side debounce:
```ts
await page.getByRole('textbox').fill('search term')
await page.waitForTimeout(300) // allow debounce
```
## Avoiding `waitForTimeout`
Never use `waitForTimeout` to wait for UI or network — always wait for something specific (the debounce case above is the sole exception):
```typescript
// BAD
await page.waitForTimeout(1000)
// GOOD - wait for UI element
await expect(page.getByText('Success')).toBeVisible()
// GOOD - wait for API response
const apiPromise = waitForApiResponse(page, 'pg-meta', ref, 'query?key=table-create')
await saveButton.click()
await apiPromise
// GOOD - wait for toast indicating operation complete
await expect(page.getByText('Table created successfully')).toBeVisible({ timeout: 15000 })
```
## Avoiding `force: true` on clicks
Instead of forcing clicks on hidden elements, make them visible first:
```typescript
// BAD
await menuButton.click({ force: true })
// GOOD - hover to reveal, then click
await tableRow.hover()
await expect(menuButton).toBeVisible()
await menuButton.click()
```
## Test Structure
Always import from the custom test utility:
```ts
import { test } from '../utils/test.js'
```
Use `withFileOnceSetup` for expensive setup that should run once per file:
```ts
test.beforeAll(async ({ browser, ref }) => {
await withFileOnceSetup(import.meta.url, async () => {
const ctx = await browser.newContext()
const page = await ctx.newPage()
await deleteTestTables(page, ref)
})
})
test.afterAll(async () => {
await releaseFileOnceCleanup(import.meta.url)
})
```
Dismiss toasts before interacting — they can overlay buttons:
```ts
const dismissToastsIfAny = async (page: Page) => {
const closeButtons = page.getByRole('button', { name: 'Close toast' })
const count = await closeButtons.count()
for (let i = 0; i < count; i++) {
await closeButtons.nth(i).click()
}
}
await dismissToastsIfAny(page)
await page.getByRole('button', { name: 'New table' }).click()
```
## Assertions
Always include descriptive messages for easier debugging:
```ts
// ❌ No context on failure
await expect(page.getByRole('button', { name: 'Save' })).toBeVisible()
// ✅ Clear message on failure
await expect(
page.getByRole('button', { name: 'Save' }),
'Save button should be visible after form is filled'
).toBeVisible()
```
Use explicit timeouts for slow operations:
```ts
await expect(
page.getByText(`Table ${tableName} is good to go!`),
'Success toast should be visible after table creation'
).toBeVisible({ timeout: 50000 })
```
## Helper Functions
Extract reusable operations into domain helpers (e.g. `e2e/studio/utils/storage-helpers.ts`).
Use the existing wait utilities:
```ts
import {
createApiResponseWaiter,
waitForApiResponse,
waitForGridDataToLoad,
waitForTableToLoad,
} from '../utils/wait-for-response.js'
```
Use `expectClipboardValue` instead of manual clipboard reads with hardcoded timeouts:
```ts
// ❌ Brittle
await page.evaluate(() => navigator.clipboard.readText())
await page.waitForTimeout(500)
// ✅ Uses Playwright auto-retries
await expectClipboardValue({ page, value: 'expectedValue' })
```
## API Mocking
```ts
await page.route('*/**/logs.all*', async (route) => {
await route.fulfill({ body: JSON.stringify(mockAPILogs) })
})
```
Use soft waits for optional API calls:
```ts
await waitForApiResponse(page, 'pg-meta', ref, 'optional-endpoint', {
soft: true,
fallbackWaitMs: 1000,
})
```
- **Clipboard:** Use `expectClipboardValue` instead of manual `navigator.clipboard.readText()`
with sleeps:
```ts
import { expectClipboardValue } from '../utils/clipboard.js'
await expectClipboardValue({ page, value: 'expectedValue' })
```
- **API mocking:** Stub external/analytics endpoints with
`await page.route('*/**/logs.all*', (route) => route.fulfill({ body: JSON.stringify(mock) }))`.
- **Domain helpers:** Extract reusable flows into `e2e/studio/utils/*-helpers.ts`
(see `storage-helpers.ts`, `filter-bar-helpers.ts`).
## Cleanup
Clean up test data in `beforeAll`/`beforeEach`. Check before deleting to handle existing state gracefully:
Prefer `withSetupCleanup` with `await using` so cleanup always runs on both pass
and failure **once `setup` resolves** (keep `setup` atomic or handle
partial-setup cleanup inside `setup` — if `setup` throws mid-way, the disposable
is never registered). Always generate a unique resource name per run (e.g.
`createBucket` no-ops on name collisions, so cleanup with a fixed/shared name
could delete a seeded bucket or another test's data):
```ts
const bucketRow = page.getByRole('row').filter({ hasText: bucketName })
if ((await bucketRow.count()) === 0) return
// proceed with deletion
import { createBucket, deleteBucket } from '../utils/storage/index.js'
const bucketName = `test-bucket-${crypto.randomUUID().slice(0, 8)}`
await using _ = await withSetupCleanup(
() => createBucket(bucketName),
async () => {
await deleteBucket(bucketName)
}
)
```
Reset local storage after tests that modify it:
- If using manual `try / finally`, create the resource inside `try` and guard
deletion on whether creation succeeded and `!page.isClosed()`. For UI cleanup,
check `(await row.count()) === 0` before deleting.
- Reset modified local storage with `resetLocalStorage(page, ref)` from
`../utils/reset-local-storage.js`.
```ts
import { resetLocalStorage } from '../utils/reset-local-storage.js'
## Debugging & CI Cold Start vs Local Dev
await resetLocalStorage(page, ref)
```
CI starts from a **blank database** (fresh containers, extensions like `pg_cron`
disabled by default), whereas `pnpm dev:studio-local` may hold leftover tables
or enabled extensions from previous runs.
## Debugging
### View trace
```bash
cd e2e/studio && pnpm exec playwright show-trace <path-to-trace.zip>
```
### View HTML report
```bash
cd e2e/studio && pnpm exec playwright show-report
```
### Error context
Error context files are saved in the `test-results/` directory.
### Playwright MCP tools
Use Playwright MCP tools to inspect UI when debugging locally.
## CI vs Local Development
The key difference is **cold start vs warm state**:
### CI (cold start)
Tests run from a blank database slate. Each test run resets the database and starts fresh containers. Extensions like pg_cron are NOT enabled by default.
### Local dev with `pnpm dev:studio-local`
When debugging with a running dev server, the database may already have state from previous runs (extensions enabled, test data present).
## Handling Cold Start Bugs
Tests that work locally but fail in CI often have assumptions about existing state.
### Common issues
1. Extension not enabled (must enable in test setup)
2. Race conditions when parallel tests try to modify shared state (use `test.describe.configure({ mode: 'serial' })`)
3. Locators matching wrong elements because the page structure differs when state isn't set up
### Reproducing CI behavior locally
The test framework automatically resets the database when running `pnpm run e2e`. This matches CI behavior.
If using `pnpm dev:studio-local` for Playwright MCP debugging, remember the state differs from CI.
## Debugging Workflow for CI Failures
1. First, run the test locally with `pnpm run e2e -- features/<file>.spec.ts` (cold start)
2. Check error context in `test-results/` directory
3. If you need to inspect UI state, start `pnpm dev:studio-local` and use Playwright MCP tools
4. Remember: what you see in the dev server may have state that doesn't exist in CI
1. Reproduce CI failures with a true cold-start run: `playwright.config.ts` sets
`reuseExistingServer: true`, so **stop any Studio server already listening on
port `8082` first** (and keep `IS_PLATFORM=false` and `CI` unset) before
running `cd e2e/studio && pnpm run e2e features/<file>.spec.ts` so Playwright
runs `e2e:setup:selfhosted` and resets the DB — or run `pnpm e2e:setup:cli`
from the repo root to reset the stack explicitly. **Warning:** both invoke
`supabase stop --all --no-backup`, which wipes data from **all** local
Supabase projects on the machine, not only the E2E stack.
2. Inspect `e2e/studio/test-results/` error context, traces
(`pnpm exec playwright show-trace <trace.zip>`), or HTML reports
(`pnpm exec playwright show-report`). To inspect live UI and locators
interactively, start `pnpm dev:studio-local` and use Playwright MCP tools
(bearing in mind local dev holds warm DB state unlike CI).
3. Watch for the 3 classic cold-start bugs: missing extension setup, parallel
tests mutating shared DB state (add `mode: 'serial'`), or locators assuming
pre-existing seed data.
+34 -39
View File
@@ -8,61 +8,58 @@ description: Error display and troubleshooting pattern for Supabase Studio. Use
# Studio Error Handling Pattern
Full docs and code examples: `apps/studio/components/interfaces/ErrorHandling/README.md`
Full architecture, SQLSTATE predicates, and mapping walkthrough: `apps/studio/components/interfaces/ErrorHandling/README.md`
## How it works
Classification happens in the **data layer**: `handleError` in `data/fetchers.ts` tests the error message against `ERROR_PATTERNS` and throws the matching tagged error (e.g. `ConnectionTimeoutError`, tag `DbConnectionTimeout`). The component (`ErrorMatcher`) looks up the mapping by the error's class — it never does regex matching.
```
handleError() → throws ConnectionTimeoutError → React Query catches → ErrorMatcher looks up the class → renders troubleshooting
handleError() → throws tagged StudioError → React Query catches → ErrorMatcher / AlertError renders UI
```
Every error `handleError` throws is an Effect `Data.TaggedError` carrying `_tag`, `fault` (`user | platform | third_party | studio`), `reason`, `classifiedBy` (`rule | default`), `retryable` and `service`, alongside the legacy fields (`message`, `code`, `requestId`, …). Check for one with `isStudioError(e)` from `lib/errors/studio-errors`, never `instanceof`. `StudioError` is the union type of all Studio errors (type only); two classifiers in `data/error-classification.ts`, and `handleError` picks between them. `classifyResponseError({ message, code })` is only for errors from an API response (pattern match wins, else 5xx `PlatformError`, 4xx `UnclassifiedApiError`, no status `UnexpectedError`). `classifyError(e)` is for everything else (tagged passes through, abort `RequestAborted`, fetch failure `NetworkUnreachable`, otherwise `UnexpectedError`). Never pass a made-up status to `classifyResponseError`. SQL errors go through `classifySqlResponseError`: SQL the user wrote is `UserSqlError`; SQL Studio wrote is `StudioSqlError`, with reason `user_input` and fault `user` when the caller passed `isUserFaultSqlState` to `executeSql` and it accepts the SQLSTATE (`isUserFaultForValues` for typed values such as table editor filters and row edits; `isUserFaultForSql` for user-written SQL such as policy and function bodies; both in `data/error-classification.ts`, composable). The class decides privacy (`UserSqlError`, the user's own SQL, is never sent; `StudioSqlError` is sent with a redacted message), `ERROR_ROUTING` gives the rate for each tag and fault. `lib/errors/error-routing.ts` is a total tag-then-fault to `{ sentrySampleRate }` table (rates are the `SAMPLE_NEVER`/`SAMPLE_OTHER`/`SAMPLE_OWNED`/`SAMPLE_ALWAYS` constants, 0-1), and `getErrorRouting(error)` looks the entry up (a user fault that can still be reported gets `SAMPLE_USER_FAULT`, default 0.01). `reportStudioError` sends to Sentry at that rate (tagging `sample_rate`, applied in `beforeSend`, and `reason`) and sets `errorEventId`. Reporting happens in the QueryCache/MutationCache `onError` (`reportQueryError`) after the last retry, using the `sentryContext` and `alwaysCapture` that `handleError` remembered. A successful JSON `GET` that stays empty after recovery rejects from the fetch layer with `MalformedResponseError` (`normalizeEmptyBodyResponse`), so it never reaches `handleError`; the query cache reports it like any other thrown tagged error. Pass `reportImmediately: true` to `handleError` only for callers outside React Query (never reached by a query or mutation). See the README for details.
- **Tagged errors**: `handleError` (`@/data/fetchers`) throws Effect `Data.TaggedError` instances (`_tag`, `fault: user | platform | third_party | studio`, `reason`, `classifiedBy: rule | default`, `retryable`, `service`, plus legacy `message`, `code`, `requestId`, …). Check with `isStudioError(e)` from `@/lib/errors/studio-errors`, never `instanceof`; `StudioError` is a union type only.
- **API vs non-API classifiers** (`data/error-classification.ts`): `classifyResponseError({ message, code })` is for HTTP API responses only (`ERROR_PATTERNS` win, else 5xx `PlatformError`, 4xx `UnclassifiedApiError`, no status `UnexpectedError` — never pass a made-up status). `classifyError(e)` handles everything else (tagged passes through, `AbortError` → `RequestAborted`, browser fetch failure → `NetworkUnreachable`, else `UnexpectedError`). Successful JSON `GET`s still empty after recovery reject from the fetch layer as `MalformedResponseError` (`normalizeEmptyBodyResponse`) without hitting `handleError` (`reportQueryError` still reports it).
- **SQL errors**: `executeSql` runs pg-meta errors through `classifySqlResponseError`: user/AI SQL becomes `UserSqlError` (never sent to Sentry); Studio SQL becomes `StudioSqlError` (redacted message, static `queryName` required; marked `fault: 'user'`, `reason: 'user_input'` when `isUserFaultSqlState` accepts the SQLSTATE via composable `isUserFaultForValues` (typed values: filters, row edits) or `isUserFaultForSql` (embedded SQL: policies, functions) in `data/error-classification.ts`).
- **Privacy & Sentry sampling**: the class decides privacy (`UserSqlError` never sent, `StudioSqlError` redacted), while `ERROR_ROUTING` (`lib/errors/error-routing.ts`) maps every tag + fault to `{ sentrySampleRate }` (`SAMPLE_NEVER` / `SAMPLE_USER_FAULT` / `SAMPLE_OTHER` / `SAMPLE_OWNED` / `SAMPLE_ALWAYS`, looked up via `getErrorRouting`). `reportStudioError` tags `sample_rate` (enforced in `beforeSend`) and sets `errorEventId`.
- **Reporting timing**: `QueryCache`/`MutationCache` `onError` (`reportQueryError`) reports once after the final retry using `sentryContext` and `alwaysCapture` remembered by `handleError`. Pass `reportImmediately: true` to `handleError` **only** for callers outside React Query.
## Key files
| File | Purpose |
| ------------------------------------- | ----------------------------------------------------------------- |
| `data/error-patterns.ts` | Array of `{ pattern, ErrorClass }` — the regex lives here |
| `lib/errors/studio-errors.ts` | Tagged error classes, `StudioError` (union type), `isStudioError` |
| `data/error-classification.ts` | `classifyResponseError`, `classifyError` (default rules) |
| `lib/errors/error-routing.ts` | `ERROR_ROUTING` rate per tag and fault, `getErrorRouting` lookup |
| `ErrorMatcher.tsx` | Component — looks up the mapping by error class, renders |
| `error-mappings.tsx` | `Map<ErrorClass, { id, Troubleshooting: ComponentType }>` |
| `errorMappings/ConnectionTimeout.tsx` | Reference troubleshooting component |
| `TroubleshootingSections.tsx` | Reusable accordion section components |
| `TroubleshootingAccordion.tsx` | Accordion wrapper with telemetry |
| File | Purpose |
| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `apps/studio/data/error-patterns.ts` | `ERROR_PATTERN_MAP` (`Map<ErrorConstructor, RegExp>`) — regex lives here, never in UI components |
| `apps/studio/lib/errors/studio-errors.ts` | Tagged error classes, `StudioError` union type, `isStudioError` |
| `apps/studio/data/error-classification.ts` | `classifyResponseError`, `classifyError`, `classifySqlResponseError`, predicates |
| `apps/studio/lib/errors/error-routing.ts` | `ERROR_ROUTING` table per tag and fault, `getErrorRouting` |
| `apps/studio/components/interfaces/ErrorHandling/ErrorMatcher.tsx` | Looks up error class in `error-mappings.tsx` and renders troubleshooting UI |
| `apps/studio/components/interfaces/ErrorHandling/error-mappings.tsx` | `Map<ErrorConstructor, ErrorMapping>` (`{ id, Troubleshooting }`) |
| `apps/studio/components/interfaces/ErrorHandling/errorMappings/ConnectionTimeout.tsx` | Reference troubleshooting component (including AI Assistant debug button wiring) |
| `apps/studio/components/interfaces/ErrorHandling/TroubleshootingSections.tsx` | Reusable accordion section components |
| `apps/studio/components/interfaces/ErrorHandling/TroubleshootingAccordion.tsx` | Accordion wrapper with telemetry |
## Which component
| Situation | Use |
| --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| A query failed and the page/section can't render its data (the default case — most of Studio) | `AlertError` from `components/ui/AlertError` |
| The error may be a **classified** type with its own troubleshooting steps (e.g. connection timeout) | `ErrorMatcher` from `components/interfaces/ErrorHandling/ErrorMatcher` — pass a `fallback` for the unclassified case |
| A mutation failed | The mutation hook's default `onError` toast (`toast.error` from `sonner`) — don't render an alert (see `studio-queries`) |
| Situation | Use |
| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| Query failed and page/section cannot render its data (default across Studio) | `AlertError` from `@/components/ui/AlertError` |
| Error may be a classified class with troubleshooting steps (e.g. timeout) | `ErrorMatcher` from `@/components/interfaces/ErrorHandling/ErrorMatcher` — pass `fallback` for unclassified errors |
| Mutation failed | The mutation hook's default `onError` toast (`toast.error` from `sonner`) — don't render an alert (see `studio-queries`) |
### `AlertError` (default)
Renders a warning `Admonition` with the error message, generic "try refreshing / contact support" instructions, and a **contact support** link pre-filled with `projectRef`, `subject`, and the error message.
```tsx
if (isError) return <AlertError error={error} subject="Failed to retrieve invoices" />
```
- `subject` is the human-readable title, phrased `Failed to <verb> <thing>`. Pass `projectRef` when in a project context so the support form is pre-filled.
- `error` is the React Query error object (anything with `message`); `503` responses are reworded automatically.
- When `error` is a Studio error (`isStudioError`), `AlertError` applies defaults by tag and fault from `getErrorPresentation` (`AlertError.utils.ts`), and props you pass still win. It shows the request ID, the Sentry event ID (labeled "before sampling") and a **Copy details** button next to `additionalActions`. Copied text (`formatErrorDetails`) never includes `formattedError`, `metadata`, `cause` or SQL, and has no message for SQL errors. An error with fault `user` (`isUserError`) shows its message with "Please try again. If the issue persists, try refreshing your browser." and no support link, IDs or copy button; offline (`NetworkUnreachable`, reason `offline`) shows only a dedicated offline message.
- Use `additionalActions` for a retry or navigate button; `hideContactSupport` only when support genuinely can't help and the error isn't already a user fault (those hide it automatically).
- Prefer the early-return form for the page/section's primary data; use inline `{isError && <AlertError … />}` for secondary panels that shouldn't block the rest of the page.
- Phrase `subject` as `Failed to <verb> <thing>` and pass `projectRef` in project context to pre-fill the support link. `503` responses are reworded automatically.
- For `StudioError`s, `getErrorPresentation` (`AlertError.utils.ts`) applies tag/fault defaults (caller props win): displays `requestId`, `errorEventId` ("before sampling"), and **Copy details** (`formatErrorDetails` strips `formattedError`, `metadata`, `cause`, SQL, and SQL error messages). `fault: 'user'` hides support/IDs/copy; offline `NetworkUnreachable` shows a dedicated offline message.
- Use `additionalActions` for retry/navigation; use `hideContactSupport` only when support cannot help on a non-user fault. Prefer early return for primary data and inline `{isError && <AlertError … />}` for secondary panels.
- **System-fault assumption**: `AlertError`'s default copy for plain or non-user-fault errors (including unclassified 4xxs) tells users to refresh/contact support — don't use it blindly for mutation or client-side user-input errors; use the mutation's `onError` toast or actionable inline copy instead.
- **Never collapse errors into empty states**: check `isError` before rendering empty states, and distinguish unparseable/dropped records from genuinely empty responses.
- **Multi-query views**: consolidate errors into a single `AlertError` rather than sprawling multiple banners, and hide dependent sub-sections whose prerequisite query failed.
### `ErrorMatcher` (classified errors)
Use when the data layer may have classified the error into a tagged class with dedicated troubleshooting UI. It looks up the error's class and renders the mapped `Troubleshooting` component, or `fallback` when there is no mapping. Today this is wired for the table editor sidebar; reach for it when adding troubleshooting for a new error type rather than as a general replacement for `AlertError`.
## `ErrorMatcher` usage
Pass the **full error object** from React Query — not `error.message`:
Reach for `ErrorMatcher` when adding dedicated troubleshooting steps for a classified error class (not as a general replacement for `AlertError`). Pass the **full error object** from React Query, never `error.message`:
```tsx
{
@@ -74,9 +71,7 @@ Pass the **full error object** from React Query — not `error.message`:
## What NOT to do
- Do not pass `error.message` to `ErrorMatcher` — pass the full `error` object so the class is preserved.
- Do not put regex patterns in `error-mappings.tsx` — they belong in `data/error-patterns.ts`.
- Do not use `Object.assign` to stamp a `_tag` onto an error — add a tagged class instead.
- Do not pass a raw URL string for support — use `supportFormParams={{ projectRef }}`.
- Do not put the page title inside the error mapping — it belongs on the `<ErrorMatcher>` caller.
- Do not add callback props (`onDebugWithAI`, `onRestartProject`) to troubleshooting components — use hooks inside them instead.
- Do not pass `error.message` to `ErrorMatcher`, put regex in `error-mappings.tsx`, or use `Object.assign` to stamp `_tag` (add a tagged class + pattern in `data/error-patterns.ts`).
- Do not pass a raw support URL (use `supportFormParams={{ projectRef }}`), put page titles inside error mappings, or add callback props (`onDebugWithAI`, `onRestartProject`) to troubleshooting components (use hooks inside them).
- Do not assume caught `unknown` rejections are `Error` instances (external/WASM libraries can reject with non-Errors) — use `getErrorMessage` from `@/lib/get-error-message`.
- Handle an error's user-facing side effect (toast or inline alert) in a **single layer** — do not toast and also rethrow to a caller that surfaces errors (or leave an unhandled rejection).
@@ -1,335 +0,0 @@
---
name: studio-mock-api-tests
description: Component tests for Supabase Studio that mock API requests at the
network layer with MSW. Use when writing or reviewing a component test that
exercises a React Query hook or mutation, or when migrating an existing
test away from vi.mock('@/data/...'). Covers the customRender + addAPIMock
template and the jsdom/MSW gotchas that cost real debugging time.
---
# Studio MSW component tests
Mount a Studio component, intercept its network calls with MSW, assert
what renders and what gets sent. The infrastructure is already wired up —
this skill is the working template plus the gotchas.
## When to use
- The component (or any descendant it renders) calls a React Query hook
or mutation that hits `/platform/...`, `/v1/...`, or another endpoint
in `apps/studio/data/api.d.ts`.
- You'd otherwise be tempted to write `vi.mock('@/data/some-query', ...)`.
**Don't.** Mock the network instead — see "Why not vi.mock" below.
If the component is purely presentational with no data fetching, you
don't need MSW; render and assert directly.
## The template
```tsx
import { screen } from '@testing-library/react'
import { platformComponents as components } from 'api-types'
import { mockAnimationsApi } from 'jsdom-testing-mocks'
import { HttpResponse } from 'msw'
import { describe, expect, test } from 'vitest'
import { MyComponent } from './MyComponent'
import { createMockOrganizationResponse } from '@/tests/helpers'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
type OrganizationResponse = components['schemas']['OrganizationResponse']
mockAnimationsApi()
describe('MyComponent', () => {
test('renders rows from the API', async () => {
addAPIMock({
method: 'get',
path: '/platform/organizations',
response: () =>
HttpResponse.json<OrganizationResponse[]>([
createMockOrganizationResponse({ name: 'Acme' }),
]),
})
customRender(<MyComponent />)
expect(await screen.findByText('Acme')).toBeInTheDocument()
})
})
```
Use `mockAnimationsApi()` when the component renders Radix UI that needs Web
Animations, such as a Sheet, Modal, or Popover. Add `fireEvent`, `waitFor`, or `userEvent` as the
interactions need them — see the gotchas below. Server lifecycle (`listen`/`resetHandlers`/
`close`) is handled by `apps/studio/tests/vitestSetup.ts` — handlers
registered via `addAPIMock` are scoped to the current test.
## Gotchas that will eat your afternoon
### 1. Path params use `:slug`, not `{slug}`
`addAPIMock` is typed from the OpenAPI `paths`, but path params are
remapped to MSW's `:param` format. Autocomplete will guide you, but if
typecheck reports the path isn't assignable, you're using the OpenAPI
`{slug}` form.
```ts
// ❌ TypeScript error, MSW won't match
path: '/platform/organizations/{slug}/projects'
// ✅ Correct
path: '/platform/organizations/:slug/projects'
```
### 2. Use `HttpResponse.json`, not `new HttpResponse`
For success responses, always go through `HttpResponse.json` — even for
204/201-no-content endpoints. A raw `new HttpResponse(null, { status: 201 })`
returns no content-type, and `openapi-fetch` can hang the mutation flow,
which silently breaks `onSuccess` callbacks.
```ts
// ❌ Mutation onSuccess silently never fires
response: () => new HttpResponse(null, { status: 201 })
// ✅ Works (pass the OpenAPI body shape explicitly — see gotcha #8)
response: () => HttpResponse.json<MyResponse>({}, { status: 201 })
```
### 3. Submit buttons in Sheets/Modals need `fireEvent.click`
The convention `<Button form={FORM_ID} type="submit" />` (button
outside the form, associated by id) doesn't reliably trigger submission
under `userEvent.click` in jsdom. Use `fireEvent.click` for the submit
button. If that still doesn't submit, call
`fireEvent.submit(document.getElementById(FORM_ID)!)` directly. Fill inputs
with `user.paste` rather than `user.type` (see "Keep Tests Fast" in
`studio-testing`).
```ts
await user.click(screen.getByPlaceholderText('value'))
await user.paste('hello')
fireEvent.click(await screen.findByRole('button', { name: 'Save' }))
```
### 4. Profile-gated queries need a `profileContext`
Many hooks (`useOrganizationsQuery`, anything in `data/projects/`,
anything that calls `useProfile`) refuse to fire until a profile is
loaded. Pass one explicitly:
```ts
import type { ProfileContextType } from '@/lib/profile'
const PROFILE_CONTEXT: ProfileContextType = {
profile: {
id: 1,
auth0_id: 'auth0|test',
gotrue_id: 'gotrue-test',
username: 'testuser',
primary_email: 'test@example.com',
first_name: null,
last_name: null,
mobile: null,
is_alpha_user: false,
is_sso_user: false,
disabled_features: [],
free_project_limit: null,
},
error: null,
isLoading: false,
isError: false,
isSuccess: true,
}
customRender(<MyComponent />, { profileContext: PROFILE_CONTEXT })
```
### 5. `useParams` is globally mocked to `{ ref: 'default' }`
You don't need to configure a router for project-scoped components.
Just use `'default'` as the project ref in your mock paths:
`/v1/projects/default/secrets`, `/platform/projects/default/...`. If
you need a different ref or dynamic route params read via `useParams`
from `'common'`, render the route with `renderRoute`
(`apps/studio/tests/lib/route-render.tsx`), which provides
`RenderedRouteContext` so the global `useParams` mock delegates to the
real hook. Passing `initialUrl` or `router` to `customRender` alone
still returns `{ ref: 'default' }` from `common`'s `useParams` (it only
drives TanStack Router hooks and `useFramework()`, unless the test also
restores the real `useParams` implementation).
### 6. Unhandled requests fail loudly — mock every endpoint a render triggers
`mswServer.listen({ onUnhandledRequest: 'error' })` is set globally. If a
component (or any child it renders) fires an unmocked request, you'll see
MSW errors in stderr and likely flaky behavior. Cards, lists, and details
panels often fire nested queries (e.g. `OrganizationCard` calls
`useOrgProjectsInfiniteQuery`) — read what the rendered subtree does and
mock those endpoints at the network boundary. Keep child components and hooks
real so the test exercises their integration. If a heavy dependency cannot run
in jsdom, use an existing injection point with a faithful test implementation
at its boundary, or extract the independently testable behavior. Do not replace
the child or shared hook with a module mock.
### 7. Don't put query strings in the handler `path`
`addAPIMock` accepts `?foo=bar` suffixes via `TrimQueryParams`, but the
helper strips them before matching. MSW v2 doesn't match query params via
path strings — read them inside the resolver instead:
```ts
addAPIMock({
method: 'get',
path: '/platform/projects',
response: ({ request }) => {
const limit = new URL(request.url).searchParams.get('limit')
// ...
},
})
```
### 8. Always pass an explicit generic to `HttpResponse.json`
`addAPIMock`'s resolver is typed against the OpenAPI success body (and the
standard `{ message: string }` error envelope, exported as `APIErrorBody`).
But MSW's `HttpResponse.json` uses `NoInfer`, so the body type doesn't
narrow from context. Pass the expected shape explicitly — it doubles as a
self-documenting contract assertion:
```ts
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
response: () => HttpResponse.json<OrganizationResponse[]>([...])
response: () =>
HttpResponse.json<APIErrorBody>({ message: 'Boom' }, { status: 500 })
```
A mock that drifts from the contract (wrong envelope, missing fields,
stale enum values) now fails at compile time, not at runtime. The cost is
one type annotation per resolver — well worth it.
For mocks at the network boundary, also prefer `createMockOrganizationResponse`
(returns the raw OpenAPI `OrganizationResponse`) over `createMockOrganization`
(which extends with frontend-derived `managed_by` / `partner_id` that the
query layer attaches). Same pattern applies to any type that's a frontend
extension of an OpenAPI schema: build a `createMockXResponse` helper that
returns the raw API shape.
### 9. Mock FGA permissions with `mockPermissions`
Components that check permissions (`useGrant`, `useAsyncCheckPermissionsV2`)
request `/platform/profile/permissions/v2`. There's no global default — mock it
in each test that needs it:
```ts
import { mockPermissions, mockPermissionsError } from '@/tests/lib/msw-permissions'
import { allPermissionsFor, NO_PERMISSIONS } from '@/tests/lib/permissions-fixtures'
mockPermissions(allPermissionsFor(['my-org'])) // everything in my-org
mockPermissions(NO_PERMISSIONS) // denied everywhere
mockPermissions({ organizations: [{ slug: 'my-org', role: 'developer', permissions: [...], projects: [] }] })
mockPermissionsError({ status: 500 }) // grant resolves to an error
```
Unit tests of fetchers or query options that take a grant can use
`testGrant(endpoint, { projectRef })` from `@/tests/lib/test-grant` instead of
going through permissions at all.
## Prefer asserting on UI state
MSW's own best-practices doc explicitly recommends asserting on what
renders, not on whether a handler was called. The "did the form
submit?" question is best answered by `expect(onClose).toHaveBeenCalled()`
or by `findByText('Saved')` — not by spying on the resolver.
There's one legitimate exception: **the request body itself is the
contract you care about**, and the server's reply doesn't reflect it
back. Bulk-create endpoints (like `POST /v1/projects/:ref/secrets`) are
the canonical case — 201 with no body, so the only way to verify the
shape sent is to capture it:
```ts
const requests: Array<{ ref: string | undefined; body: unknown }> = []
addAPIMock({
method: 'post',
path: '/v1/projects/:ref/secrets',
response: async ({ request, params }) => {
requests.push({ ref: params.ref as string | undefined, body: await request.json() })
return HttpResponse.json<CreateSecretsResponse>({}, { status: 201 })
},
})
// ... drive the UI ...
expect(requests).toEqual([{ ref: 'default', body: [{ name: 'API_KEY', value: 'new-value' }] }])
```
When in doubt, assert on the UI first; reach for request capture only
when the UI doesn't observably encode the contract.
## Debugging an MSW test
If a request isn't being matched, wire up MSW's lifecycle events at the
top of the test file (or temporarily in `msw.ts`):
```ts
import { mswServer } from '@/tests/lib/msw'
mswServer.events.on('request:unhandled', ({ request }) => {
console.log('[MSW] UNHANDLED:', request.method, request.url)
})
mswServer.events.on('response:mocked', ({ request, response }) => {
console.log('[MSW] MATCHED:', request.method, request.url, response.status)
})
```
`request:start` is already wired in `msw.ts`. Add `request:unhandled` and
`response:mocked` locally when a test misbehaves — usually surfaces a
path-param mismatch or a nested query you forgot to mock.
## Why not `vi.mock('@/data/...')`
It bypasses the network boundary, so:
- It hides real bugs: a renamed query key or a changed request payload
passes the test, then breaks in production.
- It doesn't exercise React Query's caching, retry, or invalidation
paths — `onMutate`, `onSuccess`, and `onError` callbacks won't run as
they do in real life. ([tkdodo.eu/blog/testing-react-query](https://tkdodo.eu/blog/testing-react-query))
- It drifts independently from the OpenAPI types — handlers stay in sync,
module-level mocks don't.
Do not add module mocks for non-network dependencies either. Use supported
providers and context for shared state, inject a faithful boundary implementation
for unavailable infrastructure, or extract logic behind a useful public contract.
Keep the interactions under test real.
The existing global harness includes router and environment mocks. Use its
supported configuration instead of adding local replacements; this guidance does
not require migrating unrelated harness mocks as part of a focused test change.
## Further reading
- [TkDodo — Testing React Query](https://tkdodo.eu/blog/testing-react-query) —
canonical reference for the principles behind everything in this skill.
- [MSW best practices: structuring handlers](https://mswjs.io/docs/best-practices/structuring-handlers/)
and [overriding network behavior](https://mswjs.io/docs/best-practices/network-behavior-overrides/) —
the baseline-handlers + per-test-`server.use()` pattern.
- [MSW best practices: avoid request assertions](https://mswjs.io/docs/best-practices/avoid-request-assertions/) —
the source of the "assert on UI state" guidance above.
## Codebase references
| What | Where |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| Query-only example (loading, error, success) | `apps/studio/components/interfaces/Organization/OrgNotFound.test.tsx` |
| Mutation example (form, payload assertion) | `apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EditSecretSheet.test.tsx` |
| SQL-via-pg-meta example (POST resolver branch on `query` body) | `apps/studio/components/interfaces/Integrations/Vault/Secrets/__tests__/EditSecretModal.test.tsx` |
| `addAPIMock` source | `apps/studio/tests/lib/msw.ts` |
| `customRender` source | `apps/studio/tests/lib/custom-render.tsx` |
| Global handlers + lifecycle | `apps/studio/tests/lib/msw-global-api-mocks.ts`, `apps/studio/tests/vitestSetup.ts` |
| Permissions mocks + `testGrant` | `apps/studio/tests/lib/msw-permissions.ts`, `apps/studio/tests/lib/test-grant.ts` |
| Related skills | `studio-testing` (when to write a component test at all), `studio-queries` (hook conventions), `vitest` |
+55 -56
View File
@@ -11,10 +11,17 @@ description: React Query conventions for data fetching in Supabase Studio. Use w
Follow the patterns in `apps/studio/data/`. Reference examples:
- Query options: `apps/studio/data/table-editor/table-editor-query.ts`
- Mutation hook: `apps/studio/data/edge-functions/edge-functions-update-mutation.ts`
- Query options: `apps/studio/data/storage/bucket-lifecycle-query.ts` (plain) and `apps/studio/data/jwt-signing-keys/jwt-signing-keys-query.ts` (`grantedQueryOptions`)
- Mutation hook: `apps/studio/data/storage/versioning/archived-object-restore-mutation.ts`
- Keys: `apps/studio/data/edge-functions/keys.ts`
## Folder Boundaries
- Keep `apps/studio/data/` strictly for React Query queries, mutations, and query keys — never put UI formatting or URL helpers in `data/` (colocate those with the feature under `components/interfaces/`).
- Pass scoping identifiers (`projectRef`, `clusterId`, etc.) explicitly in `variables` — never read ambient React Context inside `data/**` hooks.
- Keep `create-*-mutation.ts` and `update-*-mutation.ts` separated; put shared payload builders and types in sibling `types.ts` / `utils.ts` files inside the domain folder.
- Derive response types from generated `packages/api-types` (see [api-types](../api-types/SKILL.md)) — fix contract drift at the source rather than hiding it with `as unknown as CustomType` or defensive `Array.isArray(data) ? data : []` shims.
## Query Keys
Define a `keys.ts` per domain. Export `*Keys` helpers using array keys with `as const`. Never inline query keys in components.
@@ -24,25 +31,29 @@ export const edgeFunctionsKeys = {
list: (projectRef: string | undefined) => ['projects', projectRef, 'edge-functions'] as const,
detail: (projectRef: string | undefined, slug: string | undefined) =>
['projects', projectRef, 'edge-function', slug, 'detail'] as const,
metrics: (projectRef: string | undefined, params?: { interval?: string; limit?: number }) =>
['projects', projectRef, 'edge-functions', 'metrics', ...(params ? [params] : [])] as const,
}
```
Key hygiene rules:
- **Never flatten multiple optional positional params with `.filter()`**: `[..., limit, offset].filter((v) => v !== undefined)` collides when `(10, undefined)` vs `(undefined, 10)`. Group optional filter/pagination params into one object and spread trailing optional params (`...(params ? [params] : [])`) so `keys.metrics(ref)` doubles as the prefix key for invalidation.
- **Never fork/suffix cache keys** for the same underlying endpoint (e.g. `[...queryKey, 'permission-safe']`) — reuse the canonical `queryOptions` and layer `select` or fallbacks on top.
- Pass key-factory keys to `invalidateQueries` / `removeQueries` (never manual array-index predicates), and check TanStack Query prefix matching before issuing redundant child invalidations.
## Query Options (preferred pattern)
Use `queryOptions` from `@tanstack/react-query`. This gives type safety and works with both `useQuery()` and `queryClient.fetchQuery()`.
Use `queryOptions` from `@tanstack/react-query` so one definition works for both `useQuery()` and `queryClient.fetchQuery()`.
Rules:
- Export `XVariables`, `XData`, and `XError` types (prefixed with the domain name)
- Implement a **private** `getX(variables, signal?)` function:
- Throws if required variables are missing
- Passes `signal` for cancellation
- Calls `handleError(error)` on failure (which throws); returns `data` on success
- Not exported — use `queryClient.fetchQuery(xQueryOptions(...))` for imperative fetching
- Export `xQueryOptions()` using `queryOptions`
- Gate with `enabled` so the query doesn't run until required variables exist
- Platform-only queries: include `IS_PLATFORM` from `lib/constants` in `enabled`
- Don't add extra params to `xQueryOptions` — callers override by destructuring: `{ ...xQueryOptions(vars), enabled: true }`. Exception: grant-gated queries (see below)
- Export domain-prefixed `XVariables`, `XData`, and `XError` types.
- Implement a **private** `getX(variables, signal?)` function that validates required variables, forwards `signal`, calls `handleError(error)` on failure, and returns `data`. Do not export it — use `queryClient.fetchQuery(xQueryOptions(...))` for imperative fetching.
- Export `xQueryOptions()` gated with `enabled` on required variables (plus `IS_PLATFORM` from `lib/constants` for platform-only queries).
- **Parent `isPending` trap**: when gating on a negated value derived from another async query (e.g. `enabled: !isHighAvailability`), also gate on `!isParentPending` (`enabled: !isPending && !isHighAvailability`) so it does not fire while the parent query is unsettled.
- Default optional opt-in enable flags to `false` (safe-by-default), never `true`.
- Match query params (such as `limit`) across sibling consumers so they share one cache entry.
- **Custom polling & retries**: `apps/studio/data/query-client.ts` already skips 4xx (except 429) and retries 429/5xx globally. When writing custom `refetchInterval` or `retry` overrides, use a conservative interval (e.g. `5_000`ms, never `1_000`ms), back off on all `error.code >= 400`, and retry transient error classes (`error.code === 429 || error.code >= 500`) rather than individual status codes.
- **Caller overrides & `enabled`**: spread non-`enabled` options (`{ ...xQueryOptions(vars), select, refetchInterval }`) freely. Never override `enabled` directly (e.g. `{ ...xQueryOptions(vars), enabled: isOpen }`) — that clobbers the factory's `IS_PLATFORM` / required-variable gate. Instead, preserve the factory gate (`const opts = xQueryOptions(vars); useQuery({ ...opts, enabled: opts.enabled !== false && isOpen })`) or accept an optional 2nd `{ enabled = true }` arg in the factory and AND it with the factory's gates (except grant-gated queries below, which always take caller options as the 2nd arg).
```ts
import { queryOptions } from '@tanstack/react-query'
@@ -68,16 +79,19 @@ async function getX({ projectRef }: XVariables, signal?: AbortSignal) {
export type XData = Awaited<ReturnType<typeof getX>>
export const xQueryOptions = ({ projectRef }: XVariables) =>
queryOptions({
queryOptions<XData, XError>({
queryKey: xKeys.list(projectRef),
queryFn: ({ signal }) => getX({ projectRef }, signal),
enabled: IS_PLATFORM && typeof projectRef !== 'undefined',
})
```
## Grant-gated queries
## Grant-gated Queries
Query options that take a `grant` (see `lib/grants.ts`) are an exception to the spread-and-override guidance. Build them with `grantedQueryOptions` from `@/data/granted-query-options`, and let callers pass their options as the **second argument**. Never spread them.
Query options requiring a `grant` (`lib/grants.ts`) use `grantedQueryOptions` from `@/data/granted-query-options` and accept caller options as the **second argument**. Never spread or `Object.assign` them (`fga/no-spread-granted-query-options` enforces this via the branded `__grantedQueryOptions` return type).
- Pass `queryFn: undefined` (never `skipToken`, which breaks invalidation when a grant-less observer shares the cache entry) when a grant or required variable is missing; `grantedQueryOptions` forces `enabled: false` and supplies a delegating fallback `queryFn` (avoiding TanStack's dev `No queryFn` error).
- The factory owns `queryKey`, `queryFn`, and the grant `enabled` gate so callers cannot override the grant check.
```ts
export const xQueryOptions = <TData = XData>(
@@ -97,44 +111,34 @@ export const xQueryOptions = <TData = XData>(
useQuery(xQueryOptions({ projectRef, grant: xGrant.grant }, { select, enabled: open }))
```
Why: TanStack keeps one options object per cache entry, overwritten by whichever observer rendered last, and invalidation refetches with it. A factory passes `queryFn: undefined` when a grant or required variable is missing; `grantedQueryOptions` forces `enabled: false` and substitutes a delegating placeholder `queryFn` (not `skipToken`, which would make invalidation fail with `Missing queryFn` if a grant-less observer rendered last, and not leaving `queryFn: undefined`, which triggers TanStack's dev-mode `No queryFn was passed` console error on every render). The helper owns `queryKey`, `queryFn`, and the `enabled` gate, so a caller can't override the grant check. `grantedQueryOptions` brands its return type (a type-only `__grantedQueryOptions` property), and the type-aware `fga/no-spread-granted-query-options` lint rule reports any object spread or `Object.assign` of a branded value, however it was obtained (variable, wrapper, renamed import).
## Using Query Options in Components
## Component & Imperative Usage
```ts
import { useQuery } from '@tanstack/react-query'
import { xQueryOptions } from '@/data/x/x-query'
// Component
const { data, isPending, isError } = useQuery(xQueryOptions({ projectRef: project?.ref }))
```
## Imperative Fetching (outside React or in callbacks)
```ts
// Imperative (callbacks / outside React) — fetchQuery ignores `enabled`, so mirror factory gates first
const queryClient = useQueryClient()
const { data: project } = useSelectedProjectQuery()
const handleClick = useCallback(
async (id: number) => {
const data = await queryClient.fetchQuery(xQueryOptions({ id, projectRef: project?.ref }))
// use data...
},
[project?.ref, queryClient]
)
if (IS_PLATFORM && project?.ref) {
const data = await queryClient.fetchQuery(xQueryOptions({ projectRef: project.ref }))
}
```
- Use React Query v5 flags (`isPending` for initial load, `isFetching` for background refetches) and render states in order: pending → error → success.
- Call query hooks directly in consuming child/modal components instead of fetching in a parent solely to prop-drill `data`/`isPending`/`isError`; use `select` for single-consumer derived values instead of one-off wrapper hooks.
- Gate infinite-scroll `fetchNextPage()` behind `!isFetching` (or `!isFetchingNextPage`) to prevent duplicate page requests.
- Never `await mutate(...)` (`mutate` returns `void`). Prefer `mutate` + callbacks over `mutateAsync` unless a Promise is needed (e.g. an async dialog loading state or sequential flow), and always wrap `mutateAsync` in `try/catch` (never empty `catch { return }`).
- Read mutation `error` directly from `useMutation()` instead of mirroring it in `useState`, and pass cross-callback mutation state via React Query `context` (`onMutate` → `onSuccess`/`onSettled`) instead of a `useRef`.
## Mutation Hook
- Export a `Variables` type with `projectRef`, identifiers, and `payload`
- Implement a private `updateX(vars)` function with required variable validation and `handleError`
- Wrap in `useXMutation()`:
- Accepts `UseMutationOptions` (omit `mutationFn`)
- Invalidates `list()` + `detail()` keys in `onSuccess` with `await Promise.all([...])`
- Defaults to `toast.error(...)` when `onError` isn't provided
- Export a `Variables` type (`projectRef`, identifiers, `payload`), implement a private `updateX(vars)` function with variable validation and `handleError`, and wrap in `useXMutation()` accepting `Omit<UseMutationOptions<...>, 'mutationFn'>` (forwarding all 4 TanStack v5 callback args; existing hooks using `UseCustomMutationOptions` from `@/types` use a 3-arg callback contract).
- Don't destructure `onSuccess` unless adding custom `onSuccess` logic — otherwise caller `onSuccess` callbacks are silently swallowed (let `...options` forward it).
- In `onSuccess`, `await Promise.all([...])` to invalidate every view staled by the mutation via key factories, without wiping freshly prefetched keys or unrelated user/resource scopes.
- **Single-layer error toasts**: default to `toast.error(...)` only when `onError === undefined`; if callers handle errors inline or imperatively via `mutateAsync` + `catch`, pass a custom `onError` (or omit the default toast when all callers handle errors themselves) to avoid duplicate toasts.
```ts
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query'
import { toast } from 'sonner'
import { xKeys } from './keys'
@@ -145,29 +149,24 @@ export const useXUpdateMutation = ({
onSuccess,
onError,
...options
}: UseMutationOptions<XData, XError, XUpdateVariables> = {}) => {
}: Omit<UseMutationOptions<XData, XError, XUpdateVariables>, 'mutationFn'> = {}) => {
const queryClient = useQueryClient()
return useMutation({
return useMutation<XData, XError, XUpdateVariables>({
mutationFn: updateX,
async onSuccess(data, variables, context) {
async onSuccess(data, variables, context, mutationContext) {
await Promise.all([
queryClient.invalidateQueries({
queryKey: xKeys.detail(variables.projectRef, variables.slug),
}),
queryClient.invalidateQueries({ queryKey: xKeys.list(variables.projectRef) }),
])
await onSuccess?.(data, variables, context)
await onSuccess?.(data, variables, context, mutationContext)
},
async onError(error, variables, context) {
async onError(error, variables, context, mutationContext) {
if (onError === undefined) toast.error(`Failed to update: ${error.message}`)
else onError(error, variables, context)
else await onError(error, variables, context, mutationContext)
},
...options,
})
}
```
## Component Usage
- Use React Query v5 flags: `isPending` for initial load, `isFetching` for background refetches
- Render states explicitly in order: pending → error → success
+105
View File
@@ -0,0 +1,105 @@
---
name: studio-routes
description: TanStack Start routing and server API handler conventions for Supabase Studio.
Use when adding or modifying file routes under apps/studio/routes/**, layout shells,
permanent redirects in redirects.shared.ts, URL params or search state, or server API
endpoints under apps/studio/routes/api/**.
---
# Studio Routes & Server API Handlers
Routes live under `apps/studio/routes/**` using TanStack Start file-based routing. `apps/studio/routeTree.gen.ts` is generated by the Vite plugin — never hand-edit it.
## File Routes & Layouts (`routes/**`)
- Use native TanStack Router APIs (`createFileRoute`, `Link`, `useNavigate`, `Route.useParams()` inside route files, `useSearch`) — never import from `next/*`. Inside shared components under `components/**`, use `useParams()` from `'common'` (do not mix `useParams()` and `Route.useParams()` in the same file).
- Route files export only `Route`. Shared components live in `components/**`; avoid trivial pass-through wrappers (`function FooPage() { return <FooContent /> }`).
- Layouts are pathless (`routes/_app.tsx`, `routes/_auth.tsx`) or sibling-file shells (`routes/project/$ref/database.tsx` wraps `routes/project/$ref/database/**`); layouts like `routes/_app.tsx` and section shells read route metadata via `staticData`.
- In layout shells, always pass `select` to `useMatches({ select })` — calling `useMatches()` without `select` returns a fresh array on every router tick and re-renders the entire shell subtree.
## Navigation, Params & Redirects
- Use typed `<Link to="..." params={...} search={...}>` for known internal routes, and render navigation triggers as `<Button asChild><Link ...>` rather than `<button onClick={() => navigate(...)}>` so `⌘`/middle-click works. (For `InlineLink`, `DynamicLink`, `SupportLink`, and external `DOCS_URL` links, see `studio-ui-patterns`.)
- Prefer TanStack Router location APIs over `window.location` (Router strips `BASE_PATH` automatically). Avoid `?error=` and mixing `useParams` (see `apps/studio/AGENTS.md`).
- Validate untrusted search/route params at entry with Zod, encode dynamic segments with `encodeURIComponent` when interpolating into URLs (always validate path identifiers with an explicit allowlist regex too — `encodeURIComponent` leaves `.` and `..` intact, allowing dot-segment traversal), and avoid leaking unrelated contextual search params across routes.
- Register permanent route moves directly to their final destination in `apps/studio/redirects.shared.ts` (avoid multi-hop chains; consumed by both `apps/studio/vercel.ts` and `apps/studio/routes/__root.tsx`) and delete replaced route files.
## Server API Routes (`routes/api/**`)
Wrap every server route handler with `createApiHandlers(handlers, { withAuth })` from `@/lib/api/apiWrapper`:
- Registers `ANY` (and guards `HEAD` on `GET`-only routes) to return `405` + `Allow`, preventing unregistered methods from falling through to the SSR HTML shell.
- Converts `InvalidJsonError` (thrown by `parseJsonBody` from `@/lib/api/apiHelpers`) into `400`.
- Captures unexpected exceptions in Sentry and returns `500`.
- Verifies the platform JWT when `{ withAuth: true }` and attaches `claims` to `ApiHandlerContext`.
### Canonical template
```ts
import { createFileRoute } from '@tanstack/react-router'
import { z } from 'zod'
import { parseJsonBody } from '@/lib/api/apiHelpers'
import { createApiHandlers, type ApiHandlerContext } from '@/lib/api/apiWrapper'
import { IS_PLATFORM } from '@/lib/constants'
import { getErrorMessage } from '@/lib/get-error-message'
const RequestSchema = z.object({
// Allowlist rejects dot-segment traversal
projectRef: z.string().regex(/^[a-z0-9-]+$/i),
})
async function handlePost({ request, claims }: ApiHandlerContext) {
if (!IS_PLATFORM) {
return Response.json({ error: { message: 'Platform only' } }, { status: 404 })
}
const upstreamUrl = process.env.UPSTREAM_API_URL
if (!upstreamUrl) {
return Response.json({ error: { message: 'Missing UPSTREAM_API_URL' } }, { status: 500 })
}
const parsed = RequestSchema.safeParse(await parseJsonBody(request))
if (!parsed.success) {
return Response.json({ error: { message: 'Invalid request body' } }, { status: 400 })
}
const response = await fetch(
`${upstreamUrl}/projects/${encodeURIComponent(parsed.data.projectRef)}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: claims?.sub }),
}
)
if (!response.ok) {
const body = await response.json().catch(() => null)
const fallback = response.statusText || 'Upstream request failed'
const message = getErrorMessage(body?.error) ?? getErrorMessage(body, fallback)
return Response.json({ error: { message } }, { status: response.status || 500 })
}
const text = await response.text()
if (!text) return new Response(null, { status: response.status })
return Response.json(JSON.parse(text), { status: response.status })
}
export const Route = createFileRoute('/api/example')({
server: {
handlers: createApiHandlers({ POST: handlePost }, { withAuth: true }),
},
})
```
### Server handler rules
- **Auth by default**: Pass `{ withAuth: true }` on auth, sensitive, external-proxy, and non-trivial mutating routes. Read `claims` from `ApiHandlerContext` instead of re-calling `authenticateRequest` / `getUserClaims`.
- **Standardized errors & upstream status**: Return errors as `{ error: { message } }` (extracting upstream error messages via `getErrorMessage` from `@/lib/get-error-message`). Always check `response.ok`, handle empty/bodyless success responses before parsing JSON, and propagate upstream HTTP status codes (falling back to `500` on errors).
- **Boundary validation & env guards**: Parse JSON bodies with `parseJsonBody(request)` + Zod and query strings with `getSearchParamsRecord(url.searchParams)` + Zod, using allowlist patterns for URL path identifiers. Guard required `process.env.*` variables explicitly rather than using `!`.
- **`IS_PLATFORM` & lazy server clients**: `withAuth` is a no-op when `!IS_PLATFORM`. Gate platform-only vs self-hosted handlers explicitly. The TanStack Start server eagerly evaluates every route module at boot, so never construct a Supabase client at module scope — use `selfHostedSupabaseAdmin` from `@/lib/api/self-hosted-admin` or construct lazily inside the handler. (ESLint only catches direct top-level `createClient(...)` calls in `routes/**`, not `new SupabaseClient(...)`, aliases, helper factories, or imported `lib/**` modules.)
## Knip Entry Points
`routes/**/*.{ts,tsx}` is already registered under `workspaces["apps/studio"].entry` in `knip.jsonc`. If you add another framework-convention file that nothing imports directly, register it under `entry` — not `ignore` (an ignored file's imports are not traced, causing its dependencies to fail Knip as unused).
+7 -8
View File
@@ -1,11 +1,10 @@
---
name: studio-shortcuts
description: Keyboard shortcut conventions for Supabase Studio. Use when adding a
repeated user action, toolbar action, list/table operation, or sub-page navigation
that should have shortcut coverage, when registering or changing a shortcut, or when
adding a search/filter Input (which needs the staged-Escape handler). Covers the
shortcut registry, useShortcut, ShortcutTooltip/ShortcutBadge, the reference sheet,
and collision rules.
description: Keyboard shortcut conventions for Supabase Studio. Use when adding
shortcuts for repeated actions, toolbars, list/table operations, or sub-page
navigation, or when adding a search/filter Input (staged-Escape handler). Covers
the shortcut registry, useShortcut, ShortcutTooltip/ShortcutBadge, reference sheet,
and collisions.
---
# Studio Keyboard Shortcuts
@@ -29,7 +28,7 @@ When Studio UI changes introduce or materially alter repeated user actions, cons
- Surface visible actions with `ShortcutTooltip` or `ShortcutBadge`.
- Prefer scoped, mnemonic sequential chords over global modifier chords.
- Set `showInSettings: false` on contextual shortcuts (scoped to a specific page state, sheet, or panel).
- When a shortcut group should appear in the reference sheet (`Shift+?`), add the group key to `SHORTCUT_REFERENCE_GROUP_ORDER` in `apps/studio/state/shortcuts/referenceGroups.ts` and a human label to `GROUP_LABELS` in `ShortcutsReferenceSheet.tsx`.
- Active shortcuts appear in the reference sheet (`Shift+?`) automatically; set group ordering via `SHORTCUT_REFERENCE_GROUP_ORDER` (and labels for `SHORTCUT_REFERENCE_GROUPS` via `SHORTCUT_REFERENCE_GROUP_LABELS`) in `apps/studio/state/shortcuts/referenceGroups.ts`, or add prefix-group labels to `GROUP_LABELS` in `apps/studio/components/ui/GlobalShortcuts/ShortcutsReferenceSheet.tsx`.
- For sheet-scoped shortcuts (active only while a `<Sheet>` is open), mount `useShortcut` inside the sheet component gated by the `open` prop (`{ enabled: open }`) — `apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksDeliveryDetailsSheet.tsx` is the canonical example. A shortcut that _opens_ a sheet from anywhere is global instead, gated by whatever makes the action valid (e.g. `useConnectSheetShortcut` checks project health).
## Search inputs
@@ -52,7 +51,7 @@ Behavior:
- **Escape while the input is empty** → blurs the input
- Stops propagation on Escape so the keystroke does not accidentally close a parent dialog or sheet
When pairing with `useShortcut(LIST_PAGE_FOCUS_SEARCH, ...)` to focus a search input via keyboard, always also add `onSearchInputEscape` on the same input — focus and escape-to-blur are always a pair.
When pairing with `useShortcut(SHORTCUT_IDS.LIST_PAGE_FOCUS_SEARCH, ...)` to focus a search input via keyboard, always also add `onSearchInputEscape` on the same input — focus and escape-to-blur are always a pair.
## Key files
+170 -165
View File
@@ -1,79 +1,145 @@
---
name: studio-testing
description: Testing strategy for Supabase Studio. Use when selecting, writing,
or reviewing tests, or extracting logic for testing. Covers meaningful unit,
component, and E2E coverage and scoped verification.
description: Testing strategy and quality bar for Supabase Studio (apps/studio).
Use when deciding whether a change needs a test, writing unit or component
tests, mocking API requests with MSW, reviewing or pruning low-value tests,
or debugging test speed and flakiness.
---
# Studio Testing Strategy
Protect meaningful observable behavior and plausible regressions. Choose the
fastest test that catches the failure; do not chase coverage percentages or
exhaustive input permutations.
Write tests only when they guard a plausible runtime regression that static
analysis cannot catch. Choose the fastest layer that catches the failure; never
add tests merely because a file changed or to chase coverage percentages.
## Choose coverage by behavior
## 1. "Should I Write a Test?" Gate
Before adding a test, identify what would get worse for a user or caller if the
behavior broke. Read nearby tests first so new coverage fills a real gap.
### Step 1 — Do NOT write a test when the change is solely:
| Layer | Use for |
| --------------- | -------------------------------------------------------------------------------------------------------------- |
| Static analysis | Types, invalid imports, and other guarantees the compiler or linter already checks |
| Unit tests | Pure calculations, parsing, validation, permissions, and data transformations |
| Component tests | Rendered behavior and consequential interactions, including simple forms that submit, mutate data, or navigate |
| E2E tests | Critical user journeys and integration or environment differences that lower layers cannot establish |
- **Static guarantees:** TypeScript types, `satisfies Record<K, V>`
exhaustiveness, OpenAPI request/response shapes, ESLint rules, Knip dead-code
checks, or import paths.
- **Pass-through or declarative code:** Pure markup, layout, or styling; static
copy or link-href updates; constant maps not verified against an external
contract; re-exports; field-assigning constructors; or thin wrappers
forwarding props.
- **Standard data layer (`apps/studio/data/**`):** Thin React Query hooks,
mutations, `openapi-fetch` param forwarding, `handleError` pass-through, or
`keys.ts` factories. _(Exceptions: non-trivial client transforms/parsers,
custom retry/caching state machines, or `testGrant` security boundaries.)_
- **Library or language behavior:** Zod built-in type/enum/required checks,
TanStack Query staying idle on `{ enabled: false }`, Radix opening/closing a
dialog, or JavaScript `?.`, `||`, and `Array.filter`.
- **Trivial one-line predicates:** Single-expression boolean checks (e.g.
`error?.code === 507`) unless part of a multi-branch domain matrix or a
regressed bug.
Extract pure logic into a co-located `.utils.ts` when that clarifies the component
and gives the logic a useful independent contract. Do not extract solely to avoid
testing the component's wiring. Utility tests commonly live under
`apps/studio/tests/components/.../ComponentName.utils.test.ts`, mirroring the
source path; follow nearby conventions for co-located tests.
### Step 2 — Write the smallest test at the highest-leverage layer for:
Cover expected usage, realistic failures, relevant boundaries, and known
regressions. For a bug fix, reproduce the failure before fixing it. Respect
backend and API guarantees rather than inventing unsupported inputs. A change
to prose, a constant, a re-export, pure markup, or a guarantee already established
by static analysis does not need a new test merely because a file changed.
| Layer | Use for |
| --------------- | ---------------------------------------------------------------------------------------------- |
| Static analysis | Types, `satisfies`, OpenAPI shapes, ESLint, Knip — no runtime test needed |
| Unit tests | Non-trivial pure logic: parsers, SQL/URL builders, scoring, date/state math, permission matrix |
| Component tests | Consequential UI state machines, form submit/rollback, partial failures, flag/permission gates |
| E2E tests | Critical journeys or platform vs self-hosted differences lower layers cannot establish |
## Assert observable outcomes
Co-locate new tests directly beside the source file (`Foo.test.tsx`,
`Foo.utils.test.ts`); older tests still live under `apps/studio/tests/`. Extract
pure logic to `.utils.ts` only when it clarifies the component and gives the
logic a real independent contract — never extract a one-liner just to unit-test
it. For a bug fix, reproduce the failure in a test before fixing it.
Test what the end user sees and does, or the public contract a caller consumes.
Prefer roles and labels to test IDs. Check visible text, disabled state,
navigation, public callbacks, or a meaningful request contract.
## 2. Six Categorical Quality Litmus Tests
Do not assert on internal state, refs, private methods, child-component render
spies, hook calls inside components, CSS classes, DOM structure, or whole-tree
snapshots as proxies for behavior. A behavior-preserving refactor should not
require changing assertions. Pure utility input/output tests remain valid when
they protect a public contract.
Read nearby tests before adding new ones so each test fills a real gap. Run
these checks before committing or during code review; failing any check means
**delete or rewrite the test** (when pruning, preserve distinct boundary,
permission, security, error, and historical-data cases, and rewrite brittle
assertions around observable contracts before deleting a regression's only
guard):
Reuse production definitions, representative inputs, and existing test factories
before copying configuration or API fixtures. Keep expected outcomes independent:
do not calculate an expected result with the same helper being tested. Small
explicit inputs are useful when they make a calculation or boundary clear.
1. **Static-Analysis Kill:** If breaking the guarded behavior already fails
`pnpm typecheck`, ESLint, Knip, or OpenAPI types, delete the test.
2. **Concrete-Regression:** State in one sentence a realistic production bug
that would ship unnoticed without this test (not "someone edits this string").
If you cannot, delete it.
3. **Mirror / Tautology:** Delete tests that restate implementation literals or
Zod schemas, compute expected values with the helper under test, verify your
mock returned what you configured, or assert on a flag (`{ enabled: false }`)
the test itself hardcoded.
4. **No-Deformation:** Never add an unused optional prop (e.g. `onRedirect`),
test-only default parameter, or `// Exported for testing` helper just to test
code. Revert the seam and test the observable boundary, or delete the test.
5. **Behavior-Survives-Refactor:** Assert visible text, roles, labels, disabled
state, navigation, or network contracts — never CSS classes (`toHaveClass`,
`querySelector('.flex...')`), DOM structure, internal spies, or whole-tree
snapshots. Note `focusableWhenDisabled` buttons (including disabled
`ButtonTooltip`s) set `aria-disabled="true"` rather than `disabled`, so
assert `toBeAriaDisabled()` or `toHaveAttribute('aria-disabled', 'true')`.
For SQL generators, normalize with `apps/studio/lib/formatSql.ts` and assert
full formatted SQL instead of fragile `toContain` checks. Remove obsolete
`vi.mock(...)` stubs and stale assertions when refactoring.
6. **Async Honesty:** Always `await` `waitFor` and `expect(...).resolves`
assertions. Never test blocked async submission with bare
`await waitFor(() => expect(onSubmit).not.toHaveBeenCalled())` — it passes
immediately before `onSubmit` runs; assert on a visible validation error or
settled UI state instead. Use fake timers, never real sleeps.
Remove redundant cases when they catch the same failure. Use `test.each` for
distinct scenarios sharing a setup, not to multiply equivalent literals.
Preserve distinct boundary, permission, security, error, and historical-data
coverage. If a brittle assertion is the only protection for a meaningful
regression, replace it with an observable assertion before removing it.
## 3. Concrete Before / After Examples
## Component and E2E integration
**TypeScript-redundant constant check -> Delete:**
Use `customRender` from `@/tests/lib/custom-render` for Studio providers. Mock
API requests at the network boundary with `addAPIMock`, keeping real query and
mutation behavior. Pass the OpenAPI body type to `HttpResponse.json<…>`:
```ts
// BAD: `EMAIL_TEMPLATE_DOCS_ANCHORS` already uses `satisfies Record<AuthTemplateType, string>`.
it('covers every template type', () => {
expect(Object.keys(EMAIL_TEMPLATE_DOCS_ANCHORS).sort()).toEqual([...AUTH_TEMPLATE_TYPES].sort())
})
// AFTER: Delete the test. Keep constant tests only when checking an external contract
// (e.g. an external package JSON schema).
```
**Thin fetcher or one-line predicate -> Delete (or test the UI outcome):**
```ts
// BAD: OpenAPI already types query params; `error?.code === 507` is a one-liner.
it('is true for 507', () => expect(isFunctionBodyMaxSizeError({ code: 507 })).toBe(true))
// AFTER: Delete the unit test. If the UI fallback on 507 matters, write one MSW
// component test returning status 507 and asserting the user sees the CLI fallback.
```
**Schema restatement -> Prune built-ins, keep custom rules:**
```ts
// BAD: Re-testing `z.string()`, `z.enum()`, and required fields across every schema variant.
// AFTER: Delete tests of Zod primitives. Test only custom transforms and cross-field
// invariants (e.g. normalizing `""` to `undefined`, or `start < end` error path attribution).
```
**Test-only prop seam -> Revert seam and delete test:**
```tsx
import { screen } from '@testing-library/react'
import { platformComponents as components } from 'api-types'
import { HttpResponse } from 'msw'
// BAD: Adding `onRedirect = replaceLocation` with zero production callers just to spy in tests.
// AFTER: Remove the test-only prop and delete the wrapper test. Test pure URL logic
// directly only if it has real parsing or encoding edge cases.
```
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
**`vi.mock('@/data/...')` + CSS + broken async -> One behavioral MSW test:**
type OrganizationResponse = components['schemas']['OrganizationResponse']
```tsx
// BAD: vi.mock('@/data/...') + expect(el).toHaveClass('text-destructive-600')
// + await waitFor(() => expect(onSubmit).not.toHaveBeenCalled())
// AFTER: Mock the HTTP endpoint with `addAPIMock`, drive the form, and assert the
// rendered error/recovery state (e.g. `await screen.findByText(/failed/i)`).
```
## 4. Component (MSW) & E2E Integration
Mount components with `customRender` (`@/tests/lib/custom-render`) and intercept
HTTP calls at the network boundary with `addAPIMock` (`@/tests/lib/msw`),
passing an explicit OpenAPI type to `HttpResponse.json<T>` — never
`vi.mock('@/data/...')`:
```tsx
addAPIMock({
method: 'get',
path: '/platform/organizations',
@@ -83,122 +149,61 @@ customRender(<MyComponent />)
expect(await screen.findByText('No organizations')).toBeInTheDocument()
```
Follow [studio-mock-api-tests](../studio-mock-api-tests/SKILL.md) for the full
MSW template, faithful boundary replacements, and harness requirements. Do not
add module mocks for queries, children, or shared hooks to bypass integration.
Read [MSW component tests](references/msw-component-tests.md) before writing or
migrating any API-backed component test — it covers the full template, FGA
permissions (`mockPermissions`, `mockProjectGrantContext`), `profileContext`,
TanStack Start route rendering (`renderRoute`), and jsdom gotchas.
A feature being shared by self-hosted and platform does not alone justify E2E
coverage. Use E2E for critical journeys or behavior that differs across those
environments and cannot be established in a focused test. Cover mouse and
keyboard behavior where each protects the journey. Reuse interactions in
`e2e/studio/utils/*-helpers.ts`, and clean up resources in `finally`. Follow
[studio-e2e-tests](../studio-e2e-tests/SKILL.md) for execution.
For Playwright journeys, read [studio-e2e-tests](../studio-e2e-tests/SKILL.md).
## Keep tests fast
## 5. Keep Tests Fast
Choose the appropriate environment and avoid unnecessary work in interactions.
- **Use `.test.ts` (node) for pure logic; `.test.tsx` (jsdom) only for DOM:**
`apps/studio/vitest.config.ts` runs `.test.ts` in node and `.test.tsx` in
jsdom (~1s setup per file). Use `.test.tsx` when you need DOM, `renderHook`,
or `localStorage`; use `.platform.test.tsx` for `NEXT_PUBLIC_IS_PLATFORM=true`.
- **Never wait on real time or bump timeouts:** Use
`vi.useFakeTimers({ shouldAdvanceTime: true })` (keeps `waitFor`, MSW, and
router microtasks advancing) in `beforeEach` and `vi.useRealTimers()` in
`afterEach`, then advance with
`await act(() => vi.advanceTimersByTimeAsync(INTERVAL_MS))` (reusing the
production interval/debounce constant). Configure `userEvent.setup({ advanceTimers })`
when combining `userEvent` with fake timers.
- **Paste, don't type:** Use `await user.click(input); await user.paste('value')`
(or `fireEvent.change`) unless testing per-keystroke behavior.
- **Scope `*ByRole` queries:** Radix `Select` renders hidden `<option>` nodes,
so scope queries to the open listbox:
`within(await screen.findByRole('listbox')).findByRole('option', { name })`.
- **Consolidate with `test.each`:** Use `test.each` for distinct scenarios
sharing setup rather than duplicating test blocks (never to multiply
equivalent literals).
### Put pure logic in `.test.ts` so it runs in node
## 6. Verify & References
`vitest.config.ts` runs `**/*.test.ts` in the `node` environment and
`**/*.test.tsx` in `jsdom`. jsdom costs ~1s of setup per file, so:
Run relevant existing and new tests with retries disabled
(`pnpm --filter studio test --retry=0 <path>`, or
`pnpm --filter studio exec vitest run --retry=0 <path>` to skip coverage — omit
`--` so pnpm 12 forwards flags to Vitest), even when no new test was added for a
code change, and run typecheck/formatting separately (Vitest does not prove
TypeScript correctness):
- Utility, schema, and resolver tests: name the file `.test.ts` and don't
import anything from Testing Library.
- Tests that need the DOM, including `renderHook` and `window.localStorage`:
use `.test.tsx` rather than adding an environment directive.
- `.platform.test.tsx` files run with `NEXT_PUBLIC_IS_PLATFORM=true`.
- Environment or dependency failures are blockers, not passes.
- **Debugging flakiness or order dependence:** Repeat and shuffle with retries
disabled (`--sequence.shuffle --retry=0`, recording the seed) and fix shared
state, timing, ordering, or cleanup instead of masking failures with retries,
longer timeouts, or skips.
- **Prove new or regression-critical assertions catch failure:** Reproduce the
bug before fixing when possible, or briefly introduce a realistic scoped fault
in the guarded behavior and confirm the assertion fails for that behavior
(compile, timeout, and infra failures do not count), restoring exact original
bytes and re-running afterward.
The DOM setup file (`tests/setup/dom.ts`) no-ops in node.
### Never wait on real time
Don't sleep (`setTimeout(resolve, …)`), raise `findBy*` timeouts to wait out
a poll interval, or bump per-test timeouts. Use fake timers and advance
them. `shouldAdvanceTime: true` keeps `waitFor` polling, MSW, and router
microtasks working:
```tsx
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true })
})
afterEach(() => {
vi.useRealTimers()
})
const advancePoll = () => act(() => vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS))
await advancePoll()
expect(await screen.findByText('Restoration complete!')).toBeInTheDocument()
```
The same applies to debounces: `act(() => vi.advanceTimersByTimeAsync(650))`
instead of a 650ms sleep. Reuse the existing interval/debounce constant rather than duplicating its value.
### Paste, don't type
`user.type` fires keydown/keypress/input/keyup per character, and each one
can re-render a whole form. Unless keystroke-level behavior is what you're
testing (input masks, shortcuts, per-key validation), set the value in one go:
```tsx
await user.click(input)
await user.paste('my-project')
```
A single `fireEvent.change` is also suitable when keyboard behavior is irrelevant.
When using `userEvent` with fake timers, configure its `advanceTimers` option.
### Scope `*ByRole` queries
`*ByRole` checks accessibility (including `getComputedStyle`) for every
candidate element. Radix `Select` renders a hidden native `<option>` for
each item, so an unscoped `findByRole('option')` on a large form checks
hundreds of elements. Scope it to the open listbox:
```tsx
const findOption = async (name: string | RegExp) =>
within(await screen.findByRole('listbox')).findByRole('option', { name })
await user.click(await findOption('East US'))
```
## Verify the affected behavior
1. Run relevant existing unit and integration tests with retries disabled, even
when no new tests are needed for the executable change. Record the command
and result. An environment or dependency failure is a blocker, not a pass.
2. When investigating order dependence or flakiness, repeat affected tests and
shuffle where supported, with retries disabled. Record reproducible seeds.
Fix shared state, timing, ordering, or cleanup rather than masking failures
with retries, longer timeouts, or skips.
3. For new or changed assertions and regression-critical coverage, temporarily
introduce a realistic scoped production fault, such as omitting a side effect
or removing a guard. Confirm the relevant assertion fails for that behavior;
import errors, compile errors, timeouts, and infrastructure failures do not
count. Save the original bytes first and restore them in `finally` or an
equivalent guaranteed cleanup, preserving unrelated edits. Rerun the restored
code and check that no mutation remains.
4. Check formatting and relevant types separately; passing Vitest does not prove
TypeScript correctness. Report checks actually run and any blocked evidence.
Use focused existing tooling; do not add automated test machinery or mutation
probes for prose or static guarantees. For read-only reviews, report missing
verification evidence without changing source or introducing mutations.
## Codebase References
| What | Where |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Util test examples | `apps/studio/tests/components/Grid/Grid.utils.test.ts`, `apps/studio/tests/components/Billing/TaxID.utils.test.ts`, `apps/studio/tests/components/Editor/SpreadsheetImport.utils.test.ts` |
| Component test examples | `apps/studio/tests/features/logs/LogsFilterPopover.test.tsx`, `apps/studio/tests/components/CopyButton.test.tsx` |
| Fake timers (polling) | `apps/studio/components/layouts/ProjectLayout/RestoringState.test.tsx` |
| Fake timers (debounce) | `apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx` |
| Scoped listbox queries | `apps/studio/tests/routes/new/$slug.test.tsx`, `apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.test.tsx` |
| E2E test example | `e2e/studio/features/filter-bar.spec.ts` |
| E2E helpers pattern | `e2e/studio/utils/filter-bar-helpers.ts` |
| Custom render | `apps/studio/tests/lib/custom-render.tsx` |
| MSW mock setup | `apps/studio/tests/lib/msw.ts` (`addAPIMock`) |
| Test README | `apps/studio/tests/README.md` |
| Vitest config | `apps/studio/vitest.config.ts` |
| Related skills | `studio-e2e-tests` (running E2E), `vitest` (API reference), `vercel-composition-patterns` (component architecture) |
| What | Where |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| MSW template & gotchas | [references/msw-component-tests.md](references/msw-component-tests.md) |
| Pure logic exemplars | `apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.eszip.test.ts`, `apps/studio/tests/components/Billing/TaxID.utils.test.ts` |
| MSW & partial-failure tests | `apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.platform.test.tsx`, `apps/studio/components/interfaces/Reports/MetricOptions.test.tsx` |
| Fake timers (polling/debounce) | `apps/studio/components/layouts/ProjectLayout/RestoringState.test.tsx`, `apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx` |
| Scoped listbox queries | `apps/studio/tests/routes/new/$slug.test.tsx`, `apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.test.tsx` |
| Harness & setup | `apps/studio/tests/lib/custom-render.tsx`, `apps/studio/tests/lib/msw.ts`, `apps/studio/tests/setup/dom.ts`, `apps/studio/tests/setup/polyfills.ts`, `apps/studio/vitest.config.ts` |
| Related skills | `studio-e2e-tests` (Playwright E2E), `studio-queries` (React Query conventions) |
@@ -0,0 +1,275 @@
# Studio MSW Component Tests
Mount a Studio component, intercept its network calls with MSW, and assert what
renders and what gets sent. Load [studio-testing](../SKILL.md) first to confirm
the change warrants a component test before using this template.
## When to use
- The component (or a rendered descendant) calls a React Query hook or mutation
that hits `/platform/...`, `/v1/...`, or another endpoint typed in
`packages/api-types`.
- You would otherwise be tempted to write `vi.mock('@/data/some-query', ...)`.
**Do not** — mock the network instead (see "Why not `vi.mock`" below).
If the component is purely presentational with no data fetching, render and
assert directly without MSW.
## The template
```tsx
import { screen } from '@testing-library/react'
import { platformComponents as components } from 'api-types'
import { mockAnimationsApi } from 'jsdom-testing-mocks'
import { HttpResponse } from 'msw'
import { describe, expect, test } from 'vitest'
import { MyComponent } from './MyComponent'
import { createMockOrganizationResponse } from '@/tests/helpers'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
type OrganizationResponse = components['schemas']['OrganizationResponse_Output']
mockAnimationsApi()
describe('MyComponent', () => {
test('renders rows from the API', async () => {
addAPIMock({
method: 'get',
path: '/platform/organizations',
response: () =>
HttpResponse.json<OrganizationResponse[]>([
createMockOrganizationResponse({ name: 'Acme' }),
]),
})
customRender(<MyComponent />, { profileContext: createMockProfileContext() })
expect(await screen.findByText('Acme')).toBeInTheDocument()
})
})
```
Call `mockAnimationsApi()` when the component renders Radix UI relying on Web
Animations (Sheet, Modal, Popover). Server lifecycle (`listen` / `resetHandlers`
/ `close`) is managed in `apps/studio/tests/vitestSetup.ts` — register
`addAPIMock` inside each test or `beforeEach` (never `beforeAll`, because
handlers reset after every test).
## Gotchas that cost debugging time
### 1. Path params use `:slug`, not `{slug}`
`addAPIMock` remaps OpenAPI `{param}` segments to MSW's `:param` syntax:
```ts
// ❌ TypeScript error, MSW will not match
path: '/platform/organizations/{slug}/projects'
// ✅ Correct
path: '/platform/organizations/:slug/projects'
```
### 2. Match response body semantics (`204`, `201`, and JSON `GET`s)
- **204 No Content:** Always return a bodyless `new HttpResponse(null, { status: 204 })`
— never `HttpResponse.json({}, { status: 204 })` (204 responses must not carry
a body or `Content-Type: application/json`).
- **201 Created:** Use `HttpResponse.json<MyResponse>(body, { status: 201 })`
when the OpenAPI schema defines a response body; for empty-body 201 endpoints
(`content?: never`), return a bodyless `new HttpResponse(null, { status: 201 })`
so the real `normalizeEmptyBodyResponse` path in `apps/studio/data/fetchers.ts`
is exercised.
- **JSON `GET` endpoints:** Always return a real JSON body via
`HttpResponse.json<T>(data)` — an empty `application/json` `GET` throws
`MalformedResponseError`.
```ts
// ✅ 204 No Content
response: () => new HttpResponse(null, { status: 204 })
// ✅ 201 with an OpenAPI JSON body (pass explicit generic — see gotcha #8)
response: () => HttpResponse.json<MyResponse>(createdItem, { status: 201 })
```
### 3. Submit buttons in Sheets and Modals need `fireEvent.click`
External form submit buttons (`<Button form={FORM_ID} type="submit" />`) do not
reliably submit under `userEvent.click` in jsdom. Use `fireEvent.click` for the
submit button (or `fireEvent.submit(document.getElementById(FORM_ID)!)`), and
use `user.paste` instead of `user.type` for text inputs:
```ts
await user.click(screen.getByPlaceholderText('value'))
await user.paste('hello')
fireEvent.click(await screen.findByRole('button', { name: 'Save' }))
```
### 4. Profile-gated queries need `profileContext`
Hooks gated on a loaded profile (`useOrganizationsQuery`, `data/projects/**`,
anything calling `useProfile`) stay idle until `profileContext` is provided.
Reuse `createMockProfileContext` instead of hand-rolling the object:
```tsx
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
customRender(<MyComponent />, { profileContext: createMockProfileContext() })
```
### 5. Routing and `useParams` in TanStack Start tests
- `useParams()` from `'common'` is globally mocked to `{ ref: 'default' }` in
`apps/studio/tests/vitestSetup.ts`, so project-scoped components work out of
the box with `'default'` in mock URLs.
- Use `renderRoute` from `@/tests/lib/route-render` when testing a TanStack
Start file route or when you need a different `ref` or dynamic route params
read via `useParams()` from `'common'` (`renderRoute` provides
`RenderedRouteContext` so the global `useParams` mock delegates to the real
hook). `routeId` must match the exact string passed to `createFileRoute(...)`
(including the trailing `/` for index routes):
```tsx
import { renderRoute } from '@/tests/lib/route-render'
await renderRoute(Route, { routeId: '/project/$ref/editor/', url: '/project/my-proj/editor' })
```
- Pass `initialUrl` (or `router`) to `customRender` when a component reads
TanStack Router hooks or `useFramework()` location/navigation directly (note:
`common`'s `useParams()` still returns `{ ref: 'default' }` under
`customRender` unless the test restores the real `useParams` implementation):
```tsx
const { router } = customRender(<MyComponent />, { initialUrl: '/project/default/issues' })
```
### 6. Unhandled requests fail loudly
`mswServer.listen({ onUnhandledRequest: 'error' })` is enabled globally. If the
component or a child fires an unmocked request, mock that endpoint at the
network boundary rather than mocking the child component or shared hook. Never
add test-only props or injection seams to production components just to avoid
rendering a dependency; if a heavy browser-only dependency cannot run in jsdom,
extract the independently testable pure logic or cover the full journey in E2E.
### 7. Read query strings inside the resolver, not in `path`
`addAPIMock` strips query params only at the TypeScript type level; MSW v2
ignores query strings in URL path patterns and logs a warning. Omit `?foo=bar`
from `path` and read query params from `request.url` inside the resolver:
```ts
addAPIMock({
method: 'get',
path: '/platform/projects',
response: ({ request }) => {
const limit = new URL(request.url).searchParams.get('limit')
// ...
},
})
```
### 8. Always pass an explicit generic to `HttpResponse.json`
MSW's `HttpResponse.json` uses `NoInfer`, so pass the OpenAPI response type (or
`APIErrorBody` for errors) explicitly to catch contract drift at compile time:
```ts
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
response: () => HttpResponse.json<OrganizationResponse[]>([...])
response: () => HttpResponse.json<APIErrorBody>({ message: 'Boom' }, { status: 500 })
```
Prefer raw OpenAPI response factories like `createMockOrganizationResponse` over
frontend-extended fixtures like `createMockOrganization` at the network boundary
so query mappers still run.
### 9. Mock FGA permissions and project grant context
Components using `useGrant` or `useAsyncCheckPermissionsV2` fetch
`/platform/profile/permissions/v2` (no global default). Because FGA permission
queries are gated on `IS_PLATFORM` and authenticated state, name the file
`*.platform.test.tsx` and pass `authContext: createMockAuthContext()`
(`@/tests/lib/auth-helpers`) and `profileContext: createMockProfileContext()` to
`customRender`:
```ts
import { mockPermissions, mockPermissionsError } from '@/tests/lib/msw-permissions'
import { allPermissionsFor, NO_PERMISSIONS } from '@/tests/lib/permissions-fixtures'
import { mockProjectGrantContext } from '@/tests/lib/project-grant-mocks'
mockPermissions(allPermissionsFor(['my-org']))
mockPermissions(NO_PERMISSIONS)
mockPermissions({
organizations: [{ slug: 'my-org', role: 'developer', permissions: ['...'], projects: [] }],
})
mockPermissionsError({ status: 500 })
// Shorthand that mocks project detail, organizations, and permissions together:
mockProjectGrantContext({ ref: 'default' })
```
Reserve `testGrant(endpoint, { projectRef })` (`@/tests/lib/test-grant`) strictly
for grant/security contract tests under `data/**` — not for standard fetcher
unit tests. Components should always resolve real grants via `useGrant` against
mocked permissions.
## Prefer asserting on UI state
Assert on what the user sees (`findByText('Saved')`, `onClose` called, button
re-enabled) rather than spying on whether an MSW handler ran. Capture the
request body only when the payload itself is the contract and the UI does not
observably reflect it (such as a `201` write with no response body):
```ts
const requests: Array<{ ref: string | undefined; body: unknown }> = []
addAPIMock({
method: 'post',
path: '/v1/projects/:ref/secrets',
response: async ({ request, params }) => {
requests.push({ ref: params.ref as string | undefined, body: await request.json() })
return new HttpResponse(null, { status: 201 })
},
})
```
## Debugging an MSW test
If a request is not matching, subscribe to MSW events temporarily in the test:
```ts
import { mswServer } from '@/tests/lib/msw'
mswServer.events.on('request:unhandled', ({ request }) => {
console.log('[MSW] UNHANDLED:', request.method, request.url)
})
mswServer.events.on('response:mocked', ({ request, response }) => {
console.log('[MSW] MATCHED:', request.method, request.url, response.status)
})
```
## Why not `vi.mock('@/data/...')`
Mocking React Query hooks bypasses the network boundary, hides renamed query
keys and broken payloads, skips `onMutate`/`onSuccess`/`onError` and cache
invalidation, and drifts independently from `packages/api-types`. Keep hooks,
children, and shared queries real.
Avoid `vi.mock` for non-network dependencies too — use supported `customRender`
providers/context or an existing injection point rather than adding local module
mocks. Use the global harness's supported configuration (`vitestSetup.ts`,
`renderRoute`) instead of replacing or migrating unrelated harness mocks during
a focused test change.
## Codebase references
| What | Where |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Query-only example (empty, success, error) | `apps/studio/components/interfaces/Organization/OrgNotFound.test.tsx` |
| Mutation example (form + payload assertion) | `apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EditSecretSheet.test.tsx` |
| SQL-via-pg-meta example (branching on `query` body) | `apps/studio/components/interfaces/Integrations/Vault/Secrets/__tests__/EditSecretModal.test.tsx` |
| `addAPIMock`, `customRender`, `renderRoute` | `apps/studio/tests/lib/msw.ts`, `apps/studio/tests/lib/custom-render.tsx`, `apps/studio/tests/lib/route-render.tsx` |
| Profile, permissions, and grant helpers | `apps/studio/tests/lib/profile-helpers.tsx`, `apps/studio/tests/lib/msw-permissions.ts`, `apps/studio/tests/lib/permissions-fixtures.ts`, `apps/studio/tests/lib/project-grant-mocks.ts`, `apps/studio/tests/lib/test-grant.ts` |
| Global handlers and lifecycle | `apps/studio/tests/lib/msw-global-api-mocks.ts`, `apps/studio/tests/vitestSetup.ts` |
| Related skills | [studio-testing](../SKILL.md), `studio-queries` |
+73 -71
View File
@@ -1,42 +1,61 @@
---
name: studio-ui-patterns
description: Design system UI patterns for Supabase Studio. Use when building or updating
pages, forms, tables, charts, empty states, navigation, cards, alerts, or side panels
(sheets). Covers layout selection, component choice, and placement conventions.
pages, forms, tables, charts, empty states, navigation, cards, alerts, dialogs, side
panels (sheets), or interactive controls (tooltips, buttons, focus, accessibility).
Covers layout selection, Studio primitives, composition, and accessibility parity.
---
# Studio UI Patterns
The Design System docs and demos are the source of truth. Always check the relevant
demo file before composing new UI.
The Design System docs and demos are the source of truth. Always check the relevant demo file before composing new UI.
## Compose the House Stack
Before writing custom markup or styles, search `'ui'`, `'ui-patterns'`, `apps/studio/components/ui/`, and the Design System demos. Compose existing primitives through their documented props and slots rather than cloning them, wrapping them to override built-in behavior, or fighting their internal padding and chrome with structural CSS overrides.
- **Layout geometry**: own spacing on the parent container with `flex flex-col gap-y-*` rather than `space-y-*` (fragile under `prose`/margin resets) or ad-hoc margins on child sections.
- **Class merging**: always combine classes with `cn(...)` from `'ui'` (never template-literal concatenation); avoid deep structural selectors and conflicting Tailwind utilities.
- **Async buttons**: use `Button`'s built-in `loading` prop directly, and apply loading + disabled states to slow async actions (downloads, exports, mutations) so double-clicks cannot fire parallel requests.
### Studio Component Index
| Need | Use |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Inline link in copy | `InlineLink` (`components/ui/InlineLink`) |
| Dynamic/untyped internal/external URL | `DynamicLink` (`components/ui/DynamicLink`); prefer TanStack `<Link>` directly for known typed internal routes |
| Support link | `SupportLink` (`components/interfaces/Support/SupportLink`) |
| External or docs link | `DOCS_URL` (`lib/constants`) + `target="_blank" rel="noopener noreferrer"` (when not using `InlineLink`) |
| Disabled control needing explanation | `ButtonTooltip` (`components/ui/ButtonTooltip`) or `DropdownMenuItemTooltip` (`components/ui/DropdownMenuItemTooltip`) |
| Floating button over busy content | `FloatingPlate` (`'ui'`) |
| Small fixed filter set | `FilterPopover` (`components/ui/FilterPopover`) instead of a heavy `Command` combobox |
| Empty table search-result row | `TableRowNoResults` (`components/ui/TableRowNoResults`) |
| Expandable rows or sections | `Collapsible` (`'ui'`), never hand-rolled toggle `<div>`s |
| Dotted tooltip trigger text | `TOOLTIP_UNDERLINE_CLASS_NAME` (`components/ui/tooltip-styles`) |
| Technical identifier in copy | Plain `<code>` (auto-styled by `packages/config/inline-code.css`; opt out with `data-code-style="plain"`) |
## Layout
Docs: `apps/design-system/content/docs/ui-patterns/layout.mdx`
Build pages with `PageContainer`, `PageHeader`, and `PageSection`.
Build pages with `PageContainer`, `PageBreadcrumbs`, `PageHeader`, `PageNav`, and `PageSection` (`PageLayout` has been removed).
| Content type | `size` |
| ----------------- | ----------- |
| Settings / config | `"default"` |
| Lists / tables | `"large"` |
| Full-screen views | `"full"` |
| Content type | `size` |
| --------------------------------------------------- | -------------------------- |
| Settings, forms, and focused configuration | `"small"` (or `"default"`) |
| Lists, tables, and detail pages | `"default"` |
| Dense horizontal content (logs, editors, wide grid) | `"full"` |
- If filters/search exist on a list page, align table actions with the filters (don't use `PageHeaderAside`/`PageSectionAside` for those actions)
- If no filters, actions can go in `PageHeaderAside` or `PageSectionAside`
- If filters/search exist on a list page, align table actions with the filters (don't use `PageHeaderAside`/`PageSectionAside` for those actions).
- If no filters exist, place actions in `PageHeaderAside` or `PageSectionAside`.
Demos: `page-layout-settings.tsx`, `page-layout-list.tsx`, `page-layout-list-simple.tsx`, `page-layout-detail.tsx`
(all in `apps/design-system/registry/default/example/`)
Demos: `page-layout-settings.tsx`, `page-layout-list.tsx`, `page-layout-list-simple.tsx`, `page-layout-detail.tsx` (all in `apps/design-system/registry/default/example/`).
## Forms
Docs: `apps/design-system/content/docs/ui-patterns/forms.mdx`
- Use `react-hook-form` + `zod`
- Use `FormItemLayout` instead of manually composing `FormItem`/`FormLabel`/`FormMessage`/`FormDescription`
- Wrap inputs with `FormControl`; import primitives from `ui`
Layout selection:
Use `FormItemLayout` (not manual `FormItem`/`FormLabel`/`FormMessage`/`FormDescription`) with `FormControl` wrapping primitives from `'ui'`. For schema, subscriptions, dirty state, reset, and submit mechanics, see the `react-hook-form` skill.
| Context | Layout | Container |
| ------------------------------------------ | ------------------------------------------ | ---------------------------------------------------------- |
@@ -44,39 +63,32 @@ Layout selection:
| Side panel — wide | `FormItemLayout layout="horizontal"` | `SheetSection` |
| Side panel — narrow (`size="sm"` or below) | `FormItemLayout layout="vertical"` | `SheetSection` |
Dirty state / submit:
- Use `isDirty` to show Cancel and disable Save. Destructure it from `form.formState` only in the component that owns `useForm`; anywhere else subscribe with `useFormState({ control })` (see the `react-hook-form` skill)
- Show loading on submit button via `loading` prop
- If submit button is outside `<form>`, set a stable `formId` and use `form` prop on the button
Demos: `form-patterns-pagelayout.tsx`, `form-patterns-sidepanel.tsx`
Demos: `form-patterns-pagelayout.tsx`, `form-patterns-sidepanel.tsx`.
## Tables
Docs: `apps/design-system/content/docs/ui-patterns/tables.mdx`
| Pattern | Use when |
| ---------- | ----------------------------------------------------------------------- |
| `Table` | Simple, static, semantic display |
| Data Table | TanStack-powered; sorting, filtering, pagination; composed per use-case |
| Data Grid | Virtualization, column resizing, or complex cell editing |
| Pattern | Use when |
| ------------------ | ---------------------------------------------------------------------- |
| `Table` | Simple, static, semantic display |
| Data Table | TanStack-powered (`@tanstack/react-table`); sorting, filtering, paging |
| Data Grid (legacy) | Existing table-editor grids only (legacy) |
- Actions: above the table, aligned right
- Search/filters: above the table, aligned left
- If table is primary content with no filters, actions can live in the page's primary/secondary actions area
- For interactive or data tables, use `@tanstack/react-table` (use plain `Table` for simple static display); never add new `react-data-grid` imports.
- Place search/filters above the table aligned left, and actions above the table aligned right (or in the page actions area if the table is primary content with no filters).
- Search/filter `<Input>` fields need staged-Escape handling (see the `studio-shortcuts` skill).
Demos: `table-demo.tsx`, `data-table-demo.tsx`, `data-grid-demo.tsx`
Demos: `table-demo.tsx`, `data-table-demo.tsx`, `data-grid-demo.tsx`.
## Charts
Docs: `apps/design-system/content/docs/ui-patterns/charts.mdx`
- Use provided chart building blocks; avoid passing raw Recharts components to `ChartContent`
- Use `useChart` context flags for loading/disabled states
- Keep composition straightforward — avoid over-abstraction
- Use provided chart building blocks; avoid passing raw Recharts components to `ChartContent`.
- Use `useChart` context flags for loading/disabled states and avoid over-abstraction.
Demos (in `apps/design-system/registry/default/block/`): `chart-composed-demo.tsx`, `chart-composed-basic.tsx`, `chart-composed-states.tsx`, `chart-composed-metrics.tsx`, `chart-composed-actions.tsx`, `chart-composed-table.tsx`
Demos (in `apps/design-system/registry/default/block/`): `chart-composed-demo.tsx`, `chart-composed-basic.tsx`, `chart-composed-states.tsx`, `chart-composed-metrics.tsx`, `chart-composed-actions.tsx`, `chart-composed-table.tsx`.
## Empty States
@@ -89,51 +101,41 @@ Docs: `apps/design-system/content/docs/ui-patterns/empty-states.mdx`
| Zero results from search | Keep layout consistent with data state to avoid jarring transitions |
| Missing route | Centered `Admonition` |
Demos: `empty-state-presentational-icon.tsx`, `empty-state-initial-state-informational.tsx`, `empty-state-zero-items-table.tsx`, `data-grid-empty-state.tsx`, `empty-state-missing-route.tsx`
Demos: `empty-state-presentational-icon.tsx`, `empty-state-initial-state-informational.tsx`, `empty-state-zero-items-table.tsx`, `data-grid-empty-state.tsx`, `empty-state-missing-route.tsx`.
## Navigation
Docs: `apps/design-system/content/docs/ui-patterns/navigation.mdx`
- Use `NavMenu` for a horizontal list of related views within a consistent page layout
- Activating an item must trigger a **URL change** — no local-only tab state
- Use `NavMenu` for a horizontal list of related views within a consistent page layout; activating an item must trigger a **URL change** (no local-only tab state).
- For feature-flagged replacements, verify both states: off preserves existing navigation and destinations; on exposes the replacement (intentionally hidden surfaces are explicit exceptions).
For feature-flagged replacements in Studio, verify both states: off preserves existing navigation and destinations; on exposes the replacement. Treat intentionally hidden surfaces as explicit exceptions.
## Cards, Alerts & Banners
## Cards
- **Cards**: group related information with `CardContent` for sections and `CardFooter` for actions. Only add `CardHeader`/`CardTitle` when surrounding context doesn't already identify the card (e.g. multiple distinct settings cards).
- **Admonition** (`ui-patterns/Admonition`): use `<Admonition title="...">` for short (1–2 sentence) callouts or warnings at the top of a page or section — never as a substitute for `Card`. Consolidate stacked warnings into a single block.
- **Global banners**: mount org/app-wide banners in `components/interfaces/App/AppBannerWrapper.tsx`, not `ProjectLayout`.
- Group related information in cards
- `CardContent` for sections, `CardFooter` for actions
- Only use `CardHeader`/`CardTitle` when context isn't already provided by surrounding content
- Use headers/titles when multiple cards represent distinct groups (e.g. multiple settings sections)
## Dialogs & Sheets (Side Panels)
## Alerts
Use a `Sheet` when switching pages would break context (e.g. editing a row from a list).
- Use `Admonition` to call out important actions, restrictions, or critical context
- Place at the **top of a page's content** (below page title) or **top of the relevant section** (below section title)
- Use sparingly
- Compose with `SheetHeader`/`SheetTitle`/`SheetSection`/`SheetFooter` (`SheetContent` `size="lg"` for horizontal forms) or `DialogHeader`/`DialogTitle`/`DialogSection`/`DialogFooter` (with a separator between `DialogHeader` and `DialogSection`).
- Respect built-in primitive padding and chrome: rely on `DialogSection`/`SheetSection`/header built-in spacing instead of overriding or re-padding inner slots, and use `DialogFooter`/`SheetFooter` only when real actions exist (omit footers that only duplicate built-in dismissal).
- **Confirmation modals** (`ui-patterns/Dialogs/ConfirmationModal` and `ui-patterns/Dialogs/TextConfirmModal` for typed-confirmation destructive actions; never `window.confirm`): keep `description` concise (put multi-sentence details in `children`), reserve `variant="destructive"` for actual data loss, and compose `<Dialog>` directly for custom multi-action flows rather than adding one-off props.
- Reset dialog, sheet, and picker state on close or reopen so previous inputs or rejected selections don't leak.
- Wire dirty form dismissal in sheets/dialogs with `useConfirmOnClose` + `DiscardChangesConfirmationDialog` (Cancel, Escape, and backdrop). Source of truth: `apps/design-system/content/docs/ui-patterns/modality.mdx`.
## Sheets (Side Panels)
## Accessibility (Three-Modality Parity)
Use a `Sheet` when switching pages would be disruptive and the user needs to maintain context (e.g. selecting a row from a list to edit).
Every interactive control must work across **pointer, keyboard, and screen reader** with real semantic elements (`<h2>`–`<h4>` for headings, `<Button asChild><Link>` for navigation, never nested `<button>`s), visible focus, and zero double announcements. Source of truth: `apps/design-system/content/docs/accessibility.mdx` (`focus-ring`, `focus-inset`, `focusableWhenDisabled`).
Structure:
- `SheetContent` with `size="lg"` for forms needing horizontal layout
- Use `SheetHeader`, `SheetTitle`, `SheetSection`, `SheetFooter`
- Submit/cancel actions go in `SheetFooter`
Forms in sheets:
- `layout="horizontal"` for wider sheets
- `layout="vertical"` for narrow sheets (`size="sm"` or below)
- When the sheet contains a form, wire dirty dismissal with `useConfirmOnClose` +
`DiscardChangesConfirmationDialog` (Cancel, Escape, and backdrop). Source of
truth: `apps/design-system/content/docs/ui-patterns/modality.mdx` (Dirty form
dismissal). Also see the react-hook-form skill for `isDirty` destructuring.
- **Icon-only buttons with `<Tooltip>`**: pair `aria-label` + `<Tooltip>` + `aria-describedby={undefined}` with the exact comment `// Tooltip repeats the label; screen readers would read it twice`. Use contextual row labels (``aria-label={`${item.name} actions`}``) instead of generic `"More options"`, and keep `aria-label` synced with dynamic toggle state.
- **`<Switch>`**: give a static descriptive `aria-label` (e.g. `"Cron job active status"`), never a dynamic verb toggling `"Enable X"` / `"Disable X"` — screen readers already announce on/off state.
- **Tooltips & disabled controls**: default `<TooltipContent side="bottom">`. `<TooltipTrigger asChild>` must wrap a focusable interactive element (never a `<span>`, `<div>`, or icon). Omit tooltips on enabled buttons with descriptive labels; use `ButtonTooltip` (sets `focusableWhenDisabled`) or `DropdownMenuItemTooltip` for disabled controls needing explanation.
- **Focus & dialog parity**: pair `group-hover:opacity-100` controls inside non-focusable `group` rows with `group-focus-within:opacity-100` and/or `focus-visible:opacity-100` (plus `data-[state=open]:opacity-100` for menu/popover triggers; `group-focus-visible:opacity-100` only works when the `group` ancestor itself is focusable, such as a `<button>` or `<Link>`); restore focus to the trigger button (or `DropdownMenuTrigger`) when closing state-controlled dialogs; include `DialogTitle`/`SheetTitle` and `DialogDescription` when descriptive copy exists (never pass `aria-describedby={undefined}` on `DialogContent` to silence warnings).
- **Screen-reader & i18n markup**: omit redundant `sr-only` when visible text or `aria-label` already conveys it; keep `sr-only` inside a `relative` ancestor (so `position: absolute` doesn't break scroll containers) and never inside `hidden`. Add `translate="no"` on monetary/cost values.
## Copy
Source of truth: `apps/design-system/content/docs/copywriting.mdx` — sentence case, title case, proper nouns, voice and tone.
When changing visible copy, grep `e2e/studio/` for the old string.
Follow the `copywriting` skill and `apps/design-system/content/docs/copywriting.mdx` for all UI text (and grep `e2e/studio/` when changing visible copy).
+10 -8
View File
@@ -120,8 +120,8 @@ Telemetry only runs for visitors who accepted analytics. Consent does not make i
**The page URL goes out with every event.** Pageviews and custom events carry the current URL and the referrer automatically, so URL state is telemetry:
- Do not put tokens, user input or row values in the query string or hash of a route
- If a feature needs URL state like that, redact it in `packages/common/telemetry-utils.ts` in the same PR and add a test
- Do not put tokens, user input or row values in the URL path, query string, or hash of a route
- `redactUrlKeywords()` in `packages/common/telemetry-utils.ts` already strips all URL hashes and redacts all query parameter values outside `READABLE_URL_PARAMS` — never add sensitive query keys to `READABLE_URL_PARAMS`, and add redaction + a test in `packages/common/telemetry-utils.ts` in the same PR if a route puts sensitive data in a URL path segment
## Consent and Transport
@@ -167,8 +167,10 @@ Where the `track()` call goes:
- **Values that are never sent.** Each value in a property's union must be sent by some call site. Check the early returns above the `track()` call: a branch that returns first (a choice that only takes effect after a second step, for example) never sends its value, and it reads as zero. Track that value where the action completes. Leave out a property that can only take one value until a second exists.
- **Components rendered in several places.** A property value that names where the action happened (`source: 'project_home'`, for example) must be true at every place the component renders. Before hardcoding a page name, find every render site: a layout can render the component on pages you did not open. When it renders on more than one page, take the value from a prop each render site passes, or name the value after the component. The same check applies to anything the tracking reads: at a render site with no org or project selected, a call that needs the slug fails, or reports filters that were never applied. Pass the value in from that render site, or skip the tracking there and leave that page out of `@page`.
- **Debounced or delayed sends.** `useTrack` reads the project, org and pathname when the event is sent, not when the user acted. An event sent from a debounce or timer that outlives a navigation is attributed to the destination page. Send on the action where possible. When the send has to wait, the third argument can pin the project or org, but the page cannot be overridden.
- **Events sent just before leaving the page.** A request started right before a full-page navigation (an external link, an OAuth redirect) can be cancelled. Add the event's action to `KEEPALIVE_ACTIONS` in `packages/common/telemetry-event.ts`. Never turn keepalive on for every event: the browser's in-flight keepalive budget is small and shared, so other events would be dropped.
- **Events sent just before leaving the page.** A request started right before a full-page navigation (an external link, an OAuth redirect) can be canceled. Add the event's action to `KEEPALIVE_ACTIONS` in `packages/common/telemetry-event.ts`. Never turn keepalive on for every event: the browser's in-flight keepalive budget is small and shared, so other events would be dropped.
- **Actions that change nothing.** An event named for a result (`closed`, `removed`, `updated`) fires only when the handler changed something. Bulk and menu actions can run on nothing: Close Others with one tab open, a move into the folder the items are already in, a sort set to its current value. Guard the `track()` call on the items that will change, not on the click. A count property reports the items that changed, not the items selected.
- **Unresolved or failed async queries.** Don't compute event properties from React Query data that hasn't succeeded yet (e.g. `githubConnection ? 1 : 0`) — clicks while pending or after an error misreport unknown states as `0`/`false`. Require `isSuccess` (not merely settled / `!isPending`, since an errored query has settled while `data` is still `undefined`) or omit the property when data is unavailable.
- **Duplicated handlers & analytical purpose.** Audit literal `track()` properties after copying a mutation handler (e.g. classic vs scoped tokens). Add telemetry only when it answers a concrete product or rollout question — skip routine preference toggles unless you plan to measure them.
## Feature Flag Measurement
@@ -220,7 +222,7 @@ export interface MyFeatureClickedEvent {
Add the new interface to the `TelemetryEvent` union type so `useTrack` picks it up.
`@group Events` and `@source` are required on every event; add `@page` when the event fires from a specific page. All three must be accurate.
An event fired from an organization-level page (`/org/[slug]/...`) gets its own event name and `groups: Omit<TelemetryGroups, 'project'>` (see `organization_mfa_enforcement_updated`). Don't reuse a project-scoped event there: no project is selected, so `useTrack` sends it without the project group and the type does not catch it.
An event fired from an organization-level page (`/org/{slug}/...`) gets its own event name and `groups: Omit<TelemetryGroups, 'project'>` (see `organization_mfa_enforcement_updated`). Don't reuse a project-scoped event there: no project is selected, so `useTrack` sends it without the project group and the type does not catch it.
## Review Rules
@@ -236,7 +238,7 @@ When reviewing a PR, flag a break of any of these as a **required change**, even
8. **Tracking placement**: the placement rules under [Required Pattern](#required-pattern), including no new `data-attr` or other `data-*` attribute used for tracking
9. **Org-level events**: a project-scoped event reused on an organization-level page ([Event Definitions](#event-definitions))
When a PR adds user-facing interactions (buttons, forms, toggles, modals) **without** tracking, suggest:
When a PR adds a meaningful new user-facing flow or action (such as a feature CTA, form submission, or rollout-gated control) **without** tracking — skip routine preference toggles unless they answer a concrete analytical question — suggest:
- "This adds a user interaction that may benefit from tracking."
- Propose the event name following `[object]_[verb]` convention
@@ -263,8 +265,8 @@ track('feature_preview_enabled', {
track('index_advisor_banner_dismiss_button_clicked')
// Experiment exposure (fires on render — valid exception)
track('home_new_experiment_exposed', {
variant: 'treatment',
track('free_tier_general_region_experiment_exposed', {
variant: 'test',
})
```
@@ -276,4 +278,4 @@ To add tracking for a user action:
2. **Choose properties**: [Property Standards](#property-standards) and both Privacy sections. Search `packages/common/telemetry-constants.ts` for similar events and match their property names and casing
3. **Define the event**: [Event Definitions](#event-definitions)
4. **Call `track()`**: [Required Pattern](#required-pattern), plus [Feature Flag Measurement](#feature-flag-measurement) when a flag gates the behavior
5. **Verify**: in the browser network tab, the action sends one `telemetry/event` request with the expected properties, and the same action with nothing to change (nothing to close, the same value picked again, a cancelled confirmation) sends no result event. A `clicked` or `submitted` event for the click itself still fires
5. **Verify**: in the browser network tab, the action sends one `telemetry/event` request with the expected properties, and the same action with nothing to change (nothing to close, the same value picked again, a canceled confirmation) sends no result event. A `clicked` or `submitted` event for the click itself still fires
@@ -1,88 +0,0 @@
---
name: vercel-composition-patterns
description: React composition patterns that scale. Use when refactoring components with
boolean prop proliferation, building flexible component libraries, or
designing reusable APIs. Triggers on tasks involving compound components,
render props, context providers, or component architecture. Includes React 19
API changes.
license: MIT
metadata:
author: vercel
version: '1.0.0'
---
# React Composition Patterns
Composition patterns for building flexible, maintainable React components. Avoid
boolean prop proliferation by using compound components, lifting state, and
composing internals. These patterns make codebases easier for both humans and AI
agents to work with as they scale.
## When to Apply
Reference these guidelines when:
- Refactoring components with many boolean props
- Building reusable component libraries
- Designing flexible component APIs
- Reviewing component architecture
- Working with compound components or context providers
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
| -------- | ----------------------- | ------ | --------------- |
| 1 | Component Architecture | HIGH | `architecture-` |
| 2 | State Management | MEDIUM | `state-` |
| 3 | Implementation Patterns | MEDIUM | `patterns-` |
| 4 | React 19 APIs | MEDIUM | `react19-` |
## Quick Reference
### 1. Component Architecture (HIGH)
- `architecture-avoid-boolean-props` - Don't add boolean props to customize
behavior; use composition
- `architecture-compound-components` - Structure complex components with shared
context
### 2. State Management (MEDIUM)
- `state-decouple-implementation` - Provider is the only place that knows how
state is managed
- `state-context-interface` - Define generic interface with state, actions, meta
for dependency injection
- `state-lift-state` - Move state into provider components for sibling access
### 3. Implementation Patterns (MEDIUM)
- `patterns-explicit-variants` - Create explicit variant components instead of
boolean modes
- `patterns-children-over-render-props` - Use children for composition instead
of renderX props
### 4. React 19 APIs (MEDIUM)
> **⚠️ React 19+ only.** Skip these patterns if you're on React 18 or earlier.
- `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()`
## How to Use
Read individual rule files for detailed explanations and code examples:
```
rules/architecture-avoid-boolean-props.md
rules/state-context-interface.md
```
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references
## Full Compiled Document
For the complete guide with all rules expanded, read the files under `rules/`
@@ -1,100 +0,0 @@
---
title: Avoid Boolean Prop Proliferation
impact: CRITICAL
impactDescription: prevents unmaintainable component variants
tags: composition, props, architecture
---
## Avoid Boolean Prop Proliferation
Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
component behavior. Each boolean doubles possible states and creates
unmaintainable conditional logic. Use composition instead.
**Incorrect (boolean props create exponential complexity):**
```tsx
function Composer({
onSubmit,
isThread,
channelId,
isDMThread,
dmId,
isEditing,
isForwarding,
}: Props) {
return (
<form>
<Header />
<Input />
{isDMThread ? (
<AlsoSendToDMField id={dmId} />
) : isThread ? (
<AlsoSendToChannelField id={channelId} />
) : null}
{isEditing ? (
<EditActions />
) : isForwarding ? (
<ForwardActions />
) : (
<DefaultActions />
)}
<Footer onSubmit={onSubmit} />
</form>
)
}
```
**Correct (composition eliminates conditionals):**
```tsx
// Channel composer
function ChannelComposer() {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Attachments />
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Thread composer - adds "also send to channel" field
function ThreadComposer({ channelId }: { channelId: string }) {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<AlsoSendToChannelField id={channelId} />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Edit composer - different footer actions
function EditComposer() {
return (
<Composer.Frame>
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.CancelEdit />
<Composer.SaveEdit />
</Composer.Footer>
</Composer.Frame>
)
}
```
Each variant is explicit about what it renders. We can share internals without
sharing a single monolithic parent.
@@ -1,112 +0,0 @@
---
title: Use Compound Components
impact: HIGH
impactDescription: enables flexible composition without prop drilling
tags: composition, compound-components, architecture
---
## Use Compound Components
Structure complex components as compound components with a shared context. Each
subcomponent accesses shared state via context, not props. Consumers compose the
pieces they need.
**Incorrect (monolithic component with render props):**
```tsx
function Composer({
renderHeader,
renderFooter,
renderActions,
showAttachments,
showFormatting,
showEmojis,
}: Props) {
return (
<form>
{renderHeader?.()}
<Input />
{showAttachments && <Attachments />}
{renderFooter ? (
renderFooter()
) : (
<Footer>
{showFormatting && <Formatting />}
{showEmojis && <Emojis />}
{renderActions?.()}
</Footer>
)}
</form>
)
}
```
**Correct (compound components with shared context):**
```tsx
const ComposerContext = createContext<ComposerContextValue | null>(null)
function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
return (
<ComposerContext value={{ state, actions, meta }}>
{children}
</ComposerContext>
)
}
function ComposerFrame({ children }: { children: React.ReactNode }) {
return <form>{children}</form>
}
function ComposerInput() {
const {
state,
actions: { update },
meta: { inputRef },
} = use(ComposerContext)
return (
<TextInput
ref={inputRef}
value={state.input}
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
/>
)
}
function ComposerSubmit() {
const {
actions: { submit },
} = use(ComposerContext)
return <Button onPress={submit}>Send</Button>
}
// Export as compound component
const Composer = {
Provider: ComposerProvider,
Frame: ComposerFrame,
Input: ComposerInput,
Submit: ComposerSubmit,
Header: ComposerHeader,
Footer: ComposerFooter,
Attachments: ComposerAttachments,
Formatting: ComposerFormatting,
Emojis: ComposerEmojis,
}
```
**Usage:**
```tsx
<Composer.Provider state={state} actions={actions} meta={meta}>
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
</Composer.Provider>
```
Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
@@ -1,87 +0,0 @@
---
title: Prefer Composing Children Over Render Props
impact: MEDIUM
impactDescription: cleaner composition, better readability
tags: composition, children, render-props
---
## Prefer Children Over Render Props
Use `children` for composition instead of `renderX` props. Children are more
readable, compose naturally, and don't require understanding callback
signatures.
**Incorrect (render props):**
```tsx
function Composer({
renderHeader,
renderFooter,
renderActions,
}: {
renderHeader?: () => React.ReactNode
renderFooter?: () => React.ReactNode
renderActions?: () => React.ReactNode
}) {
return (
<form>
{renderHeader?.()}
<Input />
{renderFooter ? renderFooter() : <DefaultFooter />}
{renderActions?.()}
</form>
)
}
// Usage is awkward and inflexible
return (
<Composer
renderHeader={() => <CustomHeader />}
renderFooter={() => (
<>
<Formatting />
<Emojis />
</>
)}
renderActions={() => <SubmitButton />}
/>
)
```
**Correct (compound components with children):**
```tsx
function ComposerFrame({ children }: { children: React.ReactNode }) {
return <form>{children}</form>
}
function ComposerFooter({ children }: { children: React.ReactNode }) {
return <footer className='flex'>{children}</footer>
}
// Usage is flexible
return (
<Composer.Frame>
<CustomHeader />
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<SubmitButton />
</Composer.Footer>
</Composer.Frame>
)
```
**When render props are appropriate:**
```tsx
// Render props work well when you need to pass data back
<List
data={items}
renderItem={({ item, index }) => <Item item={item} index={index} />}
/>
```
Use render props when the parent needs to provide data or state to the child.
Use children when composing static structure.
@@ -1,100 +0,0 @@
---
title: Create Explicit Component Variants
impact: MEDIUM
impactDescription: self-documenting code, no hidden conditionals
tags: composition, variants, architecture
---
## Create Explicit Component Variants
Instead of one component with many boolean props, create explicit variant
components. Each variant composes the pieces it needs. The code documents
itself.
**Incorrect (one component, many modes):**
```tsx
// What does this component actually render?
<Composer
isThread
isEditing={false}
channelId='abc'
showAttachments
showFormatting={false}
/>
```
**Correct (explicit variants):**
```tsx
// Immediately clear what this renders
<ThreadComposer channelId="abc" />
// Or
<EditMessageComposer messageId="xyz" />
// Or
<ForwardMessageComposer messageId="123" />
```
Each implementation is unique, explicit and self-contained. Yet they can each
use shared parts.
**Implementation:**
```tsx
function ThreadComposer({ channelId }: { channelId: string }) {
return (
<ThreadProvider channelId={channelId}>
<Composer.Frame>
<Composer.Input />
<AlsoSendToChannelField channelId={channelId} />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
</ThreadProvider>
)
}
function EditMessageComposer({ messageId }: { messageId: string }) {
return (
<EditMessageProvider messageId={messageId}>
<Composer.Frame>
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.CancelEdit />
<Composer.SaveEdit />
</Composer.Footer>
</Composer.Frame>
</EditMessageProvider>
)
}
function ForwardMessageComposer({ messageId }: { messageId: string }) {
return (
<ForwardMessageProvider messageId={messageId}>
<Composer.Frame>
<Composer.Input placeholder="Add a message, if you'd like." />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Mentions />
</Composer.Footer>
</Composer.Frame>
</ForwardMessageProvider>
)
}
```
Each variant is explicit about:
- What provider/state it uses
- What UI elements it includes
- What actions are available
No boolean prop combinations to reason about. No impossible states.
@@ -1,42 +0,0 @@
---
title: React 19 API Changes
impact: MEDIUM
impactDescription: cleaner component definitions and context usage
tags: react19, refs, context, hooks
---
## React 19 API Changes
> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
**Incorrect (forwardRef in React 19):**
```tsx
const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {
return <TextInput ref={ref} {...props} />
})
```
**Correct (ref as a regular prop):**
```tsx
function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {
return <TextInput ref={ref} {...props} />
}
```
**Incorrect (useContext in React 19):**
```tsx
const value = useContext(MyContext)
```
**Correct (use instead of useContext):**
```tsx
const value = use(MyContext)
```
`use()` can also be called conditionally, unlike `useContext()`.
@@ -1,191 +0,0 @@
---
title: Define Generic Context Interfaces for Dependency Injection
impact: HIGH
impactDescription: enables dependency-injectable state across use-cases
tags: composition, context, state, typescript, dependency-injection
---
## Define Generic Context Interfaces for Dependency Injection
Define a **generic interface** for your component context with three parts:
`state`, `actions`, and `meta`. This interface is a contract that any provider
can implement—enabling the same UI components to work with completely different
state implementations.
**Core principle:** Lift state, compose internals, make state
dependency-injectable.
**Incorrect (UI coupled to specific state implementation):**
```tsx
function ComposerInput() {
// Tightly coupled to a specific hook
const { input, setInput } = useChannelComposerState()
return <TextInput value={input} onChangeText={setInput} />
}
```
**Correct (generic interface enables dependency injection):**
```tsx
// Define a GENERIC interface that any provider can implement
interface ComposerState {
input: string
attachments: Attachment[]
isSubmitting: boolean
}
interface ComposerActions {
update: (updater: (state: ComposerState) => ComposerState) => void
submit: () => void
}
interface ComposerMeta {
inputRef: React.RefObject<TextInput>
}
interface ComposerContextValue {
state: ComposerState
actions: ComposerActions
meta: ComposerMeta
}
const ComposerContext = createContext<ComposerContextValue | null>(null)
```
**UI components consume the interface, not the implementation:**
```tsx
function ComposerInput() {
const {
state,
actions: { update },
meta,
} = use(ComposerContext)
// This component works with ANY provider that implements the interface
return (
<TextInput
ref={meta.inputRef}
value={state.input}
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
/>
)
}
```
**Different providers implement the same interface:**
```tsx
// Provider A: Local state for ephemeral forms
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState(initialState)
const inputRef = useRef(null)
const submit = useForwardMessage()
return (
<ComposerContext
value={{
state,
actions: { update: setState, submit },
meta: { inputRef },
}}
>
{children}
</ComposerContext>
)
}
// Provider B: Global synced state for channels
function ChannelProvider({ channelId, children }: Props) {
const { state, update, submit } = useGlobalChannel(channelId)
const inputRef = useRef(null)
return (
<ComposerContext
value={{
state,
actions: { update, submit },
meta: { inputRef },
}}
>
{children}
</ComposerContext>
)
}
```
**The same composed UI works with both:**
```tsx
// Works with ForwardMessageProvider (local state)
<ForwardMessageProvider>
<Composer.Frame>
<Composer.Input />
<Composer.Submit />
</Composer.Frame>
</ForwardMessageProvider>
// Works with ChannelProvider (global synced state)
<ChannelProvider channelId="abc">
<Composer.Frame>
<Composer.Input />
<Composer.Submit />
</Composer.Frame>
</ChannelProvider>
```
**Custom UI outside the component can access state and actions:**
The provider boundary is what matters—not the visual nesting. Components that
need shared state don't have to be inside the `Composer.Frame`. They just need
to be within the provider.
```tsx
function ForwardMessageDialog() {
return (
<ForwardMessageProvider>
<Dialog>
{/* The composer UI */}
<Composer.Frame>
<Composer.Input placeholder="Add a message, if you'd like." />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
</Composer.Footer>
</Composer.Frame>
{/* Custom UI OUTSIDE the composer, but INSIDE the provider */}
<MessagePreview />
{/* Actions at the bottom of the dialog */}
<DialogActions>
<CancelButton />
<ForwardButton />
</DialogActions>
</Dialog>
</ForwardMessageProvider>
)
}
// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
function ForwardButton() {
const {
actions: { submit },
} = use(ComposerContext)
return <Button onPress={submit}>Forward</Button>
}
// This preview lives OUTSIDE Composer.Frame but can read composer's state!
function MessagePreview() {
const { state } = use(ComposerContext)
return <Preview message={state.input} attachments={state.attachments} />
}
```
The `ForwardButton` and `MessagePreview` are not visually inside the composer
box, but they can still access its state and actions. This is the power of
lifting state into providers.
The UI is reusable bits you compose together. The state is dependency-injected
by the provider. Swap the provider, keep the UI.
@@ -1,113 +0,0 @@
---
title: Decouple State Management from UI
impact: MEDIUM
impactDescription: enables swapping state implementations without changing UI
tags: composition, state, architecture
---
## Decouple State Management from UI
The provider component should be the only place that knows how state is managed.
UI components consume the context interface—they don't know if state comes from
useState, Zustand, or a server sync.
**Incorrect (UI coupled to state implementation):**
```tsx
function ChannelComposer({ channelId }: { channelId: string }) {
// UI component knows about global state implementation
const state = useGlobalChannelState(channelId)
const { submit, updateInput } = useChannelSync(channelId)
return (
<Composer.Frame>
<Composer.Input
value={state.input}
onChange={(text) => sync.updateInput(text)}
/>
<Composer.Submit onPress={() => sync.submit()} />
</Composer.Frame>
)
}
```
**Correct (state management isolated in provider):**
```tsx
// Provider handles all state management details
function ChannelProvider({
channelId,
children,
}: {
channelId: string
children: React.ReactNode
}) {
const { state, update, submit } = useGlobalChannel(channelId)
const inputRef = useRef(null)
return (
<Composer.Provider
state={state}
actions={{ update, submit }}
meta={{ inputRef }}
>
{children}
</Composer.Provider>
)
}
// UI component only knows about the context interface
function ChannelComposer() {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Usage
function Channel({ channelId }: { channelId: string }) {
return (
<ChannelProvider channelId={channelId}>
<ChannelComposer />
</ChannelProvider>
)
}
```
**Different providers, same UI:**
```tsx
// Local state for ephemeral forms
function ForwardMessageProvider({ children }) {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
return (
<Composer.Provider
state={state}
actions={{ update: setState, submit: forwardMessage }}
>
{children}
</Composer.Provider>
)
}
// Global synced state for channels
function ChannelProvider({ channelId, children }) {
const { state, update, submit } = useGlobalChannel(channelId)
return (
<Composer.Provider state={state} actions={{ update, submit }}>
{children}
</Composer.Provider>
)
}
```
The same `Composer.Input` component works with both providers because it only
depends on the context interface, not the implementation.
@@ -1,125 +0,0 @@
---
title: Lift State into Provider Components
impact: HIGH
impactDescription: enables state sharing outside component boundaries
tags: composition, state, context, providers
---
## Lift State into Provider Components
Move state management into dedicated provider components. This allows sibling
components outside the main UI to access and modify state without prop drilling
or awkward refs.
**Incorrect (state trapped inside component):**
```tsx
function ForwardMessageComposer() {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
return (
<Composer.Frame>
<Composer.Input />
<Composer.Footer />
</Composer.Frame>
)
}
// Problem: How does this button access composer state?
function ForwardMessageDialog() {
return (
<Dialog>
<ForwardMessageComposer />
<MessagePreview /> {/* Needs composer state */}
<DialogActions>
<CancelButton />
<ForwardButton /> {/* Needs to call submit */}
</DialogActions>
</Dialog>
)
}
```
**Incorrect (useEffect to sync state up):**
```tsx
function ForwardMessageDialog() {
const [input, setInput] = useState('')
return (
<Dialog>
<ForwardMessageComposer onInputChange={setInput} />
<MessagePreview input={input} />
</Dialog>
)
}
function ForwardMessageComposer({ onInputChange }) {
const [state, setState] = useState(initialState)
useEffect(() => {
onInputChange(state.input) // Sync on every change 😬
}, [state.input])
}
```
**Incorrect (reading state from ref on submit):**
```tsx
function ForwardMessageDialog() {
const stateRef = useRef(null)
return (
<Dialog>
<ForwardMessageComposer stateRef={stateRef} />
<ForwardButton onPress={() => submit(stateRef.current)} />
</Dialog>
)
}
```
**Correct (state lifted to provider):**
```tsx
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
const inputRef = useRef(null)
return (
<Composer.Provider
state={state}
actions={{ update: setState, submit: forwardMessage }}
meta={{ inputRef }}
>
{children}
</Composer.Provider>
)
}
function ForwardMessageDialog() {
return (
<ForwardMessageProvider>
<Dialog>
<ForwardMessageComposer />
<MessagePreview /> {/* Custom components can access state and actions */}
<DialogActions>
<CancelButton />
<ForwardButton /> {/* Custom components can access state and actions */}
</DialogActions>
</Dialog>
</ForwardMessageProvider>
)
}
function ForwardButton() {
const { actions } = use(Composer.Context)
return <Button onPress={actions.submit}>Forward</Button>
}
```
The ForwardButton lives outside the Composer.Frame but still has access to the
submit action because it's within the provider. Even though it's a one-off
component, it can still access the composer's state and actions from outside the
UI itself.
**Key insight:** Components that need shared state don't have to be visually
nested inside each other—they just need to be within the same provider.
-5
View File
@@ -1,5 +0,0 @@
# Generation Info
- **Source:** `sources/vitest`
- **Git SHA:** `4a7321e10672f00f0bb698823a381c2cc245b8f7`
- **Generated:** 2026-01-28
-58
View File
@@ -1,58 +0,0 @@
---
name: vitest
description: >-
Vitest API and config reference (Jest-compatible) — mocking with vi.*, spies,
fake timers, coverage configuration, fixtures, snapshots, and test filtering.
Use for Vitest API and configuration questions anywhere in the monorepo; for
Studio-specific test strategy and component-test setup, start with
studio-testing and studio-mock-api-tests.
metadata:
author: Anthony Fu
version: '2026.1.28'
source: Generated from https://github.com/vitest-dev/vitest, scripts located at https://github.com/antfu/skills
---
Vitest is a next-generation testing framework powered by Vite. It provides a Jest-compatible API with native ESM, TypeScript, and JSX support out of the box. Vitest shares the same config, transformers, resolvers, and plugins with your Vite app.
**Key Features:**
- Vite-native: Uses Vite's transformation pipeline for fast HMR-like test updates
- Jest-compatible: Drop-in replacement for most Jest test suites
- Smart watch mode: Only reruns affected tests based on module graph
- Native ESM, TypeScript, JSX support without configuration
- Multi-threaded workers for parallel test execution
- Built-in coverage via V8 or Istanbul
- Snapshot testing, mocking, and spy utilities
> The skill is based on Vitest 3.x, generated at 2026-01-28.
## Core
| Topic | Description | Reference |
| ------------- | --------------------------------------------------------------- | -------------------------------------------- |
| Configuration | Vitest and Vite config integration, defineConfig usage | [core-config](references/core-config.md) |
| CLI | Command line interface, commands and options | [core-cli](references/core-cli.md) |
| Test API | test/it function, modifiers like skip, only, concurrent | [core-test-api](references/core-test-api.md) |
| Describe API | describe/suite for grouping tests and nested suites | [core-describe](references/core-describe.md) |
| Expect API | Assertions with toBe, toEqual, matchers and asymmetric matchers | [core-expect](references/core-expect.md) |
| Hooks | beforeEach, afterEach, beforeAll, afterAll, aroundEach | [core-hooks](references/core-hooks.md) |
## Features
| Topic | Description | Reference |
| ------------ | -------------------------------------------------------------- | ---------------------------------------------------------- |
| Mocking | Mock functions, modules, timers, dates with vi utilities | [features-mocking](references/features-mocking.md) |
| Snapshots | Snapshot testing with toMatchSnapshot and inline snapshots | [features-snapshots](references/features-snapshots.md) |
| Coverage | Code coverage with V8 or Istanbul providers | [features-coverage](references/features-coverage.md) |
| Test Context | Test fixtures, context.expect, test.extend for custom fixtures | [features-context](references/features-context.md) |
| Concurrency | Concurrent tests, parallel execution, sharding | [features-concurrency](references/features-concurrency.md) |
| Filtering | Filter tests by name, file patterns, tags | [features-filtering](references/features-filtering.md) |
## Advanced
| Topic | Description | Reference |
| ------------ | ------------------------------------------------------- | ------------------------------------------------------------ |
| Vi Utilities | vi helper: mock, spyOn, fake timers, hoisted, waitFor | [advanced-vi](references/advanced-vi.md) |
| Environments | Test environments: node, jsdom, happy-dom, custom | [advanced-environments](references/advanced-environments.md) |
| Type Testing | Type-level testing with expectTypeOf and assertType | [advanced-type-testing](references/advanced-type-testing.md) |
| Projects | Multi-project workspaces, different configs per project | [advanced-projects](references/advanced-projects.md) |
@@ -1,264 +0,0 @@
---
name: test-environments
description: Configure environments like jsdom, happy-dom for browser APIs
---
# Test Environments
## Available Environments
- `node` (default) - Node.js environment
- `jsdom` - Browser-like with DOM APIs
- `happy-dom` - Faster alternative to jsdom
- `edge-runtime` - Vercel Edge Runtime
## Configuration
```ts
// vitest.config.ts
defineConfig({
test: {
environment: 'jsdom',
// Environment-specific options
environmentOptions: {
jsdom: {
url: 'http://localhost',
},
},
},
})
```
## Installing Environment Packages
```bash
# jsdom
npm i -D jsdom
# happy-dom (faster, fewer APIs)
npm i -D happy-dom
```
## Per-File Environment
Use magic comment at top of file:
```ts
// @vitest-environment jsdom
import { expect, test } from 'vitest'
test('DOM test', () => {
const div = document.createElement('div')
expect(div).toBeInstanceOf(HTMLDivElement)
})
```
## jsdom Environment
Full browser environment simulation:
```ts
// @vitest-environment jsdom
test('DOM manipulation', () => {
document.body.innerHTML = '<div id="app"></div>'
const app = document.getElementById('app')
app.textContent = 'Hello'
expect(app.textContent).toBe('Hello')
})
test('window APIs', () => {
expect(window.location.href).toBeDefined()
expect(localStorage).toBeDefined()
})
```
### jsdom Options
```ts
defineConfig({
test: {
environmentOptions: {
jsdom: {
url: 'http://localhost:3000',
html: '<!DOCTYPE html><html><body></body></html>',
userAgent: 'custom-agent',
resources: 'usable',
},
},
},
})
```
## happy-dom Environment
Faster but fewer APIs:
```ts
// @vitest-environment happy-dom
test('basic DOM', () => {
const el = document.createElement('div')
el.className = 'test'
expect(el.className).toBe('test')
})
```
## Multiple Environments per Project
Use projects for different environments:
```ts
defineConfig({
test: {
projects: [
{
test: {
name: 'unit',
include: ['tests/unit/**/*.test.ts'],
environment: 'node',
},
},
{
test: {
name: 'dom',
include: ['tests/dom/**/*.test.ts'],
environment: 'jsdom',
},
},
],
},
})
```
## Custom Environment
Create custom environment package:
```ts
// vitest-environment-custom/index.ts
import type { Environment } from 'vitest/runtime'
export default <Environment>{
name: 'custom',
viteEnvironment: 'ssr', // or 'client'
setup() {
// Setup global state
globalThis.myGlobal = 'value'
return {
teardown() {
delete globalThis.myGlobal
},
}
},
}
```
Use with:
```ts
defineConfig({
test: {
environment: 'custom',
},
})
```
## Environment with VM
For full isolation:
```ts
export default <Environment>{
name: 'isolated',
viteEnvironment: 'ssr',
async setupVM() {
const vm = await import('node:vm')
const context = vm.createContext()
return {
getVmContext() {
return context
},
teardown() {},
}
},
setup() {
return { teardown() {} }
},
}
```
## Browser Mode (Separate from Environments)
For real browser testing, use Vitest Browser Mode:
```ts
defineConfig({
test: {
browser: {
enabled: true,
name: 'chromium', // or 'firefox', 'webkit'
provider: 'playwright',
},
},
})
```
## CSS and Assets
In jsdom/happy-dom, configure CSS handling:
```ts
defineConfig({
test: {
css: true, // Process CSS
// Or with options
css: {
include: /\.module\.css$/,
modules: {
classNameStrategy: 'non-scoped',
},
},
},
})
```
## Fixing External Dependencies
If external deps fail with CSS/asset errors:
```ts
defineConfig({
test: {
server: {
deps: {
inline: ['problematic-package'],
},
},
},
})
```
## Key Points
- Default is `node` - no browser APIs
- Use `jsdom` for full browser simulation
- Use `happy-dom` for faster tests with basic DOM
- Per-file environment via `// @vitest-environment` comment
- Use projects for multiple environment configurations
- Browser Mode is for real browser testing, not environment
<!--
Source references:
- https://vitest.dev/guide/environment.html
-->
@@ -1,300 +0,0 @@
---
name: projects-workspaces
description: Multi-project configuration for monorepos and different test types
---
# Projects
Run different test configurations in the same Vitest process.
## Basic Projects Setup
```ts
// vitest.config.ts
defineConfig({
test: {
projects: [
// Glob patterns for config files
'packages/*',
// Inline config
{
test: {
name: 'unit',
include: ['tests/unit/**/*.test.ts'],
environment: 'node',
},
},
{
test: {
name: 'integration',
include: ['tests/integration/**/*.test.ts'],
environment: 'jsdom',
},
},
],
},
})
```
## Monorepo Pattern
```ts
defineConfig({
test: {
projects: [
// Each package has its own vitest.config.ts
'packages/core',
'packages/cli',
'packages/utils',
],
},
})
```
Package config:
```ts
// packages/core/vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
name: 'core',
include: ['src/**/*.test.ts'],
environment: 'node',
},
})
```
## Different Environments
Run same tests in different environments:
```ts
defineConfig({
test: {
projects: [
{
test: {
name: 'happy-dom',
root: './shared-tests',
environment: 'happy-dom',
setupFiles: ['./setup.happy-dom.ts'],
},
},
{
test: {
name: 'node',
root: './shared-tests',
environment: 'node',
setupFiles: ['./setup.node.ts'],
},
},
],
},
})
```
## Browser + Node Projects
```ts
defineConfig({
test: {
projects: [
{
test: {
name: 'unit',
include: ['tests/unit/**/*.test.ts'],
environment: 'node',
},
},
{
test: {
name: 'browser',
include: ['tests/browser/**/*.test.ts'],
browser: {
enabled: true,
name: 'chromium',
provider: 'playwright',
},
},
},
],
},
})
```
## Shared Configuration
```ts
// vitest.shared.ts
export const sharedConfig = {
testTimeout: 10000,
setupFiles: ['./tests/setup.ts'],
}
// vitest.config.ts
import { sharedConfig } from './vitest.shared'
defineConfig({
test: {
projects: [
{
test: {
...sharedConfig,
name: 'unit',
include: ['tests/unit/**/*.test.ts'],
},
},
{
test: {
...sharedConfig,
name: 'e2e',
include: ['tests/e2e/**/*.test.ts'],
},
},
],
},
})
```
## Project-Specific Dependencies
Each project can have different dependencies inlined:
```ts
defineConfig({
test: {
projects: [
{
test: {
name: 'project-a',
server: {
deps: {
inline: ['package-a'],
},
},
},
},
],
},
})
```
## Running Specific Projects
```bash
# Run specific project
vitest --project unit
vitest --project integration
# Multiple projects
vitest --project unit --project e2e
# Exclude project
vitest --project.ignore browser
```
## Providing Values to Projects
Share values from config to tests:
```ts
// vitest.config.ts
defineConfig({
test: {
projects: [
{
test: {
name: 'staging',
provide: {
apiUrl: 'https://staging.api.com',
debug: true,
},
},
},
{
test: {
name: 'production',
provide: {
apiUrl: 'https://api.com',
debug: false,
},
},
},
],
},
})
// In tests, use inject
import { inject } from 'vitest'
test('uses correct api', () => {
const url = inject('apiUrl')
expect(url).toContain('api.com')
})
```
## With Fixtures
```ts
const test = base.extend({
apiUrl: ['/default', { injected: true }],
})
test('uses injected url', ({ apiUrl }) => {
// apiUrl comes from project's provide config
})
```
## Project Isolation
Each project runs in its own thread pool by default:
```ts
defineConfig({
test: {
projects: [
{
test: {
name: 'isolated',
isolate: true, // Full isolation
pool: 'forks',
},
},
],
},
})
```
## Global Setup per Project
```ts
defineConfig({
test: {
projects: [
{
test: {
name: 'with-db',
globalSetup: ['./tests/db-setup.ts'],
},
},
],
},
})
```
## Key Points
- Projects run in same Vitest process
- Each project can have different environment, config
- Use glob patterns for monorepo packages
- Run specific projects with `--project` flag
- Use `provide` to inject config values into tests
- Projects inherit from root config unless overridden
<!--
Source references:
- https://vitest.dev/guide/projects.html
-->
@@ -1,237 +0,0 @@
---
name: type-testing
description: Test TypeScript types with expectTypeOf and assertType
---
# Type Testing
Test TypeScript types without runtime execution.
## Setup
Type tests use `.test-d.ts` extension:
```ts
// math.test-d.ts
import { expectTypeOf } from 'vitest'
import { add } from './math'
test('add returns number', () => {
expectTypeOf(add).returns.toBeNumber()
})
```
## Configuration
```ts
defineConfig({
test: {
typecheck: {
enabled: true,
// Only type check
only: false,
// Checker: 'tsc' or 'vue-tsc'
checker: 'tsc',
// Include patterns
include: ['**/*.test-d.ts'],
// tsconfig to use
tsconfig: './tsconfig.json',
},
},
})
```
## expectTypeOf API
```ts
import { expectTypeOf } from 'vitest'
// Basic type checks
expectTypeOf<string>().toBeString()
expectTypeOf<number>().toBeNumber()
expectTypeOf<boolean>().toBeBoolean()
expectTypeOf<null>().toBeNull()
expectTypeOf<undefined>().toBeUndefined()
expectTypeOf<void>().toBeVoid()
expectTypeOf<never>().toBeNever()
expectTypeOf<any>().toBeAny()
expectTypeOf<unknown>().toBeUnknown()
expectTypeOf<object>().toBeObject()
expectTypeOf<Function>().toBeFunction()
expectTypeOf<[]>().toBeArray()
expectTypeOf<symbol>().toBeSymbol()
```
## Value Type Checking
```ts
const value = 'hello'
expectTypeOf(value).toBeString()
const obj = { name: 'test', count: 42 }
expectTypeOf(obj).toMatchTypeOf<{ name: string }>()
expectTypeOf(obj).toHaveProperty('name')
```
## Function Types
```ts
function greet(name: string): string {
return `Hello, ${name}`
}
expectTypeOf(greet).toBeFunction()
expectTypeOf(greet).parameters.toEqualTypeOf<[string]>()
expectTypeOf(greet).returns.toBeString()
// Parameter checking
expectTypeOf(greet).parameter(0).toBeString()
```
## Object Types
```ts
interface User {
id: number
name: string
email?: string
}
expectTypeOf<User>().toHaveProperty('id')
expectTypeOf<User>().toHaveProperty('name').toBeString()
// Check shape
expectTypeOf({ id: 1, name: 'test' }).toMatchTypeOf<User>()
```
## Equality vs Matching
```ts
interface A { x: number }
interface B { x: number; y: string }
// toMatchTypeOf - subset matching
expectTypeOf<B>().toMatchTypeOf<A>() // B extends A
// toEqualTypeOf - exact match
expectTypeOf<A>().not.toEqualTypeOf<B>() // Not exact match
expectTypeOf<A>().toEqualTypeOf<{ x: number }>() // Exact match
```
## Branded Types
```ts
type UserId = number & { __brand: 'UserId' }
type PostId = number & { __brand: 'PostId' }
expectTypeOf<UserId>().not.toEqualTypeOf<PostId>()
expectTypeOf<UserId>().not.toEqualTypeOf<number>()
```
## Generic Types
```ts
function identity<T>(value: T): T {
return value
}
expectTypeOf(identity<string>).returns.toBeString()
expectTypeOf(identity<number>).returns.toBeNumber()
```
## Nullable Types
```ts
type MaybeString = string | null | undefined
expectTypeOf<MaybeString>().toBeNullable()
expectTypeOf<string>().not.toBeNullable()
```
## assertType
Assert a value matches a type (no assertion at runtime):
```ts
import { assertType } from 'vitest'
function getUser(): User | null {
return { id: 1, name: 'test' }
}
test('returns user', () => {
const result = getUser()
// @ts-expect-error - should fail type check
assertType<string>(result)
// Correct type
assertType<User | null>(result)
})
```
## Using @ts-expect-error
Test that code produces type error:
```ts
test('rejects wrong types', () => {
function requireString(s: string) {}
// @ts-expect-error - number not assignable to string
requireString(123)
})
```
## Running Type Tests
```bash
# Run type tests
vitest typecheck
# Run alongside unit tests
vitest --typecheck
# Type tests only
vitest --typecheck.only
```
## Mixed Test Files
Combine runtime and type tests:
```ts
// user.test.ts
import { describe, expect, expectTypeOf, test } from 'vitest'
import { createUser } from './user'
describe('createUser', () => {
test('runtime: creates user', () => {
const user = createUser('John')
expect(user.name).toBe('John')
})
test('types: returns User type', () => {
expectTypeOf(createUser).returns.toMatchTypeOf<{ name: string }>()
})
})
```
## Key Points
- Use `.test-d.ts` for type-only tests
- `expectTypeOf` for type assertions
- `toMatchTypeOf` for subset matching
- `toEqualTypeOf` for exact type matching
- Use `@ts-expect-error` to test type errors
- Run with `vitest typecheck` or `--typecheck`
<!--
Source references:
- https://vitest.dev/guide/testing-types.html
- https://vitest.dev/api/expect-typeof.html
-->
@@ -1,249 +0,0 @@
---
name: vi-utilities
description: vi helper for mocking, timers, utilities
---
# Vi Utilities
The `vi` helper provides mocking and utility functions.
```ts
import { vi } from 'vitest'
```
## Mock Functions
```ts
// Create mock
const fn = vi.fn()
const fnWithImpl = vi.fn((x) => x * 2)
// Check if mock
vi.isMockFunction(fn) // true
// Mock methods
fn.mockReturnValue(42)
fn.mockReturnValueOnce(1)
fn.mockResolvedValue(data)
fn.mockRejectedValue(error)
fn.mockImplementation(() => 'result')
fn.mockImplementationOnce(() => 'once')
// Clear/reset
fn.mockClear() // Clear call history
fn.mockReset() // Clear history + implementation
fn.mockRestore() // Restore original (for spies)
```
## Spying
```ts
const obj = { method: () => 'original' }
const spy = vi.spyOn(obj, 'method')
obj.method()
expect(spy).toHaveBeenCalled()
// Mock implementation
spy.mockReturnValue('mocked')
// Spy on getter/setter
vi.spyOn(obj, 'prop', 'get').mockReturnValue('value')
```
## Module Mocking
```ts
// Hoisted to top of file
vi.mock('./module', () => ({
fn: vi.fn(),
}))
// Partial mock
vi.mock('./module', async (importOriginal) => ({
...(await importOriginal()),
specificFn: vi.fn(),
}))
// Spy mode - keep implementation
vi.mock('./module', { spy: true })
// Import actual module inside mock
const actual = await vi.importActual('./module')
// Import as mock
const mocked = await vi.importMock('./module')
```
## Dynamic Mocking
```ts
// Not hoisted - use with dynamic imports
vi.doMock('./config', () => ({ key: 'value' }))
const config = await import('./config')
// Unmock
vi.doUnmock('./config')
vi.unmock('./module') // Hoisted
```
## Reset Modules
```ts
// Clear module cache
vi.resetModules()
// Wait for dynamic imports
await vi.dynamicImportSettled()
```
## Fake Timers
```ts
vi.useFakeTimers()
setTimeout(() => console.log('done'), 1000)
// Advance time
vi.advanceTimersByTime(1000)
vi.advanceTimersByTimeAsync(1000) // For async callbacks
vi.advanceTimersToNextTimer()
vi.advanceTimersToNextFrame() // requestAnimationFrame
// Run all timers
vi.runAllTimers()
vi.runAllTimersAsync()
vi.runOnlyPendingTimers()
// Clear timers
vi.clearAllTimers()
// Check state
vi.getTimerCount()
vi.isFakeTimers()
// Restore
vi.useRealTimers()
```
## Mock Date/Time
```ts
vi.setSystemTime(new Date('2024-01-01'))
expect(new Date().getFullYear()).toBe(2024)
vi.getMockedSystemTime() // Get mocked date
vi.getRealSystemTime() // Get real time (ms)
```
## Global/Env Mocking
```ts
// Stub global
vi.stubGlobal('fetch', vi.fn())
vi.unstubAllGlobals()
// Stub environment
vi.stubEnv('API_KEY', 'test')
vi.stubEnv('NODE_ENV', 'test')
vi.unstubAllEnvs()
```
## Hoisted Code
Run code before imports:
```ts
const mock = vi.hoisted(() => vi.fn())
vi.mock('./module', () => ({
fn: mock, // Can reference hoisted variable
}))
```
## Waiting Utilities
```ts
// Wait for callback to succeed
await vi.waitFor(async () => {
const el = document.querySelector('.loaded')
expect(el).toBeTruthy()
}, { timeout: 5000, interval: 100 })
// Wait for truthy value
const element = await vi.waitUntil(
() => document.querySelector('.loaded'),
{ timeout: 5000 }
)
```
## Mock Object
Mock all methods of an object:
```ts
const original = {
method: () => 'real',
nested: { fn: () => 'nested' },
}
const mocked = vi.mockObject(original)
mocked.method() // undefined (mocked)
mocked.method.mockReturnValue('mocked')
// Spy mode
const spied = vi.mockObject(original, { spy: true })
spied.method() // 'real'
expect(spied.method).toHaveBeenCalled()
```
## Test Configuration
```ts
vi.setConfig({
testTimeout: 10_000,
hookTimeout: 10_000,
})
vi.resetConfig()
```
## Global Mock Management
```ts
vi.clearAllMocks() // Clear all mock call history
vi.resetAllMocks() // Reset + clear implementation
vi.restoreAllMocks() // Restore originals (spies)
```
## vi.mocked Type Helper
TypeScript helper for mocked values:
```ts
import { myFn } from './module'
vi.mock('./module')
// Type as mock
vi.mocked(myFn).mockReturnValue('typed')
// Deep mocking
vi.mocked(myModule, { deep: true })
// Partial mock typing
vi.mocked(fn, { partial: true }).mockResolvedValue({ ok: true })
```
## Key Points
- `vi.mock` is hoisted - use `vi.doMock` for dynamic mocking
- `vi.hoisted` lets you reference variables in mock factories
- Use `vi.spyOn` to spy on existing methods
- Fake timers require explicit setup and teardown
- `vi.waitFor` retries until assertion passes
<!--
Source references:
- https://vitest.dev/api/vi.html
-->
@@ -1,166 +0,0 @@
---
name: vitest-cli
description: Command line interface commands and options
---
# Command Line Interface
## Commands
### `vitest`
Start Vitest in watch mode (dev) or run mode (CI):
```bash
vitest # Watch mode in dev, run mode in CI
vitest foobar # Run tests containing "foobar" in path
vitest basic/foo.test.ts:10 # Run specific test by file and line number
```
### `vitest run`
Run tests once without watch mode:
```bash
vitest run
vitest run --coverage
```
### `vitest watch`
Explicitly start watch mode:
```bash
vitest watch
```
### `vitest related`
Run tests that import specific files (useful with lint-staged):
```bash
vitest related src/index.ts src/utils.ts --run
```
### `vitest bench`
Run only benchmark tests:
```bash
vitest bench
```
### `vitest list`
List all matching tests without running them:
```bash
vitest list # List test names
vitest list --json # Output as JSON
vitest list --filesOnly # List only test files
```
### `vitest init`
Initialize project setup:
```bash
vitest init browser # Set up browser testing
```
## Common Options
```bash
# Configuration
--config <path> # Path to config file
--project <name> # Run specific project
# Filtering
--testNamePattern, -t # Run tests matching pattern
--changed # Run tests for changed files
--changed HEAD~1 # Tests for last commit changes
# Reporters
--reporter <name> # default, verbose, dot, json, html
--reporter=html --outputFile=report.html
# Coverage
--coverage # Enable coverage
--coverage.provider v8 # Use v8 provider
--coverage.reporter text,html
# Execution
--shard <index>/<count> # Split tests across machines
--bail <n> # Stop after n failures
--retry <n> # Retry failed tests n times
--sequence.shuffle # Randomize test order
# Watch mode
--no-watch # Disable watch mode
--standalone # Start without running tests
# Environment
--environment <env> # jsdom, happy-dom, node
--globals # Enable global APIs
# Debugging
--inspect # Enable Node inspector
--inspect-brk # Break on start
# Output
--silent # Suppress console output
--no-color # Disable colors
```
## Package.json Scripts
```json
{
"scripts": {
"test": "vitest",
"test:run": "vitest run",
"test:ui": "vitest --ui",
"coverage": "vitest run --coverage"
}
}
```
## Sharding for CI
Split tests across multiple machines:
```bash
# Machine 1
vitest run --shard=1/3 --reporter=blob
# Machine 2
vitest run --shard=2/3 --reporter=blob
# Machine 3
vitest run --shard=3/3 --reporter=blob
# Merge reports
vitest --merge-reports --reporter=junit
```
## Watch Mode Keyboard Shortcuts
In watch mode, press:
- `a` - Run all tests
- `f` - Run only failed tests
- `u` - Update snapshots
- `p` - Filter by filename pattern
- `t` - Filter by test name pattern
- `q` - Quit
## Key Points
- Watch mode is default in dev, run mode in CI (when `process.env.CI` is set)
- Use `--run` flag to ensure single run (important for lint-staged)
- Both camelCase (`--testTimeout`) and kebab-case (`--test-timeout`) work
- Boolean options can be negated with `--no-` prefix
<!--
Source references:
- https://vitest.dev/guide/cli.html
-->
@@ -1,174 +0,0 @@
---
name: vitest-configuration
description: Configure Vitest with vite.config.ts or vitest.config.ts
---
# Configuration
Vitest reads configuration from `vitest.config.ts` or `vite.config.ts`. It shares the same config format as Vite.
## Basic Setup
```ts
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
// test options
},
})
```
## Using with Existing Vite Config
Add Vitest types reference and use the `test` property:
```ts
// vite.config.ts
/// <reference types="vitest/config" />
import { defineConfig } from 'vite'
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
},
})
```
## Merging Configs
If you have separate config files, use `mergeConfig`:
```ts
// vitest.config.ts
import { defineConfig, mergeConfig } from 'vitest/config'
import viteConfig from './vite.config'
export default mergeConfig(viteConfig, defineConfig({
test: {
environment: 'jsdom',
},
}))
```
## Common Options
```ts
defineConfig({
test: {
// Enable global APIs (describe, it, expect) without imports
globals: true,
// Test environment: 'node', 'jsdom', 'happy-dom'
environment: 'node',
// Setup files to run before each test file
setupFiles: ['./tests/setup.ts'],
// Include patterns for test files
include: ['**/*.{test,spec}.{js,ts,jsx,tsx}'],
// Exclude patterns
exclude: ['**/node_modules/**', '**/dist/**'],
// Test timeout in ms
testTimeout: 5000,
// Hook timeout in ms
hookTimeout: 10000,
// Enable watch mode by default
watch: true,
// Coverage configuration
coverage: {
provider: 'v8', // or 'istanbul'
reporter: ['text', 'html'],
include: ['src/**/*.ts'],
},
// Run tests in isolation (each file in separate process)
isolate: true,
// Pool for running tests: 'threads', 'forks', 'vmThreads'
pool: 'threads',
// Number of threads/processes
poolOptions: {
threads: {
maxThreads: 4,
minThreads: 1,
},
},
// Automatically clear mocks between tests
clearMocks: true,
// Restore mocks between tests
restoreMocks: true,
// Retry failed tests
retry: 0,
// Stop after first failure
bail: 0,
},
})
```
## Conditional Configuration
Use `mode` or `process.env.VITEST` for test-specific config:
```ts
export default defineConfig(({ mode }) => ({
plugins: mode === 'test' ? [] : [myPlugin()],
test: {
// test options
},
}))
```
## Projects (Monorepos)
Run different configurations in the same Vitest process:
```ts
defineConfig({
test: {
projects: [
'packages/*',
{
test: {
name: 'unit',
include: ['tests/unit/**/*.test.ts'],
environment: 'node',
},
},
{
test: {
name: 'integration',
include: ['tests/integration/**/*.test.ts'],
environment: 'jsdom',
},
},
],
},
})
```
## Key Points
- Vitest uses Vite's transformation pipeline - same `resolve.alias`, plugins work
- `vitest.config.ts` takes priority over `vite.config.ts`
- Use `--config` flag to specify a custom config path
- `process.env.VITEST` is set to `true` when running tests
- Test config uses `test` property, rest is Vite config
<!--
Source references:
- https://vitest.dev/guide/#configuring-vitest
- https://vitest.dev/config/
-->
@@ -1,193 +0,0 @@
---
name: describe-api
description: describe/suite for grouping tests into logical blocks
---
# Describe API
Group related tests into suites for organization and shared setup.
## Basic Usage
```ts
import { describe, expect, test } from 'vitest'
describe('Math', () => {
test('adds numbers', () => {
expect(1 + 1).toBe(2)
})
test('subtracts numbers', () => {
expect(3 - 1).toBe(2)
})
})
// Alias: suite
import { suite } from 'vitest'
suite('equivalent to describe', () => {})
```
## Nested Suites
```ts
describe('User', () => {
describe('when logged in', () => {
test('shows dashboard', () => {})
test('can update profile', () => {})
})
describe('when logged out', () => {
test('shows login page', () => {})
})
})
```
## Suite Options
```ts
// All tests inherit options
describe('slow tests', { timeout: 30_000 }, () => {
test('test 1', () => {}) // 30s timeout
test('test 2', () => {}) // 30s timeout
})
```
## Suite Modifiers
### Skip Suites
```ts
describe.skip('skipped suite', () => {
test('wont run', () => {})
})
// Conditional
describe.skipIf(process.env.CI)('not in CI', () => {})
describe.runIf(!process.env.CI)('only local', () => {})
```
### Focus Suites
```ts
describe.only('only this suite runs', () => {
test('runs', () => {})
})
```
### Todo Suites
```ts
describe.todo('implement later')
```
### Concurrent Suites
```ts
// All tests run in parallel
describe.concurrent('parallel tests', () => {
test('test 1', async ({ expect }) => {})
test('test 2', async ({ expect }) => {})
})
```
### Sequential in Concurrent
```ts
describe.concurrent('parallel', () => {
test('concurrent 1', async () => {})
describe.sequential('must be sequential', () => {
test('step 1', async () => {})
test('step 2', async () => {})
})
})
```
### Shuffle Tests
```ts
describe.shuffle('random order', () => {
test('test 1', () => {})
test('test 2', () => {})
test('test 3', () => {})
})
// Or with option
describe('random', { shuffle: true }, () => {})
```
## Parameterized Suites
### describe.each
```ts
describe.each([
{ name: 'Chrome', version: 100 },
{ name: 'Firefox', version: 90 },
])('$name browser', ({ name, version }) => {
test('has version', () => {
expect(version).toBeGreaterThan(0)
})
})
```
### describe.for
```ts
describe.for([
['Chrome', 100],
['Firefox', 90],
])('%s browser', ([name, version]) => {
test('has version', () => {
expect(version).toBeGreaterThan(0)
})
})
```
## Hooks in Suites
```ts
describe('Database', () => {
let db
beforeAll(async () => {
db = await createDb()
})
afterAll(async () => {
await db.close()
})
beforeEach(async () => {
await db.clear()
})
test('insert works', async () => {
await db.insert({ name: 'test' })
expect(await db.count()).toBe(1)
})
})
```
## Modifier Combinations
All modifiers can be chained:
```ts
describe.skip.concurrent('skipped concurrent', () => {})
describe.only.shuffle('only and shuffled', () => {})
describe.concurrent.skip('equivalent', () => {})
```
## Key Points
- Top-level tests belong to an implicit file suite
- Nested suites inherit parent's options (timeout, retry, etc.)
- Hooks are scoped to their suite and nested suites
- Use `describe.concurrent` with context's `expect` for snapshots
- Shuffle order depends on `sequence.seed` config
<!--
Source references:
- https://vitest.dev/api/describe.html
-->
@@ -1,219 +0,0 @@
---
name: expect-api
description: Assertions with matchers, asymmetric matchers, and custom matchers
---
# Expect API
Vitest uses Chai assertions with Jest-compatible API.
## Basic Assertions
```ts
import { expect, test } from 'vitest'
test('assertions', () => {
// Equality
expect(1 + 1).toBe(2) // Strict equality (===)
expect({ a: 1 }).toEqual({ a: 1 }) // Deep equality
// Truthiness
expect(true).toBeTruthy()
expect(false).toBeFalsy()
expect(null).toBeNull()
expect(undefined).toBeUndefined()
expect('value').toBeDefined()
// Numbers
expect(10).toBeGreaterThan(5)
expect(10).toBeGreaterThanOrEqual(10)
expect(5).toBeLessThan(10)
expect(0.1 + 0.2).toBeCloseTo(0.3, 5)
// Strings
expect('hello world').toMatch(/world/)
expect('hello').toContain('ell')
// Arrays
expect([1, 2, 3]).toContain(2)
expect([{ a: 1 }]).toContainEqual({ a: 1 })
expect([1, 2, 3]).toHaveLength(3)
// Objects
expect({ a: 1, b: 2 }).toHaveProperty('a')
expect({ a: 1, b: 2 }).toHaveProperty('a', 1)
expect({ a: { b: 1 } }).toHaveProperty('a.b', 1)
expect({ a: 1 }).toMatchObject({ a: 1 })
// Types
expect('string').toBeTypeOf('string')
expect(new Date()).toBeInstanceOf(Date)
})
```
## Negation
```ts
expect(1).not.toBe(2)
expect({ a: 1 }).not.toEqual({ a: 2 })
```
## Error Assertions
```ts
// Sync errors - wrap in function
expect(() => throwError()).toThrow()
expect(() => throwError()).toThrow('message')
expect(() => throwError()).toThrow(/pattern/)
expect(() => throwError()).toThrow(CustomError)
// Async errors - use rejects
await expect(asyncThrow()).rejects.toThrow('error')
```
## Promise Assertions
```ts
// Resolves
await expect(Promise.resolve(1)).resolves.toBe(1)
await expect(fetchData()).resolves.toEqual({ data: true })
// Rejects
await expect(Promise.reject('error')).rejects.toBe('error')
await expect(failingFetch()).rejects.toThrow()
```
## Spy/Mock Assertions
```ts
const fn = vi.fn()
fn('arg1', 'arg2')
fn('arg3')
expect(fn).toHaveBeenCalled()
expect(fn).toHaveBeenCalledTimes(2)
expect(fn).toHaveBeenCalledWith('arg1', 'arg2')
expect(fn).toHaveBeenLastCalledWith('arg3')
expect(fn).toHaveBeenNthCalledWith(1, 'arg1', 'arg2')
expect(fn).toHaveReturned()
expect(fn).toHaveReturnedWith(value)
```
## Asymmetric Matchers
Use inside `toEqual`, `toHaveBeenCalledWith`, etc:
```ts
expect({ id: 1, name: 'test' }).toEqual({
id: expect.any(Number),
name: expect.any(String),
})
expect({ a: 1, b: 2, c: 3 }).toEqual(
expect.objectContaining({ a: 1 })
)
expect([1, 2, 3, 4]).toEqual(
expect.arrayContaining([1, 3])
)
expect('hello world').toEqual(
expect.stringContaining('world')
)
expect('hello world').toEqual(
expect.stringMatching(/world$/)
)
expect({ value: null }).toEqual({
value: expect.anything() // Matches anything except null/undefined
})
// Negate with expect.not
expect([1, 2]).toEqual(
expect.not.arrayContaining([3])
)
```
## Soft Assertions
Continue test after failure:
```ts
expect.soft(1).toBe(2) // Marks test failed but continues
expect.soft(2).toBe(3) // Also runs
// All failures reported at end
```
## Poll Assertions
Retry until passes:
```ts
await expect.poll(() => fetchStatus()).toBe('ready')
await expect.poll(
() => document.querySelector('.element'),
{ interval: 100, timeout: 5000 }
).toBeTruthy()
```
## Assertion Count
```ts
test('async assertions', async () => {
expect.assertions(2) // Exactly 2 assertions must run
await doAsync((data) => {
expect(data).toBeDefined()
expect(data.id).toBe(1)
})
})
test('at least one', () => {
expect.hasAssertions() // At least 1 assertion must run
})
```
## Extending Matchers
```ts
expect.extend({
toBeWithinRange(received, floor, ceiling) {
const pass = received >= floor && received <= ceiling
return {
pass,
message: () =>
`expected ${received} to be within range ${floor} - ${ceiling}`,
}
},
})
test('custom matcher', () => {
expect(100).toBeWithinRange(90, 110)
})
```
## Snapshot Assertions
```ts
expect(data).toMatchSnapshot()
expect(data).toMatchInlineSnapshot(`{ "id": 1 }`)
await expect(result).toMatchFileSnapshot('./expected.json')
expect(() => throw new Error('fail')).toThrowErrorMatchingSnapshot()
```
## Key Points
- Use `toBe` for primitives, `toEqual` for objects/arrays
- `toStrictEqual` checks undefined properties and array sparseness
- Always `await` async assertions (`resolves`, `rejects`, `poll`)
- Use context's `expect` in concurrent tests for correct tracking
- `toThrow` requires wrapping sync code in a function
<!--
Source references:
- https://vitest.dev/api/expect.html
-->
@@ -1,244 +0,0 @@
---
name: lifecycle-hooks
description: beforeEach, afterEach, beforeAll, afterAll, and around hooks
---
# Lifecycle Hooks
## Basic Hooks
```ts
import { afterAll, afterEach, beforeAll, beforeEach, test } from 'vitest'
beforeAll(async () => {
// Runs once before all tests in file/suite
await setupDatabase()
})
afterAll(async () => {
// Runs once after all tests in file/suite
await teardownDatabase()
})
beforeEach(async () => {
// Runs before each test
await clearTestData()
})
afterEach(async () => {
// Runs after each test
await cleanupMocks()
})
```
## Cleanup Return Pattern
Return cleanup function from `before*` hooks:
```ts
beforeAll(async () => {
const server = await startServer()
// Returned function runs as afterAll
return async () => {
await server.close()
}
})
beforeEach(async () => {
const connection = await connect()
// Runs as afterEach
return () => connection.close()
})
```
## Scoped Hooks
Hooks apply to current suite and nested suites:
```ts
describe('outer', () => {
beforeEach(() => console.log('outer before'))
test('test 1', () => {}) // outer before → test
describe('inner', () => {
beforeEach(() => console.log('inner before'))
test('test 2', () => {}) // outer before → inner before → test
})
})
```
## Hook Timeout
```ts
beforeAll(async () => {
await slowSetup()
}, 30_000) // 30 second timeout
```
## Around Hooks
Wrap tests with setup/teardown context:
```ts
import { aroundEach, test } from 'vitest'
// Wrap each test in database transaction
aroundEach(async (runTest) => {
await db.beginTransaction()
await runTest() // Must be called!
await db.rollback()
})
test('insert user', async () => {
await db.insert({ name: 'Alice' })
// Automatically rolled back after test
})
```
### aroundAll
Wrap entire suite:
```ts
import { aroundAll, test } from 'vitest'
aroundAll(async (runSuite) => {
console.log('before all tests')
await runSuite() // Must be called!
console.log('after all tests')
})
```
### Multiple Around Hooks
Nested like onion layers:
```ts
aroundEach(async (runTest) => {
console.log('outer before')
await runTest()
console.log('outer after')
})
aroundEach(async (runTest) => {
console.log('inner before')
await runTest()
console.log('inner after')
})
// Order: outer before → inner before → test → inner after → outer after
```
## Test Hooks
Inside test body:
```ts
import { onTestFailed, onTestFinished, test } from 'vitest'
test('with cleanup', () => {
const db = connect()
// Runs after test finishes (pass or fail)
onTestFinished(() => db.close())
// Only runs if test fails
onTestFailed(({ task }) => {
console.log('Failed:', task.result?.errors)
})
db.query('SELECT * FROM users')
})
```
### Reusable Cleanup Pattern
```ts
function useTestDb() {
const db = connect()
onTestFinished(() => db.close())
return db
}
test('query users', () => {
const db = useTestDb()
expect(db.query('SELECT * FROM users')).toBeDefined()
})
test('query orders', () => {
const db = useTestDb() // Fresh connection, auto-closed
expect(db.query('SELECT * FROM orders')).toBeDefined()
})
```
## Concurrent Test Hooks
For concurrent tests, use context's hooks:
```ts
test.concurrent('concurrent', ({ onTestFinished }) => {
const resource = allocate()
onTestFinished(() => resource.release())
})
```
## Extended Test Hooks
With `test.extend`, hooks are type-aware:
```ts
const test = base.extend<{ db: Database }>({
db: async ({}, use) => {
const db = await createDb()
await use(db)
await db.close()
},
})
// These hooks know about `db` fixture
test.beforeEach(({ db }) => {
db.seed()
})
test.afterEach(({ db }) => {
db.clear()
})
```
## Hook Execution Order
Default order (stack):
1. `beforeAll` (in order)
2. `beforeEach` (in order)
3. Test
4. `afterEach` (reverse order)
5. `afterAll` (reverse order)
Configure with `sequence.hooks`:
```ts
defineConfig({
test: {
sequence: {
hooks: 'list', // 'stack' (default), 'list', 'parallel'
},
},
})
```
## Key Points
- Hooks are not called during type checking
- Return cleanup function from `before*` to avoid `after*` duplication
- `aroundEach`/`aroundAll` must call `runTest()`/`runSuite()`
- `onTestFinished` always runs, even if test fails
- Use context hooks for concurrent tests
<!--
Source references:
- https://vitest.dev/api/hooks.html
-->
@@ -1,233 +0,0 @@
---
name: test-api
description: test/it function for defining tests with modifiers
---
# Test API
## Basic Test
```ts
import { expect, test } from 'vitest'
test('adds numbers', () => {
expect(1 + 1).toBe(2)
})
// Alias: it
import { it } from 'vitest'
it('works the same', () => {
expect(true).toBe(true)
})
```
## Async Tests
```ts
test('async test', async () => {
const result = await fetchData()
expect(result).toBeDefined()
})
// Promises are automatically awaited
test('returns promise', () => {
return fetchData().then(result => {
expect(result).toBeDefined()
})
})
```
## Test Options
```ts
// Timeout (default: 5000ms)
test('slow test', async () => {
// ...
}, 10_000)
// Or with options object
test('with options', { timeout: 10_000, retry: 2 }, async () => {
// ...
})
```
## Test Modifiers
### Skip Tests
```ts
test.skip('skipped test', () => {
// Won't run
})
// Conditional skip
test.skipIf(process.env.CI)('not in CI', () => {})
test.runIf(process.env.CI)('only in CI', () => {})
// Dynamic skip via context
test('dynamic skip', ({ skip }) => {
skip(someCondition, 'reason')
// ...
})
```
### Focus Tests
```ts
test.only('only this runs', () => {
// Other tests in file are skipped
})
```
### Todo Tests
```ts
test.todo('implement later')
test.todo('with body', () => {
// Not run, shows in report
})
```
### Failing Tests
```ts
test.fails('expected to fail', () => {
expect(1).toBe(2) // Test passes because assertion fails
})
```
### Concurrent Tests
```ts
// Run tests in parallel
test.concurrent('test 1', async ({ expect }) => {
// Use context.expect for concurrent tests
expect(await fetch1()).toBe('result')
})
test.concurrent('test 2', async ({ expect }) => {
expect(await fetch2()).toBe('result')
})
```
### Sequential Tests
```ts
// Force sequential in concurrent context
test.sequential('must run alone', async () => {})
```
## Parameterized Tests
### test.each
```ts
test.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('add(%i, %i) = %i', (a, b, expected) => {
expect(a + b).toBe(expected)
})
// With objects
test.each([
{ a: 1, b: 1, expected: 2 },
{ a: 1, b: 2, expected: 3 },
])('add($a, $b) = $expected', ({ a, b, expected }) => {
expect(a + b).toBe(expected)
})
// Template literal
test.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
`('add($a, $b) = $expected', ({ a, b, expected }) => {
expect(a + b).toBe(expected)
})
```
### test.for
Preferred over `.each` - doesn't spread arrays:
```ts
test.for([
[1, 1, 2],
[1, 2, 3],
])('add(%i, %i) = %i', ([a, b, expected], { expect }) => {
// Second arg is TestContext
expect(a + b).toBe(expected)
})
```
## Test Context
First argument provides context utilities:
```ts
test('with context', ({ expect, skip, task }) => {
console.log(task.name) // Test name
skip(someCondition) // Skip dynamically
expect(1).toBe(1) // Context-bound expect
})
```
## Custom Test with Fixtures
```ts
import { test as base } from 'vitest'
const test = base.extend({
db: async ({}, use) => {
const db = await createDb()
await use(db)
await db.close()
},
})
test('query', async ({ db }) => {
const users = await db.query('SELECT * FROM users')
expect(users).toBeDefined()
})
```
## Retry Configuration
```ts
test('flaky test', { retry: 3 }, async () => {
// Retries up to 3 times on failure
})
// Advanced retry options
test('with delay', {
retry: {
count: 3,
delay: 1000,
condition: /timeout/i, // Only retry on timeout errors
},
}, async () => {})
```
## Tags
```ts
test('database test', { tags: ['db', 'slow'] }, async () => {})
// Run with: vitest --tags db
```
## Key Points
- Tests with no body are marked as `todo`
- `test.only` throws in CI unless `allowOnly: true`
- Use context's `expect` for concurrent tests and snapshots
- Function name is used as test name if passed as first arg
<!--
Source references:
- https://vitest.dev/api/test.html
-->
@@ -1,250 +0,0 @@
---
name: concurrency-parallelism
description: Concurrent tests, parallel execution, and sharding
---
# Concurrency & Parallelism
## File Parallelism
By default, Vitest runs test files in parallel across workers:
```ts
defineConfig({
test: {
// Run files in parallel (default: true)
fileParallelism: true,
// Number of worker threads
maxWorkers: 4,
minWorkers: 1,
// Pool type: 'threads', 'forks', 'vmThreads'
pool: 'threads',
},
})
```
## Concurrent Tests
Run tests within a file in parallel:
```ts
// Individual concurrent tests
test.concurrent('test 1', async ({ expect }) => {
expect(await fetch1()).toBe('result')
})
test.concurrent('test 2', async ({ expect }) => {
expect(await fetch2()).toBe('result')
})
// All tests in suite concurrent
describe.concurrent('parallel suite', () => {
test('test 1', async ({ expect }) => {})
test('test 2', async ({ expect }) => {})
})
```
**Important:** Use `{ expect }` from context for concurrent tests.
## Sequential in Concurrent Context
Force sequential execution:
```ts
describe.concurrent('mostly parallel', () => {
test('parallel 1', async () => {})
test('parallel 2', async () => {})
test.sequential('must run alone 1', async () => {})
test.sequential('must run alone 2', async () => {})
})
// Or entire suite
describe.sequential('sequential suite', () => {
test('first', () => {})
test('second', () => {})
})
```
## Max Concurrency
Limit concurrent tests:
```ts
defineConfig({
test: {
maxConcurrency: 5, // Max concurrent tests per file
},
})
```
## Isolation
Each file runs in isolated environment by default:
```ts
defineConfig({
test: {
// Disable isolation for faster runs (less safe)
isolate: false,
},
})
```
## Sharding
Split tests across machines:
```bash
# Machine 1
vitest run --shard=1/3
# Machine 2
vitest run --shard=2/3
# Machine 3
vitest run --shard=3/3
```
### CI Example (GitHub Actions)
```yaml
jobs:
test:
strategy:
matrix:
shard: [1, 2, 3]
steps:
- run: vitest run --shard=${{ matrix.shard }}/3 --reporter=blob
merge:
needs: test
steps:
- run: vitest --merge-reports --reporter=junit
```
### Merge Reports
```bash
# Each shard outputs blob
vitest run --shard=1/3 --reporter=blob --coverage
vitest run --shard=2/3 --reporter=blob --coverage
# Merge all blobs
vitest --merge-reports --reporter=json --coverage
```
## Test Sequence
Control test order:
```ts
defineConfig({
test: {
sequence: {
// Run tests in random order
shuffle: true,
// Seed for reproducible shuffle
seed: 12345,
// Hook execution order
hooks: 'stack', // 'stack', 'list', 'parallel'
// All tests concurrent by default
concurrent: true,
},
},
})
```
## Shuffle Tests
Randomize to catch hidden dependencies:
```ts
// Via CLI
vitest --sequence.shuffle
// Per suite
describe.shuffle('random order', () => {
test('test 1', () => {})
test('test 2', () => {})
test('test 3', () => {})
})
```
## Pool Options
### Threads (Default)
```ts
defineConfig({
test: {
pool: 'threads',
poolOptions: {
threads: {
maxThreads: 8,
minThreads: 2,
isolate: true,
},
},
},
})
```
### Forks
Better isolation, slower:
```ts
defineConfig({
test: {
pool: 'forks',
poolOptions: {
forks: {
maxForks: 4,
isolate: true,
},
},
},
})
```
### VM Threads
Full VM isolation per file:
```ts
defineConfig({
test: {
pool: 'vmThreads',
},
})
```
## Bail on Failure
Stop after first failure:
```bash
vitest --bail 1 # Stop after 1 failure
vitest --bail # Stop on first failure (same as --bail 1)
```
## Key Points
- Files run in parallel by default
- Use `.concurrent` for parallel tests within file
- Always use context's `expect` in concurrent tests
- Sharding splits tests across CI machines
- Use `--merge-reports` to combine sharded results
- Shuffle tests to find hidden dependencies
<!--
Source references:
- https://vitest.dev/guide/features.html#running-tests-concurrently
- https://vitest.dev/guide/improving-performance.html
-->
@@ -1,238 +0,0 @@
---
name: test-context-fixtures
description: Test context, custom fixtures with test.extend
---
# Test Context & Fixtures
## Built-in Context
Every test receives context as first argument:
```ts
test('context', ({ task, expect, skip }) => {
console.log(task.name) // Test name
expect(1).toBe(1) // Context-bound expect
skip() // Skip test dynamically
})
```
### Context Properties
- `task` - Test metadata (name, file, etc.)
- `expect` - Expect bound to this test (important for concurrent tests)
- `skip(condition?, message?)` - Skip the test
- `onTestFinished(fn)` - Cleanup after test
- `onTestFailed(fn)` - Run on failure only
## Custom Fixtures with test.extend
Create reusable test utilities:
```ts
import { test as base } from 'vitest'
// Define fixture types
interface Fixtures {
db: Database
user: User
}
// Create extended test
export const test = base.extend<Fixtures>({
// Fixture with setup/teardown
db: async ({}, use) => {
const db = await createDatabase()
await use(db) // Provide to test
await db.close() // Cleanup
},
// Fixture depending on another fixture
user: async ({ db }, use) => {
const user = await db.createUser({ name: 'Test' })
await use(user)
await db.deleteUser(user.id)
},
})
```
Using fixtures:
```ts
test('query user', async ({ db, user }) => {
const found = await db.findUser(user.id)
expect(found).toEqual(user)
})
```
## Fixture Initialization
Fixtures only initialize when accessed:
```ts
const test = base.extend({
expensive: async ({}, use) => {
console.log('initializing') // Only runs if test uses it
await use('value')
},
})
test('no fixture', () => {}) // expensive not called
test('uses fixture', ({ expensive }) => {}) // expensive called
```
## Auto Fixtures
Run fixture for every test:
```ts
const test = base.extend({
setup: [
async ({}, use) => {
await globalSetup()
await use()
await globalTeardown()
},
{ auto: true } // Always run
],
})
```
## Scoped Fixtures
### File Scope
Initialize once per file:
```ts
const test = base.extend({
connection: [
async ({}, use) => {
const conn = await connect()
await use(conn)
await conn.close()
},
{ scope: 'file' }
],
})
```
### Worker Scope
Initialize once per worker:
```ts
const test = base.extend({
sharedResource: [
async ({}, use) => {
await use(globalResource)
},
{ scope: 'worker' }
],
})
```
## Injected Fixtures (from Config)
Override fixtures per project:
```ts
// test file
const test = base.extend({
apiUrl: ['/default', { injected: true }],
})
// vitest.config.ts
defineConfig({
test: {
projects: [
{
test: {
name: 'prod',
provide: { apiUrl: 'https://api.prod.com' },
},
},
],
},
})
```
## Scoped Values per Suite
Override fixture for specific suite:
```ts
const test = base.extend({
environment: 'development',
})
describe('production tests', () => {
test.scoped({ environment: 'production' })
test('uses production', ({ environment }) => {
expect(environment).toBe('production')
})
})
test('uses default', ({ environment }) => {
expect(environment).toBe('development')
})
```
## Extended Test Hooks
Type-aware hooks with fixtures:
```ts
const test = base.extend<{ db: Database }>({
db: async ({}, use) => {
const db = await createDb()
await use(db)
await db.close()
},
})
// Hooks know about fixtures
test.beforeEach(({ db }) => {
db.seed()
})
test.afterEach(({ db }) => {
db.clear()
})
```
## Composing Fixtures
Extend from another extended test:
```ts
// base-test.ts
export const test = base.extend<{ db: Database }>({
db: async ({}, use) => { /* ... */ },
})
// admin-test.ts
import { test as dbTest } from './base-test'
export const test = dbTest.extend<{ admin: User }>({
admin: async ({ db }, use) => {
const admin = await db.createAdmin()
await use(admin)
},
})
```
## Key Points
- Use `{ }` destructuring to access fixtures
- Fixtures are lazy - only initialize when accessed
- Return cleanup function from fixtures
- Use `{ auto: true }` for setup fixtures
- Use `{ scope: 'file' }` for expensive shared resources
- Fixtures compose - extend from extended tests
<!--
Source references:
- https://vitest.dev/guide/test-context.html
-->
@@ -1,207 +0,0 @@
---
name: code-coverage
description: Code coverage with V8 or Istanbul providers
---
# Code Coverage
## Setup
```bash
# Run tests with coverage
vitest run --coverage
```
## Configuration
```ts
// vitest.config.ts
defineConfig({
test: {
coverage: {
// Provider: 'v8' (default, faster) or 'istanbul' (more compatible)
provider: 'v8',
// Enable coverage
enabled: true,
// Reporters
reporter: ['text', 'json', 'html'],
// Files to include
include: ['src/**/*.{ts,tsx}'],
// Files to exclude
exclude: [
'node_modules/',
'tests/',
'**/*.d.ts',
'**/*.test.ts',
],
// Report uncovered files
all: true,
// Thresholds
thresholds: {
lines: 80,
functions: 80,
branches: 80,
statements: 80,
},
},
},
})
```
## Providers
### V8 (Default)
```bash
npm i -D @vitest/coverage-v8
```
- Faster, no pre-instrumentation
- Uses V8's native coverage
- Recommended for most projects
### Istanbul
```bash
npm i -D @vitest/coverage-istanbul
```
- Pre-instruments code
- Works in any JS runtime
- More overhead but widely compatible
## Reporters
```ts
coverage: {
reporter: [
'text', // Terminal output
'text-summary', // Summary only
'json', // JSON file
'html', // HTML report
'lcov', // For CI tools
'cobertura', // XML format
],
reportsDirectory: './coverage',
}
```
## Thresholds
Fail tests if coverage is below threshold:
```ts
coverage: {
thresholds: {
// Global thresholds
lines: 80,
functions: 75,
branches: 70,
statements: 80,
// Per-file thresholds
perFile: true,
// Auto-update thresholds (for gradual improvement)
autoUpdate: true,
},
}
```
## Ignoring Code
### V8
```ts
/* v8 ignore next -- @preserve */
function ignored() {
return 'not covered'
}
/* v8 ignore start -- @preserve */
// All code here ignored
/* v8 ignore stop -- @preserve */
```
### Istanbul
```ts
/* istanbul ignore next -- @preserve */
function ignored() {}
/* istanbul ignore if -- @preserve */
if (condition) {
// ignored
}
```
Note: `@preserve` keeps comments through esbuild.
## Package.json Scripts
```json
{
"scripts": {
"test": "vitest",
"test:coverage": "vitest run --coverage",
"test:coverage:watch": "vitest --coverage"
}
}
```
## Vitest UI Coverage
Enable HTML coverage in Vitest UI:
```ts
coverage: {
enabled: true,
reporter: ['text', 'html'],
}
```
Run with `vitest --ui` to view coverage visually.
## CI Integration
```yaml
# GitHub Actions
- name: Run tests with coverage
run: npm run test:coverage
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
files: ./coverage/lcov.info
```
## Coverage with Sharding
Merge coverage from sharded runs:
```bash
vitest run --shard=1/3 --coverage --reporter=blob
vitest run --shard=2/3 --coverage --reporter=blob
vitest run --shard=3/3 --coverage --reporter=blob
vitest --merge-reports --coverage --reporter=json
```
## Key Points
- V8 is faster, Istanbul is more compatible
- Use `--coverage` flag or `coverage.enabled: true`
- Include `all: true` to see uncovered files
- Set thresholds to enforce minimum coverage
- Use `@preserve` comment to keep ignore hints
<!--
Source references:
- https://vitest.dev/guide/coverage.html
-->
@@ -1,211 +0,0 @@
---
name: test-filtering
description: Filter tests by name, file patterns, and tags
---
# Test Filtering
## CLI Filtering
### By File Path
```bash
# Run files containing "user"
vitest user
# Multiple patterns
vitest user auth
# Specific file
vitest src/user.test.ts
# By line number
vitest src/user.test.ts:25
```
### By Test Name
```bash
# Tests matching pattern
vitest -t "login"
vitest --testNamePattern "should.*work"
# Regex patterns
vitest -t "/user|auth/"
```
## Changed Files
```bash
# Uncommitted changes
vitest --changed
# Since specific commit
vitest --changed HEAD~1
vitest --changed abc123
# Since branch
vitest --changed origin/main
```
## Related Files
Run tests that import specific files:
```bash
vitest related src/utils.ts src/api.ts --run
```
Useful with lint-staged:
```js
// .lintstagedrc.js
export default {
'*.{ts,tsx}': 'vitest related --run',
}
```
## Focus Tests (.only)
```ts
test.only('only this runs', () => {})
describe.only('only this suite', () => {
test('runs', () => {})
})
```
In CI, `.only` throws error unless configured:
```ts
defineConfig({
test: {
allowOnly: true, // Allow .only in CI
},
})
```
## Skip Tests
```ts
test.skip('skipped', () => {})
// Conditional
test.skipIf(process.env.CI)('not in CI', () => {})
test.runIf(!process.env.CI)('local only', () => {})
// Dynamic skip
test('dynamic', ({ skip }) => {
skip(someCondition, 'reason')
})
```
## Tags
Filter by custom tags:
```ts
test('database test', { tags: ['db'] }, () => {})
test('slow test', { tags: ['slow', 'integration'] }, () => {})
```
Run tagged tests:
```bash
vitest --tags db
vitest --tags "db,slow" # OR
vitest --tags db --tags slow # OR
```
Configure allowed tags:
```ts
defineConfig({
test: {
tags: ['db', 'slow', 'integration'],
strictTags: true, // Fail on unknown tags
},
})
```
## Include/Exclude Patterns
```ts
defineConfig({
test: {
// Test file patterns
include: ['**/*.{test,spec}.{ts,tsx}'],
// Exclude patterns
exclude: [
'**/node_modules/**',
'**/e2e/**',
'**/*.skip.test.ts',
],
// Include source for in-source testing
includeSource: ['src/**/*.ts'],
},
})
```
## Watch Mode Filtering
In watch mode, press:
- `p` - Filter by filename pattern
- `t` - Filter by test name pattern
- `a` - Run all tests
- `f` - Run only failed tests
## Projects Filtering
Run specific project:
```bash
vitest --project unit
vitest --project integration --project e2e
```
## Environment-based Filtering
```ts
const isDev = process.env.NODE_ENV === 'development'
const isCI = process.env.CI
describe.skipIf(isCI)('local only tests', () => {})
describe.runIf(isDev)('dev tests', () => {})
```
## Combining Filters
```bash
# File pattern + test name + changed
vitest user -t "login" --changed
# Related files + run mode
vitest related src/auth.ts --run
```
## List Tests Without Running
```bash
vitest list # Show all test names
vitest list -t "user" # Filter by name
vitest list --filesOnly # Show only file paths
vitest list --json # JSON output
```
## Key Points
- Use `-t` for test name pattern filtering
- `--changed` runs only tests affected by changes
- `--related` runs tests importing specific files
- Tags provide semantic test grouping
- Use `.only` for debugging, but configure CI to reject it
- Watch mode has interactive filtering
<!--
Source references:
- https://vitest.dev/guide/filtering.html
- https://vitest.dev/guide/cli.html
-->
@@ -1,265 +0,0 @@
---
name: mocking
description: Mock functions, modules, timers, and dates with vi utilities
---
# Mocking
## Mock Functions
```ts
import { expect, vi } from 'vitest'
// Create mock function
const fn = vi.fn()
fn('hello')
expect(fn).toHaveBeenCalled()
expect(fn).toHaveBeenCalledWith('hello')
// With implementation
const add = vi.fn((a, b) => a + b)
expect(add(1, 2)).toBe(3)
// Mock return values
fn.mockReturnValue(42)
fn.mockReturnValueOnce(1).mockReturnValueOnce(2)
fn.mockResolvedValue({ data: true })
fn.mockRejectedValue(new Error('fail'))
// Mock implementation
fn.mockImplementation((x) => x * 2)
fn.mockImplementationOnce(() => 'first call')
```
## Spying on Objects
```ts
const cart = {
getTotal: () => 100,
}
const spy = vi.spyOn(cart, 'getTotal')
cart.getTotal()
expect(spy).toHaveBeenCalled()
// Mock implementation
spy.mockReturnValue(200)
expect(cart.getTotal()).toBe(200)
// Restore original
spy.mockRestore()
```
## Module Mocking
```ts
// vi.mock is hoisted to top of file
vi.mock('./api', () => ({
fetchUser: vi.fn(() => ({ id: 1, name: 'Mock' })),
}))
import { fetchUser } from './api'
test('mocked module', () => {
expect(fetchUser()).toEqual({ id: 1, name: 'Mock' })
})
```
### Partial Mock
```ts
vi.mock('./utils', async (importOriginal) => {
const actual = await importOriginal()
return {
...actual,
specificFunction: vi.fn(),
}
})
```
### Auto-mock with Spy
```ts
// Keep implementation but spy on calls
vi.mock('./calculator', { spy: true })
import { add } from './calculator'
test('spy on module', () => {
const result = add(1, 2) // Real implementation
expect(result).toBe(3)
expect(add).toHaveBeenCalledWith(1, 2)
})
```
### Manual Mocks (__mocks__)
```
src/
__mocks__/
axios.ts # Mocks 'axios'
api/
__mocks__/
client.ts # Mocks './client'
client.ts
```
```ts
// Just call vi.mock with no factory
vi.mock('axios')
vi.mock('./api/client')
```
## Dynamic Mocking (vi.doMock)
Not hoisted - use for dynamic imports:
```ts
test('dynamic mock', async () => {
vi.doMock('./config', () => ({
apiUrl: 'http://test.local',
}))
const { apiUrl } = await import('./config')
expect(apiUrl).toBe('http://test.local')
vi.doUnmock('./config')
})
```
## Mock Timers
```ts
import { afterEach, beforeEach, vi } from 'vitest'
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
test('timers', () => {
const fn = vi.fn()
setTimeout(fn, 1000)
expect(fn).not.toHaveBeenCalled()
vi.advanceTimersByTime(1000)
expect(fn).toHaveBeenCalled()
})
// Other timer methods
vi.runAllTimers() // Run all pending timers
vi.runOnlyPendingTimers() // Run only currently pending
vi.advanceTimersToNextTimer() // Advance to next timer
```
### Async Timer Methods
```ts
test('async timers', async () => {
vi.useFakeTimers()
let resolved = false
setTimeout(() => Promise.resolve().then(() => { resolved = true }), 100)
await vi.advanceTimersByTimeAsync(100)
expect(resolved).toBe(true)
})
```
## Mock Dates
```ts
vi.setSystemTime(new Date('2024-01-01'))
expect(new Date().getFullYear()).toBe(2024)
vi.useRealTimers() // Restore
```
## Mock Globals
```ts
vi.stubGlobal('fetch', vi.fn(() =>
Promise.resolve({ json: () => ({ data: 'mock' }) })
))
// Restore
vi.unstubAllGlobals()
```
## Mock Environment Variables
```ts
vi.stubEnv('API_KEY', 'test-key')
expect(import.meta.env.API_KEY).toBe('test-key')
// Restore
vi.unstubAllEnvs()
```
## Clearing Mocks
```ts
const fn = vi.fn()
fn()
fn.mockClear() // Clear call history
fn.mockReset() // Clear history + implementation
fn.mockRestore() // Restore original (for spies)
// Global
vi.clearAllMocks()
vi.resetAllMocks()
vi.restoreAllMocks()
```
## Config Auto-Reset
```ts
// vitest.config.ts
defineConfig({
test: {
clearMocks: true, // Clear before each test
mockReset: true, // Reset before each test
restoreMocks: true, // Restore after each test
unstubEnvs: true, // Restore env vars
unstubGlobals: true, // Restore globals
},
})
```
## Hoisted Variables for Mocks
```ts
const mockFn = vi.hoisted(() => vi.fn())
vi.mock('./module', () => ({
getData: mockFn,
}))
import { getData } from './module'
test('hoisted mock', () => {
mockFn.mockReturnValue('test')
expect(getData()).toBe('test')
})
```
## Key Points
- `vi.mock` is hoisted - called before imports
- Use `vi.doMock` for dynamic, non-hoisted mocking
- Always restore mocks to avoid test pollution
- Use `{ spy: true }` to keep implementation but track calls
- `vi.hoisted` lets you reference variables in mock factories
<!--
Source references:
- https://vitest.dev/guide/mocking.html
- https://vitest.dev/api/vi.html
-->
@@ -1,207 +0,0 @@
---
name: snapshot-testing
description: Snapshot testing with file, inline, and file snapshots
---
# Snapshot Testing
Snapshot tests capture output and compare against stored references.
## Basic Snapshot
```ts
import { expect, test } from 'vitest'
test('snapshot', () => {
const result = generateOutput()
expect(result).toMatchSnapshot()
})
```
First run creates `.snap` file:
```js
// __snapshots__/test.spec.ts.snap
exports['snapshot 1'] = `
{
"id": 1,
"name": "test"
}
`
```
## Inline Snapshots
Stored directly in test file:
```ts
test('inline snapshot', () => {
const data = { foo: 'bar' }
expect(data).toMatchInlineSnapshot()
})
```
Vitest updates the test file:
```ts
test('inline snapshot', () => {
const data = { foo: 'bar' }
expect(data).toMatchInlineSnapshot(`
{
"foo": "bar",
}
`)
})
```
## File Snapshots
Compare against explicit file:
```ts
test('render html', async () => {
const html = renderComponent()
await expect(html).toMatchFileSnapshot('./expected/component.html')
})
```
## Snapshot Hints
Add descriptive hints:
```ts
test('multiple snapshots', () => {
expect(header).toMatchSnapshot('header')
expect(body).toMatchSnapshot('body content')
expect(footer).toMatchSnapshot('footer')
})
```
## Object Shape Matching
Match partial structure:
```ts
test('shape snapshot', () => {
const data = {
id: Math.random(),
created: new Date(),
name: 'test'
}
expect(data).toMatchSnapshot({
id: expect.any(Number),
created: expect.any(Date),
})
})
```
## Error Snapshots
```ts
test('error message', () => {
expect(() => {
throw new Error('Something went wrong')
}).toThrowErrorMatchingSnapshot()
})
test('inline error', () => {
expect(() => {
throw new Error('Bad input')
}).toThrowErrorMatchingInlineSnapshot(`[Error: Bad input]`)
})
```
## Updating Snapshots
```bash
# Update all snapshots
vitest -u
vitest --update
# In watch mode, press 'u' to update failed snapshots
```
## Custom Serializers
Add custom snapshot formatting:
```ts
expect.addSnapshotSerializer({
test(val) {
return val && typeof val.toJSON === 'function'
},
serialize(val, config, indentation, depth, refs, printer) {
return printer(val.toJSON(), config, indentation, depth, refs)
},
})
```
Or via config:
```ts
// vitest.config.ts
defineConfig({
test: {
snapshotSerializers: ['./my-serializer.ts'],
},
})
```
## Snapshot Format Options
```ts
defineConfig({
test: {
snapshotFormat: {
printBasicPrototype: false, // Don't print Array/Object prototypes
escapeString: false,
},
},
})
```
## Concurrent Test Snapshots
Use context's expect:
```ts
test.concurrent('concurrent 1', async ({ expect }) => {
expect(await getData()).toMatchSnapshot()
})
test.concurrent('concurrent 2', async ({ expect }) => {
expect(await getOther()).toMatchSnapshot()
})
```
## Snapshot File Location
Default: `__snapshots__/<test-file>.snap`
Customize:
```ts
defineConfig({
test: {
resolveSnapshotPath: (testPath, snapExtension) => {
return testPath.replace('__tests__', '__snapshots__') + snapExtension
},
},
})
```
## Key Points
- Commit snapshot files to version control
- Review snapshot changes in code review
- Use hints for multiple snapshots in one test
- Use `toMatchFileSnapshot` for large outputs (HTML, JSON)
- Inline snapshots auto-update in test file
- Use context's `expect` for concurrent tests
<!--
Source references:
- https://vitest.dev/guide/snapshot.html
- https://vitest.dev/api/expect.html#tomatchsnapshot
-->
+5 -5
View File
@@ -11,12 +11,12 @@ issue_enrichment:
reviews:
high_level_summary: false
# Skip machine-generated / vendored files (mirrors .prettierignore). Keeps
# Skip machine-generated / vendored files (mirrors .oxfmtrc.jsonc). Keeps
# reviews focused on hand-written code and preserves rate-limit budget on
# large codegen diffs.
path_filters:
- '!pnpm-lock.yaml'
- '!packages/api-types/types/**' # generated API types (api.d.ts, platform.d.ts)
- '!packages/api-types/types/**' # generated API types (api-v1.d.ts, api-v2.d.ts, platform.d.ts)
- '!supabase/functions/common/database-types.ts' # generated by `pnpm generate:types`
- '!**/routeTree.gen.ts' # TanStack Router generated
- '!**/__generated__/**'
@@ -122,11 +122,11 @@ reviews:
knowledge_base:
code_guidelines:
filePatterns:
# Studio code conventions — React/TS, UI patterns, composition, data fetching, errors
- files: '.agents/skills/{studio-ui-patterns,vercel-composition-patterns,studio-queries,studio-error-handling,react-hook-form}/SKILL.md'
# Studio code conventions — routing, UI patterns, data fetching, errors, forms
- files: '.agents/skills/{studio-routes,studio-ui-patterns,studio-queries,studio-error-handling,react-hook-form}/SKILL.md'
applyTo: 'apps/studio/**/*.{ts,tsx}'
# Studio unit / component test conventions
- files: '.agents/skills/{studio-testing,studio-mock-api-tests}/SKILL.md'
- files: '.agents/skills/studio-testing/{SKILL.md,references/*.md}'
applyTo: 'apps/studio/**/*.test.{ts,tsx}'
# Studio end-to-end (Playwright) test conventions
- files: '.agents/skills/studio-e2e-tests/SKILL.md'
+11 -11
View File
@@ -2,7 +2,7 @@
## Review Policy — Read This First
You are a code reviewer for a large TypeScript/Next.js/React monorepo. Your reviews must be **low-noise and high-signal**. The team acts on fewer than 20% of default Copilot suggestions, so every comment you leave must earn its place.
You are a code reviewer for a large TypeScript/React monorepo (TanStack Start for `apps/studio`, Next.js for `apps/www` and `apps/docs`, Astro for `apps/kb`). Your reviews must be **low-noise and high-signal**. The team acts on fewer than 20% of default Copilot suggestions, so every comment you leave must earn its place.
### Confidence Threshold
@@ -12,12 +12,12 @@ Only comment when you are **>85% confident** the issue is a real bug, security v
Our CI pipeline already validates the following. **Never comment on these topics:**
- **Formatting or whitespace** — oxfmt runs on every PR
- **Linting issues** — ESLint with auto-fix runs on every PR
- **Formatting or whitespace** — `oxfmt` runs on every PR for `{apps,packages,blocks,i18n}`
- **Linting issues** — ESLint and lint ratchets run on every PR
- **Type errors** — TypeScript strict-mode typecheck runs on every PR
- **Typos or spelling** — Automated typo detection runs on every PR
- **Missing tests for trivial changes** — Handled by topic-specific test instructions
- **Import ordering or grouping** — Handled by linter
- **Import ordering or grouping** — Handled by `oxfmt` in `apps/studio`
- **Naming style preferences** (camelCase vs snake_case debates) — Follow existing file conventions
- **Accessibility attributes on shadcn/Radix UI components** — handled by the primitives; see [shadcn/Radix accessibility](#shadcnradix-accessibility) below
@@ -38,11 +38,11 @@ Our CI pipeline already validates the following. **Never comment on these topics
## Repo Context
This is a TypeScript/Next.js/React monorepo:
This is a TypeScript/React monorepo:
- `apps/studio/` — Supabase Dashboard (primary review target)
- `apps/www/` — Marketing site
- `apps/docs/` — Documentation
- `apps/studio/` — Supabase Dashboard, TanStack Start (primary review target)
- `apps/www/` — Marketing site (Next.js)
- `apps/docs/` — Documentation (Next.js)
- `packages/common/` — Shared code including telemetry definitions
## Topic-Specific Guidelines
@@ -51,7 +51,7 @@ Coding conventions are not duplicated here. Read them from the shared agent inst
- `AGENTS.md` (repo root) — monorepo structure, commands, CI, conventions
- `apps/studio/AGENTS.md` — Studio-specific rules and the task → skill map
- `.agents/skills/*/SKILL.md` — the source of truth per topic. Most relevant to review: `studio-testing`, `studio-mock-api-tests`, `studio-e2e-tests`, `studio-error-handling`, `studio-queries`, `studio-ui-patterns`, `react-hook-form`, `telemetry-standards`, `safe-sql-execution`, `vercel-composition-patterns`, `studio-shortcuts`, `copywriting`
- `.agents/skills/*/SKILL.md` — the source of truth per topic. Most relevant to review: `studio-routes`, `studio-testing`, `studio-e2e-tests`, `studio-error-handling`, `studio-queries`, `studio-ui-patterns`, `react-hook-form`, `telemetry-standards`, `safe-sql-execution`, `clickhouse-logs-queries`, `dev-toolbar-review`, `studio-shortcuts`, `copywriting`
When a skill says to flag something, treat it as **advisory** here — the confidence threshold and comment style above still apply.
@@ -76,12 +76,12 @@ Studio uses **shadcn/ui** components built on **Radix UI** primitives (from `pac
| `ScrollArea` | Accessible scrollbar replacement |
| `NavigationMenu` | `role="navigation"`, keyboard navigation |
Specifically, never flag: missing `role` on Radix-based components; missing `aria-modal` on `Dialog`/`AlertDialog`; missing `aria-expanded` on `Accordion`, `Collapsible`, `Select`, or `DropdownMenu` triggers; missing `aria-selected` on `Tabs`; missing `aria-checked` on `Checkbox`, `RadioGroup`, or `Switch`; missing keyboard handlers on interactive Radix components; missing focus management in dialogs; missing `aria-label` on `DialogClose` (it renders `<span className="sr-only">Close</span>`).
Specifically, never flag: missing `role` on Radix-based components; missing `aria-modal` on `Dialog`/`AlertDialog`; missing `aria-expanded` on `Accordion`, `Collapsible`, `Select`, or `DropdownMenu` triggers; missing `aria-selected` on `Tabs`; missing `aria-checked` on `Checkbox`, `RadioGroup`, or `Switch`; missing keyboard handlers on interactive Radix components; missing focus management in dialogs; missing `aria-label` on `DialogContent`'s built-in close button (it renders `<span className="sr-only">Close</span>`; standalone icon-only `<DialogClose>` still needs an accessible name).
**Do** flag accessibility issues on:
1. **Custom interactive elements** not using Radix primitives (e.g. a `<div onClick>` that should be a `<button>`)
2. **Icon-only buttons** missing an accessible label — `<Button>` alone does not add one; use `aria-label` or `<span className="sr-only">`
3. **Missing `Label` association** — form inputs should be paired with `<Label htmlFor="...">` or wrapped in a `<Field>` component
3. **Missing `Label` association** — form inputs need a label bound either via explicit `htmlFor`/`id` (`<Label htmlFor="x">` + `<Input id="x">`, or `FormItemLayout` with `isReactForm={false}` whose rendered `htmlFor` matches the input's `id`) or via RHF context (`<FormField>` + `<FormItem>`/`FormItemLayout` + `<FormControl>`); `<Field>` alone and `name` attributes do not associate labels
4. **Images missing `alt` text**
5. **Color-only state indicators**
+20 -24
View File
@@ -11,9 +11,9 @@ pnpm 12 + Turborepo monorepo. Requires Node 26 (see `.nvmrc`).
| `apps/www` | Marketing website — Next.js, app + pages (port 3000) |
| `apps/design-system` | Component demos — source of truth for Studio UI patterns (port 3003) |
| `apps/ui-library` | shadcn-style registry site for Supabase UI blocks (port 3004) |
| `apps/lite-studio` | Lightweight Studio — different stack: React Router 7 + Vite + Tailwind v4 |
| `apps/lite-studio` | Lightweight Studio — React Router 7 + Vite + Tailwind v4 |
| `apps/kb` | Knowledge base — Astro — has its own `apps/kb/AGENTS.md` |
| `apps/learn` | Courses site — Next.js + Contentlayer (port 3007), early stage |
| `apps/learn` | Courses site — Next.js + Velite (port 3007), early stage |
| `packages/ui` | Shared UI components (shadcn/ui based) — `import { Button } from 'ui'` |
| `packages/ui-patterns` | Composite components — subpath imports, e.g. `ui-patterns/AssistantChat` |
| `packages/common` | Shared utils, telemetry constants, feature flags |
@@ -35,43 +35,39 @@ pnpm e2e # Studio E2E tests (playwright)
pnpm build --filter=studio # build Studio
pnpm lint --filter=studio # lint Studio
pnpm typecheck # typecheck all packages
pnpm format # oxfmt write (check: pnpm format:check)
pnpm format # oxfmt write for {apps,packages,blocks,i18n} (check: pnpm format:check; other paths: pnpm exec oxfmt --check <paths>)
pnpm generate:types # local DB types → supabase/functions/common/database-types.ts
pnpm api:codegen # platform Management API types → packages/api-types
```
## CI
## CI & Generated Files
Every PR must pass typecheck + lint (one workflow), oxfmt formatting, and a typos check. Other checks are path-filtered: Studio unit tests/build and the lint ratchet (ESLint warning count must not increase) run on `apps/studio/**` changes and the Tailwind class rules (`shadcn/*`) for `www`, `docs`, `design-system`, `ui-library`, `learn`, and `kb`; app-specific test suites run on their own paths.
Every PR runs typecheck, lint, `oxfmt`, and typos checks, plus path-filtered test/build workflows, lint ratchets (warning counts cannot increase), and Tailwind token rules (`shadcn/*`).
Never hand-edit generated files: `packages/api-types/types/**`, `**/routeTree.gen.ts`, `**/__generated__/**`, `apps/docs/features/docs/generated/**`, `apps/www/.generated/**`, `supabase/functions/common/database-types.ts`, `apps/docs/content/_partials/access-control/scoped_pat_*.mdx` (run `make -C apps/docs/spec generate.partials.access-control`).
Never hand-edit generated files: `packages/api-types/types/**`, `**/routeTree.gen.ts`, `**/__generated__/**`, `apps/docs/features/docs/generated/**`, `apps/www/.generated/**`, `supabase/functions/common/database-types.ts`, `apps/docs/content/_partials/access-control/scoped_pat_*.mdx` (`make -C apps/docs/spec generate.partials.access-control`).
## Conventions
**UI** — import from `'ui'`; primitives are shadcn/ui-based and exported unsuffixed (`Input`, `Select`, `Form`, …). Use `Button` — the in-house component and the standard everywhere (a raw shadcn `Button_Shadcn_` also exists but is rarely the right choice). Check `packages/ui/index.tsx` before creating new primitives. Higher-level patterns live in `packages/ui-patterns`.
**Styling** — Tailwind only, semantic tokens (`bg-muted`, `text-foreground-light`), no hardcoded colors.
**Exports** — named exports only; default exports are allowed only where a framework requires them (`pages/**`, `app/**`, config files — the eslint preset has the exact carve-out list). Lint-enforced across all apps via `eslint-config-supabase` (severity `warn` everywhere; hard-enforced in Studio by the lint ratchet).
**Language** — Use U.S. English everywhere.
**Public surfaces** — this repo is public: PR descriptions, issues, and code comments are world-readable. Keep internal content out of them: absolute production metrics (event counts, user counts, revenue figures: state percentages, ratios, or relative change instead), internal decision detail (vendor, legal, pricing, or strategy discussions), and competitor names (protocol identifiers such as user-agent strings are fine). Put that context in the Linear issue and link it.
- **UI & styling** — Import primitives from `'ui'` (`Button`, not raw `Button_Shadcn_`; check `packages/ui/index.tsx` first) and composed patterns from `'ui-patterns'`. Use Tailwind semantic tokens (`bg-muted`, `text-foreground-light`), never hardcoded colors.
- **Exports & language** — Named exports only (default exports only where a framework requires them; lint-enforced). Use U.S. English everywhere.
- **Public surfaces** — This repo is world-readable. Keep internal content out of code, comments, PRs, and issues: absolute production metrics (use percentages/ratios), internal vendor/legal/pricing/strategy detail, competitor names (protocol identifiers like user-agents are fine), private repo paths/symbols, and internal teammate names. Link Linear for internal context.
- **Comments** — Explain non-obvious _why_ (invariants, ordering constraints, or temporary workarounds with a Linear ticket ID) — never _what_, file headers, change/mock history, or scratchpad narration.
- **Dependencies & diff scope** — Use `"catalog:"` for shared workspace deps (add script tools to `devDependencies`, update the lockfile, remove unused deps). Keep diffs surgical: strip `console.log`s, isolate major dep bumps, and keep tooling version updates scoped to their own semantic boundary.
## Skills
The skills in `.agents/skills/` are the source of truth for conventions. Load the relevant ones before working, don't guess. One exception: for docs **content** style, `apps/docs/style-guide/` is the source of truth and the docs skills are the process that applies it.
`.agents/skills/` is the source of truth for conventions — load the relevant skill before working instead of guessing. (For docs **content** style, `apps/docs/style-guide/` is the source of truth applied by the docs skills.)
- [code-review](.agents/skills/code-review/SKILL.md) — read-only assessments and development-task readiness checks
- `code-review` — read-only assessments and development-task readiness checks
- `copywriting` — any user-facing text, anywhere in the monorepo
- `pm-the-docs` / `write-the-docs` / `edit-the-docs` / `ask-the-docs` / `review-the-docs` — anything under `apps/docs` (see `apps/docs/CONTRIBUTING.md` for the authoring skill model, and `apps/docs/style-guide/` for the content style rules they apply)
- `telemetry-standards` — PostHog events, `packages/common/telemetry-constants.ts`
- `dev-toolbar-review` — `packages/dev-tools`, `packages/common/posthog-client.ts`, `packages/common/feature-flags.tsx`
- `safe-sql-execution` — any code that builds or executes SQL against user databases
- `react-hook-form` — writing or modifying any form code, anywhere in the monorepo
- `turbo-scripts` — `package.json` scripts or `turbo.jsonc` in any app or package (pre/post hooks, script chains, `maybe-turbo`, task inputs, env, caching)
- `vitest` / `vercel-composition-patterns` — generic unit-testing and React composition references
- `safe-sql-execution` — any code building or executing SQL against user databases or analytics logs
- `telemetry-standards` — PostHog events, `packages/common/telemetry-constants.ts`
- `api-types` — regenerating `packages/api-types` and verifying production OpenAPI drift
- `dev-toolbar-review` — `packages/dev-tools`, `packages/common/posthog-client.ts`, `packages/common/feature-flags.tsx`
- `turbo-scripts` — `package.json` scripts or `turbo.jsonc` tasks, `maybe-turbo`, caching, env
- `pm-the-docs` / `write-the-docs` / `edit-the-docs` / `ask-the-docs` / `review-the-docs` / `test-the-docs` — anything under `apps/docs` (see `apps/docs/CONTRIBUTING.md`)
## Studio
Before working on anything in `apps/studio`, read `apps/studio/AGENTS.md` if it isn't already in context — it maps Studio tasks to required skills and covers the TanStack Start migration rules.
Before working on anything in `apps/studio`, read `apps/studio/AGENTS.md` — it maps Studio tasks to skills and covers Studio architecture, principles, and repo-specific traps.
+38 -73
View File
@@ -4,85 +4,50 @@ TanStack Start + React 19. Dev server: `pnpm dev:studio` → http://localhost:80
## Skills — load before working
Load the skills matching the task; stack them when a task spans areas:
Load every skill matching the task; stack them when a task spans areas:
| Task | Additional skills |
| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| Query/mutation hooks, query keys (`data/**`) | `studio-queries` |
| UI: pages, forms, tables, charts, sheets, empty states | `studio-ui-patterns` |
| Form logic: react-hook-form fields, watch/formState, reset, number inputs | `react-hook-form` |
| Displaying API errors | `studio-error-handling` |
| Tests (deciding, writing, reviewing) | `studio-testing`, then `studio-mock-api-tests` (component/MSW) or `studio-e2e-tests` (Playwright) |
| PostHog event tracking | `telemetry-standards` |
| SQL against user databases | `safe-sql-execution` |
| Logs Explorer SQL, `data/logs` | `clickhouse-logs-queries` |
| Component API design, boolean-prop refactors | `vercel-composition-patterns` |
| Keyboard shortcuts, search/filter inputs | `studio-shortcuts` |
| User-facing copy | `copywriting` |
## Routing
Routes live in `routes/**` (TanStack Start file routes); `routeTree.gen.ts` is generated by the Vite plugin — never hand-edit it.
- Use native TanStack APIs (`Link`, `useNavigate`, `Route.useParams()`, `useSearch`) — no `next/*` imports.
- Layouts are pathless (`routes/_app.tsx`, `routes/_auth.tsx`) or sibling-file shells (`routes/project/$ref/database.tsx` wraps `routes/project/$ref/database/**`), configured per leaf through `staticData`.
- Route files export only `Route`; shared components belong in `components/**`.
| Task | Skill |
| ------------------------------------------------------------------------- | ------------------------- |
| Routes, layouts, redirects, server API handlers (`routes/**`) | `studio-routes` |
| Query/mutation hooks, query keys (`data/**`) | `studio-queries` |
| UI: pages, links, tables, charts, dialogs, sheets, empty states, a11y | `studio-ui-patterns` |
| Form logic: react-hook-form fields, watch/formState, reset, number inputs | `react-hook-form` |
| Displaying API errors | `studio-error-handling` |
| Tests: deciding, writing, reviewing unit & MSW component tests | `studio-testing` |
| Playwright E2E tests (`e2e/studio/**`) | `studio-e2e-tests` |
| PostHog event tracking | `telemetry-standards` |
| SQL against user databases or analytics logs | `safe-sql-execution` |
| Logs Explorer SQL, `data/logs` | `clickhouse-logs-queries` |
| Keyboard shortcuts, search/filter inputs | `studio-shortcuts` |
| User-facing copy | `copywriting` |
## Orientation
- **Supabase Assistant** — before working on Assistant chat, prompts, tools, or access handling, read the [Assistant code guide](lib/ai/README.md) for entry points, request flow, and validation references. Update the guide when moving entry points or changing the request/tool lifecycle.
- **Data layer** — all platform API calls go through `data/fetchers.ts` (`openapi-fetch`, typed by the generated `api-types` package) with `handleError`; never raw `fetch`. One folder per resource in `data/`, most with a `keys.ts` query-key factory.
- **State** — valtio for global state (`state/`), nuqs for URL state, react-hook-form + zod for forms.
- **Platform vs self-hosted** — `IS_PLATFORM` gates platform-only behavior; `withAuth` is a no-op when self-hosted.
- **Telemetry** — `useTrack()` from `lib/telemetry/track`; event types live in `packages/common/telemetry-constants.ts`.
- **Tests** — default to including relevant tests with any change: a couple of unit tests for extracted logic, component tests for UI behavior, E2E only when the scope demands it (`studio-testing` has the decision tree). Not every PR needs them, but "no tests" should be a considered choice, not the default. Tooling: vitest + MSW; component tests use `customRender` + `addAPIMock` from `tests/lib/`; unhandled network requests fail tests. Don't `vi.mock('@/data/...')`.
- **Shortcuts** — use the registry in `state/shortcuts/` and `components/ui/Shortcut*.tsx`; keep `G then …` chords for navigation; no one-off keyboard listeners (`studio-shortcuts` has the full pattern, including the search-input Escape handler).
- **Scoped PAT catalog** — `packages/shared-data/scoped-access-token-permissions.ts` feeds Studio and the generated Personal Access Tokens guide. After changing it, run `make -C apps/docs/spec generate.partials.access-control`; Docs Tests rejects stale tables.
- **Reuse first** — before writing a new hook or helper, search for an existing one (`hooks/`, `lib/`, `packages/common`, `packages/ui-patterns`). If you do need a new one, make it as reusable as possible: general naming, no page-specific coupling, placed where other callers can find it.
- Co-locate sub-components with their parent; avoid barrel re-export files.
- **Routing** — TanStack Start file routes under `routes/**`; `routeTree.gen.ts` is generated (never hand-edit). Use native TanStack APIs (no `next/*` imports); load `studio-routes` for route modules, redirects, and `routes/api/**`.
- **Data & state** — Platform API calls go through `data/fetchers.ts` (`openapi-fetch` + `api-types`) with `handleError`; never raw `fetch`. State: `valtio` (`state/`), `nuqs` (URL), `react-hook-form` + `zod` (forms).
- **Platform & flags** — `IS_PLATFORM` gates platform-only behavior (`withAuth` is a no-op self-hosted). Gate platform/flag-only UI in the parent _before_ mounting or fetching; disabled flagged UI early-returns `null` (verify both states).
- **Tests** — Write tests only when they guard a plausible runtime regression static analysis cannot catch. Skipping tests for static copy, pure markup, constants, pass-through wrappers, and standard `data/**` hooks/keys is expected (`studio-testing`).
- **Assistant & PATs** — Read [lib/ai/README.md](lib/ai/README.md) before changing Assistant chat, tools, prompts, or access handling (and update it when moving entry points or changing the request/tool lifecycle). After editing `packages/shared-data/scoped-access-token-permissions.ts`, run `make -C apps/docs/spec generate.partials.access-control`.
- **Reuse first** — Search `hooks/`, `lib/`, `packages/common`, and `packages/ui-patterns` before adding helpers. Reuse `EMPTY_ARR`/`EMPTY_OBJ` (`lib/void`), `pluralize`/`formatCurrency` (`lib/helpers`), `getErrorMessage` (`lib/get-error-message`), `useLatest` (`hooks/misc/useLatest`), `useOnChange` (`common`), and `cn` (`ui`).
## Code style
## Engineering principles
Older Studio code predates some of these conventions. For new or modified code, follow them rather than mirroring nearby legacy patterns:
Older Studio code predates these conventions. Follow them in new or modified code rather than copying legacy neighbors:
- **Booleans** read as `is`/`has`/`can`/`should`. Derive them from existing state (`const isFormValid = name.length > 0 && email.includes('@')`) — mirroring a derivable value into `useState` synced by `useEffect` is a bug pattern. Give multi-condition logic a name (`const canShowAddButton = !isSchemaLocked && canUpdateColumns && …`) instead of inlining the chain in JSX.
- **Ternaries**: one is fine for a binary choice; never nest them. Anything bigger flattens — early returns in statement position, sibling `&&` blocks in JSX.
- **Fetch states** render with early returns at the top level, or a flat `&&` chain with mutually exclusive guards inline — never a nested ternary:
- **Boundary & contract honesty** — Validate untrusted inputs at entry (URL params, JSON, `process.env`, caught `unknown`) with Zod or guards; inside, trust contracts and fix drift in `packages/api-types` (`satisfies`) rather than `as` casts or defensive shims.
- **Async & lifecycle completeness** — Walk pending, in-flight, error, empty, and closed states: unsettled queries never read as `false`/`0`, errors never collapse into empty states, slow actions lock in-flight, controlled inputs stay defined, and modals reset on close.
- **State & `useEffect`** — Keep state local, derive values instead of mirroring in `useState` (`Boolean(selectedId)`), and avoid unnecessary React Context. Use `useEffect` only for external sync right before `return`; fix `exhaustive-deps` or use `useEffectEvent` from `'react'` (not `'common'`, never `eslint-disable`).
- **Modularity & refactoring** — Split components around ~200–300 lines; co-locate sub-components, avoid barrel files, and extract non-trivial pure logic to `.utils.ts` (keep static copy in `.tsx`, unit-test only real edge cases). Update importers directly (no re-export shims) and delete dead code.
- **Composition & React 19** — Prefer `children`, compound components, and explicit variants over boolean-prop proliferation or render props, and pass `ref` as a regular prop in new React 19 components.
- **Types & fetch rendering** — Model multi-state values as discriminated unions and name booleans `is`/`has`/`can`/`should`. Never nest ternaries — render fetch states with early returns or mutually exclusive sibling `&&` blocks (`isPending` → `isError` → empty → data).
- **Naming & memoization** — Prop callbacks are `onX`, internal handlers `handleX`. Custom hooks return `useMemo`-wrapped objects (not tuples); otherwise memoize only for measured cost or referential stability.
- **Runtime matrix & blast radius** — Verify platform vs self-hosted, flag on/off, plan/provider/branch, and permissions; subtract only the exact condition when relaxing a guard. Fire each side effect in one layer and update companion surfaces together.
```tsx
// Top level: early return per state
if (isLoading) return <GenericSkeletonLoader />
if (isError) return <AlertError error={error} subject="Failed to retrieve data" />
if (isSuccess && data.length === 0) return <EmptyState />
return <DataDisplay data={data} />
## Non-deducible repo traps
// Inline: flat `&&` blocks, mutually exclusive guards
<div>
{isLoading && <ShimmeringLoader />}
{isError && <AlertError error={error} />}
{isSuccess && data.length === 0 && <EmptyState />}
{isSuccess && data.length > 0 && <DataDisplay data={data} />}
</div>
```
- **`useEffect` is for synchronizing with external systems** (subscriptions, DOM, timers) — not for deriving data (compute it in render), reacting to user actions (do it in the handler), or fetching (React Query). Older code uses effects for all of these; don't copy it.
- **State** stays as local as possible — lift it only when it's actually shared. Related form fields belong in a single react-hook-form + zod form, not parallel `useState` calls.
- **Component size**: split at ~200–300 lines — or sooner when a component grows multiple distinct UI sections, tangled conditional rendering, or clusters of unrelated `useState`. Extract repeated JSX into small components, non-trivial pure logic into `.utils.ts` functions (which get unit tests), and reusable stateful logic into custom hooks.
- **Memoization is not the default**: `useMemo`/`useCallback` only for measured expense or referential stability a memoized child depends on.
- **TypeScript**: avoid `as` casts — where external data enters, parse it with zod (`schema.parse`/`safeParse`) instead. Model multi-state values as discriminated unions (`{ status: 'success'; data: T } | { status: 'error'; error: Error }`) rather than independent boolean flags.
- **Naming**: prop callbacks are `onX`, internal handlers are `handleX`. Custom hooks return objects, not tuples.
- **Refactoring**: when you move or extract code into a new module, update every importer to point at the new location directly — do **not** leave a re-export shim in the old file "for backward compatibility." It's a one-line import change per consumer, and keeping shims around makes the codebase messy and the true source of a symbol ambiguous.
## Defaults that differ here
- **ESLint warnings are ratcheted in CI**: the per-rule occurrence count must not increase, so a new `any`, unresolved `exhaustive-deps` warning, or default export fails the build even though it's "only a warning". Check locally with `pnpm --filter studio run lint:ratchet`.
- **Dead files and deps are gated in CI** by knip (`pnpm knip --workspace apps/studio` locally). Framework-convention files nothing imports (routes, Vercel functions, TanStack Start files) belong in `knip.jsonc` under `workspaces["apps/studio"].entry`, not `ignore` — an ignored file's imports aren't traced, so anything only it uses gets reported as dead. There's no inline `knip-ignore` comment; the only per-file opt-out is config. In a PR stack, a file whose first consumer lands in a later PR fails the gate on the earlier one — either add it in the same PR as its first use, or add it to `workspaces["apps/studio"].ignore` with a `used from #NNN` comment and remove it in that PR.
- **Clipboard**: `copyToClipboard` from `'ui'`, and never `await` anything before calling it (Safari requires the write inside the user gesture; lint-enforced) — pass a Promise as the argument instead.
- **`useParams()` comes from `'common'`**, not `next/navigation` — it camelCases keys and returns `string | undefined`.
- **Permissions**: `useAsyncCheckPermissions` from `hooks/misc/useCheckPermissions` (returns `can: true` when self-hosted).
- **Gating**: `useIsFeatureEnabled` for product features, `useFlag` from `'common'` for feature flags — two different systems.
- **Dates**: `dayjs` (plugins pre-loaded in `routes/__root.tsx`), not `date-fns`. **Toasts**: `toast` from `'sonner'`.
- **Import split**: `'ui'` = primitives, `'ui-patterns'` = composed patterns (`ConfirmationModal`, …), `@ui/*` = alias into `packages/ui/src`. Icons come from `lucide-react`, always imported with the `Icon` suffix (`import { CheckIcon, Trash2Icon } from 'lucide-react'`) — never the bare names (`Check`) or `Check as CheckIcon` aliases (lint-enforced).
- **New tables** use `@tanstack/react-table`; `react-data-grid` is banned for new code.
- **Ad-hoc SQL** against the user's database goes through `executeSql` / `useExecuteSqlMutation` (`data/sql/execute-sql-mutation`).
- **Confirmations**: `ConfirmationModal` / `TextConfirmModal` from `ui-patterns`, never `window.confirm`. Disabled buttons needing an explanation use `ButtonTooltip`; inline warnings use `Admonition`.
- **CI-only gates** — `pnpm --filter studio run lint:ratchet` (warning counts cannot increase) and `pnpm knip --workspace apps/studio` (dead files/deps; no inline `knip-ignore` — add unimported entry files to `knip.jsonc` `entry`, or temporary stacked-PR files to `ignoreIssues` with `used from #NNN`).
- **`?error=` query param** — Never use `?error=` as a custom URL param: `auth-js` in `AuthProvider` intercepts it across all Studio pages and fires a spurious error toast.
- **`copyToClipboard`** (`ui`) — Never `await` before calling it (Safari gesture rule, lint-enforced — pass a `Promise<string>` as the 1st arg). It catches errors internally, so run post-copy feedback (`toast.success`, `setCopied`) in its 2nd callback arg, never after `await`.
- **Params & permissions** — Inside `components/**`, `useParams()` comes from `'common'` (camelCases kebab-case keys, merges search + route params, returns `string | undefined`); inside `routes/**`, use `Route.useParams()` (don't mix both in the same file). `useAsyncCheckPermissions` (`hooks/misc/useCheckPermissions`) returns `can: true` self-hosted.
- **Feature & cloud gating** — `useIsFeatureEnabled` (product features) and `useFlag` from `'common'` (ConfigCat flags) are separate systems. `useIsAwsCloudProvider` (`hooks/misc/useSelectedProject`) matches `AWS` only — also check `useIsAwsK8sCloudProvider` / `useIsAwsNimbusCloudProvider` for AWS-hosted features.
- **Icons, dates, toasts & SQL** — `lucide-react` icons import `*Icon` directly (never `Check as CheckIcon` aliases); use `dayjs` (plugins pre-loaded in `routes/__root.tsx`), `toast` from `'sonner'`, and `executeSql` (`data/sql/execute-sql-mutation`) for ad-hoc Postgres SQL.
+58 -66
View File
@@ -1,87 +1,79 @@
# UI Testing Notes
# Studio Unit & Component Testing
## Rules
See `.agents/skills/studio-testing/SKILL.md` (and its
`references/msw-component-tests.md` guide) for the full decision gate, quality
criteria, and MSW gotchas.
- All tests should be run consistently (avoid situations whereby tests fails "sometimes")
## Conventions
- Group tests in folders based on the feature they are testing. Avoid file/folder based folder names since those can change and we will forget to update the tests.
- **Co-locate new tests** beside the source file (`MyComponent.test.tsx`,
`MyComponent.utils.test.ts`). Legacy tests still live under `apps/studio/tests/`.
- **Choose the environment by extension** (`vitest.config.ts`):
- `*.test.ts` runs in `node` (fast — use for pure logic).
- `*.test.tsx` runs in `jsdom` (use for components, `renderHook`, or DOM APIs).
- `*.platform.test.tsx` runs with `NEXT_PUBLIC_IS_PLATFORM=true`.
- **Skip low-value tests:** Do not add tests for TypeScript/ESLint/Knip
guarantees, static copy, constants, thin wrappers, or standard `data/**`
React Query hooks and `keys.ts` factories.
Examples: /logs /reports /projects /database-settings /auth
## Rendering Components, Hooks, and Routes
## Custom Render and Custom Render Hook
Use `customRender` and `customRenderHook` from `@/tests/lib/custom-render`
(wraps `QueryClientProvider`, `TooltipProvider`, `NuqsTestingAdapter`, and
TanStack Router memory history):
`customRender` and `customRenderHook` are wrappers around `render` and `renderHook` that add some necessary providers like `QueryClientProvider`, `TooltipProvider` and `NuqsTestingAdapter`.
```tsx
import { customRender, customRenderHook } from '@/tests/lib/custom-render'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
Generally use those instead of the default `render` and `renderHook` functions.
customRender(<MyComponent />, {
initialUrl: '/project/default/issues',
nuqs: { searchParams: { search: 'hello' } },
profileContext: createMockProfileContext(),
})
```ts
import { customRender, customRenderHook } from 'tests/lib/custom-render'
customRender(<MyComponent />)
customRenderHook(() => useMyHook())
```
## Mocking API Requests
To mount a TanStack Start file route that reads `Route.useParams()`, use
`renderRoute` from `@/tests/lib/route-render`.
To mock API requests, we use the `msw` library.
## Mocking API Requests with MSW
Global mocks can be found in `tests/lib/msw-global-api-mocks.ts`.
Mock API calls at the network boundary with `addAPIMock` (`@/tests/lib/msw`),
not `vi.mock('@/data/...')`. Register `addAPIMock` per test or in `beforeEach`
(never `beforeAll` — handlers reset after every test in
`apps/studio/tests/vitestSetup.ts`), and unhandled requests fail tests loudly.
To mock the current user's FGA permissions, use `mockPermissions` (with `allPermissionsFor` or `NO_PERMISSIONS` from `tests/lib/permissions-fixtures.ts`) or `mockPermissionsError` from `tests/lib/msw-permissions.ts`.
```tsx
import { platformComponents as components } from 'api-types'
import { HttpResponse } from 'msw'
To mock an endpoint you can use the `addAPIMock` function. Make sure to add the mock in the `beforeEach` hook. It won't work with `beforeAll` if you have many tests.
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
```ts
beforeEach(() => {
addAPIMock({
method: 'get',
path: '/api/my-endpoint',
response: {
data: { foo: 'bar' },
},
})
type OrganizationResponse = components['schemas']['OrganizationResponse_Output']
addAPIMock({
method: 'get',
path: '/platform/organizations',
response: () => HttpResponse.json<OrganizationResponse[]>([]),
})
// Error response
addAPIMock({
method: 'get',
path: '/platform/organizations',
response: () => HttpResponse.json<APIErrorBody>({ message: 'Failed' }, { status: 500 }),
})
```
### API Mocking Tips:
- Global defaults live in `apps/studio/tests/lib/msw-global-api-mocks.ts`.
- Mock FGA permissions with `mockPermissions` / `mockPermissionsError`
(`@/tests/lib/msw-permissions`), `allPermissionsFor` / `NO_PERMISSIONS`
(`@/tests/lib/permissions-fixtures`), or `mockProjectGrantContext`
(`@/tests/lib/project-grant-mocks`).
- Keep mocks in the same folder as the tests that use them
- Add a test to verify the mock is working
## Popovers & Dropdowns
This will make debugging and updating the mocks easier.
```ts
test('mock is working', async () => {
const response = await fetch('/api/my-endpoint')
expect(response.json()).resolves.toEqual({ data: { foo: 'bar' } })
})
```
## Mocking Nuqs URL Parameters
To render a component that uses Nuqs with some predefined query parameters, you can use `customRender` with the `nuqs` prop.
```ts
customRender(<MyComponent />, {
nuqs: {
searchParams: {
search: 'hello world',
},
},
})
```
## `<Popover>` vs `<Dropdown>`
When simulating clicks on these components, do the following:
```js
// for Popovers
import userEvent from '@testing-library/user-event'
await userEvent.click('Hello world')
// for Dropdowns
import clickDropdown from 'tests/helpers'
clickDropdown('Hello world')
```
Use `userEvent.click` for Popovers, and `clickDropdown(element)` from
`@/tests/helpers` when opening a Radix Dropdown trigger in jsdom.