mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
docs/tutorial-template
162
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
7e56800992 |
fix(assistant): update support assistant messaging for clarity and consistency (#54112)
## Problem The AI Assistant follow-up on support requests (behind the `supportAssistantFollowUp` flag) told users with service restrictions to ask Support for an exception. In almost every restriction ticket we reviewed during the production test, the Assistant suggested this, and Support then declined. ## Solution Rather than a rule for each ticket type, this adds one general rule to the server-side support-mode context and removes the "a human will reply" framing. `escalate_to_human` is unchanged, so users who ask for a person can still be escalated. ## Review instructions Read the diff to `assistant-context.ts` and `SupportAssistant.utils.ts`, and check that the rule is general and doesn't name a particular ticket type. ## Checklist Check all before review: - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [x] 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) |
||
|
|
0c97b9789b |
[FE-3107] chore(studio): remove remaining Next.js references (#54426)
Removes the remaining Next.js dependencies, compatibility shims, test
mocks, ESLint/TypeScript presets, and webpack/Next workarounds from
Studio following the TanStack Start migration.
Addresses FE-3107.
**Removed:**
- `next` and `next-router-mock` from `apps/studio/package.json` (and
updated `pnpm-lock.yaml`)
- Orphaned `apps/studio/compat/next/script.tsx` shim, `script.test.tsx`,
`compat/**` knip entry, and `nextCompat()` / `ssr.noExternal` `/^next/`
plumbing from `apps/studio/vite.config.ts`
- `apps/studio/tests/lib/route-mock.ts` and all `next-router-mock`
setup/imports across `tests/vitestSetup.ts`,
`tests/lib/custom-render.tsx`, and 12 test files
- `apps/studio/tests/pages/` directory (moved the 3 remaining tests to
`components/interfaces/Organization/Organization.utils.test.ts` and
`apps/studio/tests/routes/`)
- Unused `'use client'` directives across 23 Studio files
- Next.js/webpack workarounds: `graphiqlViteWorkers()` in
`vite.config.ts`, webpack `import.meta.glob` `try/catch` fallback in
`ConnectStepsSection.tsx`, shell `NODE_ENV=test` override in
`vite.config.ts` / root `package.json` / `studio-e2e-test.yml`, Next
`getPathMatch` and `_next` passthrough in `redirects.shared.*`,
`window.next?.router` check in `monaco-graphiql-coexistence.spec.ts`,
and unused `ANALYZE` env var in `apps/studio/turbo.jsonc`
- Next-only Sentry/chunk-load filters (`NEXT_NOT_FOUND`,
`NEXT_REDIRECT`, Next `/org/[slug]/` regex, `/app:\/\//`, dead
`includeThirdPartyErrorFilter` plumbing, webpack chunk error regex) and
stale Next/Pages Router comments, docs, and `#__next` CSS selector
**Changed:**
- `apps/studio/eslint.config.cjs`: switched from
`eslint-config-supabase/next` to the new `eslint-config-supabase/react`
preset (dropping `@next/next/no-img-element: off`, keeping `.next` /
`next-env.d.ts` ignored for local checkouts with stale pre-migration
build artifacts)
- `apps/studio/tsconfig.json`: extends `tsconfig/base.json` directly
instead of `tsconfig/nextjs.json` (identical resolved compiler options)
- `apps/studio/.github/eslint-rule-baselines.json`: pruned 33 stale
`pages/...` and `types/next.ts` entries without changing any rule
thresholds
- `apps/studio/tests/lib/custom-render.tsx`: backed
`TestFrameworkProvider` with TanStack Router instead of
`next-router-mock`
-
`apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx`:
imports `graphiql/setup-workers/vite` directly
- `apps/studio/styles/globals.css`: replaced `@source
'../pages/**/*.{js,ts,jsx,tsx}'` with `@source
'../routes/**/*.{js,ts,jsx,tsx}'`
- `apps/studio/turbo.jsonc`: declared `"NEXT_PUBLIC_*"` in
`tasks.build.env` now that Turborepo infers `nitro` instead of `nextjs`
-
`apps/studio/components/interfaces/Organization/Organization.utils.ts`:
narrowed `buildOrgUrl`'s `slug` parameter to `string[] | undefined`
**Added:**
- `packages/eslint-config-supabase/shared.js` and
`packages/eslint-config-supabase/react.js` (plus `presets.test.ts`),
decoupling non-Next React apps from `eslint-config-next` with verified
zero non-`@next/*` rule drift while keeping
`eslint-config-supabase/next` unchanged for the Next.js apps
## To test
- Run `pnpm --filter eslint-config-supabase run test` and confirm preset
parity tests pass
- Run `pnpm --filter studio run lint`, `pnpm --filter studio run
lint:ratchet`, `pnpm --filter studio run typecheck`, `pnpm knip
--workspace apps/studio`, and `pnpm --filter studio run test`
- Run `pnpm --filter studio run build` and verify the production build,
prerendered routes, chunk-cycle check, and GraphiQL web workers succeed
- Smoke-test Studio locally (`pnpm dev:studio`): verify GraphiQL loads
cleanly, ConnectSheet framework steps render, and Tailwind styles on
route pages are intact
---------
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> |
||
|
|
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 |
||
|
|
afe5b4ed58 |
fix(studio): remove Braintrust tool output masking workaround (#53244)
Removes the temporary `TODO:` tool output masking introduced in https://github.com/supabase/supabase/pull/52106 now that [Braintrust 3.40.0](https://github.com/braintrustdata/braintrust-sdk-javascript/releases/tag/braintrust%403.40.0) logs `toModelOutput` in tool spans and parent span results. SQL error redaction remains in place. Verified locally at the `schema` opt-in level by running the Assistant against a development project. The Braintrust traces for [SQL rows](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=2bca625a69c40d34ee41289acc073ea5&sid=a6304c155ecf7eed), [SQL error](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=b6f0581cbd273c7cd1d70bb6713877d8&sid=43fbbf283faa0da9), and [notebook results](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=05409f3af4e66131efa768a03bb8a67f&sid=321520afdd3fa7af) omit the sample rows and errors shown in Studio. | Studio | Braintrust | | --- | --- | | <a href="https://github.com/user-attachments/assets/dbf43dda-c78e-4782-acf7-951d8920a283"><img src="https://github.com/user-attachments/assets/dbf43dda-c78e-4782-acf7-951d8920a283" width="350" alt="Notebook results at limited sharing"></a> | <a href="https://github.com/user-attachments/assets/4ff513ae-c76c-47ad-ba1f-0dbc8bcfeee7"><img src="https://github.com/user-attachments/assets/4ff513ae-c76c-47ad-ba1f-0dbc8bcfeee7" width="350" alt="Braintrust notebook output with redacted results"></a> | Closes AI-1374 |
||
|
|
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> |
||
|
|
c0e92057a6 |
feat(studio): split SQL errors into user and Studio SQL (#53059)
Part of FE-4772. ## Why Errors from the pg-meta query endpoint didn't say who wrote the SQL, so a Sentry issue like SUPABASE-APP-KXE couldn't tell a user's query from one Studio composed. That event came from the assistant's `execute_sql` tool and was captured by the Vercel AI integration on the server, so it skipped `reportStudioError` and had no fault tags. The Postgres message also went to Sentry as-is, and it can contain user SQL and data. ## What - **`sqlOrigin` is required on `executeSql`.** `'user'` covers SQL the user or an AI agent wrote, in whole or in part: SQL editor, editor panel, Explorer, AI `execute_sql` and `run_notebook`, report blocks, Query Insights EXPLAIN, the policy, function, and cron editors, and running a stored cron job. Everything else is `'studio'`. The policy, function, and cron mutation hooks and `useDbQuery` take `sqlOrigin` too. - **`classifySqlResponseError`** turns a 400 from the query endpoint into `UserSqlError` (`user`, `user_sql`) or `StudioSqlError` (`studio`, `studio_sql`). Pattern rules (connection timeouts) and other statuses keep their classes. - **`UserSqlError` never reaches Sentry.** Its routing is `SAMPLE_NEVER`, `alwaysCapture` doesn't override it, and `beforeSend` drops it. - **`StudioSqlError` is redacted.** Error classes can set `sentryMessage`; for `StudioSqlError` it is the SQLSTATE and the query's `queryName`, a static name that `executeSql` requires for Studio SQL. The query key is never reported, since its segments can hold IDs, schemas, and search terms. `applyStudioErrorPolicy` applies it from `beforeSend` on the client and the server, so it holds however the error was captured. The server config gets a `beforeSend` for this. Events get `query_name` and `sql_state` tags and are grouped by both, since every SQL error shares the `executeSql` stack. - **A custom `handleError` gets the classified error**, matching its declared type. The SQL editor, editor panel, and policy editor rethrow it, so their errors are now `UserSqlError` instead of being reported as `UnexpectedError`. The error keeps Postgres's `position` for the editor's line highlight. The error message, `formattedError`, and `position` stay on the error for the UI. The query-performance Sentry context no longer carries the raw error message, which bypassed redaction. ## Known gaps - Index advisor queries run users' query text from `pg_stat_statements` but are marked `'studio'`. Redaction keeps the text out of Sentry, but their failures count as Studio faults. - 5xx responses for user SQL are still `PlatformError` and keep their message. - The self-hosted MCP `executeSql` calls `executeQuery` directly and isn't covered. ## Testing - Unit tests for `classifySqlResponseError`, `applyStudioErrorPolicy`, and the client `beforeSend`. - Full Studio vitest suite passes except `useReportDateRange.test.ts` (169 vs 168 hourly buckets across the DST change), which this PR doesn't touch. |
||
|
|
a05e7ec1d7 |
refactor(studio): move self-hosted Assistant tools to contracts (#52468)
Stacked on supabase/supabase#52422. ## What The self-hosted Assistant tools become contracts, so every tool the Assistant can call now comes from the registry and the allowlist is derived from it. * The fallback tools (`getSchemaTables`, `getRlsKnowledge`, `getFunctions`, `getEdgeFunctionKnowledge`) are deleted. Self-hosted now gets the shared tools plus: * `list_tables`: a local contract with the same input as the MCP tool and a similar output, built from pg-meta. It shares its prompt guidance with the remote contract, which moves to `list-tables.remote.ts`. On platform the remote contract is still used. * `list_functions`: self-hosted only, filtered by schema in SQL. * `list_policies`: now available in both environments. * `runPgMetaQuery` (`tool-sql.server.ts`) runs pg-meta-built SQL and validates the rows with the builder's zod schema. Off platform it calls `executeQuery` directly, because the default fetcher goes through a relative API URL that doesn't resolve server-side. * The allowlist comes from the registry: * `ToolName` and the tool set validation schema are built from the contract keys. The tool category map is removed. * `mcp-tools.ts` keeps only tools with a remote contract, before opt-in filtering, so `UI_EXECUTED_TOOLS` is gone. `EXPECTED_MCP_TOOLS` is derived from the contracts and type-checked against the MCP package. * Saved chats: the legacy contracts now trim replayed outputs. `getRlsKnowledge` replays only the saved policy list, without the stale RLS instructions. `getEdgeFunctionKnowledge` replays a pointer to `load_knowledge`. * The logs reference text no longer names `query_logs`. ## Behavior changes * `list_policies` on platform validates rows before formatting, so a row that fails pg-meta's schema now errors the tool call instead of returning text. * `list_tables` on self-hosted doesn't include the MCP tool's optional `advisory` field. * `list_functions` with an empty `schemas` list returns every non-system schema. * On platform, if the MCP tools fail to load, `list_tables` is dropped from the tool set like the other remote tools. ## Tests * Unit tests for `runPgMetaQuery`, the local `list_tables` and `list_functions`, and the output mapping. The SQL boundary is mocked; not yet run against a live self-hosted database. * Legacy contract tests cover trimming, the empty and missing policy cases, and that replaying an already-trimmed output leaves it unchanged. ## Checklist Check all before review: - [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>) |
||
|
|
6aefa45d2b |
refactor(studio): build the Assistant tool prompt from contracts (#52422)
Stacked on supabase/supabase#52398. ## What The chat system prompt's tool guidance now comes from the contracts available to the request, so the prompt never names a tool the request doesn't have. * `ToolContract` and `RemoteToolContract` gain an optional `promptGuidance`: rules for using the tool that its description doesn't cover. * `buildToolsPrompt` generates a `## Tools` section: every available tool by name, sorted, plus a section with the guidance of each tool that has any. Tool descriptions aren't repeated, since the model already gets them in the tool definitions. * `getToolRequest` computes the environment and satisfied requirements once, for both `getTools` and the prompt. * `buildSystemPrompt` assembles the full chat system prompt, used by `generateAssistantResponse` and by the tests. * Rules that named a tool move out of `GENERAL_PROMPT`, `CHAT_PROMPT`, `LIMITATIONS_PROMPT`, `NOTEBOOKS_PROMPT` (deleted), the hardcoded Available Knowledge list, and the opt-in, support-mode, and logs-snippet context messages into the `promptGuidance` of the tool each rule is about. * `SECURITY_PROMPT` is unchanged because it's shared with code completion. ## Prompt changes * Platform: the same guidance, reorganized under the tool it applies to. Small rewording: the two `search_docs` rules are merged, the opt-in rule no longer starts with "if `update_opt_in_level` is available", and two typos are fixed. The tool list also names tools the old prompt didn't mention. * Self-hosted: the prompt lists only `execute_sql`, `load_knowledge`, and `rename_chat`, and no longer mentions platform-only tools like `search_docs`, `query_logs`, notebooks, or the opt-in tool. The self-hosted fallback tools aren't listed until they become contracts in a later PR. ## Prompt caching The tools section varies with the actual provided tools. That adds no cache misses: providers cache tool definitions before the system prompt, so a change to the tool set already invalidates the cached system prompt ([Anthropic](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache>), [Bedrock](<https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html#prompt-caching-converse>), [OpenAI](<https://developers.openai.com/api/docs/guides/prompt-caching>)). ## Tests * For every combination of environment, Explorer, support mode, and base URL, the system prompt and context messages name only tools available to that request. * Outside its generated section, the system prompt names no tools except `execute_sql` in the shared `SECURITY_PROMPT`. * Labeled `run-evals` to check the reworded prompt for regressions. ## Checklist Check all before review: - [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>) |
||
|
|
6397239315 |
refactor(studio): replay removed Assistant tool outputs through legacy contracts (#52398)
Stacked on #52396. ## What Self-hosted Studio's Assistant uses four fallback tools (`getSchemaTables`, `getRlsKnowledge`, `getFunctions`, `getEdgeFunctionKnowledge`) that a later PR replaces with contract tools. Saved chats in IndexedDB still hold their outputs, and today those replay to the model unchecked. - New `LegacyToolContract` type: only `name`, `outputSchema`, `toModelOutput`, and `outputOnInvalid`. - New `tools/legacy-tools.ts` with a legacy contract for each fallback tool. Only history replay reads them, through `sanitizeContractPart`; nothing registers them as tools. - Schema tables, RLS policies, and function lists replay at the `schema` opt-in level and above; below it, the model gets a short note instead. The Edge Functions guide has no project data, so it replays at every level. - A saved output that doesn't match its stored shape is replaced with a short "couldn't be read" note. - README documents legacy contracts. ## Behavior changes Self-hosted always runs at the `schema` level, so valid saved outputs replay as before. Malformed saved outputs are now replaced instead of passed through. ## Tests - `legacy-tools.test.ts` covers every stored shape at every opt-in level, plus invalid outputs. - `registry.test.ts` checks legacy names don't overlap live contract names. - A saved self-hosted chat replays through `prepareMessagesForModel` and `convertToModelMessages` without errors. ## Checklist Check all before review: - [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) |
||
|
|
51b7cd6a4b |
refactor(studio): declare Assistant tool availability on contracts (#52396)
## What
Assistant tool contracts now declare where they're available, and
`getTools` builds tools from the registry.
- `ToolContract` and `RemoteToolContract` gain `availability: {
environments, requires? }`, both read-only sets. `environments` is
`platform` and/or `self-hosted`; `requires` is any of `explorer`,
`supportMode`, `baseUrl`.
- New `tools/registry.server.ts` maps every contract to its factory in
`TOOL_FACTORIES`; its type makes a missing or mismatched factory a
compile error. `buildLocalTools` builds only the tools available for a
request.
- `getTools` no longer branches per tool module. Local contract tools
take precedence over remote MCP tools with the same name. The
self-hosted fallback tools are unchanged for now.
- Deleted the per-module getters (`studio-tools.ts`, `schema-tools.ts`,
`report-tools.ts`, `notebook-tools.ts`, `incident-tools.ts`,
`support-tools.ts`); their tests now call the factories directly.
## Behavior changes
- Self-hosted no longer offers `deploy_edge_function`. Its server half
calls `/v1/projects/{ref}/functions/deploy`, which self-hosted Studio
doesn't serve.
- Self-hosted no longer offers the support tools (`escalate_to_human`,
`resolve_support_conversation`) in support mode.
- Platform offers `list_databases` without the Explorer flag.
Everything else produces the same tool set as before.
## Tests
- `index.availability.test.ts` asserts the exact tool names for every
combination of environment, Explorer, support mode, and `baseUrl`.
- `registry.test.ts` checks registry invariants: keys match contract
names, every contract has a factory, and a name in both the local and
remote maps has disjoint environments and matching gates.
This is the first step in moving the self-hosted Assistant tools to
contracts.
## Checklist
Check all before review:
- [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)
|
||
|
|
28e5d2fd64 |
refactor(studio): migrate search_docs remote MCP tool to a contract (#52305)
Migrates `search_docs` to `RemoteToolContract`. Follow-up to #52226. - It is the last remote MCP tool that was still gated by `TOOL_CATEGORY_MAP`. - Opt-in level is unchanged: always available (`minOptInLevel: null`). `needsApproval` is `false`. - Registered in `REMOTE_TOOL_CONTRACTS` and removed from `TOOL_CATEGORY_MAP`. No change to what the model sees. |
||
|
|
254e24b170 |
feat(studio): require grants in fetch wrappers for FGA-annotated endpoints (#52238)
## Problem Resolves FE-4689 and FE-4690. Builds on #52105. Studio's fetch wrappers don't know which FGA permissions an endpoint requires, so a UI guard and the request it protects can drift apart. This makes the `grant` minted by `useGrant`/`getGrant`/`ensureGrant` part of the request itself: calling an annotated endpoint without a matching grant is a compile error. ## Solution ### What changed - **Fetch wrappers** (`data/fetchers.ts`, `data/guarded-fetch.ts`): `get`/`post`/`put`/`patch`/`del` keep their names, so no imports change. - The `grant` option is required for endpoints annotated with `x-fga-permissions`, and forbidden for unannotated ones. - It accepts a `Grant` for that exact endpoint (or one of its variants) or `unguarded`. - The wrapper strips the grant before calling openapi-fetch. - `head`/`trace`/`options` are unchanged. - **Owned params**: refinements can declare query params the wrapper sets from the grant's variant (`ownedQuery`). These params are removed from the init type (`Omit<Query, Owned> & { [K in Owned]?: never }`), so callers can't pass them. Nothing uses this yet: the api-keys `reveal` variant is the first. - **`assertGrant`** runs in development only and throws `GrantAssertionError`. It checks: - the endpoint; - a missing grant; - the variant against `when(init)` predicates; - the path `ref` against the grant's project, also accepting the parent project ref for a grant minted on a branch; - the path `slug` against the grant's organization. - **Escape hatches**: - `unguarded.migrating` for unmigrated call sites. - `unguarded.byDesign('reason')` for calls that intentionally skip the check. - **Grants** now record `permissionsProjectRef`, the ref permissions were evaluated against. It's required once the scope is resolved. - **Readable errors**: a missing or wrong grant reports the caller's own init type plus the expected `grant` type, instead of openapi-fetch's full options type. Under `noErrorTruncation`, the old message was tens of KB per call site. - **`executeSql`** now requires a grant for `POST /platform/pg-meta/{ref}/query`, so every caller counts as unmigrated. - **Codemod**: added `grant: unguarded.migrating` at every existing call site that hits an annotated endpoint, including all `executeSql` callers. No behavior change. A follow-up lint rule ratchets the count down. - **Dependencies**: adds `openapi-typescript-helpers` (the version openapi-fetch already uses) for the helper types. Only openapi-fetch's unexported `InitParam` is copied locally. ### Type-level notes - The grant is checked in the parameter type rather than in `Init`'s constraint. That way `Init` is still inferred from the argument, which keeps both the return type and the error message tied to the caller's code. - The grant is replaced rather than intersected. Intersecting a wrong grant with the expected one can reduce the init type to `never`, which then accepts the call. - `NoInfer<Path>` stops a grant's endpoint from becoming an inference candidate for the path. ## Review instructions ### Tests - `data/guarded-fetch.test.ts`: - Type equality with the raw client: required params and body, template-literal paths, `parseAs`, `signal`/`headers`, optional-init endpoints, and `unguarded`. An openapi-fetch upgrade that breaks the local `InitParam` copy fails typecheck. - Negative type cases: - a missing or `undefined` grant; - a missing init on an annotated endpoint; - a grant for a different path or method; - any grant or `unguarded` on an unannotated endpoint; - a forged grant; - params and body still checked; - an unknown path. - `guardMethod` and `assertGrant` runtime behavior, including branch-parent refs and org slugs. - Variant and owned-param tests are deferred to the api-keys (`reveal`) and pg-meta (`read`/`write`) PRs, since no refinements exist yet. 1. Run `pnpm typecheck` and confirm Studio passes. Then remove a `grant: unguarded.migrating` and check that the error is short and names the expected grant. 2. Run `pnpm test:studio`. 3. Skim the codemod commit: it only adds `grant: unguarded.migrating` and the `unguarded` import. ## 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 applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) |
||
|
|
af876fafc0 |
refactor(studio): migrate more remote MCP tools to contracts (#52226)
Migrates \`list_tables\`, \`list_edge_functions\`, \`list_branches\`, \`get_advisors\`, and \`query_logs\` to \`RemoteToolContract\`. Follow-up to #52175. - Opt-in levels are unchanged: \`schema\` for the first three, \`schema_and_log\` for the last two. - \`needsApproval\` is \`false\` for all five. - They are removed from \`TOOL_CATEGORY_MAP\` and registered in \`REMOTE_TOOL_CONTRACTS\`. - \`getMcpTools\` now applies \`needsApproval\` only to object-valued remote tool entries. A malformed non-object entry now fails validation. Before, spreading a string produced a junk object that passed. No change to what the model sees. Tests: \`lib/ai\` vitest, \`tsc\`, and Prettier pass. |
||
|
|
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
|
||
|
|
23a56b2e60 |
refactor(studio): add remote tool contracts, starting with list_extensions (#52175)
## Problem Assistant tools served by the remote MCP server have no Studio-side contract, so Studio can't declare their opt-in level or approval policy the way it does for local tools. This PR adds a contract type for them and migrates `list_extensions` as the first one. ## Solution Adds `RemoteToolContract` for Assistant tools served by the remote MCP server, and migrates `list_extensions` as the first one. A remote contract declares only what Studio owns: `name`, `minOptInLevel`, and `needsApproval`. The MCP server keeps owning the description, input schema, execution, and output, so there's no server file and the tool's parts stay `dynamic-tool`. - `types.ts`: `RemoteToolContract` is `Pick<ToolContract, 'name' | 'minOptInLevel' | 'needsApproval'>`. - `registry.ts`: `REMOTE_TOOL_CONTRACTS` and `getRemoteToolContract`. - `tool-filter.ts`: minimum opt-in levels resolve from local or remote contracts; `list_extensions` leaves `TOOL_CATEGORY_MAP` (it stays on the allowlist). - `mcp-tools.ts`: applies the contract's `needsApproval` to the discovered tool, since MCP tool definitions can't declare approval. - README: documents remote contracts. ## Review instructions 1. Behavior: no change in what the model sees or how history replays. `list_extensions` keeps the same opt-in level (`schema`) and still runs without approval. 2. Run `pnpm exec vitest run lib/ai components/ui/AIAssistantPanel` from `apps/studio`. 3. Run `pnpm run typecheck`, eslint (no new warnings), prettier, and knip. ## 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 applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) |
||
|
|
96d51239c6 |
refactor(studio): migrate update_opt_in_level to a tool contract (#52081)
## Problem `update_opt_in_level` is the last local assistant tool not on the tool contract pattern. Its input schema is built for each request: a transform captures the org's opt-in level, stamps `levelWhenAsked`, and drops `requiredLevel` when the org already has it. The SDK stores that parsed value, and the approval card reads it before the tool runs. A contract has one static `inputSchema`, so this didn't fit. Separately, `pages/api/ai/sql/policy.ts` passes every assistant tool to a one-shot `generateText` and only removes `update_opt_in_level`. Any tool with `needsApproval` (`execute_sql`, `deploy_edge_function`, the notebook mutation and run tools) stops the step loop with no result, so `output` is never set and the route returns a 500. ## Solution - `ToolContract` gains an optional `createInputSchema(ctx)`. `toolFromContract` parses with it when present. `inputSchema` stays the shape stored on the message, which is what history replay and the client parse. - `update_opt_in_level` moves to `update-opt-in-level.ts` and `update-opt-in-level.server.ts`: - The per-request transform becomes `createInputSchema`; the stored shape is `inputSchema`. - The output schema moves out of `OptInRequest.tsx` into the contract; `toModelOutput` returns it unchanged, since it only contains level names. - `minOptInLevel: null` and `needsApproval: true`, as before. It uses plain `toolFromContract`, since it promotes no SQL. - Registered in `TOOL_CONTRACTS`, removed from `TOOL_CATEGORY_MAP`. `getOptInTools` still registers it on platform at every level. - `Message.Parts.tsx`, `OptInRequest.tsx`, and `evals/opt-in-replay.ts` use the contract's schemas; the old schemas in `tool-filter.ts` and `studio-tools.ts` are removed. - `ToolContext.aiOptInLevel` is now required. The `'schema'` defaults in `toolFromContract`, `execute-sql.server.ts`, and `run-notebook.server.ts` are gone, and every caller passes the real level. The eval mocks pin the mocked studio tools to `'schema'` so eval results don't shift. - New `withoutApprovalTools(tools)` in `tool-filter.ts` drops any tool whose `needsApproval` is set (including a function, and privacy-stubbed tools). `policy.ts` uses it instead of deleting one tool. ## Behavior changes - Replayed `update_opt_in_level` outputs are validated against the output schema and dropped if invalid (previously unchecked). - The policy generator no longer offers approval-gated tools to the model. ## Testing - New `update-opt-in-level.test.ts` (transform, per-request schema, execute at a new level, replay) and `tool-from-contract.test.ts` (`createInputSchema` used when present and receives the context). - `withoutApprovalTools` tests in `tool-filter.test.ts`. - `pnpm exec vitest run lib/ai components/ui/AIAssistantPanel evals` passes in `apps/studio`. |
||
|
|
e21b69c602 |
refactor(studio): migrate list_policies, list_reports, get_report, get_active_incidents, escalate_to_human, and resolve_support_conversation to tool contracts (#52015)
## Problem
Six assistant tools are still defined inline with `tool({...})`, unlike
the others that moved to the tool contract pattern.
## Solution
Migrate them to a contract file plus a `.server.ts` implementation,
registered in `TOOL_CONTRACTS`, removed from `TOOL_CATEGORY_MAP`, and
kept in the allowlist. The `*-tools.ts` modules remain as thin wrappers.
`ToolContext` gains an optional `baseUrl`, used by
`get_active_incidents`.
- `list_policies`, `list_reports`, `get_report`: `minOptInLevel:
'schema'`, output unchanged for the model at every level.
- `get_active_incidents`, `escalate_to_human`,
`resolve_support_conversation`: `minOptInLevel: null` (always
available), same as before.
- `needsApproval: false` for all.
Stored-shape changes for replayed outputs:
- Replayed outputs are now validated against the output schema and
dropped if invalid (previously unchecked).
- Zod strips unknown keys, so fields outside the schema no longer
replay.
- Enum-like fields use plain `z.string()` so new values don't break
replay.
Not migrated yet: `update_opt_in_level` (input schema is built per
request from the org's level), remote MCP tools, and self-hosted
fallback tools.
|
||
|
|
922937f6f7 |
Fix auto limit handling of limit all and limit null (#51917)
## Context Resolves https://github.com/supabase/supabase/issues/51836 Resolves FE-4666 The auto limit logic in the SQL Editor doesn't handle correctly when the query contains a `LIMIT ALL` or `LIMIT NULL` and will append another `LIMIT x` at the end of the query, so this PR fixes that Also added a fix to ensure that auto limit applies for select statements in CTEs ## To test - [ ] Verify that result does not have auto limit applied if running `select 1 limit all` or `select 1 limit null` in SQL Editor - [ ] Verify that there's auto limit for a CTE statement like `WITH numbers AS (SELECT generate_series(1, 2000) AS n) SELECT n FROM numbers;` |
||
|
|
2d79674ab3 |
refactor: migrate list_databases, list_notebooks, and get_notebook to tool contracts (#51937)
## Problem
The read-only notebook tools (`list_databases`, `list_notebooks`,
`get_notebook`) are still defined inline with `tool({...})`. The other
AI tools have moved to the tool contract pattern, so these three are
inconsistent with the rest.
## Solution
Migrate the three tools to the tool contract pattern: a contract file
plus a `.server.ts` implementation, registered in `TOOL_CONTRACTS`. They
are removed from `TOOL_CATEGORY_MAP` and kept in the allowlist.
Behavior is unchanged:
- `minOptInLevel: 'schema'`, same as before.
- `needsApproval: false`.
- `toModelOutput` returns the output unchanged, so the model sees the
same data at every opt-in level.
Stored-shape changes for replayed outputs:
- Replayed outputs are now validated against the output schema and
dropped if invalid. Previously they passed through unchecked.
- Zod strips unknown keys, so fields outside the schema no longer
replay.
- `status`, `region`, and `visibility` use plain `z.string()`, so new
enum values do not break replay.
## Review instructions
1. Run `pnpm exec vitest run lib/ai` in `apps/studio`. It should pass
(323 tests).
2. In `apps/studio/lib/ai/tools/registry.test.ts`, check the new
coverage: `toModelOutput` at all four opt-in levels, for both live and
replayed outputs, and invalid replayed outputs being dropped.
3. Confirm the three tools still appear for the schema opt-in level in
`tool-filter.test.ts` and `notebook-tools.test.ts`.
## Checklist
Check all before review:
- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [x] 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)
|
||
|
|
f4b2401831 |
docs(ai): update guide (#51847)
Added this guide recently so it'd be nice to keep it up to date https://github.com/supabase/supabase/pull/51785. --------- Co-authored-by: Charis Lam <26616127+charislam@users.noreply.github.com> |
||
|
|
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). |
||
|
|
a499db95f9 |
refactor(studio): migrate execute_sql, deploy_edge_function, rename_chat, and load_knowledge to tool contracts (#51803)
## Summary
Migrates four more assistant tools to the contract + `.server.ts`
pattern used by the notebook tools. Each tool now declares its schemas,
opt-in level, approval and model-visible output once.
## Changes
* Add contracts and server factories for `execute_sql`,
`deploy_edge_function`, `rename_chat`, `load_knowledge`;
`getStudioTools` now composes them.
* Add `execute-sql-output.ts` (output schema, `toModelRows`,
`NO_DATA_PERMISSIONS`) and `knowledge-topics.ts` (topic names + UI
labels, replacing the copy in `Message.Parts.utils.ts`).
* Delete `executeSqlSanitizer` and `ALL_TOOL_SANITIZERS`; history replay
goes through `sanitizeContractPart` only.
* Drop the four tools from `TOOL_CATEGORY_MAP`; the UI and evals import
schemas from the contracts; `rename_chat` input casts now use the
contract type.
## Deviations worth reviewing
* `execute_sql` replay: a bare-array legacy output is stamped `schema`
via a union transform (still hidden from the model, still shown in the
UI). A malformed non-array output is now dropped, where before it passed
through at the data level.
* The "no data permission" message now reaches the model as a JSON
string value instead of a text part. The text the model sees is
unchanged.
* `deploy_edge_function` output is now strictly `{ success: boolean }`
in the UI parse (was optional/passthrough).
|
||
|
|
9ae8432dc7 |
refactor(studio): migrate create, delete, and run notebook tools to tool contracts (#51754)
## Summary Migrates the create, delete, and run notebook assistant tools to the tool contract + server pattern used by `update_notebook`. Each tool now defines its schema once in a shared contract, with server-only execution split into a `.server.ts` module. This removes duplicated client-side schemas and gives the three tools one shared notebook mutation output schema. ## Changes - Add `create-notebook`, `delete-notebook`, and `run-notebook` tool contracts, each with a `.server.ts` implementation. - Remove the duplicated client-side schemas for these tools from `notebook-tools.ts` and the registry. - Add `notebook-mutation-output.ts` as the single output schema shared by the notebook mutation tools. - Add `lib/ai/opt-in-level.ts` with the opt-in level helpers, extracted from the existing module to break an import cycle. - Add optional `ToolContract.outputOnInvalid` so `run_notebook` history replay can reuse a stored output when input fails validation. - Update the AI assistant panel renderers (proposal, run, opt-in modal and request) and the tool filter, sanitizer, and cache invalidation to use the new contracts. ## Deviations worth reviewing - **`outputOnInvalid` on `ToolContract`.** This is a new optional hook. It exists so `run_notebook` history replay can return a valid output when stored input no longer passes validation. Reviewers should confirm this is the right level for the hook rather than handling it inside the tool. - **`opt-in-level.ts` extraction.** The helpers were moved into their own module to break a circular import between the tool modules and the opt-in components. This adds one file, but no behavior change is intended. - **`create-notebook` contract imports the data-layer `notebook-schema`.** This matches `update-notebook`. It should be moved behind the contract before the planned ESLint rule step, which restricts contract modules from importing data-layer code. ## Testing - `vitest` for `lib/ai`, `components/ui/AIAssistantPanel`, and `state`: 920 tests pass across 71 files. - `tsc`: one error remains in `packages/ui-patterns` (`InstructionBlocks.tsx`), which is unrelated to this change. I have not verified whether it also fails on the base branch. - ESLint reports no errors on the changed files (9 `no-explicit-any` warnings in `tool-filter.ts` and its test); Prettier is clean. - Not run: knip and the lint ratchet. |
||
|
|
78348a767a |
docs(ai): Add Assistant code guide (#51785)
## Problem A starting point for humans and agents whenever they need to modify the AI assistant. Working on an issue for the Supabase Assistant for the first time, I missed having a starting point so I could guide the LLM / myself on where to start looking. A link to share with someone so they know its current architecture. ## Solution Links from the agents.md so the reference is not lost and a main readme that includes some diagrams. <!-- ## Preview links If relevant, include links to changed pages for easy review access. Copy the preview base URL from the Vercel bot comment on this PR. Use the following table as an example template. | Site | Live | Preview | Search for | | -------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------- | | WWW | [/blog/your-post](https://supabase.com/blog/your-post) | [/blog/your-post](https://zone-www-dot-com-git-branch-name-supabase.vercel.app/blog/your-post) | unique phrase from the change | | Docs | [/docs/guides/your-page](https://supabase.com/docs/guides/your-page) | [/docs/guides/your-page](https://docs-git-branch-name-supabase.vercel.app/docs/guides/your-page) | unique phrase from the change | | Studio | [/dashboard](https://supabase.com/dashboard) | [/dashboard](https://studio-git-branch-name-supabase.vercel.app/dashboard) | unique phrase from the change | | Design system | [/design-system](https://supabase.com/design-system) | [/design-system](https://design-system-git-branch-name-supabase.vercel.app/design-system) | unique phrase from the change | | UI library | [/library](https://supabase.com/library) | [/library](https://ui-library-git-branch-name-supabase.vercel.app/library) | unique phrase from the change | | Knowledge base | [/kb/guides/your-page](https://supabase.com/kb/guides/your-page) | [/kb/guides/your-page](https://kb-git-branch-name-supabase.vercel.app/kb/guides/your-page) | unique phrase from the change | --> <!-- ## Additional context Optionally add any other context or screenshots. --> ## Review instructions Check the references make sense (i.e.: it fits well your existing workflow and doesn't break any existing one). Main file lives [here](https://github.com/supabase/supabase/blob/f87b248056837df5abacb1e581fc70c234fb0037/apps/studio/lib/ai/README.md) ## Checklist Check all before review: - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) |
||
|
|
c3fd259904 |
fix(ai): assistant sql row cap (#51608)
## Problem attempt to [fix this ticket](https://supabase.frontapp.com/inboxes/teams/folders/27650590/unassigned/116845868830): when the studio ai assistant runs a query with previously set database opt-in, `execute_sql` returns every row while the query cell's footer says "Limit 100 rows" causing in case of large amount of returned rows browser to freeze + the chat fails with "Sorry, I'm having trouble responding right now" until the user clears it ## Solution - `execute_sql` now keeps the first 100 rows using the cell's existing `DEFAULT_CELL_ROW_LIMIT` - uses in history sanitizer the same `toModelRows` helper - chats saved before this change have no `totalRows` so the helper falls back to `rows.length` and cuts them to 100 too <!-- ## Preview links If relevant, include links to changed pages for easy review access. Copy the preview base URL from the Vercel bot comment on this PR. Use the following table as an example template. | Site | Live | Preview | Search for | | -------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------- | | WWW | [/blog/your-post](https://supabase.com/blog/your-post) | [/blog/your-post](https://zone-www-dot-com-git-branch-name-supabase.vercel.app/blog/your-post) | unique phrase from the change | | Docs | [/docs/guides/your-page](https://supabase.com/docs/guides/your-page) | [/docs/guides/your-page](https://docs-git-branch-name-supabase.vercel.app/docs/guides/your-page) | unique phrase from the change | | Studio | [/dashboard](https://supabase.com/dashboard) | [/dashboard](https://studio-git-branch-name-supabase.vercel.app/dashboard) | unique phrase from the change | | Design system | [/design-system](https://supabase.com/design-system) | [/design-system](https://design-system-git-branch-name-supabase.vercel.app/design-system) | unique phrase from the change | | UI library | [/library](https://supabase.com/library) | [/library](https://ui-library-git-branch-name-supabase.vercel.app/library) | unique phrase from the change | | Knowledge base | [/kb/guides/your-page](https://supabase.com/kb/guides/your-page) | [/kb/guides/your-page](https://kb-git-branch-name-supabase.vercel.app/kb/guides/your-page) | unique phrase from the change | --> <!-- ## Additional context Optionally add any other context or screenshots. --> ## Review instructions 1. In a test project, run this in the SQL editor: ```sql create table "emailSubscriber" (id bigint generated always as identity primary key, email text); create table "stripeCustomer" (id bigint generated always as identity primary key, email text); insert into "emailSubscriber" (email) select md5(g::text) || '@example.com' from generate_series(1, 50000) g; insert into "stripeCustomer" (email) select md5(g::text) || '@example.com' from generate_series(1, 1000) g; 2. on the live dashboard, open the assistant in a new chat and send "i want all the emails in emailSubscriber where the email is not in the stripeCustomer table" 3. in the opt in requested settings choose "Schema, Logs & Database Data" 4. then click run query, the cell should show 100 rows (vs 50000 rows in prod) ## Checklist Check all before review: - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [x] 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: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
cd6afdd8b2 |
refactor(studio): add tool contracts and migrate update_notebook (#51626)
## Summary Each assistant tool's identity and contract is currently written in up to nine places that nothing ties together at compile time. This PR adds a contract/server split and migrates `update_notebook`, the tool with the most copies, as the first proof of the design. - **Contract** (`lib/ai/tools/update-notebook.ts`): isomorphic file with the input and output schemas, approval flag, minimum opt-in level, and `toModelOutput`, the single rule for what the model may see. - **Server** (`update-notebook.server.ts`): the executable tool, built with `approvalGatedToolFromContract`. - **Registry** (`registry.ts`): collects contracts, derives a typed `StudioUIMessage`, and provides `sanitizeContractPart` for history replay. - **Shared types** (`types.ts`): `ToolContract`, `ToolContext`, `ToolFactory`, plus a single `getAuthHeaders` replacing three variants. - **Approval gate** (`approval-gate.ts`): approval-gated tools get `acceptUntrustedSql` / `acceptUntrustedLogsSql` through a gate passed to `execute`, and `*.server.ts` files can't import the raw functions (ESLint). - **Opt-in level**: `update_notebook` is gated by its contract's `minOptInLevel`. `TOOL_CATEGORY_MAP` is now typed against `ToolName` and excludes migrated tools, which exposed `get_active_incidents` missing from the name enum. Removed duplicates: the `update_notebook` sanitizer in `tool-sanitizer.ts`, the client-side `stripNotebookSnapshot`, and the copied update schemas in `Message.utils.ts`. ## Behavior changes - The client no longer strips `previous_content` from `update_notebook` outputs before sending history, so requests carry the previous notebook snapshot. The server still strips it before the model sees it. - On history replay, an `update_notebook` output that doesn't match its schema is dropped instead of passed through minus `previous_content`. ## Testing - New `registry.test.ts` (typed parts, replay sanitizer) and a contract case in `tool-filter.test.ts`. - Studio typecheck, lint ratchet, knip, Prettier and the affected vitest suites pass. |
||
|
|
0d8cd9c315 |
feat(studio): prompt for a higher AI opt-in level instead of "no tool access" (#51411)
## Motivation When an Assistant tool needs a higher opt-in level than the org has, the user only sees the model say it has no access with (inconsistent) written instructions how to fix, instead of Assistant proactively facilitating the fix. <img width="400" alt="CleanShot 2026-10-07 at 3 44 29 PM@2x" src="https://github.com/user-attachments/assets/ba95568a-5db4-4d8c-b4ff-64855f2b87ec" /> The majority of recent labelled [Assistant Issues](https://www.braintrust.dev/app/supabase.io/p/Assistant/topics) in Braintrust are tools or query results blocked by the org opt-in level. We've considered making Assistant disabled entirely when data opt-in is off to eliminate the most common footgun (AI-405), but that's an intrusive change which could break legitimate use cases. ## Changes https://github.com/user-attachments/assets/206a2438-630e-4368-9cec-2b04b66c9cd4 A new `update_opt_in_level` tool renders an inline card which prompts admins to review the opt-in level and highlights the proposed change (non-admins see a message telling them to contact their admin to change the setting). Saving approves the call and the turn resumes at the new level. Results appear in a Braintrust tool span based on https://github.com/supabase/supabase/pull/45654. I added 5 evals that simulate the user answering the opt-in card to verify that the Assistant asks when blocked, continues after the user accepts, and doesn't invent data after a skip. Tool Usage and Correctness are at 100% in the [sample run](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/experiments/mattrossman%2Fai-158-prompt-users-to-update-settings-instead-of-showing-no-tool-1791483991). <details> <summary>📸 Screenshots</summary> | Admin, pending | Modal, Current and Proposed | | -- | -- | | <img width="100%" alt="CleanShot 2026-10-07 at 3 23 37 PM@2x" src="https://github.com/user-attachments/assets/2fc8ba11-0530-4028-a056-40ca02afd3ef" /> | <img width="1184" height="1754" alt="CleanShot 2026-10-07 at 3 32 37 PM@2x" src="https://github.com/user-attachments/assets/73639633-89ac-4d4c-b869-d9301735d5b9" /> | | **After saving, turn continues** | **Non-admin** | | <img width="100%" alt="CleanShot 2026-10-07 at 3 27 14 PM@2x" src="https://github.com/user-attachments/assets/a91c6760-6dfb-4f51-9ef8-4bdbe1b22495" /> | <img width="100%" alt="CleanShot 2026-10-07 at 3 15 33 PM@2x" src="https://github.com/user-attachments/assets/ecb9aa87-26dc-4b69-a086-cb77a28bb860" /> | </details> ## Verification To test in staging, set your org's Assistant opt-in level to Disabled, ask "What tables do I have?", and review the card. Try selecting the proposed (or different) opt-in level and saving to continue. [This trace](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/experiments/mattrossman%2Fai-158-prompt-users-to-update-settings-instead-of-showing-no-tool-1791483991?r=90066cd9-4da3-4817-9650-c369d2b42cea) is a sample from the accept eval case after saving Schema Only, note the `update_opt_in_level` span. ## Safety considerations I added a banner to the modal to make it more obvious that this setting impacts the whole org, not just the current chat or project: <img width="592" height="78" alt="CleanShot 2026-10-08 at 2 04 44 PM@2x" src="https://github.com/user-attachments/assets/6b140ed6-65fb-4bc0-b5cc-9c82fe2a67aa" /> I leave the current opt-in value selected by default in the form so the user has to consciously select the proposed value instead of mindlessly clicking save without understanding implications. `execute_sql` and `run_notebook` outputs are now stamped with the level they ran under, and history is sanitized by the least permissive of the stamped vs current opt-in levels. That way raising the level mid-chat doesn't unexpectedly expose earlier query rows to the model. Closes AI-158 |
||
|
|
ffe1ebc940 |
fix(studio): do not ignore requested model if available in base (#51388)
## Problem The model selection logic in `generate-v4.ts` was incorrectly ignoring the requested model even when it was available in the base model set. The condition checked for access to advanced models or throttling in a way that would force fallback to the default base model even when the requested model was already a base model. ## Solution Reordered the logical condition to first check if the effective model is a base model ID, and only apply the access/throttle checks when the requested model is not already a base model. This ensures the requested model is respected when it's available. Also threaded the `effectiveModel` parameter through to the assistant response generator for better telemetry and debugging context. ## Review instructions 1. Check the logic change in `apps/studio/pages/api/ai/sql/generate-v4.ts` line 164 2. Verify the condition now correctly checks `isAssistantBaseModelId(effectiveModel)` first 3. Confirm `effectiveModel` is now passed to `generateAssistantResponse` for proper telemetry ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) 🤖 Generated with [Claude Code](https://claude.com/claude-code) |
||
|
|
87681812a0 |
fix(studio): assistant get_active_incidents url in prod (#51047)
The Assistant's `get_active_incidents` tool has [failed in prod 99.8% of the time over the past 60 days](https://supabase.slack.com/archives/C051L8U2EJF/p1790712805774689), so users reporting outages get told it couldn't check incident status. The failures never showed up as errors, which is why nobody noticed. The Assistant now includes the `/dashboard` base path when it calls its own API routes, so the tool stops hitting a 404 in prod ([`/api/incident-status`](https://supabase.com/api/incident-status) is a 404, [`/dashboard/api/incident-status`](https://supabase.com/dashboard/api/incident-status) is a 200). The tool also throws on a failed fetch now instead of returning an `{ error }` result. That way failures show up as span errors in Braintrust and as a failed tool call in the UI. The model still gets the error message and tells the user it couldn't check. When the fetch fails (in dashboard): | Before (prod) | After (local, path temporarily broken) | | --- | --- | | <img width="1036" height="784" alt="CleanShot 2026-09-29 at 5 08 49 PM@2x" src="https://github.com/user-attachments/assets/4539f968-4aa6-49a5-8c7f-7911b6b497a0" /> | <img width="1026" height="716" alt="CleanShot 2026-09-29 at 5 08 06 PM@2x" src="https://github.com/user-attachments/assets/7c9a565c-efe1-4d1a-901b-e440bbb5a739" /> | When the fetch fails (in Braintrust): | Before (prod) | After (local, path temporarily broken) | | --- | --- | | <img width="2218" height="920" alt="CleanShot 2026-09-29 at 5 19 07 PM@2x" src="https://github.com/user-attachments/assets/87860568-b50f-49ee-98fd-4c82f14d1913" /> | <img width="2218" height="920" alt="CleanShot 2026-09-29 at 5 19 10 PM@2x" src="https://github.com/user-attachments/assets/64f58d47-e083-464e-b8d0-8b9c57710a05" /> | When the fetch works (local): | Dashboard | Braintrust | | --- | --- | | <img width="1054" height="808" alt="CleanShot 2026-09-29 at 5 20 58 PM@2x" src="https://github.com/user-attachments/assets/1c9e4cf8-79f0-48e6-b95a-1694fc00a9f9" /> | <img width="2918" height="1144" alt="CleanShot 2026-09-30 at 9 07 03 AM@2x" src="https://github.com/user-attachments/assets/0d2b9685-57a9-4028-a451-272b3de8e23a" /> | Ran it locally with tracing on. Here's a [successful call](https://www.braintrust.dev/app/supabase.io/p/Assistant/logs?r=251bcd44-c55b-44bb-9ce2-b034b26f8832), and one with the path temporarily broken, which now [logs a span error](https://www.braintrust.dev/app/supabase.io/p/Assistant/logs?r=637f2dc8-f65b-4d65-9d86-0511b36e8685). Local dev has no base path, so the prod URL is covered by the new `getBasePathURL` tests. Closes AI-1272 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Incident lookups now report fetch, HTTP, parsing, and validation errors rather than returning an empty incident result. * AI SQL generation now accounts for the configured site base path when building its service URL. * **Improvements** * Site URLs now handle trailing slashes and existing base paths consistently, avoiding duplicate path segments. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
13de8189c9 |
feat(studio): assistant get_active_incidents on status page endpoint (#50994)
## Summary * Adds a second branch to the assistant's `get_active_incidents` tool (`apps/studio/lib/ai/tools/incident-tools.ts`) that reads `/api/status-page` when the global ConfigCat flag `incidentIoStatusPage` is on, instead of the legacy `/api/incident-status` endpoint. * Filters on `visible`, ignores `show_banner` (only the global banner respects it), and concatenates ongoing incidents + in-progress maintenances (not scheduled maintenances). * Adds `isServerFlagEnabled` to `lib/server/configcat.ts` for reading global, non-user-targeted ConfigCat flags server-side, and threads the flag through `getTools` from `pages/api/ai/sql/generate-v4.ts`. This is PR 3 of 6 in the [FE-4057](https://linear.app/supabase/issue/FE-4057/frontend-bannerbot-reconfigured) stack — stacked on `charis/fe-4057-pr2-support-form`. Behind the `incidentIoStatusPage` flag (default off), so this ships no user-visible change on its own. See Linear [FE-4057](https://linear.app/supabase/issue/FE-4057/frontend-bannerbot-reconfigured) for full 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 lib/ai/tools/incident-tools.test.ts` (19/19 passing, including 7 new tests for the status-page branch) |
||
|
|
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 --> |
||
|
|
ec574f3a51 |
fix(studio): pass Authorization header to assistant list_policies tool (#50756)
<!-- ccr-slack-attribution --> _Requested by **Saxon Fletcher** · [Slack thread](https://supabase.slack.com/archives/C051L8U2EJF/p1789995309253479?thread_ts=1789995309.253479&cid=C051L8U2EJF)_ Resolves AI-1246 ## Problem **Before:** The Assistant's `list_policies` tool fails in about 70% of traces. It only "succeeds" when the org has AI opt-in disabled, because then it returns the privacy stub and never makes a request. When opt-in is enabled, it runs the pg-meta query server-side with no `Authorization` header, so the request is unauthenticated and fails. The Assistant then falls back to `execute_sql`. **After:** `list_policies` sends the caller's `Authorization` header, the same way `execute_sql` in `studio-tools.ts` already does, so it returns the project's RLS policies. ## Solution `getTools` already receives `authorization` but didn't pass it to `getSchemaTools`. This PR passes it through. `list_policies` builds `{ Authorization }` from it, and `getDatabasePolicies` gets an optional `headersInit` argument that it forwards to `executeSql`, the same pattern `getDatabaseFunctions` uses. Existing client-side callers of `getDatabasePolicies` don't change. Files: `lib/ai/tools/index.ts`, `lib/ai/tools/schema-tools.ts`, `data/database-policies/database-policies-query.ts`, plus tests in `lib/ai/tools/schema-tools.test.ts` (new) and `lib/ai/tools/index.test.ts`. ## Review instructions 1. Read `schema-tools.ts` and compare it with the `authHeaders` handling in `studio-tools.ts` (`execute_sql`). 2. On the preview, use an org with AI opt-in set to at least "schema" and ask the Assistant to list the RLS policies on `public`. `list_policies` should return the policies without falling back to `execute_sql`. Local gates (all passed): - `pnpm typecheck` in `apps/studio` (next typegen + `tsc --noEmit`) - `npx eslint` on touched files: 0 errors. The 2 warnings are on lines this PR doesn't change. - `npx vitest run lib/ai/tools/schema-tools.test.ts lib/ai/tools/index.test.ts lib/ai/tool-filter.test.ts`: 24/24 passed. I also ran the new header test against the old `schema-tools.ts` and it failed, as expected. - `SORT_IMPORTS=false npx prettier --config prettier.config.mjs --check` on touched files Follow-up, not in this PR: `getRlsKnowledge` in `fallback-tools.ts` (self-hosted path) also calls `getDatabasePolicies` without headers, even though a `headers` object is already in scope there. ## AI disclosure Claude Code (agent) wrote this PR from the Slack request. @SaxonF (Saxon Fletcher) is the accountable human owner. A human needs to review it before merge. ## 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 (N/A, no docs changes) 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_0171Mk7SiKYLDDoAQvbDYfeK --- _Generated by [Claude Code](https://claude.ai/code/session_0171Mk7SiKYLDDoAQvbDYfeK)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
ea3a7743b1 |
feat(studio): default AI Assistant to GPT-6 Luna (AI-1245) (#50757)
<!-- ccr-slack-attribution --> _Requested by **Saxon Fletcher** · [Slack thread](https://supabase.slack.com/archives/C051L8U2EJF/p1790104861710199?thread_ts=1790104861.710199&cid=C051L8U2EJF)_ ## Problem **Before:** The Assistant's base model is `gpt-5.6-luna` at medium reasoning effort. **After:** The base model is `gpt-6-luna`, its direct successor, still at medium effort. It costs half as much: $0.10/$0.50 per MTok against $0.20/$1.20. Resolves [AI-1245](https://linear.app/supabase/issue/AI-1245/move-the-assistants-base-model-to-gpt-6-luna). ## Solution This swaps `gpt-5.6-luna` for `gpt-6-luna` in `apps/studio/lib/ai/model.utils.ts`: the model ID union, the reasoning-support map, `ASSISTANT_MODELS`, `DEFAULT_ASSISTANT_BASE_MODEL_ID`, and the OpenAI provider registry. The old ID is removed, not kept next to the new one. A stored selection of `gpt-5.6-luna` is no longer a known ID, so the client and `generate-v4` both fall back to the new default. The eval cost table (AI-1242) and eval experiments (AI-1243) are out of scope. Source for the model ID and supported efforts (none/low/medium default/high/xhigh/max): [OpenAI model docs: GPT-6 Luna](https://developers.openai.com/api/docs/models/gpt-6-luna). `@ai-sdk/openai@4.0.41` types model IDs as a union plus `string & {}`, so no SDK bump is needed. ## Review instructions 1. Check the diff in `model.utils.ts`. Say so if you'd rather keep `gpt-5.6-luna` selectable as a fallback. 2. AI-1245 asks for the Assistant evals before shipping. Add the `run-evals` label to run `braintrust-evals.yml` on this PR, or run `pnpm --filter studio evals:run` locally. They have not been run yet because they need OpenAI/Braintrust credentials. 3. Already run: studio `typecheck`, eslint + prettier on the changed files, vitest for `lib/ai`, `pages/api/ai` and `state/ai-assistant` (264 passed), and `evals:preflight`. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [x] No docs topics changed **AI disclosure:** Claude Code wrote this PR from start to finish. Saxon Fletcher (@SaxonF) is the accountable human and must review it before merge. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01W21zLTfzde6FFPyYGbGC6K --- _Generated by [Claude Code](https://claude.ai/code/session_01W21zLTfzde6FFPyYGbGC6K)_ Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
4bb36b944f |
feat(studio): let High Compliance projects opt-in to Assistant data access (#50548)
Orgs with the HIPAA add-on had the Assistant's opt-in level forced to `disabled` on any project marked High Compliance, regardless of what the org picked in its AI settings. The restriction predated our AI provider BAAs. The consequence is those users see the Assistant failing to answer questions about their data w/ no clear path how to fix it, even though the LLM provider supports this use case. This PR removes these Assistant restrictions on the server and client so those projects honor the org's chosen level. Braintrust conversation tracing is unchanged and still blocked for these projects, see [this test case](https://github.com/supabase/supabase/blob/b9800ccf16/apps/studio/lib/ai/braintrust-logger.test.ts#L16-L20). See [comments](https://linear.app/supabase/issue/AI-1153/allow-hipaa-orgs-to-opt-in-to-assistant-data-access-for-high#comment-485a0d46) for legal approval and conditions. The client-side changes enable features like "Debug with AI" on SQL query failures, “Generate/Rename with AI” for snippet titles, and generated Assistant chat titles for these customers. The AI opt-in copy now adds a reminder to obtain consent from data subjects, linking the [shared responsibility model](https://supabase.com/docs/guides/deployment/shared-responsibility-model) based also on [this comment](https://linear.app/supabase/issue/AI-1153/allow-hipaa-orgs-to-opt-in-to-assistant-data-access-for-high#comment-f81ee610). <img width="400" alt="CleanShot 2026-09-17 at 5 01 02 PM@2x" src="https://github.com/user-attachments/assets/d02123f2-3e32-4d83-9f98-7d15e59222ef" /> To test with a HIPAA-enabled project in staging, you can use this [Plan Change [Staging]](https://app.hex.tech/supabase/app/Plan-Change-Staging-032BD32jo1EaisCS85qunf/latest) Hex to add the HIPAA add-on. Once the add-on is present, you can turn on High Compliance from a project's settings. Also in org settings, crank up the Assistant data opt-in level and verify the Assistant is able to answer questions about the project's data. My results testing with opt-in level "Schema, Logs & Database Data": | High compliance setting | Data opt-in working | |--------|--------| | <img width="1302" height="422" alt="CleanShot 2026-09-17 at 5 03 36 PM@2x" src="https://github.com/user-attachments/assets/c416371b-2eb8-49df-9c07-6d8eababb443" /> | <img width="1566" height="1516" alt="CleanShot 2026-09-17 at 5 05 14 PM@2x" src="https://github.com/user-attachments/assets/39624355-7f8f-46ce-9f08-a8acfb9da830" /> | Closes AI-1153 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## New Features - AI-assisted query renaming, snippet title generation, debugging, and tools now follow organization AI opt-in settings rather than project HIPAA status. - Debugging assistance and AI actions remain available for eligible users without additional HIPAA-based blocking. - AI metadata warnings consistently show standard opt-in messaging and permission settings. - AI settings remind users to obtain consent before entering personal data and link to shared responsibility guidance. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
a133ef60a6 |
fix(studio): correct the Assistant's blocked-tool privacy message (#50411)
When the Assistant calls a tool that's blocked on permissions, the response had two problems. First, it told users their data goes to Amazon Bedrock when production inference [routes to OpenAI](https://github.com/supabase/supabase/blob/b824acdfd204071f931a0aee01bee953ef164b6b/apps/studio/pages/api/ai/sql/generate-v4.ts#L170-L172). It now says "third-party AI providers" like the [opt-in settings](https://github.com/supabase/supabase/blob/b824acdfd204071f931a0aee01bee953ef164b6b/apps/studio/components/interfaces/Organization/GeneralSettings/AIOptInLevelSelector.tsx#L84-L88) do. I verified that was the last user-facing Bedrock mention. Second, HIPAA-restricted projects got that same copy telling them to change data opt-in settings, but for those projects `getAIDetails` [forces their level to `disabled`](https://github.com/supabase/supabase/blob/b824acdfd204071f931a0aee01bee953ef164b6b/apps/studio/lib/ai/ai-details.ts#L70-L73). They get separate copy now to prevent confusion. Closes AI-1154 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added HIPAA-aware AI controls for eligible projects. - AI opt-in is automatically disabled when HIPAA requirements apply. - Privacy messages now distinguish standard AI opt-in restrictions from HIPAA-related restrictions. - AI-assisted SQL and tool experiences consistently apply HIPAA restrictions when determining available capabilities. - **Bug Fixes** - Improved handling of AI settings for HIPAA-sensitive projects and invalid project or organization configurations. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
22d7bc0cfd |
feat(studio-evals): custom search_docs tool for the eval harness (no token / no PAT) (#50092)
- Eval harness's only live tool, `search_docs`, no longer needs the in-process MCP client or its dummy token — it now calls the public docs GraphQL API (`https://supabase.com/docs/api/graphql`) directly. Low risk as this is an eval-harness change only. Production assistant path (`mcp-tools.ts`) untouched. **Update:** per [@mattrossman's review](https://github.com/supabase/supabase/pull/50092#discussion_r3980396341), the eval tool's description embeds the Content API's own GraphQL schema (fetched via a `{ schema }` query and minified with `gqlmin`), mirroring how `@supabase/mcp-server-supabase`'s `docs-tools.ts`/`loadSchema` populates production's `search_docs` description. Without it, the model had no schema to work from and issued malformed queries, which caused the 218 `search_docs` errors and the -25pp Docs Faithfulness regression in the first eval run on this PR. Schema loading is required: `createSearchDocsTool()` rejects if the schema fetch fails, so preflight and the gated eval job fail loudly instead of producing untrustworthy fallback results. `createSearchDocsTool` is async because the `ai` package's `tool()` only accepts a plain string `description`, unlike the MCP SDK's async description support; both callers (`getMockTools`, `evals/preflight.ts`) await it. `gqlmin` is a direct `apps/studio` dependency and was already transitive via `@supabase/mcp-server-supabase`. ### Verification - `pnpm -C apps/studio exec -- tsc --noEmit` reaches the compiler; it reports only the pre-existing unrelated `packages/ui-patterns/src/McpUrlBuilder/components/InstructionBlocks.tsx` `StaticImageData` error. - `pnpm -C apps/studio exec -- vitest run lib/ai/tools/mock-tools.test.ts lib/ai/tools/mcp-tools.test.ts` — 21/21 passed. - `pnpm exec tsx evals/preflight.ts` — live docs API schema fetch and search_docs call passed. - `NEXT_PUBLIC_CONTENT_API_URL=http://127.0.0.1:1/graphql pnpm -C apps/studio exec -- tsx evals/preflight.ts` — failed fast as expected, proving schema/API failures gate evals. - Fresh `run-evals` pass: Docs Faithfulness 55.7% (0pp), with no systemic `search_docs` regression. Risk: eval-harness-only; schema/API outage now fails the eval job before scoring rather than allowing fallback descriptions. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added documentation search powered by the public Supabase documentation GraphQL API. * Documentation search results now include live schema information and clearer error handling for failed or invalid requests. * **Bug Fixes** * Improved evaluation tooling reliability by removing unnecessary connection-abort behavior. * Updated validation to detect missing search tools and malformed documentation responses. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
e5f2b29625 |
refactor(studio): remove USE_REMOTE_MCP gate, always use remote MCP server (#50089)
## Summary - Removes the `USE_REMOTE_MCP` env-var gate from the dashboard assistant: `getMcpTools` now always connects to the remote MCP server (the rollout from #47479 has been stable ~2 months and is enabled in prod). - Drops the var from `apps/studio/turbo.jsonc` and deletes the now-obsolete transport-selection tests. - The legacy in-process client (`createInProcessSupabaseMCPClient`) stays, re-scoped to the hermetic eval harness (`mock-tools.ts`, `evals/preflight.ts`); removing it is tracked by AI-897. ## Verification - `pnpm exec tsc --noEmit` in apps/studio: no errors in any changed file (one pre-existing unrelated error in `packages/ui-patterns/.../InstructionBlocks.tsx`). - `mcp-tools.test.ts` (7), `mock-tools.test.ts` (15), `tools/index.test.ts` (6), `supabase-mcp.test.ts` (11) all pass. ## Risk Low. Remote failure already degrades to non-MCP tools in `getTools`; rollback = revert this PR (or re-add the gate). ## Follow-up After this lands in prod, `USE_REMOTE_MCP` can be removed from the Vercel env vars — nothing in the repo reads it anymore. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Improvements** * AI tools now consistently use the remote service when retrieving available tools. * If the remote service is unavailable, times out, or cannot authenticate, the assistant continues operating with the tools that remain available. * Evaluation and development behavior now more closely reflects the remote service experience. * **Maintenance** * Updated supporting documentation and automated coverage to reflect the streamlined tool connection behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> |
||
|
|
e0280cb650 |
docs: restructure observability navigation and overview (#49505)
<!-- CURSOR_AGENT_PR_BODY_BEGIN --> ## Stack Draft stack extracted from `docs/monitoring`. Merge bottom-up. The troubleshooting *catalog* rewrite (`content/troubleshooting` and the Diagnosing UI) stays out of scope. 1. #49503 move inspect and advisors 2. #49501 split Studio logs from ClickHouse queries 3. #49500 treat reports as signal dashboards 4. #49502 add Observe the data hub 5. #49506 add agent setup components 6. #49504 add hire-an-agent templates 7. **#49505** restructure observability nav, overview, Detecting, and flatten Observe the data ← **this PR** ## 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? Docs update. Top layer in the observability stack. ## What is the current behavior? The section is still titled Monitoring and Debugging, with a Debugging / Monitoring split that does not match the new pages. The debugging guide is still the master layer-isolation + symptom table. Observe the data is split into “what data” vs “where to observe it,” which duplicates the source pages. ## What is the new behavior? - Section title is Observability - Overview groups Observe the data, Detect and resolve, Hire an agent, and Export - **Observe the data is flattened by source.** Logs, Metrics API, Database, Advisors, and Reports each list where to read that source. There is no separate MCP/API/CLI/Studio nav group. - **Observe vs Detecting:** Observe is the catalog (what exists, how to access it). Detecting is how to *use* those sources to pick up a Health / Security / Performance / Usage signal. Named errors skip to Diagnosing. - Studio Logs sits under Logs. Reports sits beside the other sources. - Troubleshooting stays in the global menu and also appears as Diagnosing under Detect and resolve ## Additional context This is the last PR in the stack. Together the seven PRs reconstruct the `docs/monitoring` observability IA and guide content, without shipping the troubleshooting catalog overhaul. <!-- CURSOR_AGENT_PR_BODY_END --> <div><a href="https://cursor.com/agents/bc-a3cb5ece-925b-4046-b58a-5d69e9a9d794?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/background-agent?bcId=bc-a3cb5ece-925b-4046-b58a-5d69e9a9d794&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img alt="Open in Cursor" width="131" height="28" src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a> </div> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Saxon Fletcher <SaxonF@users.noreply.github.com> Co-authored-by: Nik Richers <nik@validmind.ai> |
||
|
|
0bbd64743c |
docs: move inspect and advisors into observability (#49503)
<!-- CURSOR_AGENT_PR_BODY_BEGIN --> ## Stack Draft stack extracted from `docs/monitoring`. Merge bottom-up. Troubleshooting / debugging-guide rewrite is out of scope. 1. **#49503** move inspect and advisors ← **this PR** 2. #49501 split Studio logs from ClickHouse queries 3. #49500 treat reports as signal dashboards 4. #49502 add Observe the data hub 5. #49506 add agent setup components 6. #49504 add hire-an-agent templates 7. #49505 restructure observability nav and overview ## 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? Docs update. First layer in the observability stack. ## What is the current behavior? Inspect and advisors live under Database (`/guides/database/inspect`, `/guides/database/database-advisors`). Observability readers have to leave the monitoring section to find them. ## What is the new behavior? - Moves inspect into `/guides/monitoring-and-debugging/inspect` - Adds `/guides/monitoring-and-debugging/advisors` (replaces the Database Advisors page) - Adds redirects and updates Studio/docs links so old URLs keep working - Adds both pages to the existing Monitoring nav so they are discoverable before the later IA PR ## Additional context Inspect and advisors pages render as standard MDX. Redirects cover `/docs/guides/database/inspect`, `/docs/guides/database/database-advisors`, and `/docs/guides/database/database-linter`. Debugging-guide content is unchanged except the inspect URL. ## Self-review - No leftover `/guides/database/inspect` or `/guides/database/database-advisors` links in docs guides or Studio linter/AI surfaces (historical blog posts left as-is) - Smoke test path updated to `/docs/guides/monitoring-and-debugging/advisors` <!-- CURSOR_AGENT_PR_BODY_END --> <div><a href="https://cursor.com/agents/bc-a3cb5ece-925b-4046-b58a-5d69e9a9d794?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/background-agent?bcId=bc-a3cb5ece-925b-4046-b58a-5d69e9a9d794&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img alt="Open in Cursor" width="131" height="28" src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a> </div> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added a centralized Advisors guide for security and performance checks. - Updated database inspection guidance with live Postgres statistics, cache hit-rate context, and query-analysis resources. - **Documentation** - Reorganized Advisors and database inspection content under Monitoring and Debugging. - Updated navigation, cross-references, in-product help links, and CLI documentation links. - Added permanent redirects from previous documentation URLs to preserve access. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Saxon Fletcher <SaxonF@users.noreply.github.com> Co-authored-by: Nik Richers <nik@validmind.ai> |
||
|
|
9b17ce8f2c |
chore(studio): default assistant to GPT-5.6 Luna (#49749)
## 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 / chore: hide assistant model selection in the UI and default chats to GPT-5.6 Luna. ## What is the current behavior? The assistant composer exposes a model picker. Paid orgs default to `gpt-5.3-codex`; everyone else defaults to `gpt-5.4-nano`. ## What is the new behavior? - The model picker is hidden in the assistant composer and Explorer home. - Chats default to `gpt-5.6-luna` with `reasoningEffort: medium`. - Model selection plumbing is kept (registry, entitlements, `setModel`, generate-v4 request body) so a requested model can still be honored when provided. - Other completion endpoints still use `gpt-5.4-nano`. ## Additional context Model selector UI can be re-enabled by passing `selectedModel` / `onSelectModel` to `AssistantChatForm`. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for the GPT-5.6 Luna model with medium reasoning capability. * Made GPT-5.6 Luna the default assistant model. * **Improvements** * Simplified assistant chat by removing model selection from the primary chat experience. * Updated model fallback behavior to use the standard assistant model. * Chat forms can now optionally display model selection when configured. * **Tests** * Updated model coverage and assistant chat tests for the new defaults and behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
8790e657e9 |
feat(ai): include org slug in Assistant Braintrust span metadata (#49692)
<!-- ccr-slack-attribution --> _Requested by **Matt Rossman** · [Slack thread](https://supabase.slack.com/archives/D0A79RYJKRB/p1787926891744399)_ # Problem Assistant spans in Braintrust record only the numeric `orgId`, whereas support tickets show org slug. This incurs an extra manual step to resolve the ID through admin studio before the trace can be found. # Fix Adds `orgSlug` to spans, sourced from the same verified org lookup that produces `orgId`. Renamed the request body's `orgSlug` to `rawOrgSlug` to distinguish the verified slug from getAIDetails, following the existing rawRequestedModel / requestedModel pattern. ## How to review See sample trace [94863b6d-aaa9-449a-a9c9-981ad40e614a](https://www.braintrust.dev/app/supabase.io/p/Assistant/trace?object_type=project_logs&object_id=5a8d02e5-b3b6-40cc-ba76-ecee286478f4&r=223112cd-33f4-45c4-a273-8d3781689448&s=223112cd-33f4-45c4-a273-8d3781689448) produced from sending a chat from the [Preview](https://studio-staging-git-mattrossman-ai-1149-include-698a5f-supabase.vercel.app/dashboard/org) on this PR. Note it now includes the org slug in span metadata: <img width="873" height="548" alt="CleanShot 2026-08-28 at 10 59 49@2x" src="https://github.com/user-attachments/assets/bcf47a94-6782-434a-9006-c7b9c95f1c37" /> If desired you can test yourself too by chatting with Assistant in the preview and looking up the corresponding Chat ID from Braintrust [logs](https://www.braintrust.dev/app/supabase.io/p/Assistant/logs). Closes AI-1149 --- _Generated by [Claude Code](https://claude.ai/code/session_01N2ziJech9dV19pJ9MisYdX)_ --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
4dee589735 |
fix(studio): stop assistant fabricating database_identifier for notebooks (#49558)
## Summary * Fixes [FE-4275](https://linear.app/supabase/issue/FE-4275/assistant-always-creates-notebooks-with-wrong-identifier-first-try): the assistant always created database notebook cells with a fabricated `database_identifier` (`"primary"`, later observed as `""` / `"_primary"` under different prompt wording) instead of omitting the key for the project's primary database, which tripped the tool's reject-and-retry validation on the very first attempt. * Prompt wording alone wasn't reliable — live eval runs against the real model kept substituting a new placeholder every time the prompt was tightened further. * Normalizes an empty-string `database_identifier` to absent at the schema level (`databaseIdentifierSchema` in `notebook-schema.ts`), which is inherited by every schema built from it — the AI SDK's `inputSchema` for `create_notebook`/`update_notebook`, and the write-boundary `writableNotebookSchema` used right before the PUT to the backend. * Adds an eval case (`evals/dataset.ts`) reproducing the original bug, plus unit tests covering schema-level and write-boundary normalization. ## Test plan - [X] `pnpm --filter studio exec tsc --noEmit` passes - [X] `pnpm exec prettier --check` passes on touched files - [X] Unit tests pass: `notebook-schema.test.ts`, `notebook-upsert-mutation.test.ts`, `notebook-tools.test.ts` (104 tests) - [X] Ran the new eval case against the real model 3x before the code fix (0% correctness, fabricated `""`/`"_primary"`) and 3x after (100% correctness) ## Summary by CodeRabbit * **Bug Fixes** * Improved notebook handling of empty database identifiers by treating them as absent. * Ensured notebook requests omit unused database identifier fields. * Added validation guidance for read-replica database identifiers. |
||
|
|
632e099487 |
feat(studio): track assistant notebook divergence (#49539)
## Summary - record server divergence when an assistant changes a notebook with local unsaved edits - clear the session-only marker after a successful save or notebook removal - cover update, delete, saved eviction, and lifecycle behavior ## Verification - pnpm --dir apps/studio exec vitest run state/notebooks/notebooks-state.test.ts lib/ai/notebook-cache-invalidation.test.ts - pnpm --dir apps/studio exec eslint state/notebooks/notebooks-state.ts state/notebooks/notebooks-state.test.ts lib/ai/notebook-cache-invalidation.ts lib/ai/notebook-cache-invalidation.test.ts - pnpm --dir apps/studio typecheck Stacked on the approval-warning PR for FE-4255. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved handling of server changes to notebooks with unsaved local edits. * Server updates and deletions are now tracked as divergences instead of being silently skipped. * Divergence indicators are cleared when changes are saved or notebooks are removed. * Unrelated notebook changes no longer create false conflicts. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
dcac820571 |
feat(studio): add assistant notebook run tool (#49361)
## 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? Assistant feature and data-handling plumbing. ## Stack context This stack is based on #49352 (`chore/assistant-tool-outcomes`) and assumes #49350–#49352 merge first. Review bottom to top: 1. #49361 — assistant notebook run tool 2. #49362 — assistant notebook run UI 3. #49364 — terminal-state polish ## What is the current behavior? The Assistant can read and edit notebooks, but it cannot execute all saved query cells as one approved operation. ## What is the new behavior? - Adds a `run_notebook` tool with one approval gate for the complete notebook. - Executes database and log cells sequentially in notebook order. - Rejects stale runs when the notebook changed after the Assistant read it. - Resolves primary and read-replica connections and forwards authorization to log and replica requests. - Shares rows with the model only when the organization's AI data-sharing level permits it. - Strictly validates and sanitizes persisted notebook-run output before replaying message history. - Registers the tool in prompts, filtering, mocks, and tool construction. ## How to test manually This is the tool/data layer; use the top-of-stack preview from #49364 for the complete UI while checking these behaviors. 1. In Explorer, create and save a notebook named **Assistant run smoke test** with: - a markdown cell - a working database query - a working Logs query - a database query that returns no rows, such as `select 1 where false` 2. Open the AI Assistant and ask: **Read the “Assistant run smoke test” notebook and analyze it using its current results.** 3. Confirm the Assistant reads the notebook and requests one `run_notebook` approval for all query cells, rather than requesting one approval per cell. 4. Approve the run. Confirm database and Logs queries execute in notebook order, the markdown cell is not executed, and the Assistant responds only after the complete run finishes. 5. Start another run but do not approve it yet. In another tab, edit and save the notebook. Return to the pending approval and approve it. 6. Confirm the stale run is rejected, the Assistant reads the latest notebook version, and a new approval is required. 7. Optional privacy check: set the organization AI data-sharing level to schema-only, run a query containing a recognizable value, and confirm the value remains visible in the notebook result UI but is not repeated in the Assistant's answer. ## Automated test `mise exec node@22 -- pnpm --dir apps/studio exec vitest --run lib/ai/tool-filter.test.ts lib/ai/tools/index.test.ts lib/ai/tools/mock-tools.test.ts lib/ai/tools/notebook-tools.test.ts lib/ai/tools/tool-sanitizer.test.ts` 80 tests pass at this stack boundary. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added AI-assisted notebook execution for database and log cells, with approval, freshness checks, replica support, and per-cell error handling. - Added notebook deletion and database discovery and validation for notebook management. - Added configurable privacy controls for notebook results. - Added request header support for analytics SQL execution. - **Bug Fixes** - Improved replica lookup handling so other notebook cells can continue when one lookup fails. - Prevented invalid, unauthorized, or overly detailed notebook execution results from being exposed. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Saxon Fletcher <SaxonF@users.noreply.github.com> |
||
|
|
40d9a2e929 |
fix(studio): invalidate notebook cache after assistant delete (#49496)
Stacked on supabase/supabase#49415. ## Summary - collect completed assistant delete_notebook tool calls as deleted cache effects - evict deleted notebooks from the React Query cache and notebook state - cover collector, cache eviction, and the open-tab Notebook not found state ## Verification - pnpm test:studio -- notebook-cache-invalidation ExplorerNotebookTab.assistant-cache-invalidation - pnpm --filter studio typecheck - touched-file ESLint and Prettier checks <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved notebook deletion handling so removed notebooks no longer remain visible after deletion. * Navigation and cached notebook data now update promptly when a notebook is deleted. * Attempting to access a deleted notebook now displays a clear “Notebook not found” message. * **Tests** * Added coverage for notebook deletion, cache invalidation, navigation updates, and the resulting not-found state. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |