mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
docs/reference-template
113
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
0252fd8cad |
[FE-5114] (part 7) – refactor(studio): remove Next API adapter (#54034)
## Problem With all Studio API routes migrated to native TanStack Start handlers (or removed when unused) in parts 1–6, the Next Pages Router API adapter and legacy `NextApiRequest`/`NextApiResponse` wrappers are no longer used. Part 7 of 7 for [FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the) tears them down. ## Solution **Removed:** - `compat/next/api.ts` and `compat/next/api.test.ts` (`toWebHandler`) - Legacy `apiWrapper`, `apiAuthenticate`, and `fetchUserClaims` (`NextApiRequest`/`NextApiResponse`) functions and their legacy tests in `lib/api/apiWrapper.ts`, `lib/api/apiAuthenticate.ts`, `lib/api/apiWrappers.test.ts`, and `lib/api/apiAuthenticate.test.ts` - The now-unused `fromNodeHeaders` helper (and its `node:http` import) and its tests in `lib/api/apiHelpers.ts` / `lib/api/apiHelpers.test.ts` **Changed:** - Updated comment in `lib/server/configcat.ts` from `apiAuthenticate` to `authenticateRequest` ## Review instructions 1. Confirm `git grep -E "NextApiRequest|NextApiResponse|compat/next/api|toWebHandler|fromNodeHeaders|from 'next'" apps/studio/` returns no matches. 2. Run `pnpm --filter studio run typecheck`, `pnpm knip --workspace apps/studio`, and `pnpm --filter studio exec vitest run lib/api/ tests/routes/api/ scripts/__tests__/server-source-maps.test.ts`. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
ccd691423b |
[FE-5114] (part 6) – refactor(studio): migrate platform storage routes (#54033)
## Problem Studio's `routes/api/platform/storage/**` routes still run legacy Next Pages Router handlers through `compat/next/api.ts`, and `buckets/$id/objects/download.ts` has no remaining callers. Part 6 of 7 for [FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the) migrates the 14 active storage routes to native TanStack Start handlers and removes the unused download route. ## Solution **Changed:** - Migrated 14 `buckets/**` and `vector-buckets/**` routes to `createApiHandlers` and `parseJsonBody` - Replaced the `parseAsInt`/`parseAsString`/`parseAsStringEnum` helpers in `buckets/index.ts` with a zod query schema that drops invalid values, keeping the conditional spreads so unset keys aren't sent to storage-js - Forwarded upstream `StorageError` status codes across all storage and vector-bucket routes via `storageErrorResponse` / `getStorageErrorStatus` (falling back to the route's default 400/500 when no valid HTTP status is present) - Guarded missing/invalid `SUPABASE_PUBLIC_URL` with a `500` error response in `objects/public-url`, `objects/sign`, and `objects/sign-multi` - Typed the `vector-buckets/$id/indexes` POST body from storage-js's `createIndex` options - Corrected stale `Allow` headers on `vector-buckets/$id` (`GET, DELETE`) and `vector-buckets/$id/indexes/$indexName` (`DELETE`) via `createApiHandlers` **Added:** - `lib/api/self-hosted/storage.ts` with `getStorageErrorStatus`, `storageErrorResponse`, `getStoragePublicOrigin`, `missingStoragePublicUrlResponse`, and `remapStoragePublicUrl` - Unit tests for `buckets/index` query parsing, `buckets/$id/objects/sign-multi` (`SUPABASE_PUBLIC_URL` guard, origin remapping, and upstream error status), and `vector-buckets` POST (exercising the real storage client through MSW) **Removed:** - Removed unused `routes/api/platform/storage/$ref/buckets/$id/objects/download.ts` and regenerated `routeTree.gen.ts` **Behavior changes vs master:** - `buckets` GET drops malformed `limit`/`offset`/sort values instead of `parseInt`-truncating them (e.g. `offset=1.5` is ignored rather than sent as `1`) - `vector-buckets` POST validates the body with zod and returns `400` when `bucketName` is missing or not a string - Storage routes forward the upstream HTTP status code from `StorageApiError` instead of hardcoding `400`/`500` - `objects/public-url`, `objects/sign`, and `objects/sign-multi` return a `500` JSON error when `SUPABASE_PUBLIC_URL` is unset or invalid instead of throwing an uncaught `TypeError` - Unused `buckets/$id/objects/download` route has been removed ## Review instructions 1. Run `pnpm --filter studio exec vitest run tests/routes/api/platform/storage/`. 2. On self-hosted Studio, create/list/empty/delete a storage bucket, upload/download/move/sign/delete an object, and check vector bucket operations. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
37414c5a61 |
[FE-5114] (part 5) – refactor(studio): migrate platform project routes (#54032)
## Problem Studio's `routes/api/platform/projects/**` routes still run legacy Next Pages Router handlers through `compat/next/api.ts`, and `projects/$ref/config/index.ts` and `projects/$ref/billing/addons.ts` are unused in self-hosted mode. Part 5 of 7 for [FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the) migrates the 19 active project routes to native TanStack Start handlers and removes the 2 unused routes. ## Solution **Changed:** - Migrated 19 project routes — analytics (`endpoints/$name`, `log-drains`, `log-drains/$uuid`), API proxies (`api/graphql`, `api/rest`), content snippets & folders (`content/**`), and config/settings/databases/lints/keys/monitoring routes — to `createApiHandlers` - Preserved FE-5124 fixes on `log-drains/$uuid` (empty-body `204` on `DELETE`, `try`/`catch` + `!response.ok` → `500`); its `Allow: GET, PUT, DELETE` and the previously stale `Allow` on `log-drains` (`GET, POST`) now come from `createApiHandlers` - Forwarded upstream error status and JSON body (falling back to `500` / `{ error: { message } }`) in `api/graphql` and `api/rest` - Parsed the JSON body once in `content/index.ts` `PUT` so the `not found` create fallback does not attempt to re-read the request stream - `content/index.ts` and `content/folders/index.ts` read query params through `getSearchParamsRecord`, so repeated `ids` (and repeated GET params on `content/index`) return `400` as they did with Next's query parsing - `run-lints` forwards headers via `constructHeaders(Object.fromEntries(request.headers))` **Added:** - `getSearchParamsRecord` in `lib/api/apiHelpers.ts`: collects URL search params into a record, mapping repeated keys to arrays so zod string schemas reject them - `folderQueryParamsSchema` and `listFolderContents(request, folderId?)` in `lib/api/snippets.utils.ts`, shared by `content/folders/index` and `content/folders/$id` - `getLogflareConfig()` in `lib/api/self-hosted/logflare.ts`: reads the Logflare env vars at call time (same `500` naming the missing vars) and builds the request URLs and headers for `analytics/log-drains` and `analytics/log-drains/$uuid` - Unit tests for `getSearchParamsRecord`, `analytics/endpoints/$name`, `analytics/log-drains/$uuid`, `content/index`, `content/folders`, and `api/rest` (`HEAD` and upstream error forwarding) **Removed:** - Removed 2 unused routes (`routes/api/platform/projects/$ref/config/index.ts` and `routes/api/platform/projects/$ref/billing/addons.ts`) and regenerated `routeTree.gen.ts` **Behavior changes vs master:** - `analytics/endpoints/$name` GET strips `name` and `ref` from the forwarded query (parity with master, where they arrived as route params in `req.query`) - `content/folders` and `content/folders/$id` GET validate query params and return `400` for invalid or repeated values - `api/graphql` and `api/rest` forward upstream non-OK status codes and error bodies instead of always returning `500` - Unused `projects/$ref/config/index` and `projects/$ref/billing/addons` routes have been removed ## Review instructions 1. Run `pnpm --filter studio exec vitest run lib/api/apiHelpers.test.ts tests/routes/api/platform/projects/`. 2. On self-hosted Studio, create/update/delete a log drain, create/save/delete a SQL snippet and folder, and verify REST/GraphQL API docs load. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
be32a941cd |
[FE-5114] (part 4) – refactor(studio): migrate platform auth and misc routes (#54031)
## Problem Studio's `routes/api/platform/auth/**` and platform misc/stub routes still run legacy Next Pages Router handlers through `compat/next/api.ts`, and 4 legacy database/props routes have no callers left. Part 4 of 7 for [FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the) migrates the 16 active routes to native TanStack Start handlers and removes the 4 unused ones. ## Solution **Changed:** - Migrated `platform/auth/$ref/{invite,magiclink,otp,recover}` to one-line `createAuthSenderHandlers` routes, and `users/index`, `users/$id/index`, and `users/$id/factors` to `createApiHandlers`, preserving the FE-5124 fixes (`Promise.all` MFA factor deletion, `code ?? 500` on auth senders, `Allow: PATCH, DELETE` on `users/$id`, now derived by `createApiHandlers`) - Migrated 9 platform misc/stub routes (`deployment-mode`, `integrations/{$slug,github/*}`, `organizations/{index,$slug/billing/subscription}`, `profile/index`, and `telemetry/event`) - Moved the `FETCH_TYPE_BYPASS_EXCEPTIONS` entries for the four sender routes in `eslint.config.cjs` to `lib/api/self-hosted/auth-senders.ts` **Added:** - `createAuthSenderHandlers(endpoint, field)` in `lib/api/self-hosted/auth-senders.ts`: shared POST handler for the self-hosted GoTrue `invite`, `magiclink`, `otp`, and `recover` endpoints (forwards only `email` or `phone`, uses `constructHeaders` with the service role key, and passes upstream errors through with `code ?? 500`) - Regression tests for `auth/$ref/users/$id/factors`, `auth/$ref/users/$id`, and all four auth sender routes **Removed:** - Removed 4 unused routes (`platform/database/$ref/pooling`, `platform/props/org/$slug`, `platform/props/project/$ref/index`, and `platform/props/project/$ref/api`) and regenerated `routeTree.gen.ts` ## Review instructions 1. Run `pnpm --filter studio exec vitest run tests/routes/api/platform/auth/`. 2. On self-hosted Studio, invite/ban/delete a user, remove MFA factors for a user, and confirm `GET /api/platform/auth/default/users/<id>` returns `405` with `Allow: PATCH, DELETE`. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
20a5212c42 |
[FE-5114] (part 3) – refactor(studio): migrate pg-meta and v1 routes (#54030)
## Problem Studio's `routes/api/platform/pg-meta/**` and `routes/api/v1/**` routes still run legacy Next Pages Router handlers through `compat/next/api.ts`, and 10 legacy `pg-meta` GET proxy routes are no longer called anywhere in the repo. Part 3 of 7 for [FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the) migrates the 9 active routes to native TanStack Start handlers and deletes the 10 unused proxy routes. ## Solution **Changed:** - Migrated `platform/pg-meta/$ref/query/index.ts` and all 8 `v1` routes (`api-keys`, `api-keys/$id`, `config/auth/signing-keys/{index,legacy}`, `database/migrations`, `functions/{index,$slug/index}`, `types/typescript`) to `createApiHandlers`; `query` and `database/migrations` share `pgMetaErrorResponse` - Enabled `{ withAuth: true }` on `api-keys`, `api-keys/$id`, and `config/auth/signing-keys/{index,legacy}` for consistency with the other `v1` routes - Updated `api-keys` route tests to use `callRoute` **Added:** - `pgMetaErrorResponse(error)` in `lib/api/self-hosted/pg-meta.ts` (keeps a `PgMetaDatabaseError`'s status and `{ message, formattedError }` payload expected by `data/error-classification.ts`, otherwise `500`) - Unit test for `pg-meta/$ref/query` (`tests/routes/api/platform/pg-meta/$ref/query/index.test.ts`) **Removed:** - Removed all 10 unused `pg-meta` GET proxy routes (`column-privileges`, `extensions`, `foreign-tables`, `materialized-views`, `policies`, `publications`, `tables`, `triggers`, `types`, `views`), removed their `FETCH_TYPE_BYPASS_EXCEPTIONS` entries from `eslint.config.cjs`, and regenerated `routeTree.gen.ts` - Removed `getPgMetaRedirectUrl` (`lib/api/apiHelpers.ts`) and `parseRevealQuery` (`lib/api/self-hosted/api-keys.ts`) **Behavior changes vs master:** - Routes forward only `cookie` and `x-connection-encrypted` to pg-meta via `constructHeaders(Object.fromEntries(request.headers))`, matching what master's adapter forwarded - `database/migrations` GET now forwards headers to `listMigrationVersions` (master passed them as the wrong argument) - `v1/projects/$ref/api-keys*` and `config/auth/signing-keys*` now pass `{ withAuth: true }` (no-op in self-hosted mode; consistent with the other `v1` routes) - The 10 unused `pg-meta` GET proxy routes have been removed (`pg-meta/$ref/query` and `v1/projects/$ref/types/typescript` remain) ## Review instructions 1. Run `pnpm --filter studio exec vitest run tests/routes/api/v1/ tests/routes/api/platform/pg-meta/`. 2. On self-hosted Studio, load tables/views/policies/extensions, run a query in the SQL Editor, check API keys, and generate TypeScript types. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
c5fca0a0d7 |
[FE-5114] (part 2) – refactor(studio): migrate AI API routes (#54029)
## Problem Studio's AI API routes under `routes/api/ai/**` still run legacy Next Pages Router handlers through `compat/next/api.ts`. Part 2 of 7 for [FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the) migrates the active AI routes to native TanStack Start (`Request` → `Response`) handlers and drops 3 unused AI endpoints. ## Solution **Changed:** - Migrated 8 active AI routes (`ai/code/complete`, `ai/feedback/{classify,rate}`, and `ai/sql/{check-api-key,cron-v2,filter-v1,generate-v4,title-v2}`) to `createApiHandlers` and `parseJsonBody` - Replaced Node `pipeUIMessageStreamToResponse` in `ai/sql/generate-v4.ts` with native `createUIMessageStreamResponse`, preserving the `x-braintrust-span-id` header - Replaced `req.on`/`res.on` in `ai/sql/generate-v4.ts` with `AbortSignal.any([request.signal, done.signal])` and a `TransformStream` whose `flush`/`cancel` tear down the MCP connection opened in `getTools` on stream completion, cancellation, or setup error - Removed the custom malformed-JSON handling in `ai/code/complete.ts` in favor of the wrapper's `400` - Updated `lib/api/generate-v4.test.ts` to assert against the real native SSE `Response` stream instead of mocking `pipeUIMessageStreamToResponse`, with a shared `mockOpenStream()` helper, a stream-cancellation abort test, and a Braintrust tracing test asserting `x-braintrust-span-id` matches the exported root span - Updated `lib/ai/README.md` to drop references to removed endpoints **Removed:** - Removed 3 unused AI routes (`routes/api/ai/onboarding/design.ts`, `routes/api/ai/sql/parse-client-code.ts`, and `routes/api/ai/sql/policy.ts`), dropped them from `lib/hosted-api-allowlist.ts`, and regenerated `routeTree.gen.ts` - Removed the now-unused `withoutApprovalTools` helper from `lib/ai/tool-filter.ts` and its test from `lib/ai/tool-filter.test.ts` **Behavior changes vs master:** - `ai/code/complete` returns the wrapper's `400` JSON `{ error: { message: 'Invalid JSON' } }` for malformed bodies - Unused `ai/onboarding/design`, `ai/sql/parse-client-code`, and `ai/sql/policy` endpoints have been removed ## Review instructions 1. Run `pnpm --filter studio exec vitest run lib/api/generate-v4.test.ts lib/api/rate.test.ts lib/ai/tool-filter.test.ts`. 2. Send a prompt in the AI Assistant panel, verify streaming output, and cancel mid-stream. 3. Trigger SQL title, cron, and filter generation as well as AI code completion. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
b6c391a058 |
[FE-5114] (part 1) – refactor(studio): add native API helpers & routes (#54028)
## Problem Studio's `routes/api/**` server routes still run legacy Next Pages Router handlers through the `toWebHandler` shim in `compat/next/api.ts`. Part 1 of 7 for [FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the) adds native TanStack Start (`Request` → `Response`) helpers and migrates the top-level utility routes so we can remove the adapter at the end of the stack. ## Solution **Added:** - `createApiHandlers` in `lib/api/apiWrapper.ts`: wraps native TanStack Start route handlers with optional platform JWT auth, JSON `400` (`{ error: { message: 'Invalid JSON' } }`) on `InvalidJsonError`, Sentry capture + generic `500` on unexpected throws, and an `ANY` handler that returns `405` with an `Allow` header derived from the registered methods. Exports `ApiHandler` / `ApiHandlerContext` (`params` is `Record<string, string>`) - `authenticateRequest` in `lib/api/apiAuthenticate.ts` (Web `Request` counterpart of `apiAuthenticate`, same error messages) - `InvalidJsonError` and `parseJsonBody` in `lib/api/apiHelpers.ts` - `callRoute(route, request, params)` test helper in `tests/lib/server-route.ts` - Unit tests for `createApiHandlers` (exercising real `authenticateRequest` through MSW in `lib/api/createApiHandlers.test.ts`), `authenticateRequest`, `parseJsonBody`, `/api/generate-attachment-url`, and `/api/integrations/stripe-sync` **Changed:** - Updated `getRouteHandler` in `tests/lib/server-route.ts` to mirror TanStack Start's `HEAD` → `GET` → `ANY` dispatch order - Migrated 11 top-level API routes (`check-cname`, `cli-release-version`, `content/graphql`, `edge-functions/test`, `enabled-features-overrides`, `generate-attachment-url`, `get-deployment-commit`, `get-ip-address`, `get-s3-keys`, `get-utc-time`, `integrations/stripe-sync`) to native handlers - Added `withAuth: true` to `check-cname`, `content/graphql`, and `integrations/stripe-sync`, and updated `check-cname-mutation.ts` and `data/graphql/execute.ts` to attach `constructHeaders()` - Reused `withAuth` `claims` in `generate-attachment-url` to avoid a duplicate GoTrue lookup in platform mode - Converted `tests/routes/api/get-deployment-commit.test.ts` to `callRoute` **Removed:** - Removed 2 unused routes (`routes/api/connect/index.ts` and `routes/api/parse-query.ts`), dropped `/parse-query` from `lib/hosted-api-allowlist.ts`, removed Nitro's `traceDeps: ['libpg-query*']` in `vite.config.ts` (no server runtime route imports `libpg-query` anymore), and regenerated `routeTree.gen.ts` **Behavior changes vs master:** - Methods a route doesn't register now get a JSON `405` with an `Allow` header (previously they fell through to the SSR app). `HEAD` requests that TanStack Start dispatches to a `GET` handler also get `405`, matching master's method switches - `InvalidJsonError` returns JSON `{ error: { message: 'Invalid JSON' } }` (`400`) instead of plain text - `check-cname`, `content/graphql`, and `integrations/stripe-sync` now verify the platform JWT via `withAuth: true` - Unexpected throws return a generic `500` with `{ error: { message: 'Internal Server Error' } }` - Unused `/api/connect` and `/api/parse-query` routes have been removed ## Review instructions 1. Run `pnpm --filter studio exec vitest run lib/api/apiAuthenticate.test.ts lib/api/apiHelpers.test.ts lib/api/apiWrappers.test.ts lib/api/createApiHandlers.test.ts tests/routes/api/ scripts/__tests__/server-source-maps.test.ts`. 2. Smoke-test `/api/get-deployment-commit`, `/api/check-cname`, `/api/content/graphql`, `/api/generate-attachment-url`, and `/api/edge-functions/test` in Studio and confirm unsupported HTTP methods return `405` with an `Allow` header. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
90a0bcdcfe |
feat(studio): bump @supabase/mcp-server-supabase to 0.20.0 and pass schemas to type generation (#54139)
## Problem Self-hosted Studio still uses `@supabase/mcp-server-supabase` 0.17.0, two releases behind even before [0.20.0](https://github.com/supabase/mcp/releases/tag/mcp-server-supabase-v0.20.0). ## Solution Bump `^0.17.0` to `^0.20.0` in `apps/studio/package.json` and update the lockfile, which takes `@supabase/mcp-utils` from 0.10.0 to 0.11.1. The platform interface only gained optional arguments, so the bump itself compiles without changes. - The debugging group gains `get_issues`, which covers security and performance checks on self-hosted. It reports the health check as unavailable because self-hosted has no health advisors. - `generate_typescript_types` now accepts an optional `schemas` parameter. Without this fix, self-hosted would silently ignore it and could return types for different schemas than the caller requested. `lib/api/self-hosted/mcp.ts` now passes `schemas` to `generateTypescriptTypes` in `lib/api/self-hosted/generate-types.ts`, which sends it to pg-meta as `included_schemas`. When the caller omits `schemas`, self-hosted still uses the schemas PostgREST exposes. Tests in `generate-types.test.ts` and `mcp.test.ts` cover both cases. The MCP Apps support from 0.18.0 and 0.19.0 stays off because Studio doesn’t opt in. ## Review instructions 1. Confirm CI passes. 2. With self-hosted Studio running, connect an MCP client to `/api/mcp` and confirm `tools/list` includes `get_issues`. 3. Call `generate_typescript_types` with `schemas: ["auth"]` (or another schema PostgREST doesn’t expose) and confirm it returns types only for the requested schema. Closes [AI-1582](https://linear.app/supabase/issue/AI-1582) |
||
|
|
bbb0af65cb |
[FE-3106] (part 14) – refactor(studio): drop the dual-runtime shims and aliases (#53223)
Drops the remaining Next-era shims and aliases that only existed for the dual runtime (FE-3106). Part 14 of the stack. **Depends on:** #53222 **Changed:** - ~45 files – import Sentry from `@sentry/react` directly instead of the aliased `@sentry/nextjs` - `hooks/ui/usePreventNavigationOnUnsavedChanges.ts` – is now the TanStack `useBlocker` implementation (previously swapped in by a Vite alias) - `components/interfaces/App/RouteValidationWrapper.tsx` – `next/router` → `useNavigate` + the leaf route's `fullPath` (`/project/$ref/sql/$id`) for the exempt-route and last-visited checks - `hooks/misc/withAuth.tsx` – no `getLayout` forwarding - `TemplateEditor.test.tsx` – renders inside a router for the unsaved-changes blocker **Removed:** - `compat/sentry-nextjs.ts` and its Vite alias, the `usePreventNavigationOnUnsavedChanges` alias and Next hook, `types/next.ts` (`NextPageWithLayout`), the `@sentry/nextjs` dependency The `compat/next/*` shims for `link`, `router`, `head`, `image`, `navigation`, `dynamic` and `script` stay: about 300 components outside `routes/**` still import them. Addresses [FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages). ## To test - Trigger an error (e.g. a failing query) – it reaches Sentry as before - Edit an email template or edge function and navigate away – the unsaved-changes prompt appears - Open an org you don't belong to – toast and redirect home; open a SQL snippet, leave and come back – last snippet is restored --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
cf223ae74a |
[FE-3106] (part 13) – chore(studio): remove next entry files and config (#53222)
Removes the Next-only entry files and config now that every page lives in `routes/**` (FE-3106). `routes/__root.tsx` already mirrors `pages/_app.tsx` (dayjs plugins, providers, telemetry, error boundary, favicons). Part 13 of the stack. **Depends on:** #53221 **Changed:** - `components/interfaces/App/{NotFoundPage,ServerErrorPage}.tsx` – the 404/500 pages, rendered by `__root.tsx`, now with native `Link`/`useNavigate` and `<img>` - `routes/api/{status-page,scoped-access-token-permissions}.ts` – App Router handlers from `app/api/**` moved in (`NextResponse.json` → `Response.json`); `buildAPIPermissionScopeMap` moves to `lib/api/` - `package.json`, `tsconfig.json` – no `next typegen` step or `.next/types` include - `packages/ui-patterns/.../InstructionBlocks.tsx` – asset map typed `StaticImageData | string`: under Vite a png import is a URL string, which Next's global image types used to hide - `vite.config.ts`, `knip.jsonc`, `turbo.jsonc` and comments across studio – Next build references removed **Removed:** - `pages/{_app,_document,404,500}.tsx`, `pages/_error.jsx`, `pages/README.md`, `app/**`, `next.config.ts`, `proxy.ts`, `instrumentation{,-client}.ts`, `sentry.{server,edge}.config.ts`, `fonts/index.ts` (next/font), `BootTimeoutFallback`, `postcss.config.cjs`, the `next/server` shim - `@next/bundle-analyzer`, `raw-loader`, `postcss`, `@tailwindcss/postcss` dev dependencies Addresses [FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages). ## To test - Open an unknown URL – the 404 page renders with working "Head back" - `/api/status-page` and `/api/scoped-access-token-permissions` on platform – same JSON and `Cache-Control` - Fonts (Inter, Manrope, Source Code Pro) still load --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
04a7b1ac64 | fix(studio): reject cross-origin writes on self-hosted (#53452) | ||
|
|
ddabeac30c |
feat(studio): enable EU Assistant tracing (#53332)
Enables Braintrust tracing and feedback for Assistant chats on EU-region projects. This was the final holdout that makes it so that tracing is applied consistently across all projects. Adds `projectRegion` metadata to root traces so the project’s region is recorded with each chat (consistent with the existing [isHighComplianceProject metadata](https://github.com/supabase/supabase/blob/917dcb388939b8c54ea13c1e31b3c7285fb2ca65/apps/studio/lib/ai/generate-assistant-response.ts#L188)). Verified in staging with a [successful Assistant trace recording `projectRegion: eu-central-1`](https://www.braintrust.dev/app/supabase.io/p/Assistant/logs?r=1b4a05d7a6c1414e62f532094aa39dc1&sid=4fdc76b08a4c5a43). <img width="2656" height="1560" alt="CleanShot 2026-11-12 at 1 12 30 PM@2x" src="https://github.com/user-attachments/assets/4e81033a-c754-46db-845d-586d1d71e035" /> Closes AI-1197 |
||
|
|
c8748c7c26 |
chore: pin Node.js to v24 across the repository (#53287)
## Problem `engines.node` used open-ended ranges (`>=22.23.4` at the root, `>=22.12.0` in `apps/kb`). Vercel resolves an open-ended range to the newest Node.js major, so it overrides the project's configured version and warns that future majors will be picked automatically. The other apps declared no engine at all, and `.nvmrc` (used by local dev and CI) still pointed at Node 22. ## Solution Pin Node.js 24 everywhere the repo declares a Node version: - `.nvmrc`: `22.23.4` -> `24.22.3` (latest v24 LTS). CI workflows read `node-version-file: .nvmrc`, so they follow. - Root `package.json` and `apps/kb/package.json`: `engines.node` -> `24.x`. - Every other app (`design-system`, `docs`, `learn`, `lite-studio`, `studio`, `ui-library`, `www`): add `engines.node: "24.x"`. Vercel reads the Node.js version from `engines.node` in the project's `package.json`; `vercel.json` has no setting for it, so this is how each Vercel project gets an explicit version. - `.agents/skills/test-the-docs/sandbox/Dockerfile`: `node:22-bookworm-slim` -> `node:24-bookworm-slim`. - `AGENTS.md`: update the stated Node requirement. Notes: - `engineStrict: true` is set in `pnpm-workspace.yaml`, so `pnpm install` now requires Node 24 locally. - `.github/workflows/self-host-tests-smoke.yml` hardcodes `node-version: '22'` and is not changed here. - No builds or tests were run for this change. Checked that all changed `package.json` files parse and that Prettier passes on the changed files. ## Review instructions 1. Open the Vercel build logs for this PR's deployments (studio, docs, www, kb, and so on). 2. Confirm each build uses Node.js 24.x. 3. Confirm the logs no longer show the warning that the `engines` field overrides the project's Node.js version, or the warning about automatic upgrades to new major versions. 4. Confirm CI jobs that use `.nvmrc` set up Node 24.22.3. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) [FE-5004](https://linear.app/supabase/issue/FE-5004/bump-the-nodejs-version-across-the-repository) --------- Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com> Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com> |
||
|
|
0e29dfda1b |
fix(studio): return no edge functions when the self-hosted functions folder is missing (#53229)
## Problem In self-hosted and local Studio, `FileSystemFunctionsArtifactStore` reads the folder set by `EDGE_FUNCTIONS_MANAGEMENT_FOLDER` with `readdir`. When that folder does not exist yet (for example, a fresh project before any function is created), `readdir` throws `ENOENT`, the `/api/v1/projects/[ref]/functions` route returns a 500, and the Edge Functions page shows "Failed to retrieve edge functions" instead of its empty state. ## Solution - Add a private `readFunctionsFolder()` helper that returns an empty list when the folder is missing (`ENOENT`) and rethrows every other error. - `getFunctions()` now returns `[]` and `getFunctionBySlug()` returns `undefined` for a missing folder. - Add `fileSystemStore.test.ts`, which uses real temp folders to cover the missing folder, a non-ENOENT error (path is a file), and the normal listing (skips `main` and folders without an `index` entrypoint). No change to the hosted platform path. ## Review instructions This only affects self-hosted Studio, so the Vercel preview cannot show it. Check it with: 1. `cd apps/studio && pnpm exec vitest run lib/api/self-hosted/functions/`: all tests pass. 2. Optional, locally: run self-hosted Studio with `EDGE_FUNCTIONS_MANAGEMENT_FOLDER` pointing to a folder that does not exist, open Edge Functions, and see the empty state instead of a 500. Checks run: the Vitest command above, `pnpm turbo run typecheck --filter='...[origin/master]'`, ESLint and Prettier on the changed files. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) [FE-4923](https://linear.app/supabase/issue/FE-4923/fix-studio-edge-functions-500-error-when-local-functions-folder-does) --------- Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com> Co-authored-by: Ali Waseem <waseema393@gmail.com> |
||
|
|
1854331fb6 |
[FE-3106] (part 2) – refactor(studio): move api handlers into route files (#53202)
Moves every `pages/api/**` handler into its TanStack server route under `routes/api/**` and deletes `pages/api/**`, part of the final pass of the TanStack Start migration (FE-3106). Handlers move verbatim and still run through `toWebHandler`, so auth (`apiWrapper`), response shapes and headers are unchanged. Part 2 of the stack. **Depends on:** #53199 **Changed:** - `routes/api/**` – each route now holds its handler (formerly the `pages/api` default export) as a local `nextHandler`/named function. Next-only `config`/`maxDuration` exports are dropped: `vite.config.ts` already sets the function `maxDuration`, and `toWebHandler` parses bodies itself - `routes/api/ai/docs.ts` – Web-native handler inlined, `NextRequest` → `Request` - `lib/api/apiHelpers.ts` – `getPgMetaRedirectUrl` moved here from the old `tables` handler, which the other pg-meta routes imported it from - `eslint.config.cjs`, `.github/CODEOWNERS` – `pages/api` paths → `routes/api` - `tests/routes/api/**`, `lib/api/{generate-v4,rate}.test.ts`, `scripts/__tests__/server-source-maps.test.ts` – call the route's registered handler with a Web `Request` (`tests/lib/server-route.ts`); the MCP query-validation cases now run against the native route **Removed:** - `pages/api/**` (102 files), including the Next twins of the already-native `routes/api/mcp/index.ts` and `functions/$slug/body.ts` - unused `ProjectSettings` types and the `node-mocks-http` dev dependency Parity: every route registers the same methods its handler serves. The exceptions are `check-cname`, `get-ip-address`, `get-utc-time`, `get-s3-keys`, `get-deployment-commit`, `cli-release-version` and `connect`: in Next they answered any method, and their routes register `GET` only, as before this PR. Addresses [FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages). ## To test - Load the table editor, SQL editor and Auth users on a self-hosted build – `/api/platform/**` and `/api/v1/**` respond as before - Use the Assistant and the docs search – `/api/ai/**` streams as before - `GET /api/get-deployment-commit` – same JSON and `Cache-Control` Ran typecheck, ESLint, lint ratchet, knip, Prettier, the TanStack build and the full Studio vitest suite: all pass except `lib/server/configcat.test.ts`, which also fails on `master` in an environment with ConfigCat env vars set. Self-hosted E2E is CI-only. --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
31711c0762 |
fix(studio): validate edge function test proxy target url (#53256)
The edge function test proxy (`pages/api/edge-functions/test.ts`, also
served by `routes/api/edge-functions/test.ts`) fetched the URL from the
request body after checking it only with the regexes in
`isValidEdgeFunctionURL`, and on self-hosted any
`http(s)://<host>/functions/vN/...` URL passed. It now fetches only a
URL rebuilt from parts it has validated.
**Changed:**
- `apps/studio/lib/api/edgeFunctions.ts` – replaced
`isValidEdgeFunctionURL` with `getEdgeFunctionTestUrl`, which parses the
URL, rejects non-http(s) schemes and credentials, requires a
`/functions/vN/` path, checks the host (platform:
`<ref>.supabase.co|red` over https; the Nimbus apex domain when
`NIMBUS_PROD_PROJECTS_URL` is set; self-hosted: the `SUPABASE_URL` or
`SUPABASE_PUBLIC_URL` host) and returns the fetch target rebuilt from
the validated origin, path and query. Self-hosted requests always go to
the `SUPABASE_URL` origin, replacing the old `SUPABASE_PUBLIC_URL`
string rewrite.
- `apps/studio/pages/api/edge-functions/test.ts` – fetches the URL
returned by `getEdgeFunctionTestUrl` and returns 400 when there is none.
`redirect: 'manual'` is unchanged.
**Added:**
- `apps/studio/lib/api/edgeFunctions.test.ts` – allowed platform,
`.red`, Nimbus and self-hosted URLs, and rejected cases: other hosts,
lookalike hosts, userinfo, ports, non-http schemes, paths outside
`/functions/vN/`.
- `apps/studio/tests/pages/api/edge-functions/test.test.ts` – handler
rejects userinfo and non-functions paths, and on self-hosted calls the
public URL through `SUPABASE_URL` and rejects other hosts.
## To test
- [ ] On platform (including staging `.red`), open an edge function,
click **Test**, and send a request with a query parameter: the response
shows as before.
- [ ] On self-hosted (`docker compose`), do the same from the edge
function tester: the response shows as before.
- [ ] `POST /api/edge-functions/test` with `{ "url":
"https://example.com/functions/v1/hello", "method": "GET" }`: the
response is 400 with "Provided URL is not a valid Supabase edge function
URL".
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
|
||
|
|
5e7e9d2cf5 |
fix(studio): parse stripe sync bearer token without backtracking regex (#53254)
`getBearerToken` in the Stripe Sync API handler parsed the
`Authorization` header with `/^Bearer\s+(.+)$/i`. Both `\s+` and `(.+)`
can match whitespace, so a header made of `Bearer` and a long run of
whitespace backtracks in quadratic time (CodeQL `js/polynomial-redos`).
The token is now parsed with `slice`, a case-insensitive scheme check
and `trim`.
**Changed:**
- `apps/studio/lib/api/apiHelpers.ts` – new shared
`getBearerToken(authorization)` that parses in linear time. It returns
`null` for a missing, array-valued, non-Bearer or empty/whitespace-only
header. Previously a whitespace-only token returned `''` instead of
`null`, which still got a 401.
- `apps/studio/pages/api/integrations/stripe-sync.ts` – drops the local
regex helper and uses the shared one.
`apps/studio/routes/api/integrations/stripe-sync.ts` re-exports this
handler on `master`, so both routes get the fix.
**Added:**
- `apps/studio/lib/api/apiHelpers.test.ts` – `getBearerToken` cases: a
valid token, lowercase `bearer`, extra whitespace,
missing/array/wrong-scheme/empty headers, and a 100k-whitespace header
that has to return in under 100 ms (the old regex takes about 4 s).
No other API handlers in `apps/studio` or `packages/` use this regex.
The remaining `Authorization` parsing in `lib/api/apiAuthenticate.ts`
and `lib/gotrue.ts` uses `replace(/bearer /i, '')`, which runs in linear
time.
## To test
- [ ] On a project, install the Stripe Sync integration from Studio
(Integrations → Stripe Sync). Installation starts and finishes.
- [ ] Uninstall it again. Uninstallation starts and finishes.
- [ ] `curl -i -X POST <studio-url>/api/integrations/stripe-sync -H
'Authorization: Basic abc' -H 'Content-Type: application/json' -d '{}'`
returns 401. Do the same with `Authorization: Bearer` followed only by
spaces, and with no `Authorization` header: both return 401.
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
|
||
|
|
da6360147c |
chore(studio): bump @supabase/mcp-server-supabase to 0.16.0 (#53044)
## Summary - Bump `@supabase/mcp-server-supabase` from `^0.15.0` to `^0.16.0`. - Share the self-hosted MCP platform between both `/api/mcp` routes, typed without `notebooks`, so the notebook tools enabled in 0.16.0 stay out of self-hosted. Self-hosted Studio doesn't support notebooks yet. Closes [AI-1407](https://linear.app/supabase/issue/AI-1407/2b-update-self-hosted-remote-mcp-server-self-hosted-studio-assistant) |
||
|
|
b3dd6612d7 |
feat(studio): classify errors with fault, reason, and per-tag Sentry sampling (#52730)
Follows #52707 (rename `ResponseError` to `StudioError`). Resolves FE-4772. ## What Introduces the error core for Studio error classification. - **Tagged errors.** `lib/errors/studio-errors.ts` defines `Data.TaggedError` classes (`RequestAborted`, `NetworkUnreachable`, `MalformedResponse`, `PlatformError`, `UnclassifiedApiError`, `DbConnectionTimeout`, `UnexpectedError`). Each carries `fault`, `reason`, `classifiedBy` (`rule` or `default`), `retryable`, and `service`. `StudioError` is the union type; use `isStudioError` instead of `instanceof`. - **Two classifiers** in `data/error-classification.ts`: - `classifyResponseError` is only for errors from an API response: known message patterns first, then defaults by status (5xx `PlatformError`, 4xx `UnclassifiedApiError`, no status `UnexpectedError`). - `classifyError` is for everything else: aborts, browser fetch failures (matched by message, so ordinary `TypeError` bugs stay `UnexpectedError`), and unexpected errors. - `handleError` picks between them, reports, and rethrows the same instance so React Query receives the classified error. - **Routing and sampling.** `lib/errors/error-routing.ts` maps every tag to a Sentry sample rate (`SAMPLE_NEVER`, `SAMPLE_OTHER`, `SAMPLE_OWNED`, `SAMPLE_ALWAYS`). `reportStudioError` tags events with `sample_rate`, and `beforeSend` applies it. `alwaysCapture` reports at rate 1. The global Sentry error `sampleRate` stays unset so the rates don't multiply. - **Network failures.** A fetch failure is a `user` fault with reason `offline` when the browser reports being offline, and a `platform` fault otherwise. - **Hand-built errors.** Call sites that wrapped caught exceptions or made up status codes now use `classifyError` or a specific class instead of `classifyResponseError`. ## Behavior changes - Errors that previously went unreported, including unexpected errors with a message, are now reported to Sentry at their routed sample rate. - `handleError` no longer logs the stack with `console.error`. - `MalformedResponse` is defined but not produced yet; a follow-up adds the empty-body check. ## Testing - Unit tests for classification, routing, reporting, and the `beforeSend` sampling helper. - `pnpm vitest run data lib components/interfaces/ErrorHandling`, typecheck, lint ratchet, and knip pass locally. |
||
|
|
df742bdb3b |
refactor(studio): rename ResponseError to StudioError (#52707)
## What
Moves the `ResponseError` class (`types/base.ts`) and the classified
error classes (`types/api-errors.ts`) into
`lib/errors/studio-errors.ts`, and renames `ResponseError` to
`StudioError`.
## Why
Studio's error classification is being expanded to cover errors that
don't come from API responses (thrown network failures, aborted
requests, unexpected client errors). The API-specific name and location
no longer fit. Landing the rename on its own keeps the follow-up PR,
which introduces the classified error model, small and reviewable.
## Notes for reviewers
- Mechanical change, no behavior change. Most of the diff is a one-line
import change per file plus import re-sorting by Prettier.
- Files that only use the type now use `import type { StudioError }`.
- `ResponseError` is no longer re-exported from `@/types`; there are no
compatibility shims at the old paths.
- Unrelated identifiers like `QueryResponseError` and
`parseResponseErrors` are unchanged.
|
||
|
|
26a88e792d |
chore(studio): bump @supabase/mcp-server-supabase to 0.15.0 (#52454)
## Summary - Bump `@supabase/mcp-server-supabase` from `^0.12.0` to `^0.15.0`. - Add `submit_feedback` / `delete_feedback` to self-hosted `/api/mcp` via upstream `createFeedbackOperations`, without the self-hosted project ref. Notebook tools stay out of self-hosted. ## Verification Against the pkg.pr.new preview: `tsc --noEmit` in `apps/studio` passes, MCP vitest suites pass (14/14), and `tools/list` on `/api/mcp` includes the feedback tools and no notebook tools. Closes: [AI-1369](https://linear.app/supabase/issue/AI-1369/2b-update-self-hosted-remote-mcp-server-self-hosted-studio-assistant) --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
1bd6ce0bc8 |
fix(studio): redact query rows and errors from Braintrust traces below the data opt-in level (#52106)
## Why Braintrust's AI SDK wrapper captures a tool's raw `execute` result instead of what `toModelOutput` sent to the model. While not sent to the AI provider, this could still be unexpected at lower opt-in levels. The upstream report of the footgun is in https://github.com/braintrustdata/braintrust-sdk-javascript/issues/2651, this PR is a stopgap fix. ## What `execute_sql` and `run_notebook` traces now use [span customizers](https://www.braintrust.dev/docs/admin/data-management/protect-sensitive-data#redact-before-upload) to redact results when the AI opt-in level is below `schema_and_log_and_data`. Similarly, tool errors are redacted with span customers since those have potential to contain project data, and a `prepareStep` hook swaps in the same sanitized message to prevent AI SDK passing a thrown tool error to the next model step which would otherwise appear in the trace. The user still sees the real error clientside in chat panel. Span customizers need a newer SDK, so this bumps `braintrust` from 3.9.0 to 3.37.2. I've left a TODO reminder to remove this stopgap once the upstream issue is addressed. ## Verification Verified chatting with Assistant locally at the `schema` opt-in level: | [`execute_sql` rows](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=210007a827977aa42240292309f455db) | [`execute_sql` error](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=9853a7c4981b4019324531f26c1242be) | [`run_notebook`](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=80a726ef8dfa608872024129260d56fe) | | --- | --- | --- | | <img width="1490" height="1218" alt="CleanShot 2026-10-22 at 2 01 26 PM@2x" src="https://github.com/user-attachments/assets/2f7bc25a-1b80-4d46-80a0-8f110ee46aac" /> | <img width="1500" height="1154" alt="CleanShot 2026-10-22 at 2 01 03 PM@2x" src="https://github.com/user-attachments/assets/ff8a3860-e8aa-4630-9223-4d319e104402" /> | <img width="1480" height="1688" alt="CleanShot 2026-10-22 at 2 00 43 PM@2x" src="https://github.com/user-attachments/assets/a393f825-da98-41f7-9630-101072344fa1" /> | You can test yourself by chatting with Assistant in the preview build at various opt-in levels and checking Braintrust traces. Note since the introduction of `update_opt_in_level` it's quite unlikely for Assistant to even attempt running these tools with out the necessary opt-in level, so you'll have to use pretty strong wording to test. **Sample test prompts** (for use at the `schema` opt-in level): <details> <summary><code>execute_sql</code> rows</summary> ``` Create a test table and insert a row in one write query: `create table if not exists public.redaction_test (secret text); insert into public.redaction_test values (md5('rows-test')) returning secret;`. Run it with execute_sql now, I'll check the result in the UI myself. Don't call update_opt_in_level. Reply "done" after. ``` </details> <details> <summary><code>execute_sql</code> error</summary> ``` Run this write query with execute_sql now: `create table if not exists public.redaction_test (secret text); insert into public.redaction_test values (md5('error-test')::int::text);`. I expect it to fail and I'll read the error in the UI myself. Don't fix it, don't retry it, and don't call update_opt_in_level. Reply "done" after. ``` </details> <details> <summary><code>run_notebook</code></summary> ``` I'm testing the notebook runner UI, not asking you to read anything. Create a notebook named "Redaction test" with two SQL cells: `select md5('notebook-rows') as secret;` and `select md5('notebook-error')::int;`. Then call run_notebook on it. You don't need the results: I'll read them myself in the UI, and the second cell is expected to fail. Don't fix anything, don't retry, and don't call update_opt_in_level. After it runs, just reply "done". ``` </details> Closes AI-1319 |
||
|
|
60b51d74d5 |
Audit existing unit tests + Remove redundant ones (#52215)
## Context
_TLDR: Changes here speeds up unit tests on CI from ~14 minutes to ~3
minutes_ 😂
_TLDR 2: The file changes are solely only test files +
`studio-unit-tests.yml`_
We've currently got a lot of unit tests in the repository which while
great for coverage, hasn't been ideally written. There's a lot of
redundancy + overly specific tests that break easily, and our current
unit test takes about 15 minutes to run in the GHA per PR. Hence am
doing a audit clean up of all existing unit tests in the studio repo.
## Changes involved
- `.test.ts` files now run in `node`, `.test.tsx` in `jsdom`
- jsdom costs about 1s of setup per file. A `.ts` test that needs the
DOM opts in with `// @vitest-environment jsdom` (46 files do).
- Removed redundant and over-specific tests
- Duplicates are merged into `test.each`. Tests that only covered
libraries, existed for coverage, or asserted class names and snapshots
are deleted. 19 files are merged into a sibling or deleted.
- Fixed about 15 tests that couldn't fail
- Examples: unawaited assertions, fixtures equal to the default, and a
`semverGte` test calling `semverLte`.
- Sped up the slowest files
- Real sleeps are replaced with fake timers, `user.type` with paste, and
Radix option queries are scoped to the open listbox. For example,
`RestoringState` went from 18s to 0.3s and
`useTableEditorFiltersSort.navigation` from 20s to 3s.
- These ^ already shave down the unit tests time from 14 mins to 9 mins,
but am also sharding unit tests across 4 jobs to increase speed up
further which then shaves down time to 3 mins now
|
||
|
|
d8b4d7bc8f |
Revert "Joshenlim/fe 4676 port log drains api endpoints from platform to v2" (#52137)
Reverts supabase/supabase#51995 |
||
|
|
3af897e6d6 |
Joshenlim/fe 4676 port log drains api endpoints from platform to v2 (#51995)
## Context Just porting over log drains API from `platform` to `v2` - verified that log drains management still works locally ## To test - [ ] Staging preview: Verify that you can create, read, and delete - there's no way to update log drains atm - [ ] Local / Self-hosted: Verify that you can create, read, and delete |
||
|
|
27e6259a39 |
chore(studio): remove legacy status banner and incidentIoStatusPage flag (#51852)
## Summary The incident.io status page is now the only status banner for everyone, so the legacy status banner path is removed: - Removed the `incidentIoStatusPage` ConfigCat flag. The incident.io path is unconditional. - Deleted the legacy status banner code (`StatusPageBanner` and its utils/visibility hook) and its tests. - Deleted the legacy API endpoints `/api/incident-banner`, `/api/incident-status`, and `/api/status-override` (pages, app, and routes variants), along with their data hooks, query keys, and lib helpers. - Removed `STATUSPAGE_*` env vars from the Turbo config and the `INCIDENT_BANNER_DISMISSED_IDS` local storage key from `packages/common`. - Updated the AI tools and SQL generation endpoint that read the flag. `NEXT_PUBLIC_ONGOING_INCIDENT` / the `ongoingIncident` override is kept. The `incident_status_cache` table and its migration are intentionally untouched. Studio no longer reads it, and dropping it is a separate cleanup. ## Testing - Studio typecheck passes. - Related vitest suites pass (414 tests). |
||
|
|
16bd06dfb8 |
fix(studio): silence status page errors when incident.io isn't configured (#51315)
Running Studio locally without the incident.io env vars produces a 500 from `/api/status-page` on every fetch, plus a server-side log and a client `console.error`. Retries and the 5-minute refetch keep repeating them, so the dev console stays noisy. **Changed:** - `lib/api/status-page.ts` – when `INCIDENT_IO_WIDGET_URL` is unset outside production, return an empty (degraded, short-cached) status page instead of throwing. The missing API key / status page ID log is also limited to production. Production behavior is unchanged. - `data/platform/status-page-query.ts` – remove the client-side `console.error`, which repeated the error that React Query already exposes **Added:** - Tests for the missing widget URL in dev (empty payload, no error log) and in production (still throws) ## To test - Run Studio locally in platform mode without `INCIDENT_IO_*` set: no status page errors in the terminal or the browser console, and `/api/status-page` returns 200 with empty arrays - Support form and project creation still render normally (no status banner, status page link points to status.supabase.com) Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
b2cf3693dd |
feat(studio): /api/status-page endpoint backed by incident.io Widget API (#50931)
## Summary * Adds `/api/status-page` (Next route + TanStack wrapper), backed by the [incident.io](<http://incident.io>) Widget API, annotating each item with `visible`, `show_banner`, and (for scheduled maintenances) `banner_lead_days`. * Deployment-mode visibility is driven by a new `status_page:visibility_field_ids` custom-content key. * Widget array parsing is fault-tolerant: a malformed item in one array is dropped and logged rather than failing the whole response, so one bad item can't hide a real ongoing incident. * 429s from [incident.io](<http://incident.io>) are retried with equal-jitter exponential backoff, respecting `Retry-After`, up to 2 retries. * Nothing consumes this endpoint yet — it replaces no existing behavior and changes nothing user-visible. Later PRs (this is PR 1 of a stack) wire up consumers behind the `incidentIoStatusPage` ConfigCat flag. Part of [FE-4057](https://linear.app/supabase/issue/FE-4057/frontend-bannerbot-reconfigured) — see Linear for full design context. ## Test plan - [X] `pnpm --filter studio run typecheck` - [X] `pnpm --filter studio run lint:ratchet` - [X] `pnpm knip --workspace apps/studio` - [X] `pnpm test:prettier` - [X] `pnpm --filter studio exec vitest run status-page` — 44 tests passing, including a regression test built from a real production [incident.io](<http://incident.io>) payload that initially failed to parse, and a compile-time type-safety regression test for the array-parsing helper Co-authored-by: Claude Code [charis@supabase.io](<mailto:charis@supabase.io>) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a status page that displays ongoing incidents and maintenance, with visibility and banner settings based on linked incident details. * Status page data is available through a new API endpoint, with caching for successful responses and degraded results. * **Bug Fixes** * Status page data can still display when some linked incident details are unavailable; affected results are marked as degraded. * Improved handling of invalid widget entries so they don’t prevent valid items from being processed. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Code <charis@supabase.io> |
||
|
|
5e59b6047e |
chore(studio): extend Assistant response time and handle timeouts (#50892)
## Problem
- Assistant responses were capped at 120 seconds and 10 steps, which is
too short for longer reasoning or multi-step tool work.
- When the hosting platform ended a request at that limit, the
connection just dropped. The user got no explanation, and "Thinking…"
and tool rows kept spinning.
- Studio's own tools ignored the request's abort signal, so a stop,
disconnect or deadline couldn't cancel their in-flight requests.
- Aborted responses never closed their Braintrust span. Under TanStack
Start, the remote MCP client was only released on `res.on('close')`,
which the adapter never emits.
## Solution
Uses AI SDK options instead of custom stream handling:
- `maxDuration` goes to 300s and the step limit to 20. `streamText({
timeout: { totalMs } })` stops the response at 270s, leaving time to
finish the stream before the platform cutoff.
- `toUIMessageStream({ messageMetadata })` marks an aborted response
`timedOut: true`. `Chat` ignores `abort` chunks, so the client reads
this flag instead and shows a timeout alert with Retry. The flag is
saved with the message, so the alert survives a reload.
- `toUIMessageStream({ onEnd })` aborts the request whenever the stream
ends, releasing the MCP client on both runtimes. `streamText({ onAbort
})` ends the Braintrust span.
- Studio tools pass the SDK's `abortSignal` to their fetches. MCP tools
already did.
- Reasoning and server-tool rows that never finished show "Response
interrupted" instead of a spinner or "Ran X ✓".
There's no per-tool timeout. Approved SQL and migrations can
legitimately run longer, and aborting the HTTP request doesn't stop the
query in Postgres.
## Review instructions
1. Run the unit tests: `cd apps/studio && pnpm vitest run
lib/api/generate-v4.test.ts lib/ai components/ui/AIAssistantPanel`
2. To see a timeout without waiting 4.5 minutes, temporarily set
`ASSISTANT_TIMEOUT_MS` in `apps/studio/lib/ai/assistant-timeout.ts` to
`15_000` and run `pnpm dev:studio`.
3. Ask the Assistant something that needs several tool calls or long
reasoning, for example "Audit my schema for missing indexes and RLS
gaps, then write the fixes."
4. After 15 seconds, check that:
- the response stops and a "Assistant response timed out" alert appears
with Retry
- any in-progress reasoning or tool row shows "Response interrupted"
instead of spinning
- Retry starts a new response
- reloading the page still shows the alert on that chat
5. Stop a response with the Stop button before the deadline. It should
stop without the timeout alert.
6. With the default 270s, confirm that a normal response completes as
before.
## Checklist
Check all before review:
- [ ] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which references
[WORD_LIST](https://github.com/supabase/supabase/blob/master/apps/docs/WORD_LIST.md)
and the docs
[CONTRIBUTING](https://github.com/supabase/supabase/blob/master/apps/docs/CONTRIBUTING.md)
guide
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Improvements**
* AI assistant responses can now run for up to five minutes, supporting
longer requests.
* When a response times out, the assistant displays a message suggesting
you retry or ask for a smaller change.
* Incomplete responses now show a “Response interrupted” notice, and
loading indicators stop when generation ends.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
fd5ef806d6 |
feat(studio): enable Assistant tracing for High Compliance projects (#50759)
Assistant chats from High Compliance projects now flow to Braintrust like any other project. The constraint that required suppressing them no longer applies, see AI-1241 for the details. `isTracingAllowed` now takes only the project region to maintain EU exclusion. Traces also carry an `isHighComplianceProject` metadata field, so the project's status at the time of the trace is recorded rather than looked up later against a setting customers can toggle. To verify, see [this sample trace](https://www.braintrust.dev/app/supabase.io/p/Assistant/logs?r=afabbdcc-aa89-446e-aa52-78aaa90d44a4&v=Production&s=afabbdcc-aa89-446e-aa52-78aaa90d44a4&tvt=trace) from a High Compliance project on staging which indicates that tracing is now enabled for these projects and that it carries metadata showing the high compliance status. | High Compliance project setting | `isHighComplianceProject` metadata | |--------|--------| | <img width="1554" height="454" alt="CleanShot 2026-09-22 at 5 14 58 PM@2x" src="https://github.com/user-attachments/assets/23901c6e-0d79-44e8-a6dd-43cdedba1799" /> | <img width="1674" height="990" alt="CleanShot 2026-09-22 at 5 17 40 PM@2x" src="https://github.com/user-attachments/assets/fb2fba55-bcc1-4136-a432-b33a5c7f9ca2" /> | Closes AI-1241 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Changes** * AI project compliance information is now represented by a unified high-compliance project status. * AI response tracing is now determined by project region: tracing remains disabled for EU and unknown regions, while known non-EU regions are eligible. * AI feedback and SQL generation now use the updated compliance and regional handling. * **Tests** * Updated coverage to reflect the revised compliance and tracing behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
737b8595f2 |
Update API types (#50234)
## Problem platform, v1 and v2 have been already completely migrated and introduced some changes. Some types have been renamed, some outputs and inputs updated. ## Solution - Update the API types - Fix the TS errors ## Update Taking this over to unblock #50134, which needs the new scoped token permission ids from the regenerated types. - Merged `master`. - Regenerated `api-v2.d.ts` from the production spec. The previous files came from a local API that exposed a webhook events endpoint production doesn't have yet. Production has since added standardized 400 error responses on the v2 organization endpoints. `api-v1.d.ts` and `platform.d.ts` already matched production. - Fixed `verify-production-types`. It formatted the regenerated files in a temp directory outside the repository, so Prettier fell back to its defaults and the comparison could never match the committed files. It now passes the repository config explicitly. `pnpm api:verify-types` passes on this branch. - Verified locally: `pnpm typecheck`, `pnpm api:verify-types`, Studio unit tests. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Preserved descriptions when saving, sharing, moving, or unsharing notebooks, reports, SQL snippets, and saved queries. * Improved handling of empty or null values across notebook descriptions, billing usage, pooler settings, and infrastructure fields. * Improved read-replica connection handling, including read-only connection strings. * Updated storage configuration and capability handling to match current settings. * **API and Compatibility** * Updated organization, project, storage, OAuth, billing, and infrastructure data handling to match current API responses. * OAuth app creation and updates now require scopes. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
1966209483 |
chore(deps): upgrade vitest to v5 (#49994)
Upgrades Vitest from 4.1.4 to 5.0.0 across the monorepo, fixes the handful of things v5 turned into hard errors, and drops the `vi.clearAllMocks()` boilerplate that v5's `clearMocks` default makes redundant. **Changed:** - `vitest`, `@vitest/ui`, `@vitest/coverage-v8` 4.1.4 → 5.0.0 (catalog) - `vi.mock` calls that lived inside `beforeAll`/`beforeEach`/test bodies moved to module scope (v5 throws on nested calls). Affects the Studio and docs setup files and four Studio tests. - `detectBrowser` test restores `navigator` via `vi.unstubAllGlobals()` instead of assigning `global.navigator`, which now reaches jsdom's getter-only property. - `RowEditor.utils.test.ts` restores its `JSON.stringify` spy. It used to leak a throwing mock for the rest of the file, which v5's coverage provider now trips over. A later test in the same file had been asserting the leak's side effect (valid JSON reported as invalid) and now asserts the correct behavior. - `@testing-library/jest-dom` 6.6 → 7.0.1. Its vitest type augmentation resolves through a peer now, so it lands on each package's own `vitest` instead of whichever copy pnpm hoisted. Fixes `toBeInTheDocument` type errors in dev-tools after the reshuffle. - `@testing-library/react` 16.0.0 → 16.3.3 for the React 19 peer range. - `vite: catalog:` added to dev-tools, www, and common. Without it they resolved a newer vite than the catalog pin, which forked a second vitest instance in the lockfile. There's now one. - ai-commands custom matcher types use v5's `Matchers<R, T>` form. - 110 test files: `vi.clearAllMocks()` removed from `beforeEach`/`afterEach` hooks, along with hooks that only did that and the imports they left unused. Calls that also reset/restore mocks are untouched. Second commit, mechanical. **Added:** - `.vitest/` to the root gitignore (v5 writes JSON/JUnit/HTML reporter output there) **Removed:** - `vite-tsconfig-paths` catalog entry and deps. Vitest 5 resolves tsconfig paths itself. Release-age note: this sat in draft with a temporary `minimumReleaseAgeExclude` entry for `vitest` and `@vitest/*` while 5.0.0 was inside the workspace's 3-day `minimumReleaseAge` window. That window has closed, so the exclusion is gone and nothing bypasses the release-age gate. **Perf** (local, medians of 3 runs, same machine): | Suite | v4.1.4 | v5.0.0 | |---|---|---| | studio | 144.1s | 141.7s (-2%) | | studio `--coverage` | 156.9s | 146.4s (-7%) | | ui-patterns | 6.27s | 5.07s (-19%) | | ui `--coverage` | 3.35s | 2.14s (-36%) | | www | 0.89s | 0.47s (-47%) | Studio is dominated by jsdom environment setup per file, which v5 doesn't change. `vitest doctor` recommends keeping the current pool config: the vm pools and `isolate: false` all break tests. ## To test - `pnpm install --frozen-lockfile` succeeds with no `minimumReleaseAgeExclude` entry for vitest. - CI: Studio unit tests, ui, ui-patterns, www, docs, and typecheck/lint should all be green. The lint ratchet was checked locally: warning counts on touched Studio files are identical to master. - `pnpm test:studio` locally passes with coverage (588 files, 6240 tests). - Open a Studio test that uses `toBeInTheDocument` in your editor and confirm no type errors on jest-dom matchers, in Studio and in `packages/dev-tools`. - Known pre-existing failures unrelated to this PR: one dev-tools test (`getEventCountBadge` capped pill) fails on master too. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Tests - Improved test coverage for JSON validation and mobile navigation behavior. - Updated test setup, cleanup, environment configuration, and matcher support across application and shared package suites. - Removed obsolete coverage for alternate MCP transport selection. ## Chores - Streamlined TypeScript path resolution and Vitest reporter output handling. - Updated testing libraries and Vitest tooling across documentation, Studio, website, and shared packages. - Added Vitest reporter output to ignored files. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com> |
||
|
|
b5477a89a3 |
chore: Update API types (#48981)
Update the API types by running `api:codegen`. Some of the changes are fixed in code, some of the type changes had to be reverted (JIT Access, SSO features). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Billing** * Updated subscription messaging to reflect AWS Marketplace billing. * Removed outdated partner-billing downgrade notices. * **Bug Fixes** * Improved request handling for API keys, custom domains, SQL snippets, branches, and storage operations. * Improved legacy signing-key compatibility. * Refined temporary database access availability messaging. * **Updates** * Removed Fly as an available cloud provider for region selection. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
47595f8ac7 |
feat(self-hosted): implement queryLogs for the MCP debugging tools (#48900)
> [!IMPORTANT] > > Only merge this when (https://github.com/supabase/platform/pull/36804) is merged, as the AI assistant will not have access to the `query_logs` tool for the remote MCP server ## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Feature (self-hosted / CLI Studio MCP server). ## What is the current behavior? Self-hosted `getDebuggingOperations` (`apps/studio/lib/api/self-hosted/mcp.ts`) implements only `getLogs`, so the MCP `debugging` group exposes `get_logs` — a fixed per-service log dump built by `getLogQuery`. Logs are served by Logflare, which speaks BigQuery SQL. ## What is the new behavior? Bumps `@supabase/mcp-server-supabase` to `^0.10.0` (adds `query_logs` + `logsDialect`, and hides `get_logs` wherever a platform declares `queryLogs`) and moves logs over to it. - **Self-hosted `query_logs`:** declares `logsDialect: 'bigquery'` and implements `queryLogs`, passing the model's SQL straight through to the same Logflare `logs.all` endpoint (arbitrary `sql` param) — no new endpoint, no dialect translation. - **Drops `get_logs` from self-hosted:** `getLogs` throws (the server hides it once `queryLogs` exists) and the per-service `getLogQuery` builder is deleted; the model now writes its own BigQuery SQL, guided by the dialect schema hint. - **Honors no-logs mode:** `query_logs` throws when `logs:all` is disabled — the self-hosted default, enabled via the `docker-compose.logs.yml` override. - **Assistant:** switches the dashboard assistant from `get_logs` to `query_logs` (allowlist, drift guard, prompt, mocks, evals). Refs AI-1046 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * AI debugging can query recent project logs using read-only SQL. * Log queries support optional time-range filters, filtering, aggregation, and joins. * Self-hosted debugging checks whether logging is enabled before running queries. * **Bug Fixes** * Updated debugging workflows and validation to consistently use the new log-query capability. * Removed reliance on legacy service-specific log filtering and query behavior. * **Documentation** * Updated MCP debugging tool guidance to describe SQL-based log queries. * **Tests** * Expanded coverage for enabled, disabled, and unsupported logging scenarios. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
b04d14856a |
Resolve AI opt-in and tracing settings server-side (#48855)
The AI endpoints resolved organization and project settings independently and applied them together without confirming they belonged to the same pairing. Consolidates both into a single `getAIDetails` that reconciles them and falls back to the most restrictive posture when unconfirmed, and applies the HIPAA sensitivity gate to the opt-in level, which previously only existed on the client. Fixes FE-4110 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Consolidated AI access details across organization and project settings. - AI functionality now validates project ownership and disables access for mismatched or HIPAA-sensitive projects. - AI responses include plan, region, opt-in status, sensitivity, authorization, and advanced model access information. - **Bug Fixes** - Improved fail-closed behavior when project or organization data is missing or inconsistent. - Updated AI generation, feedback, rate, and policy flows to consistently apply consolidated access settings. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
05d8dd356c | fix: selfhost edge URLs (#47861) | ||
|
|
dc23320e43 |
Add sentry capture exception to apiWrapper (#47804)
## Context As per PR title - also adjusts the imports for files consuming `apiWrapper` to remove the default export for `apiWrapper` Have tested locally by throwing an error in one of the API routes - verified that the event shows up on Sentry <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * API errors are now captured in Sentry before returning server error responses, improving production visibility while keeping endpoint behavior the same. * **Tests** * Added coverage to confirm rejected handler executions are reported to Sentry and return the expected HTTP 500 JSON payload. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
0acc0eb8b3 |
feat: Support Form - Sync AI assistant conversation to Front (#46778)
# Sync AI assistant conversation to Front ## What & why When a user submits a support ticket, an AI assistant chat opens so they get help immediately while waiting for a human agent. This PR mirrors every turn of that chat into the Front conversation the support form already created, so the support team sees the full context and Front automations (routing, emails, CSAT) can act on it. Studio holds no Front credentials — it calls the platform endpoints (see the platform PR) to do the syncing. The assistant card is gated behind the `supportAssistantFollowUp` ConfigCat flag. ## How it works 1. **Submit** — `SupportFormV3` generates a stable `threadRef` (via the `uuid` package — `crypto.randomUUID()` is `undefined` in insecure contexts like non-localhost HTTP and would throw, silently aborting the submit) and sends it on `/platform/feedback/send`. The response returns the Front `conversationId`. Both are stored on `SubmittedSupportRequest`. 2. **Open chat** — `SupportAssistantSuccessCardContent` opens a chat seeded with `supportMetadata` (`threadRef`, `frontConversationId`, subject, category, severity, …). The first message is a `<support>…</support>` XML block. 3. **First user message** — the chat is tagged `isSupportChat = true`; the `onFinish` hook fires `syncSupportChatToFront`. 4. **Subsequent turns** — each `onFinish` slices the unsynced delta, strips the XML metadata block from the seed message, and posts to the platform messages endpoint. 5. **Escalation / resolve** — the `escalate_to_human` / `resolve_support_conversation` tools (and manual **Escalate**/**Resolve** buttons in the assistant input) flip lifecycle status via `setSupportLifecycleStatus` → `syncSupportLifecycleToFront`, which calls the escalation/resolve endpoints. Front rules act on `ai_support_status`. The assistant only resolves after the user explicitly confirms the issue is fixed. ## Key design decisions - **`threadRef` as the shared key** — one UUID travels as `threadRef` on submit and as `chatId` on every sync, so all messages thread into a single Front conversation. - **`conversationId` from the form response** — passed to all sync/lifecycle calls so the platform skips lazy derivation and PATCHes custom fields directly. - **Delta-only sync** — `lastSyncedMessageCount` tracks what's been sent; the boundary is snapshotted before the async call to avoid skipping messages that arrive mid-flight. - **Server-side de-dup** — stable `external_id` (`chatId:msg.id`) means retries don't duplicate in Front. - **Fire-and-forget** — sync failures log to Sentry, never break the chat; `isSyncing` resets on rehydration so the next `onFinish` retries the same delta. Message and lifecycle syncs use separate guards (`isSyncing` / `isLifecycleSyncing`) so an in-flight message sync can't drop an escalate/resolve. - **Lifecycle queued until the conversation exists** — if a lifecycle transition is requested before the initial message sync has returned a `frontConversationId`, it's stored as `pendingLifecycleStatus` and flushed once the id is assigned, rather than dropped. - **Tools return immediately** — the lifecycle tools return a stub to the AI SDK; the real Front call happens in `onFinish`, keeping async I/O out of the tool execute path. - **XML seed stripped before sync** — only the user's actual `<message>` is sent to Front (or dropped entirely if the form already created the conversation). ## Changes | Area | File(s) | | --- | --- | | Support form state | `SupportForm.state.ts` — `threadRef` / `frontConversationId` on `SubmittedSupportRequest` | | Support form submit | `support-ticket-send.ts` — sends `threadRef`, reads `conversationId` | | Support form UI | `SupportFormV3.tsx` — generates `threadRef`, stores `conversationId` | | AI assistant state | `ai-assistant-state.tsx` — `SupportChatMetadata`, `setSupportLifecycleStatus`, `onFinish` wiring, tool handling | | Message sync | `state/ai-chat-front-sync.ts` — delta tracking, message filtering, initial vs. incremental | | API data layer | `data/feedback/ai-chat-front-sync.ts` — typed platform-client wrappers for the three conversation endpoints | | Support tools | `lib/ai/tools/support-tools.ts` — `escalate_to_human`, `resolve_support_conversation` | | Tool integration | `lib/ai/tool-filter.ts`, `tools/index.ts`, `generate-assistant-response.ts` | | Success card | `SupportAssistantSuccessCardContent.tsx` — tags chat on first engagement | | Assistant panel UI | `AIAssistant.tsx` — Escalate/Resolve buttons, disabled input on closed chats, support placeholders | <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Summary by CodeRabbit - **New Features** - Support chats now include “Escalate to human” and “Resolve” actions. - Support submissions can be associated with a stable Front thread via a generated `threadRef`, preserving linkage across follow-ups. - AI assistant responses and input hints adapt when support mode is active. - **Bug Fixes** - Improved support chat state management and lifecycle handling to keep conversation metadata and message history synchronized more reliably with Front. - **Chores** - Added/updated coverage to reflect the new support-chat state and syncing behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
c4c213ce3d |
feat(studio): switch dashboard assistant to remote MCP server (#47479)
## I have read the [CONTRIBUTING.md](<https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md>) file. YES ## What kind of change does this PR introduce? Feature / refactor. ## What is the current behavior? The dashboard assistant runs `@supabase/mcp-server-supabase` in-process over an in-memory transport (`lib/ai/supabase-mcp.ts`). ## What is the new behavior? The assistant connects to the **remote MCP server** over HTTP (`@ai-sdk/mcp`), forwarding the dashboard session token as a bearer. URL comes from `NEXT_PUBLIC_MCP_URL` with a local-dev fallback; platform-only, and Nimbus works via the same env var. * **Tool model unchanged:** UI-controlled `execute_sql` (with `needsApproval`) and `deploy_edge_function` still come from Studio; the allowlist (`TOOL_CATEGORY_MAP`) remains the gate keeping the remote's write tools away from the assistant (`read_only` is defense-in-depth). * **Attribution:** sends `x-source-name: supabase-studio` (+ `x-source-version`) → logged as `source_name`/`client_name`. * **Connection lifecycle:** the HTTP client is closed via the request's `AbortSignal` (tools execute later during streaming); `signal` is required on `getTools`/`getMcpTools`. * **Resilience:** a remote-MCP failure degrades to the remaining tools instead of failing the assistant. * **Drift protection:** relied-upon tools are typed against `keyof typeof supabaseMcpToolSchemas`, so a package bump that renames/removes one fails `pnpm typecheck`; a runtime check also warns if the deployed server returns fewer tools. * Adds unit tests for the above. ## Additional context * Verified end-to-end against a local remote MCP server with a dashboard token: `initialize` 200, tools listed, a tool executed, client closed cleanly. * The remote MCP (mgmt-api) already accepts dashboard session tokens (GoTrue-JWT auth path) — no backend change needed. `NEXT_PUBLIC_MCP_URL` must point at each env's `/mcp`. * `@supabase/mcp-server-supabase` is kept — still used by the self-hosted `/api/mcp` routes. Closes [AI-137](https://linear.app/supabase/issue/AI-137/switch-dashboard-assistant-to-remote-mcp) ## Rollout * **Rollout:** merges with `USE_REMOTE_MCP` off (in-process); flip it to `true` per environment (staging → prod → Nimbus) once each one's prerequisites land. * **Rollback:** unset `USE_REMOTE_MCP` and redeploy to fall back to the in-process client — no revert needed. ## Summary by CodeRabbit * **Bug Fixes** * Improved AI request handling so tool loading and generation clean up properly when a request is cancelled or the browser connection closes. * Added safer fallback behavior when remote tool loading fails, so AI features can continue with available tools instead of stopping entirely. * Updated remote tool access to use the current project reference and preserve the correct access headers. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * AI tools now connect more reliably to remote services and stop cleanly when requests end or are canceled. * Tool loading is more resilient, continuing with available tools if remote access is unavailable. * **Bug Fixes** * Improved cleanup to prevent lingering connections during SQL generation and policy workflows. * Added safer handling for remote tool changes and invalid responses. * **Tests** * Expanded automated coverage for remote tool setup, cancellation, and fallback behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
514c3aa0d0 | fix(self-hosted): type generation should respect exposed schemas (#47577) | ||
|
|
8a9a9948a8 | fix(studio): self-hosted folder listings return metadata only (#47403) | ||
|
|
e81c714aae |
refactor(studio): lazy self-hosted admin client + enforce in API routes (from #46424) (#47104)
Extracted from the TanStack Start migration (#46424) to shrink that PR. The self-hosted storage/auth API routes each constructed a module-scope admin client (`createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_SERVICE_KEY!)`). Those env vars only exist on self-hosted, so eager module-scope construction is wasteful on platform and fragile on any runtime that evaluates an API module before its route is hit (constructing with `undefined` credentials throws on import). **Changed:** - Add `lib/api/self-hosted-admin.ts` — `selfHostedSupabaseAdmin`, a `Proxy` that defers `createClient(...)` until first property access (inside a handler, i.e. on self-hosted where the vars are set). - Swap **all 17** storage/auth/vector-bucket handlers from module-scope `createClient(...)` to `import { selfHostedSupabaseAdmin as supabase }`. - **Enforce it:** add an eslint `no-restricted-syntax` rule banning module-scope `createClient` in `pages/api/**` + `routes/**` (now that every flagged handler is lazy). The same eslint config block also carries an analytics-SQL boundary rule — 0 violations on master. Behaviour is unchanged (the client is still built lazily inside the handler). This is also the change that makes those routes safe under TanStack's single-handler module evaluation. ## To test - Self-hosted Studio: storage buckets/objects, vector buckets, and auth users operations work as before. ## Verification studio lint (0 errors, both rules active) ✓ · studio typecheck ✓. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Refactor** * Standardized self-hosted Supabase admin client usage across platform authentication and storage endpoints, removing per-route client setup. * Improved reliability by lazily creating the admin client only when first used. * **Chores / Tooling** * Updated ESLint rules to prevent module-scope Supabase client creation in API routes and to enforce safe analytics SQL access patterns. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> Co-authored-by: Ali Waseem <waseema393@gmail.com> |
||
|
|
1baaded0bb |
Consolidate execute-sql-query into execute-sql-mutation (#46944)
## Context Just some clean up as I was going through stuff - `useExecuteSqlQuery` is deprecated and not used at all - As such `execute-sql-query` is technically irrelevant, the more relevant file is `execute-sql-mutation` - Hence opting to consolidate `execute-sql-query` into `execute-sql-mutation` - Also removing `ExecuteSqlError` since its just re-exporting the `ResponseError` type There's a lot of file changes but its essentially just updating the importing statements across the files |
||
|
|
b28f91741f | fix(self-hosted): reveal and copy secret api key in project settings (#46592) | ||
|
|
ca9b02b5ac | feat(self-hosted): add minimal project settings (#46554) | ||
|
|
1d203f6c93 |
feat: Support CLI for Vector buckets (#46381)
## Context > [!IMPORTANT] > Will open up for review once CLI PR is merged and deployed so that it's easier to test Related PR: https://github.com/supabase/cli/pull/5230 Adding support for vector buckets for local CLI - will need to be tested locally via `pnpm run dev:studio-local` ## To test There's a bit of testing instructions in the linear ticket [here](https://linear.app/supabase/issue/FE-3474/show-vector-buckets-in-local-admin-studio) as it involves using a branch of CLI - otherwise do reach out to Fabrizio if any help might be needed, but generally: ### Local CLI You might need to manually set `isCli` to `true` in `StorageMenuV2` if the "Vectors" nav item isn't showing up on the storage UI given we're testing via `pnpm run dev:studio-local` - [x] Can create bucket - [x] Can delete bucket - [x] Can create indexes - [x] Can insert data into indexes (via FDW) - [x] Can delete indexes Known issues (that aren't directly solvable from FE end) Reach out to Fabrizio for context as we were both investigating this - PG database needs to be on 17.6 (otherwise there's no S3 vectors FDW) - Storage version needs to be on 1.59.0 ### Self-hosted (This might be tricky to actually test, but just ensure that the code satisfies this) - [x] Cannot see vector buckets ### Hosted - [x] Everything works status quo <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Vector bucket management UI and platform APIs (create/list/delete buckets & indexes) * Local S3 credentials endpoint and client-side hook for self‑hosted/CLI use * **Bug Fixes** * Improved S3 vector setup notifications and clearer error guidance for manual installation * **Refactor** * Deployment-mode gating: platform vs CLI/self‑hosted now controls feature visibility and page behavior * **Tests** * Added suites covering deployment-mode gates and vector bucket error/usage scenarios * **Chores** * Build env updated to expose local S3 credential vars <!-- review_stack_entry_start --> [](https://app.coderabbit.ai/change-stack/supabase/supabase/pull/46381?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Ali Waseem <waseema393@gmail.com> |
||
|
|
c1b473e472 | fix: adjust connect sheet for cli and self-hosted (#46217) | ||
|
|
c1276c8e9a | feat(self-hosted): add new API keys to self-hosted Studio and MCP server (#46173) | ||
|
|
39ec777d22 |
studio: SafeSql stragglers + remaining tests (6/7) (#46006)
## Summary Part 6 of 7 in the SafeSql migration stack. Picks up the few remaining files that didn't fit cleanly into earlier batches: - `components/Docs/Description.tsx` — comment statements built via `safeSql`. - `components/Integrations/IntegrationOverviewTabV2/InstallIntegrationSheet.test.tsx` — test fixture updated to `SafeSqlFragment`. - `lib/ai/tools/studio-tools.test.ts` — test fixture updated. - `lib/api/generate-v4.test.ts` — test fixture updated. Sets up PR 7, which flips the `executeSql` signature itself. ## Test plan - [x] `pnpm typecheck` passes - [x] Specific Studio unit tests run on top of the stack (`Policies.utils.test.ts`, `SidePanelEditor.utils.createTable.test.ts`, `useQueryInsightsIssues.utils.test.ts`) - [x] Dev-server smoke: Docs panel renders / accepts edits <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Tests** * Updated test suites to reflect internal type definition changes. * **Refactor** * Internal code improvements to enhance type safety and consistency across the codebase. <!-- review_stack_entry_start --> [](https://app.coderabbit.ai/change-stack/supabase/supabase/pull/46006) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
d143571586 |
feat(assistant): trace-level scorers + server-side tool execution with needsApproval (#45654)
## Motivation When Assistant runs a potentially destructive tool like `execute_sql`, it stops the LLM request and prompts for client-side approval and execution of the tool. After approval, a second request kicks off under a separate trace. This has made scoring and [Topics](https://www.braintrust.dev/blog/topics) classification challenging, as the generated `output` is split across stateless requests. The [span-level scoring](https://www.braintrust.dev/docs/evaluate/custom-code#score-spans) approach we've used thusfar (after the LLM call, we massage the result into an `output` payload that's stuck onto the root span) has been cumbersome and led to invalid scores / topics where only part of the assistant response is considered. It's also inefficient, as we're duplicating potentially large info (like the `search_docs` output) that already exists within the trace. An alternative to scoring spans is to [score traces](https://www.braintrust.dev/docs/evaluate/custom-code#score-traces). Braintrust [best practices](https://www.braintrust.dev/docs/evaluate/score-online#best-practices) advise: > Use span scope for evaluating individual operations or outputs. Use trace scope for evaluating multi-turn conversations, overall workflow completion, or when your scorer needs access to the full execution context. We've also received [direct guidance](https://supabase.slack.com/archives/C05QYJBLX89/p1777925770927149?thread_ts=1777905716.911979&cid=C05QYJBLX89) from their team to use this approach. ## Changes Migrates eval scorers from custom `AssistantEvalOutput` shape to trace-level scoring via `trace.getThread()` / `trace.getSpans()`, with thread parsing that scores the full latest Assistant turn and passes prior conversation separately where relevant. Moves `execute_sql` and `deploy_edge_function` from client-side execution after approval to AI SDK `needsApproval` + server-side `execute()`. SQL results returned to the model are gated by AI opt-in level, so row data is only included with `schema_and_log_and_data`; otherwise the tool returns the no-data-permissions sentinel. Adds `metadata.isFinalStep` to disambiguate multiple LLM requests within an "assistant" turn due to tool call requests/responses. For online evals, this means we should configure automations to only score traces with `metadata.isFinalStep = true` to ensure we're judging the complete generated response. Other minor kaizen changes: - Renamed `promptProviderOptions` to `systemProviderOptions` to clarify that this is associated with the "system" message and disambiguate from the root `providerOptions` - Adds `evals/trace-utils.ts` to handle Zod validation of the `unknown` span shapes from Braintrust, to more easily access typed inputs/output on tool spans. - Bumps AI SDK floor version `^6.0.116` → `^6.0.174` - Tweaked the "Conciseness" scorer to not unfairly dock points for the new `[called tool_name]` labels in serialized assistant response ## Verification In the studio staging build, I asked Assistant to create a todos table with 3 sample todos. I manually approved the `execute_sql` call and saw Assistant generate text before & after the call. In Braintrust I verified two traces were produced (see [filtered logs](https://www.braintrust.dev/app/supabase.io/p/Assistant/logs?v=Staging&tvt=trace&search={%22filter%22:[{%22text%22:%22metadata.environment%2520%253D%2520%27staging%27%22,%22label%22:%22metadata.environment%2520%253D%2520%27staging%27%22,%22originType%22:%22btql%22},{%22text%22:%22%2560Chat%2520ID%2560%2520%253D%2520%25221cb2ac45-e5e7-458c-9da4-3bf6863b8842%2522%22,%22label%22:%22Chat%2520ID%2520equals%25201cb2ac45-e5e7-458c-9da4-3bf6863b8842%22,%22originType%22:%22form%22}]})), the first with `metadata.isFinalStep = false` and the second with `metadata.isFinalStep = true`. In the Braintrust staging scorers, I ran the preview Completeness scorer on the second trace and verified it sees the complete Assistant response including markers for tool calls ([link to trace](https://www.braintrust.dev/app/supabase.io/p/Assistant%20(Staging%20Scorers)/trace?object_type=project_logs&object_id=b5214b62-ad1e-4929-9d5b-40b1daebe948&r=0ed0a4f8-8aff-4a34-bb1d-1df1d88a5070&s=ff9015f8-6bf7-4ab3-83a9-ca4e69e27e82)) <img width="1193" height="960" alt="CleanShot 2026-05-07 at 11 27 10@2x" src="https://github.com/user-attachments/assets/509d4858-c3a1-4068-986d-3aa4d5617d1a" /> I also tested the `deploy_edge_function` workflow and verified it still prompts for permission and warns on deployment of existing functions. **References** - https://www.braintrust.dev/docs/evaluate/custom-code#score-traces - https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling#tool-execution-approval Supercedes https://github.com/supabase/supabase/pull/45556 and https://github.com/supabase/supabase/pull/45339 Closes AI-473 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Tool actions (SQL execution, edge-function deploy) now require explicit user Approve/Deny before proceeding. * **Improvements** * Assistant pauses for approval responses before sending follow-ups, giving clearer control over risky actions. * Deploy/replace flows show confirmation and clearer replace warnings. * Evaluation/scoring updated to use richer trace data for more accurate assistant performance signals. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |