Commit Graph

63 Commits

Author SHA1 Message Date
Charis 0433eeb5f5 feat(studio): mark sql provenance for safety (#45336)
Mark provenance of SQL via the branded types SafeSqlFragment and
UntrustedSqlFragment. Only SafeSqlFragment should be executed;
UntrustedSqlFragments require some kind of implicit user approval (show
on screen + user has to click something) before they are promoted to
SafeSqlFragment.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Editor and RLS tester show loading states for inferred/generated SQL
and include a dedicated user SQL editor for safer edits.

* **Refactor**
* Platform-wide SQL handling tightened: snippets and AI-generated SQL
are treated as untrusted/display-only until promoted, improving safety
and consistency.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-05-04 13:08:06 -04:00
Ivan Vasilov 0dec08c96f chore: Bump vulnerable dependencies (#45513)
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Chores**
* Upgraded the UUID library to a newer major version across apps and
removed a now-unneeded dev dependency.
  * Pinned PostCSS to a workspace-specific version to stabilize builds.
* **Refactor**
* Improved internal identifier generation for more consistent behavior
without changing outward functionality.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-05-04 13:41:08 +02:00
Matt Rossman 36ae9beb0c chore(ai): remove DPA signer killswitch for assistant tracing (#45134)
Removes the temporary killswitch added when Braintrust was onboarded as
a subprocessor, to satisfy the 30-day DPA notice obligation. The window
has elapsed and legal has cleared removal.

Drops the `orgIsDpaSigned` check from `isTracingAllowed`, removes the
extra `/platform/organizations/{slug}/documents/dpa-signed` network hop
from `getOrgAIDetails`, and cleans up all call sites and tests.

Closes AI-596

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Refactor**
* Simplified AI tracing eligibility logic by removing DPA signing status
checks. Tracing authorization decisions now depend solely on region,
HIPAA addon status, and project sensitivity settings.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-04-27 13:53:24 -04:00
Joshen Lim 7f5865872a Enforce noUnusedLocals and noUnusedParameters in tsconfig.json + fix all related issues (#45264)
## Context

Enforce `noUnusedLocals` and `noUnusedParameters` in tsconfig.json + fix
all related issues
2026-04-27 17:42:34 +08:00
Alaister Young 1b1d05ff96 chore: upgrade vite to v8 and vitest to v4 (#44833)
Upgrade vite and vitest to their latest major versions across the
monorepo, along with related packages.

**Changed:**
- `vite` catalog: `^7.3.2` → `^8.0.8` (Rolldown replaces esbuild/Rollup)
- `vitest` catalog: `^3.2.0` → `^4.1.4`
- `@vitejs/plugin-react`: `^4.3.4` → `^6.0.1`
- `@vitest/coverage-v8`: `^3.2.0` → `^4.1.4`
- `@vitest/ui`: `^3.2.0` → `^4.1.4`
- `vite-tsconfig-paths`: `^4.3.2` / `^5.1.4` → `^6.1.1`

**Pinned to vite 7:**
- `apps/lite-studio` — `@react-router/dev` hasn't declared vite 8
support yet
- `blocks/vue` — Nuxt plugins (`vite-plugin-inspect`, `vite-dev-rpc`,
`vite-hot-client`, `vite-plugin-vue-tracer`) haven't declared vite 8
support yet

**Test fixes for vitest 4 breaking changes:**
- **`apps/studio/lib/api/snippets.utils.test.ts`** — Replaced
`vi.mock('fs/promises')` automock with an explicit factory. Vitest 4's
automocking doesn't create mock functions for getter-based exports on
Node built-ins, so `mockedFS.access.mockResolvedValue` etc. were
`undefined`.
- **`apps/studio/lib/api/self-hosted/functions/index.test.ts`** —
Changed `mockReturnValue` to `mockImplementation(function() { ... })`
for a constructor mock. Vitest 4 no longer allows `mockReturnValue` when
the mock is called with `new`.
- **`apps/studio/tests/pages/api/mcp/index.test.ts`** — Changed arrow
function to regular `function` in `mockImplementation` for
`StreamableHTTPServerTransport`. Arrow functions can't be constructors,
and vitest 4 now enforces this.
- **`packages/ui-patterns/vitest.setup.ts`** — Changed `ResizeObserver`
mock from arrow function to regular `function` for the same constructor
enforcement reason. This was crashing Radix popover rendering in jsdom.

## To test

- `pnpm test:studio` — all 226 test files should pass
- `pnpm --filter ui-patterns vitest run` — all 183 tests should pass
- `pnpm --filter www test -- --run` — all 19 tests should pass
- `pnpm --filter ui vitest run` — all tests should pass
- `pnpm --filter dev-tools vitest run` — all tests should pass
- `pnpm --filter ai-commands vitest run` — all tests should pass

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Chores**
* Standardized and updated development tooling versions and version
sources for consistent installs across the repo (Vite, Vitest,
vite-tsconfig-paths and related plugins/catalog entries).
* **Tests**
* Improved test mocks and typings (updated mock
factories/implementations and tightened spy/type assertions) to increase
test reliability and compatibility with updated tooling.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-04-16 00:13:48 +09:00
Charis 205cbe7d26 chore(studio}: enforce import order, remove bare import specifiers (#44585) 2026-04-07 20:34:10 -04:00
Matt Rossman 8aeacc6152 feat(assistant): disable Braintrust tracing for EU regions and DPA signers (#44504)
**Changes**

- Extracted tracing conditional to an `isTracingAllowed` helper with
unit tests (the function is simple but sensitive hence the extra testing
precaution)
- Disables Braintrust tracing for projects in EU database regions
(region prefix `eu-`) to address GDPR data residency concerns
- Disables Braintrust tracing for orgs whose owners have signed the
previous DPA, as a stopgap during the 30-day notice period for the
updated DPA that adds Braintrust as a subprocessor
- Refactored `org-ai-details.ts` → `ai-details.ts`, splitting
`getOrgAIDetails` into separate org and project helpers to cleanly scope
the EU-region check at the project level

DPA check uses the newly added `/documents/dpa-signed` endpoint from
https://github.com/supabase/platform/pull/31060. This PR includes
regenerated `api.d.ts` and `platform.d.ts` from running `pnpm codegen`
in `packages/api-types` to get type safety on this new endpoint.

Note tracing is still yet to be activated in production, this is a
preparatory step.

**To verify**

Send a chat message and check for the `x-braintrust-span-id` response
header on `POST /api/ai/sql/generate-v4` — it should be absent for
DPA-signed orgs or EU-region projects, and present otherwise.

<img width="3594" height="1992" alt="CleanShot 2026-04-03 at 14 28
58@2x"
src="https://github.com/user-attachments/assets/4c91d7ad-2604-4531-a78e-dedf41632fa5"
/>

If you have access to the Braintrust dashboard, you can also verify
whether logs are produced or not in the Assistant project there.


Closes AI-570
Closes AI-569

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
  * Tracks organization DPA signing and detects EU-region projects
* Assistant tracing now follows a combined compliance policy (HIPAA
addon, DPA, project sensitivity, region)
  * Added helpers to fetch org and project AI details

* **Documentation**
* Expanded API docs with additional examples and clarified parameter
descriptions
  * Added response schemas for subscription preview and document status

* **Tests**
* Added/updated tests covering DPA/region behavior and tracing policy
enforcement
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-04-07 13:09:34 -04:00
Matt Rossman adf8b0c67c feat(assistant): per-endpoint reasoningEffort + model config cleanup (#43981)
We're exploring support for newer models like
[gpt-5.4-nano](https://openai.com/index/introducing-gpt-5-4-mini-and-nano/)
in Assistant. This model doesn't support the `'minimal'` reasoning
effort level we use for gpt-5-mini which leads to vague errors.

<img width="595" height="263" alt="CleanShot 2026-03-18 at 17 13 05@2x"
src="https://github.com/user-attachments/assets/cf7c2370-322d-4a8a-be55-23e680db0aa0"
/>


Also, we've [previously
discussed](https://supabase.slack.com/archives/C0161K73J1J/p1771544464850199?thread_ts=1771493920.775699&cid=C0161K73J1J)
that reasoning adds unnecessary latency to otherwise simple AI
completion endpoints like `title-v2`. We want more control of reasoning
level independent of model/endpoint.

This PR aims to solve both problems by:
- making reasoning effort configurable on a per-request basis
- adding compile-time guardrails to prevent selecting an incompatible
reasoning level for models
- adding a `DEFAULT_COMPLETION_MODEL` with minimal reasoning that we can
update with newer models that support disabling reasoning (independent
of Assistant chat model reasoning)

Other improvements to our model config logic:
- Fixes bug in `onboarding/design.ts` and `assistant.eval.ts` where
`providerOptions` was being dropped
- `getModel()` now returns a bundled `modelParams` object (spread into
AI SDK calls) so `providerOptions` can't be accidentally omitted (this
[has happened
before](https://supabase.slack.com/archives/C0161K73J1J/p1771518443534309?thread_ts=1771493920.775699&cid=C0161K73J1J))
- Introduces an `ASSISTANT_MODELS` registry as a single source of truth
for assistant model config, eliminating hardcoded model IDs across the
codebase
- Aligns free/pro model conditional logic with `assistant.advance_model`
entitlement naming conventions instead of the `isLimited` pattern
- Adds `console.error` logging of Assistant stream errors so we can
interpret reasoning effort compatibility errors in the future (instead
of just opaque "Sorry, I'm having trouble responding right now" card)
- Removes unnecessary type casts and generally making the model config
logic stricter
- Removes pre-existing dead code: `anthropic` provider variant in
`GetModelParams` / `PROVIDERS` registry that was never implemented in
`getModel()`

Now if you try to select an unsupported reasoning level you get a type
error:

<img width="1306" height="320" alt="CleanShot 2026-03-20 at 14 37 24@2x"
src="https://github.com/user-attachments/assets/a6ac234b-5ea5-4d81-8e01-ac4be34a0800"
/>

And if for some reason an invalid reasoning level slips through, you now
get a server-side error surfacing the issue:

<img width="1268" height="204" alt="CleanShot 2026-03-20 at 14 58 14@2x"
src="https://github.com/user-attachments/assets/aadc1b7a-9495-475f-9741-39979bd27cd7"
/>

I've tested gpt-5 and gpt-5-mini are still working on the staging
preview and verified the models were selected properly in Braintrust
logs. Both models are available on my Pro test account, and my Free test
account shows the Pro upgrade CTA.


Closes AI-446
Closes AI-551
2026-03-25 11:29:23 -04:00
Ali Waseem aa12ae790a fix: flatten AI generation schema for filters (#44092)
## 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?

OpenAI claims to support recursive schemas with $defs/$ref, but in
practice it's unreliable. When Zod's z.lazy() is converted to JSON
Schema, it produces recursive $ref entries that OpenAI's structured
output frequently rejects with errors like "Recursive reference
detected" or "Invalid schema for response_format".

Simplify the AI generation schema since we only support AND and don't
need the recursion because we don't support nesting of groups.
2026-03-24 07:38:40 -06:00
Joshen Lim 98b1b79909 Chore/shift manual queries into pg meta 04 (#43956)
## Context

Shifts all remaining dashboard queries into pg-meta so that we
centralize all manually written queries in one place
Having them in packages/pg-meta also allows us to write tests for them

## To test

Just needs a smoke test on
- Role Impersonation
- Lints
- Data API
- Database
  - Enumerated Types
- Integrations
  - Foreign Data Wrappers
  - Vault
2026-03-24 16:23:13 +08:00
Matt Rossman d29fbf6eb7 feat(assistant): upgrade AI SDK v5 → v6 (#43931)
Upgrades `ai` from v5 to v6 and all related packages.

**Package bumps:**
- `ai`: `5.0.52` → `^6.0.116`
- `@ai-sdk/openai`: `2.0.32` → `^3.0.41`
- `@ai-sdk/react`: `2.0.52` → `^3.0.118`
- `@ai-sdk/provider`: `^2.0.0` → `^3.0.8`
- `@ai-sdk/provider-utils`: `^3.0.0` → `^4.0.19`
- `@ai-sdk/amazon-bedrock`: `^3.0.0` → `^4.0.81`
- `@ai-sdk/mcp`: N/A → `^1.0.25`
- `openai`: bumped to `^4.104.0`
- `braintrust`: `3.0.x` → `^3.4.0`

**Breaking change migrations:**
- `generateObject` removed in v6 — migrated 5 API routes to
`generateText` with `Output.object({ schema })`, returning
`result.output`
- `convertToModelMessages` is now async — added `await`
- MCP import path changed: `experimental_createMCPClient` from `ai` →
`createMCPClient` from `@ai-sdk/mcp`
- `openai()` defaults to Responses API — added `store: false` to
provider options for ZDR org compatibility

**Streaming fix:**
Added `Content-Encoding: none` header to `pipeUIMessageStreamToResponse`
calls. Without it, proxy middleware buffers the entire SSE response
before flushing, causing the full reply to appear at once.

**Zero Data Retention fix:**
In recent AI SDK versions, `openai()` default to Responses API instead
of the legacy chat completions API. This produces a 404 from OpenAI with
message `"Items are not persisted for Zero Data Retention organizations.
Remove this item from your input and try again."` The Responses API is
OpenAI's [recommended
endpoint](https://developers.openai.com/api/docs/guides/migrate-to-responses).

This PR adds `store: false` as mentioned in
https://github.com/vercel/ai/issues/10060 to avoid incompatible
persistence attempts.

**References:**
- https://ai-sdk.dev/docs/migration-guides/migration-guide-6-0
-
https://ai-sdk.dev/docs/troubleshooting/streaming-not-working-when-proxied
- https://github.com/vercel/ai/issues/10060

Closes AI-514
Related AI-509
2026-03-19 09:07:33 -04:00
Charis fe0da16820 refactor: move /incident-banner to app router (#43930)
## 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?

Refactor

## What is the current behavior?

The `/incident-banner` endpoint is implemented using the Pages Router.

## What is the new behavior?

The `/incident-banner` endpoint is moved to the App Router, enabling
caching of the upstream fetch. This does not turn on the querying from
the frontend yet, making that a separate PR so we can revert easily if
needed.

## Additional context
2026-03-19 09:26:21 +01:00
Charis a4641d0b9f refactor: move /incident-status to app router (#43881)
## 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?

Refactor

## What is the current behavior?

`/incident-status` is handled via Pages Router.

## What is the new behavior?

`/incident-status` is handled via App Router, enabling use of Vercel
Data Cache to cache the upstream fetch.

## Additional context

Adding the first App Router route handler triggered `next typegen` (run
as `pretypecheck`) to generate `.next/dev/types/validator.ts`, which
imports all route files and expanded the type-checked graph. This
surfaced pre-existing `null`-safety errors in:

- `components/grid/SupabaseGrid.utils.ts` — `useSearchParams()` result
- `components/layouts/ProjectLayout/UpgradingState/index.tsx` —
`useSearchParams()` result
- `pages/project/[ref]/sql/quickstarts.tsx` — `useParams()` result
- `pages/project/[ref]/sql/templates.tsx` — `useParams()` result

These are fixed with optional chaining. The `tsconfig.json` change
(adding `.next/dev/types/**/*.ts` to `include`) is auto-generated by
Next.js and committed as correct behavior.
2026-03-18 09:36:19 +01:00
Etienne Stalmans b79a645f4f fix: escape regex control character (#43806)
## 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?

Bug fix

## What is the current behavior?

regex control character, `.` is not escaped.

## What is the new behavior?

Escapes control characters and makes regex a little stricter. Use regex
literal
2026-03-17 16:28:38 +01:00
Pedro Rodrigues 62426253c3 fix: pass exposedSchemas to getLints in MCP advisor operations (#43790)
## Summary

- MCP `getSecurityAdvisors` and `getPerformanceAdvisors` now pass
`exposedSchemas` to `getLints`, fixing empty advisor results in
local/self-hosted environments
- Extracts `DEFAULT_EXPOSED_SCHEMAS` constant shared between the MCP
handler and the `run-lints` API route (cc @joshenlim related
https://github.com/supabase/supabase/pull/40043)
- Adds unit tests for `enrichLintsQuery` and the MCP advisor operations

## The bug

The MCP advisor tools (`get_advisors`) return empty arrays (`[]`) for
**all** scenarios when running locally via `supabase start`. No security
or performance advisors are surfaced, even when the database has clear
issues (e.g., tables with no RLS).

### Root cause

In `lib/api/self-hosted/mcp.ts`, both `getSecurityAdvisors` and
`getPerformanceAdvisors` call `getLints({ headers })` **without passing
`exposedSchemas`**:

```typescript
// Before (mcp.ts:131)
const { data, error } = await getLints({ headers })
```

When `exposedSchemas` is `undefined`, `enrichLintsQuery` in `lints.ts`
skips the `SET LOCAL pgrst.db_schemas = '...'` SQL statement:

```typescript
// lints.ts:23
${!!exposedSchemas ? `set local pgrst.db_schemas = '${exposedSchemas}';` : ''}
```

Without this GUC being set, the splinter SQL queries filter results
using `current_setting('pgrst.db_schemas', 't')` — which returns an
empty string in local environments. Every schema-filtered lint matches
no schemas and returns zero rows.

### Why this only affects local/self-hosted environments

In **hosted Supabase**, PostgREST sets the `pgrst.db_schemas` GUC on its
own database connections based on the project's API configuration. The
Studio MCP server in production reads the same project configuration, so
the GUC is already available.

**Locally**, PostgREST runs in a separate Docker container and only sets
this GUC on _its own_ connections. Studio connects directly to
PostgreSQL (bypassing PostgREST), so
`current_setting('pgrst.db_schemas', 't')` returns `''`.

The HTTP API endpoint (`/api/platform/.../run-lints`) already worked
because `run-lints.ts` passes `exposedSchemas: 'public, storage'` — this
parameter was simply never added to the MCP code path.

## How we verified the fix

### 1. Tests written to fail against the previous code

We wrote two test files that target the exact bug:

**`tests/unit/lints/enrichLintsQuery.test.ts`** — validates the SQL
generation:
- Confirms `SET LOCAL pgrst.db_schemas` is included when
`exposedSchemas` is provided
- Confirms it's omitted when `undefined` or empty (documenting current
behavior)

**`tests/unit/lints/mcp-advisors.test.ts`** — validates the MCP
operations:
- Asserts `getSecurityAdvisors` passes `exposedSchemas` to `getLints`
- Asserts `getPerformanceAdvisors` passes `exposedSchemas` to `getLints`
- Asserts the value matches `DEFAULT_EXPOSED_SCHEMAS`
- Verifies SECURITY/PERFORMANCE category filtering still works

Before the fix, the two `exposedSchemas` assertions failed:

```
FAIL  getSecurityAdvisors should pass exposedSchemas to getLints
  → expected { Object (headers) } to have property "exposedSchemas"

FAIL  getPerformanceAdvisors should pass exposedSchemas to getLints
  → expected { Object (headers) } to have property "exposedSchemas"
```

### 2. Fix applied, all tests pass

After adding `exposedSchemas: DEFAULT_EXPOSED_SCHEMAS` to both MCP
operations, all 14 tests pass (9 new + 5 existing MCP tests).

## Test plan

run `supabase start`, create a table without RLS, call `get_advisors`
via MCP — should return `rls_disabled_in_public` lint

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 09:48:34 +00:00
Joshen Lim 7d1b38f804 Float up error code from status page into incident-status endpoint (#43737)
## Context

Just a nit change to float the status code from status page API into
incident-status endpoint so its clearer what the error is from the
network tab

---------

Co-authored-by: Charis Lam <26616127+charislam@users.noreply.github.com>
2026-03-17 09:55:39 +08:00
Chris Stavitsky e217f747bd feat(studio) instrument sentry on table creation flow (#43673)
(working with @charislam @awaseem on this one)

## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

Per
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md):
-  `pnpm --filter studio build`
-  `pnpm test:prettier`
-  `pnpm format`

## What kind of change does this PR introduce?

Instruments `studio` app's table creation flow with Sentry.

## What is the current behavior?

The table creation flow isn't instrumented in detail, which means we
have less visibility into understanding performance problems or errors
within this specific flow.

## What is the new behavior?

The table creation flow is instrumented in detail. This instrumentation
allows for Sentry dashboards like this one (created based on locally
generated Supabase data), to help monitor anything going wrong with this
critical flow:

<img width="1915" height="1131" alt="image"
src="https://github.com/user-attachments/assets/e2c5380e-7b00-41c1-9109-3ee4e47ff63b"
/>

---------

Co-authored-by: Ali Waseem <waseema393@gmail.com>
2026-03-16 09:57:43 -06:00
Ivan Vasilov c5b6695380 fix: Remove auth from /incident-status and /incident-banner endpoints (#43751) 2026-03-13 15:29:54 +01:00
Charis befc817f94 feat: version who-knows-what of incident banner (#43726)
Feature

## What is the current behavior?

Incident banner logic depends on StatusPage and Supabase project for
metadata.

## What is the new behavior?

New incident banner logic that depends only on incident.io. Displays in
non-production environments for now because I haven't wired up the rest
of the workflow. This is just to allow a total end-to-end
testing/playground for test incidents <-> Slack <-> preview dashboard
for people to try out the UX.

## Additional context

You can test using my [test
incident](https://app.incident.io/supabase/incidents/405). This has
severity minor, so the preview site should have a banner. Toggle to
informative, hard refresh dashboard with cache off, and banner should
disappear. Toggle back to minor, hard refresh without cache again, and
banner should reappear. Same thing if you edit the "Banner shown" field
from 1 to -1 and back.
2026-03-12 16:55:53 -04:00
Charis 5a01291c23 feat(studio): smart incident banner targeting (#43112)
Feature enhancement — smarter incident banner targeting logic

## What is the current behavior?

Displaying the incident banner requires toggling a flag or environment
variable. Banners are shown to all users regardless of whether their
projects are in affected regions or whether the incident affects project
creation.

## What is the new behavior?

Banner visibility is now driven by `show_banner` metadata from the
StatusPage API — no manual flag or env var toggle needed. Per-user
targeting is then applied:
- Users with projects only see the banner when they have a database in
an affected region
- Users without projects only see the banner when the incident affects
project creation

Incident responses are enriched with cache data (`affected_regions`,
`affects_project_creation`) fetched from a Supabase table. Visibility
logic is extracted into a dedicated hook and pure utility function,
backed by unit tests.

## Additional context

Resolves FE-2562
2026-02-25 17:18:33 +00:00
Matt Rossman e8ab92408f feat(assistant): enable Braintrust tracing for non-sensitive chats (#42963)
Enables Braintrust tracing for AI Assistant chats to support debugging
and future online evals.

**Code Changes**

- Wraps `generateAssistantResponse` in a Braintrust `traced()` span,
logging the user's latest message as input along with metadata
(`chatId`, `chatName`, `projectRef`, `userId`, `orgId`, `planId`, etc.)
- Threads JWT claims from `apiWrapper` → handler to log `userId` in
Braintrust without an extra API call (+ expanded `apiWrapper` tests)
- Threads `orgId` and `planId` from `getOrgAIDetails` to log in
Braintrust

**Infrastructure Changes**

- Created a "Vercel" service account in Braintrust
- Added `BRAINTRUST_API_KEY` and `BRAINTRUST_PROJECT_ID` env vars to the
studio-staging project in Vercel using a service token for the above
service account
- Added an "Overview" view to the Logs tab in the Braintrust Assistant
project to surface the new metadata

**Precautions**

- HIPAA sensitive projects are excluded from logging (see
https://github.com/supabase/supabase/pull/42787 for the detection logic)
- Production is temporarily excluded from logging until we're confident
in the setup

**Testing steps**

- Chat with the AI Assistant in the [studio-staging preview
build](https://github.com/supabase/supabase/pull/42963#issuecomment-3917178023)
below
- Visit the [Logs tab in the Braintrust Assistant
project](https://www.braintrust.dev/app/supabase.io/p/Assistant/logs)
and inspect the trace

<img width="4680" height="962" alt="CleanShot 2026-02-18 at 17 43 55@2x"
src="https://github.com/user-attachments/assets/c3a11b21-4e7f-4e90-bdab-a25ab8ee0d1f"
/>

<img width="2632" height="1288" alt="CleanShot 2026-02-18 at 17 45
04@2x"
src="https://github.com/user-attachments/assets/6c7b6ebc-5090-4ede-8f71-859ff7e386aa"
/>

**References**
- https://www.braintrust.dev/docs/integrations/sdk-integrations/vercel
- https://www.braintrust.dev/docs/instrument/custom-tracing

Closes AI-438
2026-02-19 11:43:47 -05:00
Kalleby Santos 70510acf5b feat(studio-local): functions management api - test functions (#42350)
Feature

## What is the current behavior?

Functions page on self-hosted differs from Platform

## What is the new behavior?

Adds the possibility to try/test functions in Self-Host version.

## Summary by CodeRabbit

* **Bug Fixes**
* Improved edge function URL validation so testing works reliably both
on-platform and off-platform, including proper URL handling for local
setups.

* **UI Improvements**
* Moved the Test button in the edge functions interface for more
consistent layout while preserving its behavior.

* **Tests**
  * Expanded tests to cover platform-aware URL validation scenarios.

---------

Co-authored-by: Charis Lam <26616127+charislam@users.noreply.github.com>
2026-02-11 21:26:42 +00:00
Jordi Enric ac64a902c1 chore: adds tests (#42653) 2026-02-11 09:50:11 +01:00
Kalleby Santos 997203cd64 feat(studio-local): functions management api - function blob artifacts (#42349)
## What kind of change does this PR introduce?

Feature

## What is the current behavior?

Functions page on self-hosted differs from Platform

## What is the new behavior?

> [!NOTE]  
> This PR only add readonly operations. Function edit and deploy should
be implemented in a future one.

Adds the possibility to download and see function code in Self-Host
version.

<details>

<img width="1465" height="944" alt="image"
src="https://github.com/user-attachments/assets/4bbf8f5c-3390-4de6-9e8b-8ec9cd59ebad"
/>

</details>

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* API endpoint to stream function files/artifacts as
multipart/form-data.
* New function file entry type and server-side file listing for
functions.

* **Improvements**
  * Edge Functions "Code" navigation item always visible.
* Download popover reworked: ZIP download always available; CLI section
shown only on supported platforms.
* Editor set to read-only and file actions disabled on unsupported
environments.

* **Editor**
* Added JavaScript, TypeScript, and Markdown language modules for the
embedded editor.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Charis Lam <26616127+charislam@users.noreply.github.com>
2026-02-06 20:06:37 +00:00
Kalleby Santos 8c3655cd71 feat(studio-local): functions management api - function details (#42322)
Functions page on self-hosted differs from Platform Adds the possibility to see function details page in Self-Host version.

## Summary by CodeRabbit

* **New Features**
* Edge function detail lookup added for self‑hosted deployments (new
retrieval endpoint & store method).
  * Consistent navigation to function pages from the functions list.

* **Improvements**
  * UI tabs, download, and test controls adapt to deployment type.
* Region, JWT verification, local development, and delete controls shown
only on the platform.
* Edit/save/delete controls enable/disable correctly based on deployment
and permissions.
  * Function details load reliably across deployments.
2026-01-30 21:14:28 +00:00
Kalleby Santos 1862b71745 feat(studio-local): functions management api - list functions (#40690)
## What is the current behaviour?

Functions page on self-hosted differs from Platform

## What is the new behaviour?

Adds the possibility to see a list of edge-functions in Self-Host
version.

## Summary by CodeRabbit

* **New Features**
* Added self-hosted edge functions support with filesystem-based
artifact listing and a new API endpoint to list local functions.
* Improved functions UI: unified view, enhanced search and adjacent sort
controls, and clearer local-hosting guidance.

* **Chores**
* Added environment configuration and docker volume for edge functions
management.
* Updated build/task config to pass through edge functions env and
include contentlayer outputs.

Co-authored-by: Ali Waseem <waseema393@gmail.com>
Co-authored-by: Charis Lam <26616127+charislam@users.noreply.github.com>
Co-authored-by: Terry Sutton <saltcod@gmail.com>
2026-01-30 08:00:21 +08:00
Danny White 05dc676d36 feat(studio): incident-aware AI assistant (#41603)
* handling and mock data support

* admonition

* only show in empty state

* rabbit

* mock without local overrides

* remove admonition

* make incident banner more prominent

* remove mock data

* move to tool

* prettier

* fix(studio): get_active_incidents tool

---------

Co-authored-by: Charis Lam <26616127+charislam@users.noreply.github.com>
2026-01-21 13:52:29 +11:00
Ali Waseem 75af928495 feat: added new rules for splinter updates (#41719)
* added new rules for splinter updates

* Use Markdown instead of ReactMarkdown

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-01-06 16:09:54 +00:00
Saxon Fletcher d2f4e808e5 Filter pattern refactor (#41545)
* filter refactor

* update tests

* prettier

* fix ts

* remove filter preview

* Filter bar in table editor behind flag (#41546)

filter bar in table editor behind flag

* fixes

* ts fix

* filter v1 refactor

* rename helpers

* unmount timeout

* fixes

* fix

* more
2026-01-06 08:04:28 +10:00
Ivan Vasilov f3af2c3d3c feat: SQL Snippets (#41112)
* Use the .sql suffix when generating ids.

* Fix a bug where a new snippet would not show up in the snippet list until refresh.

* Add API routes which serve file snippets.

* Refactor the renameSnippet and moveSnippet to work with file snippets.

* Change the link to the SQL Editor.

* Minor fixes from CodeRabbit.

* Check the file/folder name for invalid chars.

* More fixes from CodeRabbit review.

* Fix minor issues.

* Use zod to parse the snippet ids when deleting.

* Try to fix snyk issue.

* Add validation to the GET content index route.

* Minor fixes.

* Show create a new folder, it was hidden by mistake.

* Add SNIPPETS_MANAGEMENT_FOLDER env var.

* Add snippets folder in the docker-compose.

* Add error toasts if the env var is not set.

* Add snippets management folder to the generateLocalEnv script.

* Revert the docker-compose changes, will be done in a followup PR.

* Revert also the snippets volume folder.

* Remove unneeded line.
2025-12-23 12:09:37 +01:00
Matt Rossman 072883bcec feat: assistant evals (#41311)
* chore: bump `supabase` CLI

* chore: stricter message types in `generate-v4.ts`

* feat: tutorial eval

https://www.braintrust.dev/docs/evaluation

* feat: project ID for eval

* refactor: `generateAssistantResponse` out of `handlePost`

* refactor: generateAssistantResponse to lib/ai

* feat: factuality eval with assistant response

* chore: upgrade braintrust to v1.0.1

* chore: silence tsconfig warning

* feat: assertion scorer

* fix: aggregate tools across all steps

* refactor: strict tool names, remove need for `as const`

* refactor: generic tool name type in assertions

* feat: transfer mocks from `feature/braintrust`

* feat: LLM criteria assertion

* feat: braintrust evals workflow

* fix: BRAINTRUST_PROJECT_ID

* feat: `sql_similar` assertion

* fix: `OPENAI_API_KEY` in workflow env

* feat: split AssertionScorer into separate scorers

* feat: remove tutorial eval

* feat: 20 minute CI timeout

* feat: category in test case metadata

* feat: score with gpt-5

* refactor: dataset to own file, colocate scorers

* feat: "gpt-5.2-2025-12-11" for llm as a judge

* feat: SQL syntax scorer with `libpg-query`

* feat: `evals:setup` and `evals:run` scripts

* feat: `evals:setup` in CI

* feat: human readable scorer names

* chore: rename to "SQL Validity"

* feat: add 2 "sql_generation" test cases

* feat: update requiredTools in test cases

* chore: ignore Cursor MCP config

* feat: "Conciseness" score

* feat: "Completeness" scorer

* fix: generate-v4 test mocks

* feat: serialize "steps" for scorer inputs

* updated node mem options for typecheck

* updated runner

* remove ram update as actions handle this

* feat: read `BRAINTRUST_PROJECT_ID` from secrets

* feat: score helpfulness, remove old scorers

* feat: separate `evals:run` and `evals:upload` scripts

* feat: passthrough entire classifier result

* feat: use live `search_docs` impl, store docs result in metadata

* feat: reduce classifier options

* feat: filter workflow by `run-evals` PR label or `master` branch

* chore: cleanup stubbed mock tools

* fix: checkout actual branch with `ref:`

* fix: capture search_docs results from all content parts

* feat: simplify sql syntax score calculation

* feat: use AI SDK's UI message validator

* docs: justification for relative `extends`

* fix: cleanup leftover validatedMessages

* doc: note mock token isn't secret for snyk

* fix: mock ui message to pass validation

* feat: revert ignoring Cursor MCP config

Using `.git/info/exclude` instead until we have an opinion on this

* feat: add "tsconfig" as shared-data devDependency, revert relative path in tsconfig

* refactor: tool call parsing into function

* Update apps/studio/evals/assistant.eval.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* refactor: organize mock schemas and tool factories

---------

Co-authored-by: Ali Waseem <waseema393@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-12-22 23:45:48 -05:00
Danny White f0acececce feat(studio): incident notice on support ticket creation (#41379)
* callout

* progress

* plural issues

* better handle multiple issues

* refactor

* remove fancy copywriting

* return IncidentAdmonition to support form page

* progress

* cleanup

* rabbit

Potential control flow issue: execution continues after handleError when data is undefined. When a non-401 error occurs, handleError(error) is called but execution continues to line 24 where data is accessed. If handleError doesn't throw, this will cause a runtime error accessing (data as any).is_healthy on undefined. Additionally, the as any cast on line 24 violates the coding guidelines. Consider validating the response shape instead.

* animate in

* fix

* reset

* remove unused dayjs

* rabbit

* rabbit

* fixes from code review

* rabbit

* rabbit

---------

Co-authored-by: Charis Lam <26616127+charislam@users.noreply.github.com>
2025-12-19 00:28:02 +00:00
Ivan Vasilov 5fb5acc0b9 chore: Refactor the generation of ids for snippets (#41264)
* Add a generateDeterministicUuid function and tests for it.

* Use the new function and generate an id automatically when creating a snippet.

* Clean up extra code.

* Don't pass in id when creating a snippet.

* Add generateSnippetTitle function and use it instead of fixed string.

* When SQL editor is open, generate an id form a generated snippet title.

* Add id override for SQL editor to avoid flash when saving the snippet.

* Merge the two generate functions to happen in the same useMemo block.

* Save the snippet to the API when adding it.

* Minor fixes from CodeRabbit review.

* Hide new folder CTA in sql editor for self-hosted

* Don't add the snippet for saving, just set the value.

* UpsertContentPayload always has an id.

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2025-12-16 09:43:59 +01:00
Charis 657ca2d97c feat(studio): endpoint to retrieve incident status (#41355)
Incident status banners/alerts should be automatically determined from
the status page, rather than being manually configured.

Adds a new endpoint, /api/incident-status, to return information about
active incidents. This information is fetched from the StatusPage API.
The endpoint is cached to reduce number of third-party API requests.

Co-authored-by: Ali Waseem <waseema393@gmail.com>
2025-12-15 22:42:37 +00:00
Pedro Rodrigues 9d12f0bc86 chore: bump mcp version to 0.5.9 (#41052)
chore: bump MCP server to 0.5.9 and utils to 0.2.4
2025-12-09 16:31:34 +00:00
Joshen Lim 91209faab1 Remove unused old env var (#41178)
* Remove unused old env var

* Update apps/studio/lib/api/apiHelpers.ts

Co-authored-by: Alaister Young <alaister@users.noreply.github.com>

* Fix

* Add comment

---------

Co-authored-by: Alaister Young <alaister@users.noreply.github.com>
2025-12-09 13:22:10 +08:00
Joshen Lim 27200aa52a Patch lints (#40783) 2025-11-26 00:16:45 +08:00
Zach Gorton 9bf15f9675 fix(mcp): postgres-meta parameters binding for list_tables (#40499)
* add params to executeQuery

* revert env change

* chore: upgrade "supabase" to v2.58.5

---------

Co-authored-by: Matt Rossman <22670878+mattrossman@users.noreply.github.com>
Co-authored-by: Ali Waseem <waseema393@gmail.com>
2025-11-18 16:01:03 +00:00
Ali Waseem 23224301f2 updated to override pg vars (#40093)
Co-authored-by: Alaister Young <alaister@users.noreply.github.com>
2025-11-04 16:02:12 +08:00
Joshen Lim 0d44090aac Update lints for self-hosted (#40043)
* Update lints for self-hosted

* update comment

* Update apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx

Co-authored-by: Ali Waseem <waseema393@gmail.com>

* revert

* Fix

* update comment

---------

Co-authored-by: Ali Waseem <waseema393@gmail.com>
2025-11-01 01:28:05 +08:00
Joshen Lim 64e3e047eb Final final cleaning up barrel files (#40018)
* Final final cleaning up barrel files

* Fix merge conflict
2025-10-31 14:02:59 +08:00
Matt Rossman 9540428962 fix: supabase_admin user for self-hosted read/write queries (#39946) 2025-10-28 15:55:23 -04:00
Matt Rossman 9f5620c7cd feat: self-hosted MCP debugging tools (#39366)
* feat: stub `getDebuggingOperations`

* fix: logflare variables in `generateLocalEnv.js`

* chore: upgrade `supabase`, `@supabase/mcp-server-supabase`

* feat: shared `retrieveAnalyticsData`, implement `getLogs` for MCP

* feat: shared `getLints`, implement MCP security/performance advisors with filter

* chore: update lockfile

* fix: prefer `??`

Co-authored-by: Greg Richardson <greg.nmr@gmail.com>

* docs: comment origin of `LINT_SQL`

Co-authored-by: Greg Richardson <greg.nmr@gmail.com>

* chore: bump `supabase` devDependency for latest images

Changes rely on fix from loglare v1.23.0

* fix: edge function logs query

Based on https://github.com/supabase/supabase/pull/39388/files#diff-b4e9726d34a406fa1a6133a18bdb972c90be9df0c89598de0695592514e22941R199-R206

---------

Co-authored-by: Greg Richardson <greg.nmr@gmail.com>
2025-10-20 13:11:15 -04:00
Charis 4f0ce0a0e3 fix(support form): create api route to upload attachments (#39543)
* fix(support form): api route to create attachment urls

* clean: remove console log

* fix staging and prod

* Minor clean up

* Shift generation of urls to data folder

* refactor

* Final

* Fix tests

* Nit

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2025-10-15 16:29:35 +08:00
Alaister Young ec6c90bce2 fix: support nimbus project urls for testing edge functions (#39548) 2025-10-15 15:12:35 +08:00
Han Qiao e5bab8208e fix: set 24h format when converting postgres timestamp (#39494) 2025-10-14 00:42:30 +08:00
Kevin Grüneberg f0436716f9 perf: use getClaims for API endpoint auth (#39311)
Use getClaims instead of getUser which avoids a network call to GoTrue to validate the user in case of asymmetric keys - this shaves off a good amount of latency for every API call.
2025-10-08 09:59:27 +08:00
Saxon Fletcher d5bf4ef13b Rate assistant responses (#39224)
* rate assistant responses

* test

* always show
2025-10-06 22:46:30 +00:00
Matt Rossman 31b6368049 feat: read-only mode for self-hosted MCP (#39041)
* feat: add `crypto-js`, `encryptString` with sample key

* feat: include POSTGRES_PASSWORD in generated .env.test

* feat: include POSTGRES_PASSWORD in turbo.json for studio

* feat: read only query support

* feat: configurable `POSTGRES_HOST`, `POSTGRES_DB`, `POSTGRES_PORT`

* chore: rename POSTGRES_USER to clarify write permission

* feat: configurable `PG_META_CRYPTO_KEY`

* chore: add `PG_META_CRYPTO_KEY` to generateLocalEnv

* feat: add 'postgres-meta' to linter dictionary

* feat: restore read-only toggle in local MCP URL builder
2025-10-06 16:14:27 -04:00
Saxon Fletcher 626eb30e77 Assistant action orientated approach (#38806)
* update onboarding

* update model and fix part issue

* action orientated assistant

* fix tool

* lock

* remove unused filter

* fix tests

* fix again

* update package

* update container

* fix tests

* refactor(ai assistant): break out message markdown and profile picture

* wip

* refactor(ai assistant): break up message component

* refactor: break ai assistant message down into multiple files

* refactor: simplify ReportBlock state

* fix: styling of draggable report block header

When the drag handle is showing, it overlaps with the block header.
Decrease the opacity of the header so the handle can be seen and the two
can be distinguished.

* fix: minor tweaks to tool ui

* refactor: simplify DisplayBlockRenderer state

* fix: remove double deploy button in edge function block

When the confirm footer is shown, the deploy button on the top right should be
hidden (not just disabled) to avoid confusion.

* refactor, test: message sanitization by opt-in level

Refactor the message sanitization to have more type safety and be more testable.
Add tests to ensure:

- Message sanitization always runs on generate-v4
- Message sanitization correctly works by opt-in level

* Fix conflicts in pnpm lock

* Couple of nits and refactors

* Revert casing for report block snippet

* adjust sanitised prompt

* Fix tests

---------

Co-authored-by: Charis Lam <26616127+charislam@users.noreply.github.com>
Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2025-09-29 03:57:36 +00:00