From 2eb00165c3aa8bb7e2e2ac7d19d8129831626a9d Mon Sep 17 00:00:00 2001 From: Alaister Young Date: Thu, 3 Dec 2026 18:30:27 +0800 Subject: [PATCH] chore(studio): improve AGENTS.md and skills from PR review data (#54467) --- .../skills/clickhouse-logs-queries/SKILL.md | 46 +- .../references/codebase-integration.md | 168 +++--- .agents/skills/code-review/SKILL.md | 8 +- .agents/skills/copywriting/SKILL.md | 20 +- .agents/skills/dev-toolbar-review/SKILL.md | 15 +- .agents/skills/react-hook-form/SKILL.md | 238 ++------ .agents/skills/safe-sql-execution/SKILL.md | 502 ++++------------- .agents/skills/studio-e2e-tests/SKILL.md | 528 +++++------------- .agents/skills/studio-error-handling/SKILL.md | 73 ++- .agents/skills/studio-mock-api-tests/SKILL.md | 335 ----------- .agents/skills/studio-queries/SKILL.md | 111 ++-- .agents/skills/studio-routes/SKILL.md | 105 ++++ .agents/skills/studio-shortcuts/SKILL.md | 15 +- .agents/skills/studio-testing/SKILL.md | 335 +++++------ .../references/msw-component-tests.md | 275 +++++++++ .agents/skills/studio-ui-patterns/SKILL.md | 144 ++--- .agents/skills/telemetry-standards/SKILL.md | 18 +- .../vercel-composition-patterns/SKILL.md | 88 --- .../rules/architecture-avoid-boolean-props.md | 100 ---- .../rules/architecture-compound-components.md | 112 ---- .../patterns-children-over-render-props.md | 87 --- .../rules/patterns-explicit-variants.md | 100 ---- .../rules/react19-no-forwardref.md | 42 -- .../rules/state-context-interface.md | 191 ------- .../rules/state-decouple-implementation.md | 113 ---- .../rules/state-lift-state.md | 125 ----- .agents/skills/vitest/GENERATION.md | 5 - .agents/skills/vitest/SKILL.md | 58 -- .../references/advanced-environments.md | 264 --------- .../vitest/references/advanced-projects.md | 300 ---------- .../references/advanced-type-testing.md | 237 -------- .../skills/vitest/references/advanced-vi.md | 249 --------- .agents/skills/vitest/references/core-cli.md | 166 ------ .../skills/vitest/references/core-config.md | 174 ------ .../skills/vitest/references/core-describe.md | 193 ------- .../skills/vitest/references/core-expect.md | 219 -------- .../skills/vitest/references/core-hooks.md | 244 -------- .../skills/vitest/references/core-test-api.md | 233 -------- .../vitest/references/features-concurrency.md | 250 --------- .../vitest/references/features-context.md | 238 -------- .../vitest/references/features-coverage.md | 207 ------- .../vitest/references/features-filtering.md | 211 ------- .../vitest/references/features-mocking.md | 265 --------- .../vitest/references/features-snapshots.md | 207 ------- .coderabbit.yaml | 10 +- .github/copilot-instructions.md | 22 +- AGENTS.md | 44 +- apps/studio/AGENTS.md | 111 ++-- apps/studio/tests/README.md | 124 ++-- 49 files changed, 1280 insertions(+), 6645 deletions(-) delete mode 100644 .agents/skills/studio-mock-api-tests/SKILL.md create mode 100644 .agents/skills/studio-routes/SKILL.md create mode 100644 .agents/skills/studio-testing/references/msw-component-tests.md delete mode 100644 .agents/skills/vercel-composition-patterns/SKILL.md delete mode 100644 .agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md delete mode 100644 .agents/skills/vercel-composition-patterns/rules/architecture-compound-components.md delete mode 100644 .agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md delete mode 100644 .agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md delete mode 100644 .agents/skills/vercel-composition-patterns/rules/react19-no-forwardref.md delete mode 100644 .agents/skills/vercel-composition-patterns/rules/state-context-interface.md delete mode 100644 .agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md delete mode 100644 .agents/skills/vercel-composition-patterns/rules/state-lift-state.md delete mode 100644 .agents/skills/vitest/GENERATION.md delete mode 100644 .agents/skills/vitest/SKILL.md delete mode 100644 .agents/skills/vitest/references/advanced-environments.md delete mode 100644 .agents/skills/vitest/references/advanced-projects.md delete mode 100644 .agents/skills/vitest/references/advanced-type-testing.md delete mode 100644 .agents/skills/vitest/references/advanced-vi.md delete mode 100644 .agents/skills/vitest/references/core-cli.md delete mode 100644 .agents/skills/vitest/references/core-config.md delete mode 100644 .agents/skills/vitest/references/core-describe.md delete mode 100644 .agents/skills/vitest/references/core-expect.md delete mode 100644 .agents/skills/vitest/references/core-hooks.md delete mode 100644 .agents/skills/vitest/references/core-test-api.md delete mode 100644 .agents/skills/vitest/references/features-concurrency.md delete mode 100644 .agents/skills/vitest/references/features-context.md delete mode 100644 .agents/skills/vitest/references/features-coverage.md delete mode 100644 .agents/skills/vitest/references/features-filtering.md delete mode 100644 .agents/skills/vitest/references/features-mocking.md delete mode 100644 .agents/skills/vitest/references/features-snapshots.md diff --git a/.agents/skills/clickhouse-logs-queries/SKILL.md b/.agents/skills/clickhouse-logs-queries/SKILL.md index 91960c73179..a167256adc0 100644 --- a/.agents/skills/clickhouse-logs-queries/SKILL.md +++ b/.agents/skills/clickhouse-logs-queries/SKILL.md @@ -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. diff --git a/.agents/skills/clickhouse-logs-queries/references/codebase-integration.md b/.agents/skills/clickhouse-logs-queries/references/codebase-integration.md index d49866ffe56..9a0e4f283c5 100644 --- a/.agents/skills/clickhouse-logs-queries/references/codebase-integration.md +++ b/.agents/skills/clickhouse-logs-queries/references/codebase-integration.md @@ -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`). diff --git a/.agents/skills/code-review/SKILL.md b/.agents/skills/code-review/SKILL.md index 954ec3e0a35..2fd142648dd 100644 --- a/.agents/skills/code-review/SKILL.md +++ b/.agents/skills/code-review/SKILL.md @@ -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 ` 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: diff --git a/.agents/skills/copywriting/SKILL.md b/.agents/skills/copywriting/SKILL.md index f69a7e0ed90..a1a2b4c9aba 100644 --- a/.agents/skills/copywriting/SKILL.md +++ b/.agents/skills/copywriting/SKILL.md @@ -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. diff --git a/.agents/skills/dev-toolbar-review/SKILL.md b/.agents/skills/dev-toolbar-review/SKILL.md index 687fcd09680..292bfa65ffb 100644 --- a/.agents/skills/dev-toolbar-review/SKILL.md +++ b/.agents/skills/dev-toolbar-review/SKILL.md @@ -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` diff --git a/.agents/skills/react-hook-form/SKILL.md b/.agents/skills/react-hook-form/SKILL.md index ae333a4fd5f..62956e4cb15 100644 --- a/.agents/skills/react-hook-form/SKILL.md +++ b/.agents/skills/react-hook-form/SKILL.md @@ -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 `
` (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 ``. +- **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 }) { - 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 }) { 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` → `` → `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` → `` → `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 - const defaultValues: FormValues = { name: '', maxConnections: '' } // Inside the component -const form = useForm({ - resolver: zodResolver(FormSchema), - defaultValues, -}) +const form = useForm({ resolver: zodResolver(FormSchema), defaultValues }) @@ -136,90 +89,34 @@ const form = useForm({ ``` -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 `
` and its buttons. +- **`FormItemLayout` + `` auto-ID contract:** + - Never pass manual `id` props to `` or its child input — `FormItem`/`FormLabel`/`FormControl` auto-bind `formItemId`. + - Wrap the single input control directly in `` (no layout `
` 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 `` + ``. -Submit buttons living outside the `` (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 `` 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 ``. +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 ``). -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 `
` (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` | diff --git a/.agents/skills/safe-sql-execution/SKILL.md b/.agents/skills/safe-sql-execution/SKILL.md index cec2d534118..96008ddfba4 100644 --- a/.agents/skills/safe-sql-execution/SKILL.md +++ b/.agents/skills/safe-sql-execution/SKILL.md @@ -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 - - export type SafeSqlInputProps = Omit< - InputProps, 'placeholder' | 'value' | 'onChange' - > & { - placeholder?: SafeSqlFragment - value: SafeSqlFragment - onChange?: - (event: ChangeEvent, value: SafeSqlFragment) => void - } - - export const SafeSqlInput = ({ onChange, ...props }: SafeSqlInputProps) => ( - 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 ( - - ) -} -``` - -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 `` 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(safeSql``) - return ( setSql(value)} + onChange={(_event, value) => setSql(value)} /> ) } + +// 🛑 BAD: raw mixes plain strings with SafeSqlFragment +// 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(safeSql``) - - return ( - 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 -} -``` - -```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 +}) { + 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 ( - <> - - - + ) } + +// 🛑 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). diff --git a/.agents/skills/studio-e2e-tests/SKILL.md b/.agents/skills/studio-e2e-tests/SKILL.md index 9e618ae4e78..a608a4974e8 100644 --- a/.agents/skills/studio-e2e-tests/SKILL.md +++ b/.agents/skills/studio-e2e-tests/SKILL.md @@ -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 - -``` - -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 + + ``` +- 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 -``` - -### 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/.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/.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 `), 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. diff --git a/.agents/skills/studio-error-handling/SKILL.md b/.agents/skills/studio-error-handling/SKILL.md index 08a93cd82b9..9a9699fea52 100644 --- a/.agents/skills/studio-error-handling/SKILL.md +++ b/.agents/skills/studio-error-handling/SKILL.md @@ -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` | -| `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`) — 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` (`{ 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 ``` -- `subject` is the human-readable title, phrased `Failed to `. 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 && }` for secondary panels that shouldn't block the rest of the page. +- Phrase `subject` as `Failed to ` 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 && }` 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 `` 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). diff --git a/.agents/skills/studio-mock-api-tests/SKILL.md b/.agents/skills/studio-mock-api-tests/SKILL.md deleted file mode 100644 index 3016d564c67..00000000000 --- a/.agents/skills/studio-mock-api-tests/SKILL.md +++ /dev/null @@ -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([ - createMockOrganizationResponse({ name: 'Acme' }), - ]), - }) - - customRender() - - 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({}, { status: 201 }) -``` - -### 3. Submit buttons in Sheets/Modals need `fireEvent.click` - -The convention ` -} - -// 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 - - - - - - - - - - -``` - -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. diff --git a/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md b/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md deleted file mode 100644 index d4345ee30ae..00000000000 --- a/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md +++ /dev/null @@ -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 ( -
- {renderHeader?.()} - - {renderFooter ? renderFooter() : } - {renderActions?.()} - - ) -} - -// Usage is awkward and inflexible -return ( - } - renderFooter={() => ( - <> - - - - )} - renderActions={() => } - /> -) -``` - -**Correct (compound components with children):** - -```tsx -function ComposerFrame({ children }: { children: React.ReactNode }) { - return
{children}
-} - -function ComposerFooter({ children }: { children: React.ReactNode }) { - return
{children}
-} - -// Usage is flexible -return ( - - - - - - - - - -) -``` - -**When render props are appropriate:** - -```tsx -// Render props work well when you need to pass data back - } -/> -``` - -Use render props when the parent needs to provide data or state to the child. -Use children when composing static structure. diff --git a/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md b/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md deleted file mode 100644 index 56e32e8bee5..00000000000 --- a/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md +++ /dev/null @@ -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? - -``` - -**Correct (explicit variants):** - -```tsx -// Immediately clear what this renders - - -// Or - - -// Or - -``` - -Each implementation is unique, explicit and self-contained. Yet they can each -use shared parts. - -**Implementation:** - -```tsx -function ThreadComposer({ channelId }: { channelId: string }) { - return ( - - - - - - - - - - - - ) -} - -function EditMessageComposer({ messageId }: { messageId: string }) { - return ( - - - - - - - - - - - - ) -} - -function ForwardMessageComposer({ messageId }: { messageId: string }) { - return ( - - - - - - - - - - - ) -} -``` - -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. diff --git a/.agents/skills/vercel-composition-patterns/rules/react19-no-forwardref.md b/.agents/skills/vercel-composition-patterns/rules/react19-no-forwardref.md deleted file mode 100644 index e0d8f8a76f1..00000000000 --- a/.agents/skills/vercel-composition-patterns/rules/react19-no-forwardref.md +++ /dev/null @@ -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((props, ref) => { - return -}) -``` - -**Correct (ref as a regular prop):** - -```tsx -function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref }) { - return -} -``` - -**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()`. diff --git a/.agents/skills/vercel-composition-patterns/rules/state-context-interface.md b/.agents/skills/vercel-composition-patterns/rules/state-context-interface.md deleted file mode 100644 index d961bede0c6..00000000000 --- a/.agents/skills/vercel-composition-patterns/rules/state-context-interface.md +++ /dev/null @@ -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 -} -``` - -**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 -} - -interface ComposerContextValue { - state: ComposerState - actions: ComposerActions - meta: ComposerMeta -} - -const ComposerContext = createContext(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 ( - 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 ( - - {children} - - ) -} - -// Provider B: Global synced state for channels -function ChannelProvider({ channelId, children }: Props) { - const { state, update, submit } = useGlobalChannel(channelId) - const inputRef = useRef(null) - - return ( - - {children} - - ) -} -``` - -**The same composed UI works with both:** - -```tsx -// Works with ForwardMessageProvider (local state) - - - - - - - -// Works with ChannelProvider (global synced state) - - - - - - -``` - -**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 ( - - - {/* The composer UI */} - - - - - - - - - {/* Custom UI OUTSIDE the composer, but INSIDE the provider */} - - - {/* Actions at the bottom of the dialog */} - - - - - - - ) -} - -// This button lives OUTSIDE Composer.Frame but can still submit based on its context! -function ForwardButton() { - const { - actions: { submit }, - } = use(ComposerContext) - return -} - -// This preview lives OUTSIDE Composer.Frame but can read composer's state! -function MessagePreview() { - const { state } = use(ComposerContext) - return -} -``` - -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. diff --git a/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md b/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md deleted file mode 100644 index 71a5afaa7d7..00000000000 --- a/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md +++ /dev/null @@ -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 ( - - sync.updateInput(text)} - /> - sync.submit()} /> - - ) -} -``` - -**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 ( - - {children} - - ) -} - -// UI component only knows about the context interface -function ChannelComposer() { - return ( - - - - - - - - ) -} - -// Usage -function Channel({ channelId }: { channelId: string }) { - return ( - - - - ) -} -``` - -**Different providers, same UI:** - -```tsx -// Local state for ephemeral forms -function ForwardMessageProvider({ children }) { - const [state, setState] = useState(initialState) - const forwardMessage = useForwardMessage() - - return ( - - {children} - - ) -} - -// Global synced state for channels -function ChannelProvider({ channelId, children }) { - const { state, update, submit } = useGlobalChannel(channelId) - - return ( - - {children} - - ) -} -``` - -The same `Composer.Input` component works with both providers because it only -depends on the context interface, not the implementation. diff --git a/.agents/skills/vercel-composition-patterns/rules/state-lift-state.md b/.agents/skills/vercel-composition-patterns/rules/state-lift-state.md deleted file mode 100644 index d7fe27b5493..00000000000 --- a/.agents/skills/vercel-composition-patterns/rules/state-lift-state.md +++ /dev/null @@ -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 ( - - - - - ) -} - -// Problem: How does this button access composer state? -function ForwardMessageDialog() { - return ( - - - {/* Needs composer state */} - - - {/* Needs to call submit */} - - - ) -} -``` - -**Incorrect (useEffect to sync state up):** - -```tsx -function ForwardMessageDialog() { - const [input, setInput] = useState('') - return ( - - - - - ) -} - -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 ( - - - submit(stateRef.current)} /> - - ) -} -``` - -**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 ( - - {children} - - ) -} - -function ForwardMessageDialog() { - return ( - - - - {/* Custom components can access state and actions */} - - - {/* Custom components can access state and actions */} - - - - ) -} - -function ForwardButton() { - const { actions } = use(Composer.Context) - return -} -``` - -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. diff --git a/.agents/skills/vitest/GENERATION.md b/.agents/skills/vitest/GENERATION.md deleted file mode 100644 index 9bc76640e49..00000000000 --- a/.agents/skills/vitest/GENERATION.md +++ /dev/null @@ -1,5 +0,0 @@ -# Generation Info - -- **Source:** `sources/vitest` -- **Git SHA:** `4a7321e10672f00f0bb698823a381c2cc245b8f7` -- **Generated:** 2026-01-28 diff --git a/.agents/skills/vitest/SKILL.md b/.agents/skills/vitest/SKILL.md deleted file mode 100644 index 69776b6edad..00000000000 --- a/.agents/skills/vitest/SKILL.md +++ /dev/null @@ -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) | diff --git a/.agents/skills/vitest/references/advanced-environments.md b/.agents/skills/vitest/references/advanced-environments.md deleted file mode 100644 index 25a1d5b0788..00000000000 --- a/.agents/skills/vitest/references/advanced-environments.md +++ /dev/null @@ -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 = '
' - - 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: '', - 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 { - 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 { - 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 - - diff --git a/.agents/skills/vitest/references/advanced-projects.md b/.agents/skills/vitest/references/advanced-projects.md deleted file mode 100644 index 57b9a735641..00000000000 --- a/.agents/skills/vitest/references/advanced-projects.md +++ /dev/null @@ -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 - - diff --git a/.agents/skills/vitest/references/advanced-type-testing.md b/.agents/skills/vitest/references/advanced-type-testing.md deleted file mode 100644 index f67a034e30e..00000000000 --- a/.agents/skills/vitest/references/advanced-type-testing.md +++ /dev/null @@ -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().toBeString() -expectTypeOf().toBeNumber() -expectTypeOf().toBeBoolean() -expectTypeOf().toBeNull() -expectTypeOf().toBeUndefined() -expectTypeOf().toBeVoid() -expectTypeOf().toBeNever() -expectTypeOf().toBeAny() -expectTypeOf().toBeUnknown() -expectTypeOf().toBeObject() -expectTypeOf().toBeFunction() -expectTypeOf<[]>().toBeArray() -expectTypeOf().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().toHaveProperty('id') -expectTypeOf().toHaveProperty('name').toBeString() - -// Check shape -expectTypeOf({ id: 1, name: 'test' }).toMatchTypeOf() -``` - -## Equality vs Matching - -```ts -interface A { x: number } -interface B { x: number; y: string } - -// toMatchTypeOf - subset matching -expectTypeOf().toMatchTypeOf() // B extends A - -// toEqualTypeOf - exact match -expectTypeOf().not.toEqualTypeOf() // Not exact match -expectTypeOf().toEqualTypeOf<{ x: number }>() // Exact match -``` - -## Branded Types - -```ts -type UserId = number & { __brand: 'UserId' } -type PostId = number & { __brand: 'PostId' } - -expectTypeOf().not.toEqualTypeOf() -expectTypeOf().not.toEqualTypeOf() -``` - -## Generic Types - -```ts -function identity(value: T): T { - return value -} - -expectTypeOf(identity).returns.toBeString() -expectTypeOf(identity).returns.toBeNumber() -``` - -## Nullable Types - -```ts -type MaybeString = string | null | undefined - -expectTypeOf().toBeNullable() -expectTypeOf().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(result) - - // Correct type - assertType(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` - - diff --git a/.agents/skills/vitest/references/advanced-vi.md b/.agents/skills/vitest/references/advanced-vi.md deleted file mode 100644 index 57a47842524..00000000000 --- a/.agents/skills/vitest/references/advanced-vi.md +++ /dev/null @@ -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 - - diff --git a/.agents/skills/vitest/references/core-cli.md b/.agents/skills/vitest/references/core-cli.md deleted file mode 100644 index 7a05c049bee..00000000000 --- a/.agents/skills/vitest/references/core-cli.md +++ /dev/null @@ -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 to config file ---project # 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 # 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 / # Split tests across machines ---bail # Stop after n failures ---retry # Retry failed tests n times ---sequence.shuffle # Randomize test order - -# Watch mode ---no-watch # Disable watch mode ---standalone # Start without running tests - -# Environment ---environment # 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 - - diff --git a/.agents/skills/vitest/references/core-config.md b/.agents/skills/vitest/references/core-config.md deleted file mode 100644 index 76002a58fbc..00000000000 --- a/.agents/skills/vitest/references/core-config.md +++ /dev/null @@ -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 -/// -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 - - diff --git a/.agents/skills/vitest/references/core-describe.md b/.agents/skills/vitest/references/core-describe.md deleted file mode 100644 index 3f7f3fe1cb6..00000000000 --- a/.agents/skills/vitest/references/core-describe.md +++ /dev/null @@ -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 - - diff --git a/.agents/skills/vitest/references/core-expect.md b/.agents/skills/vitest/references/core-expect.md deleted file mode 100644 index 91de00a64ed..00000000000 --- a/.agents/skills/vitest/references/core-expect.md +++ /dev/null @@ -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 - - diff --git a/.agents/skills/vitest/references/core-hooks.md b/.agents/skills/vitest/references/core-hooks.md deleted file mode 100644 index d0c2bfa098d..00000000000 --- a/.agents/skills/vitest/references/core-hooks.md +++ /dev/null @@ -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 - - diff --git a/.agents/skills/vitest/references/core-test-api.md b/.agents/skills/vitest/references/core-test-api.md deleted file mode 100644 index 1f3c93238a3..00000000000 --- a/.agents/skills/vitest/references/core-test-api.md +++ /dev/null @@ -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 - - diff --git a/.agents/skills/vitest/references/features-concurrency.md b/.agents/skills/vitest/references/features-concurrency.md deleted file mode 100644 index 412f60d8214..00000000000 --- a/.agents/skills/vitest/references/features-concurrency.md +++ /dev/null @@ -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 - - diff --git a/.agents/skills/vitest/references/features-context.md b/.agents/skills/vitest/references/features-context.md deleted file mode 100644 index a9db0a1f61b..00000000000 --- a/.agents/skills/vitest/references/features-context.md +++ /dev/null @@ -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({ - // 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 - - diff --git a/.agents/skills/vitest/references/features-coverage.md b/.agents/skills/vitest/references/features-coverage.md deleted file mode 100644 index aaf44cfb2bf..00000000000 --- a/.agents/skills/vitest/references/features-coverage.md +++ /dev/null @@ -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 - - diff --git a/.agents/skills/vitest/references/features-filtering.md b/.agents/skills/vitest/references/features-filtering.md deleted file mode 100644 index 24a41cb521d..00000000000 --- a/.agents/skills/vitest/references/features-filtering.md +++ /dev/null @@ -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 - - diff --git a/.agents/skills/vitest/references/features-mocking.md b/.agents/skills/vitest/references/features-mocking.md deleted file mode 100644 index e351efef62a..00000000000 --- a/.agents/skills/vitest/references/features-mocking.md +++ /dev/null @@ -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 - - diff --git a/.agents/skills/vitest/references/features-snapshots.md b/.agents/skills/vitest/references/features-snapshots.md deleted file mode 100644 index 6868fb13b7a..00000000000 --- a/.agents/skills/vitest/references/features-snapshots.md +++ /dev/null @@ -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__/.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 - - diff --git a/.coderabbit.yaml b/.coderabbit.yaml index 5954c98cc97..e51df55a1e8 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -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' diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 5b53b2b67bc..07b74ef7115 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -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 `Close`). +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 `Close`; standalone icon-only `` still needs an accessible name). **Do** flag accessibility issues on: 1. **Custom interactive elements** not using Radix primitives (e.g. a `
` that should be a `