Commit Graph
25 Commits
Author SHA1 Message Date
Pamela ChiaandJoshen Lim 4a941518e3 feat(studio): track Explorer runs and saves (#51004)
I added outcome events for Explorer query runs and successful manual
notebook saves. Existing page visits and preview toggles do not show
whether users complete queries or persist notebooks.

**Changed:**
- **Query usage:** Accepted runs from query tabs and notebook cells emit
submitted and terminal outcome events with a shared run ID. Canceled
confirmations emit no run events.
- **Notebook adoption:** Successful manual saves emit created or updated
events. Recreated notebooks count as creations. Unsaved drafts and
failed saves emit neither.
- **Event metadata:** Explorer action events use `Explorer` as their
page title.

**Note:** Assistant-generated saves are outside this PR. Custom
properties omit SQL and notebook content. Page visits still carry the
browser title, which can include a notebook name.

## To test

Tested on the staging preview:
- [x] Run valid and invalid SQL from an Explorer query tab. Each run
emits one submitted event and one matching completed or failed event
with the same run ID.
- [x] Run database and Logs notebook query cells, then add a markdown
cell. The query cells emit matching event pairs; the markdown cell emits
no query event.
- [x] Save a new notebook, then edit and save it again. The successful
saves emit created and updated events.
- [x] Cancel a guarded query. It emits no query run event.
- [ ] Recreate a notebook deleted on the server after local edits. A
successful save emits created, not updated.
- [x] Inspect an Explorer action event request. Its page title is
`Explorer`; page visits still use the browser title.
- [ ] Force a notebook save failure. It should emit no save event. This
case was not tested manually.

## Linear
- fixes GROWTH-1298


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

* **Analytics**
* Explorer query runs are tracked for database and log queries,
including whether they complete or fail.
* Query activity is associated with its location in Explorer, such as a
query tab or notebook cell.
  * Successful notebook saves are tracked as creations or updates.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-09-29 13:54:13 -07:00
Gildas GarciaandAlaister Young 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>
2026-09-11 12:17:49 +08:00
Joshen Lim a1686025b6 Joshenlim/fe 4291 keep unsaved notebooks accessible after page refresh (#49673)
## Context

Changes here adds a "Draft" state for notebooks with a new
`notebook-drafts` store - similar to how we handle query tabs in the
explorer.
This implies that if a user refreshes the tab while there's unsaved
changes to notebooks, the changes can be persisted locally and the user
will be able to continue from where they left off.

This also implies that If you create a new notebook (OR open an existing
notebook and make some changes) and refresh the browser, we no longer
show the native browser confirmation dialog about discarding changes.

We also reuse the existing confirmation dialog when saving a notebook if
its draft has diverged from the server side content - just updated the
language to be more generic rather than saying that the Assistant made
changes
<img width="429" height="238" alt="image"
src="https://github.com/user-attachments/assets/5c392aed-1633-4428-8060-28f495a01f04"
/>

Also fixes an unrelated issue - renaming a notebook should mark the
notebook as having unsaved changes (with the orange indicator)

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

## Summary by CodeRabbit

* **New Features**
* Unsaved notebook edits are saved locally and restored when reopening
Studio.
* Drafts are scoped by project and protected from server changes through
conflict detection.
* Notebook tabs indicate unsaved changes, including drafts from unsaved
notebooks.
* **Bug Fixes**
* Closing a tab with local edits prompts for confirmation and removes
its saved draft.
  * Notebook save state reflects the server-confirmed update time.
  * Conflict messages clearly describe changes made on the server.
* **Style**
  * Improved keyboard focus behavior for tab controls.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-09-09 17:17:25 +08:00
Charis 86c813ec03 fix(notebooks): reset insert offset when anchor cell moves (#49694)
## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

Bug fix

## What is the current behavior?

When a cell gets moved via `move_cell` operation in
`deriveNotebookDiff`, the `insertedAfter` offset map is not cleared for
that anchor cell. This causes later `insert_cell` operations anchored on
the same (now-moved) cell to apply the stale offset on top of the
correct current-position lookup, resulting in the new cell landing after
the wrong position.

## What is the new behavior?

The offset for an anchor cell is now cleared from `insertedAfter` when
it gets moved, since cells previously inserted after it stay behind at
its old location and should not affect subsequent inserts at its new
position.

A regression test has been added that reproduces the exact ticket
scenario (insert after cell-1, move cell-1 after cell-3, insert after
cell-1 again) and verifies the correct final cell order.

## Additional context

Fixes:
https://linear.app/supabase/issue/FE-4308/insert-anchored-to-a-previously-moved-cell-lands-after-the-wrong-cell

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

## Summary by CodeRabbit

* **Bug Fixes**
* Fixed notebook cell insertions after moving an anchor cell, ensuring
new inserts appear relative to the anchor’s updated position.
* Preserved the placement of inserts made before the anchor cell was
moved.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-28 12:12:04 -04:00
Charis eabb87564b fix(studio): resolve dirty notebook save conflicts (#49540)
## Summary
- require an explicit choice before saving a notebook that diverged
while dirty
- let users save over assistant changes or discard their local edits,
with deleted notebooks recreating safely
- keep dismissals side-effect free and close deleted notebook tabs when
edits are discarded

## Testing
- pnpm --filter studio exec vitest run
components/interfaces/Explorer/__tests__/ExplorerNotebookTab.assistant-cache-invalidation.test.tsx
data/content/notebooks/notebook-cache.test.ts --reporter=dot
- pnpm --filter studio typecheck

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

- **New Features**
- Added conflict handling when server-side notebook changes overlap with
local edits.
- Users can overwrite, recreate, discard, or dismiss changes through a
confirmation dialog.
- Deleted notebooks can be recreated when saved, while discarded deleted
notebooks are automatically removed from open tabs.
  - Conflict dialogs remain open while an action is in progress.

- **Bug Fixes**
- Improved notebook cache cleanup to remove stale and unsaved notebook
data reliably.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-26 17:12:10 +08:00
Charis 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.
2026-08-25 15:08:28 -04:00
Charis de3a8799d6 fix(studio): invalidate notebook caches after assistant create/update (#49415)
## Summary
- The assistant's `create_notebook`/`update_notebook` tools run entirely
server-side, so an open notebook tab's React Query cache and Valtio
store never learn a write happened — the tab keeps showing stale content
until a manual reload.
- Adds `collectNotebookCacheEffects`/`applyNotebookCacheEffects`
(`apps/studio/lib/ai/notebook-cache-invalidation.ts`), which scan
finished assistant messages for completed
`create_notebook`/`update_notebook` tool calls and evict the affected
notebook via `evictNotebookFromCaches`
(`apps/studio/data/content/notebooks/notebook-cache.ts`), plus
invalidate the nav list.
- Wired into `createChatInstance`'s `onFinish` in
`state/ai-assistant-state.tsx`, with per-chat dedupe so replayed history
isn't reprocessed.
- Removes the cache entry outright rather than invalidating it, since a
remounting `useNotebookQuery` would otherwise read the stale cached
value synchronously before its refetch lands.
- Explicitly skips eviction when the open tab has unsaved local edits,
so an assistant write can't silently discard them.

Related: [FE-4235](https://linear.app/supabase/issue/FE-4235)

**Out of scope:** this only protects the client-side cache/store from
being clobbered after the fact. Preventing the assistant's
`update_notebook` tool call itself from overwriting a user's unsaved
edits (a data-layer conflict, not a cache-freshness one) is tracked
separately in [FE-4255](https://linear.app/supabase/issue/FE-4255).

## Test plan
- [x] `pnpm test:studio -- notebook-cache notebook-cache-invalidation
ai-assistant-state.notebook-cache-invalidation
ExplorerNotebookTab.assistant-cache-invalidation
ExplorerNotebookTabCoordinator` — all passing
- [x] Reproduction-first component test
(`ExplorerNotebookTab.assistant-cache-invalidation.test.tsx`) — verified
it fails without the fix (stale content persists) and passes with it
- [x] Regression test for the dirty-notebook guard (an edited, unsaved
notebook is left untouched by an assistant write)
- [x] `pnpm typecheck --filter=studio` / `pnpm lint --filter=studio`
clean


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

* **Bug Fixes**
* Notebook changes made through the AI assistant now appear correctly in
open notebook tabs and after reopening them.
* Saved notebook caches are refreshed after completed create or update
actions, preventing stale content from being displayed.
  * Unsaved notebook changes are preserved during cache cleanup.
  * Closing a notebook tab now consistently removes its cached content.

* **Tests**
* Added coverage for assistant-driven updates, remounts, duplicate
actions, project context changes, and cache behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-25 14:15:27 +08:00
Saxon FletcherandJoshen Lim de2a7d8d9e Add view options to Query (#49447)
Currently Query tabs in explorer do not support view options e.g. table
vs chart. This adds display state to query tabs to match the behaviour
of Notebooks

## To test
- create a query in explorer
- Run a query
- Set the display options via toolbar

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

* **New Features**
  * Query results can now be displayed as either a table or chart.
* Chart settings are saved with each query draft and restored when
reopened.
* Display preferences are maintained independently across query drafts.
  * Editing a preview query now converts it into a permanent tab.
* **Bug Fixes**
* Invalid or legacy display settings safely fall back to the table view
without removing saved drafts.
* Charts and empty states now use the available editor space more
effectively.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-08-24 16:19:17 +08:00
CharisandJoshen Lim 48cc37f0d2 refactor(studio): extract notebook cache eviction helper (#49414)
## Summary

Part 1 of the FE-4247 stack
([FE-4247](https://linear.app/supabase/issue/FE-4247/assistant-invalidate-cache-after-notebook-editdeletion)).
Pure refactor, no behavior change — extracts the notebook cache eviction
logic that `ExplorerNotebookTabCoordinator` had open-coded into a shared
helper, so the upcoming assistant create/update/delete cache
invalidation (PR 2/3 in the stack) can reuse it instead of duplicating
the two-cache-layer eviction dance.

- New `evictNotebookFromCaches({ queryClient, projectRef, id, mode })`
in `apps/studio/data/content/notebooks/notebook-cache.ts`. `mode:
'refresh' | 'remove'` selects `invalidateQueries` vs `removeQueries` on
`contentKeys.resource`. Drops the notebook from `notebooksState` only
when its status is `'saved'`, matching the original open-coded guard
exactly. Returns whether it evicted, so callers can branch.
- `ExplorerNotebookTabCoordinator` now calls the helper with `mode:
'remove'` instead of inlining the logic.

## Test plan

- [x] `pnpm test:studio -- notebook-cache
ExplorerNotebookTabCoordinator` — new helper tests
(refresh/remove/dirty-guard/unknown-id) and existing coordinator tests
all pass
- [x] `pnpm typecheck --filter=studio`
- [x] `pnpm lint --filter=studio` — 0 errors, no new warnings

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

- **Bug Fixes**
- Improved detection of unsaved notebook changes for tab indicators and
close confirmations.
- Empty, never-saved notebooks are no longer included in discard
prompts.
- Improved cache cleanup when closing saved notebooks while preserving
unsaved work.
  - Added safeguards for missing notebook records.
- **Tests**
- Added coverage for notebook cache refresh, removal, preservation, and
no-op scenarios.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-08-24 15:59:41 +08:00
Charis 7b04fc7d09 revert(studio): reinstate database_identifier on the agent notebook schema (#49332)
## Summary
- Reverts #49326's temporary mitigation, which stripped
`database_identifier` from the agent-facing notebook cell schema
(`agentCellSchema`) because the assistant had no legitimate source of
truth for valid read-replica identifiers.
- The previous PR in this stack (#49328) added the `list_databases`
tool, so that source of truth now exists — `database_cell`s can carry
`database_identifier` again.

Part 3/6 of the stack for FE-4225 (expose valid database identifiers to
the notebook AI agent). Stacked on #49328.

## Test plan
- [x] Existing schema/preview tests (reverted alongside the mitigation)
pass
- [x] `pnpm --filter studio exec tsc --noEmit` passes

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

* **New Features**
* AI-generated notebook database cells now support database identifiers.
* Notebook previews display the associated database source, including
transitions between primary and replica databases.

* **Bug Fixes**
* Improved database metadata handling to preserve identifiers when
updating notebook cells.
* Database information is now shown only when available, preventing
inaccurate or missing metadata displays.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-21 10:36:20 -04:00
Charis 717927f4f2 fix(studio): AI assistant notebooks no longer set an invalid database_identifier (#49326)
## Summary

- The AI assistant's `create_notebook`/`update_notebook` tools could set
a `database_cell`'s `database_identifier` to a value that doesn't
correspond to any real database, because no tool exposes a project's
actual read-replica identifiers to the model.
- An unresolvable `database_identifier` silently breaks the cell:
`QueryEditor`'s connection-string lookup fails to find a match, and
running the cell fails with `Unable to run query: Connection string is
missing` — even though the exact same SQL runs fine when pasted into a
manually-created cell (which never sets this field).
- Fix: strip `database_identifier` from the agent-facing schema
(`agentCellSchema` in `notebook-schema.ts`) entirely, so the model can
no longer emit it at all. **This is a temporary fix** until we wire in
real read-replica support for the AI assistant (e.g. a tool exposing a
project's valid replica identifiers) — the field can be reintroduced
once the model has a legitimate source of truth to pull a valid
identifier from.
- Updated tests that relied on agent cells carrying
`database_identifier` to reflect the new behavior, and added a
regression test asserting `agentNotebookSchema` rejects a
`database_cell` with that field set.

Resolves FE-4224

## Test plan

- [x] `notebook-schema.test.ts`, `notebook-operations.test.ts`,
`notebook-tools.test.ts`, `AssistantNotebookPreview.test.tsx`,
`AssistantNotebookPreview.utils.test.ts` all pass
- [x] `tsc --noEmit` clean
- [x] Prettier clean on touched files

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

## Summary by CodeRabbit

* **Bug Fixes**
* Improved handling of database notebook cells when database metadata is
unavailable.
* Cells without database identifiers now display “No metadata” instead
of an incorrect replica identifier.
* Prevented invalid database identifiers from being accepted in
agent-generated notebook content.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-20 16:26:12 -04:00
Joshen Lim 2893c783d5 Hook up APIs for Notebooks CRUD (#49254)
## Context

API changes are ready so hooking up the endpoints for full CRUD UX E2E
- Can create notebooks
- Can load notebooks
- Can delete notebooks
- Can update notebooks
2026-08-20 22:23:20 +08:00
CharisandJoshen Lim 8bdfe03fe7 refactor(studio): drop notebook type widening now that the API supports it (#49272)
## Summary

- Regenerates `packages/api-types` for the content endpoints now that
the Platform API's `notebook` content type has landed (list/get/upsert
`type` enums, plus `UpsertContentBody`'s notebook cell shape with
`_id`/`y_series`). Unrelated schema drift from the same regen
(Warehouse, SSO, notification exceptions, etc.) is excluded — only the
content-endpoint hunks are applied.
- Removes every local widening cast added while the API support was
pending (`content-query.ts`, `content-infinite-query.ts`,
`notebook-query.ts`, `notebook-upsert-mutation.ts`,
`sql-folders-query.ts`).
- What remains is scoped and renamed to match: draft ids
(`generateDraftId`/`isDraftId`), used only for cells created client-side
in the editor before their first save, dropped before they'd ever reach
the backend as a fake `_id`.

## Test plan

- [x] `pnpm typecheck` — clean
- [x] `pnpm --filter studio test` — full suite passes (518 files / 5471
tests)
- [x] `pnpm --filter studio run lint:ratchet` — no new warnings
- [x] `pnpm format` / prettier — clean

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

* **Bug Fixes**
* Improved notebook cell tracking during editing, reordering, insertion,
and deletion.
* Preserved existing cell identifiers while removing temporary draft
identifiers before saving.
* Improved chart configuration for selecting and displaying multiple
Y-axis series.
  * Strengthened notebook validation and content persistence behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-08-20 13:06:41 +08:00
Joshen Lim 6fd48944a8 Support multi series bar charts in explorer and chart-bar (#49241)
## Context

- Updates the BarChart in our design system to support multi series in a
similar fashion to how the LineChart already supports multi series
- Update chart renderer in explorer notebooks to support multiple Y axes
using the `MultiSelector` component
- Up to 3 y columns can be selected for now (Arbitrary limit from a
color's selection POV but also just felt like anything more and the
chart doesn't feel useful)
- Only linear scale will be supported if multiple y columns are selected
(Will switch back to linear if originally on log scale)

<img width="943" height="493" alt="image"
src="https://github.com/user-attachments/assets/2eba46f0-7e41-4544-a3ff-2bf08773d11b"
/>
<img width="946" height="497" alt="image"
src="https://github.com/user-attachments/assets/4ffe7a73-6f97-4f0d-a33a-31e4035800ab"
/>


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

* **New Features**
* Charts now support selecting and displaying up to three Y-axis data
series.
  * Bar and line charts render multiple series with distinct colors.
* Cumulative calculations work independently across multiple selected
series.
* Chart controls provide clearer responsive layouts and limit selections
appropriately.

* **Bug Fixes**
* Logarithmic scaling automatically switches to linear when multiple
series or unsupported values are selected.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-19 16:58:35 +08:00
Charis 79fbe467ba feat(studio): wire notebook create/update proposals into assistant panel (#49159)
## Summary

PR 4 of the notebook-approval-preview stack.

- Adds `NotebookProposalRenderer`, wiring
`create_notebook`/`update_notebook` into `MessagePartSwitcher` and
rendering `NotebookPreview` across all 6 tool states (drafting,
approval-requested, approval-responded, output-available, output-denied,
output-error).
- `update_notebook` fetches the live notebook via `useNotebookQuery`,
checks `expected_updated_at` against the fetched `updated_at`, and gates
the confirm action behind a refresh when stale.
- A tool-input parse failure renders a raw-input admonition instead of
returning `null`, so `ConfirmFooter` — and the ability to Skip/deny —
stays available rather than leaving the chat stuck.

Towards FE-4143

## Test plan

- [x] `tsc --noEmit` clean
- [x] `eslint` clean on touched files
- [x] `prettier --check` clean
- [x] New `NotebookProposalRenderer.test.tsx` (create/update previews +
approve, version-mismatch warning, parse-failure fallback with working
Skip, output-available/output-denied summaries)
- [x] Existing notebook test suites (`notebook-tools.test.ts`,
`notebook-operations`, `NotebookPreview`) still pass

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

## Summary by CodeRabbit

* **New Features**
* Added AI-assisted notebook creation and updating with previews,
approval controls, and operation summaries.
* Added clear handling for loading, errors, denied actions, stale
notebook versions, and invalid proposals.
  * Added links to open notebooks after successful creation or updates.
  * Preserved notebook SQL content when displaying proposed changes.

* **Bug Fixes**
* Improved notebook proposal handling for conflicts and incomplete tool
responses.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-18 11:56:50 -04:00
Charis 2e68f2bf6e refactor(studio): derive notebook diff entries (#49109)
## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

Refactor, plus one bug fix.

Groundwork for showing the user a preview of what they are approving
when the AI Assistant creates or edits a notebook. No UI in this PR.

Towards FE-4143

## What is the current behavior?

`applyNotebookOperations` resolves an ordered list of notebook
operations into the resulting cells and nothing else. Rendering a diff
for the approval gate needs to know *what happened* to each cell
position, not just where things landed, so there is no way to build the
preview on top of it.

Separately, replacing a cell dropped its id, so `[replace cell-2, insert
after cell-2]` failed with a spurious `unknown_cell_id`.

## What is the new behavior?

`deriveNotebookDiff` resolves operations into one annotated entry per
cell position (`unchanged`, `added`, `removed`, `replaced`, `moved`).
`applyNotebookOperations` becomes a thin projection over its result, so
there is a single interpreter of notebook operations and the diff a user
approves cannot disagree with the cells that get written. The
pre-existing tests pass untouched, which is the evidence that the
projection is faithful.

Notes on the annotations:

- `removed` entries stay in the position the cell used to hold so the
list reads as a diff. This does not perturb insert-anchor arithmetic:
prior inserts still sit contiguously after their anchor.
- Moves that cancel out are downgraded to `unchanged`, since two moves
can anchor on each other and leave every cell where it started. Badging
those as moved would make the preview lie.
- `fromIndex` is the cell's position in the original notebook rather
than in the shifted working order, so `was #3` means what a reader
expects.

A replaced cell now stays addressable as an anchor. Anchoring and
targeting are separate lookups: a replaced cell can be anchored on, but
is never a legitimate target.

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

* **New Features**
* Notebook changes now provide a structured view of added, removed,
replaced, moved, and unchanged cells.
* Replaced cells can be used as insertion anchors, while invalid or
duplicate targets are rejected.
  * No-op moves are handled as unchanged cells.
* Notebook edits preserve operation ordering and original cell positions
for more predictable results.

* **Bug Fixes**
* Improved notebook operation handling and error reporting for complex
cell edits.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-17 13:11:40 -04:00
Charis e126b68390 feat(studio): make the notebook wire schema the source of truth for query sources (#49069)
First of a stack. Groundwork only — additive, no behavior change,
nothing else in the tree touched.

The notebook content schema is the contract shared with the API and the
agent tool surface, so it is where source parameters and their
validation belong. A follow-up PR has the runtime query-source registry
borrow from here instead of keeping its own parallel definitions, which
had already drifted (different discriminant, different field names, a
narrower set of relative units).

## What changed

- **`timeRangeSchema` is exported**, and picks up the two validations
that existed only in the registry's copy and not here: a positive
integer `amount`, and an absolute range whose end follows its start.
- **`databaseSourceSchema` / `logsSourceSchema`** give each backend's
parameters a single definition. They are spread flat into their cells
with `...shape` rather than nested under a `source` key, so the JSON an
agent has to author stays shallow.
- **`database_identifier`** lets a database cell persist a read-replica
selection, which it previously had no field for. Named that rather than
`identifier` because every cell already carries an `id`.
- **`queryCellBaseSchema`** holds what every runnable cell shares
(`title`, `view`, `chart`), which was duplicated across `database_cell`
and `log_cell`. `sql` deliberately stays on the members so the domain
transform can brand it per dialect and generic code holding a query cell
can't hand it to the wrong wire boundary.
- **`CELL_KINDS` + `isQueryCell`** classify cells for query-generic UI.
The `satisfies Record<Cell['_tag'], CellKind>` clause makes this the
registration point for a new backend: adding a cell type fails to
compile until it is classified, and `QueryCell` widens on its own once
it is.

## Wire compatibility

The only wire shape change is the new optional `database_identifier`, so
`schema_version` stays at 1 and no persisted content needs migrating.
Notebooks are still behind the `explorer` flag, so there is no saved
`user_content` to worry about either way.

`view` keeps master's current handling — optional on the wire, defaulted
to `'table'` in the domain transform — and `chart` stays persisted
independently of it, so switching to the table view and back returns the
user's chart settings rather than rebuilding them.

## Tests

`notebook-schema.test.ts` covers the new validations (unit set,
non-positive/fractional amounts, absolute ordering, which field an
invalid bound is reported against), `database_identifier`, `isQueryCell`
narrowing, and that a chart survives alongside `view: 'table'`.

Typecheck, Prettier, and the lint ratchet all clean; 120 tests pass
across `data/content/notebooks` and `lib/ai/tools`.

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

## Summary by CodeRabbit

- **New Features**
- Added support for database identifiers in notebook query
configurations.
- Improved handling of database and log query cells for more consistent
notebook behavior.
  - Preserved chart configuration when switching to a table view.

- **Bug Fixes**
- Time ranges now require valid dates, positive whole-number relative
amounts, and correctly ordered absolute start and end times.
- Validation errors now identify the specific time-range field with
invalid date values.

- **Tests**
- Expanded coverage for query-cell detection, time-range validation,
optional database identifiers, and chart settings.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-14 13:18:41 +07:00
Joshen Lim 2f89014f74 Add logs cells (#49064)
## Context

Related to Explorer/Notebooks - adds the source selector for query cell
within a notebook

<img width="1108" height="648" alt="image"
src="https://github.com/user-attachments/assets/d1434197-3738-41b0-a8ef-1919c91181d9"
/>

<img width="1103" height="633" alt="image"
src="https://github.com/user-attachments/assets/97f8c6a3-629d-4a41-aab4-3fdc5e8b2c7e"
/>


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

* **New Features**
  * Added support for displaying log cells in the query editor.
  * Added switching between database and log query sources.
  * Log and database cells can display results as tables or charts.
  * Log queries support optional row limits.
  * Improved reliability when changing query settings.
  * Notebook query views now default to table display when unspecified.

* **Bug Fixes**
  * Log cells no longer appear blank or get omitted from notebook views.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-14 02:23:06 +07:00
Joshen Lim d434c63bad joshen/fe 4150 explorer query cells result display settings (#49003)
## Context

Related to Explorer / Notebooks - this adds chart functionality for the
Query cells
<img width="250" alt="image"
src="https://github.com/user-attachments/assets/4ea37c14-87dc-4c43-ba7f-cb9436085c81"
/>

Query results can be rendered as either bar or line chart - using the
chart packages from `ui-patterns`
[NOTE]: For design team reviewers - am patching the chart packages to be
agnostic to the `timestamp` property within the provided data set. Would
love to use this component from a consistency POV instead of the old
`BarChart` component we have.

Have intentionally omitted log scale functionality from this PR - will
have that separately 🙏

<img width="999" height="483" alt="image"
src="https://github.com/user-attachments/assets/14356ee4-c658-4fd1-90e0-17c38dac4822"
/>
<img width="988" height="478" alt="image"
src="https://github.com/user-attachments/assets/cd0ca088-9a03-4aa3-9884-17bc36d3cabf"
/>



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

- **New Features**
- Added chart views for notebook query results, including bar and line
charts.
- Added display settings for selecting X/Y columns, chart type, scale,
cumulative values, and label visibility.
  - Added configurable X-axis support for charts.
  - Display preferences are saved with each notebook cell.

- **Improvements**
  - New database cells default to table view.
  - Chart results better handle varied data types.
- Empty results and incomplete chart settings now display clear
placeholders.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-13 10:09:54 +07:00
Charis b9835e419c test(studio): mock notebook tools (#48952)
## Summary
- Adds deterministic `list_notebooks`/`get_notebook` fixtures (two
seeded notebooks, each with markdown/database/log cells) and stateful
in-memory `create_notebook`/`update_notebook` mocks to
`apps/studio/lib/ai/tools/mock-tools.ts`, so Braintrust evals can
exercise notebook tool calls without a real project.
- Both write-tool mocks force `needsApproval: false`, matching the
existing `execute_sql`/`deploy_edge_function` mock pattern — the eval
harness filters out tool-parts in `'approval-requested'` state and can
never answer an approval gate.
- All four notebook tools are wrapped from the real `getNotebookTools()`
definitions (only `execute`/`needsApproval` overridden), so evals
validate the model's arguments against the exact production schemas.
- Dedupes `describeOperationError` (previously duplicated between this
new mock and `notebook-tools.ts`) into a single exported
`describeNotebookOperationError` in `notebook-operations.ts`.

**Stacked on #48949** (`feature/notebooks-update-tool`) — this PR's base
branch is that PR, not `master`, because it reuses `update_notebook` and
the shared error helper that only exist there. Merge #48949 first, then
retarget/merge this one.

## Test plan
- [x] \`pnpm --filter studio typecheck\` passes
- [x] \`pnpm --filter studio test\` — all notebook-related suites pass
(\`mock-tools.test.ts\`, \`notebook-tools.test.ts\`,
\`data/content/notebooks/*\`)
- [x] \`eslint\` / \`prettier --check\` clean on all touched files
2026-08-12 10:34:37 -04:00
Charis 810d292121 feat(studio): notebook cell operations (#48940)
## Summary
- Pure module (`data/content/notebooks/notebook-operations.ts`) for
applying `update_notebook` cell edits client-side: `insert_cell`
(`after_cell_id` incl. `'start'`), `replace_cell`, `delete_cell`,
`move_cell`.
- Never touches the safe-sql brands — SQL promotion still happens at the
tool-execute boundary, matching `create_notebook`.
- Stacked on #48938. No wiring yet — `update_notebook` tool wiring is
next.

Towards FE-4083

## Test plan
- [x] `pnpm vitest run
data/content/notebooks/notebook-operations.test.ts` — 13 unit tests
covering every op, combinations, and all three error cases.
- [x] `pnpm exec tsc --noEmit` clean
- [x] `pnpm exec eslint` clean on new files

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

* **New Features**
* Added support for applying notebook cell operations, including
insertion, replacement, deletion, and movement.
* Operations are applied in a predictable order, with support for
anchoring new cells at the beginning or near existing cells.
* Added validation for invalid references, conflicting operations, and
self-referential moves.
* Added clear handling when operations produce an empty notebook result.

* **Tests**
* Added comprehensive coverage for individual, combined, ordered,
conflicting, invalid, and empty-result notebook operations.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-11 12:35:27 -04:00
Charis ddb3e2c442 feat(studio): create_notebook AI tool (#48938)
## Summary
- Adds a `create_notebook` AI assistant tool (`needsApproval: true`)
that lets the assistant create a new notebook after explicit user
approval.
- Cell SQL is promoted from untrusted to safe via
`acceptUntrustedSql`/`acceptUntrustedLogsSql` inside `execute`, using
the approval gate as the confirming user gesture (same pattern as
`execute_sql`).
- Input is validated against the existing agent-writable notebook
schema, which rejects any agent-supplied cell `id` at the schema level.
- Threads an optional auth-headers param through
`upsertContent`/`createNotebook`/`updateNotebook` so the tool can pass
its own bearer token server-side.
- Registers the tool in the tool-filter (`SCHEMA` category, alongside
`list_notebooks`/`get_notebook`) and adds a `## Notebooks` prompt
section guiding the assistant on when to use `create_notebook` vs.
one-off `execute_sql`.

Resolves FE-4082

## Test plan
- [x] `notebook-tools.test.ts` covers: tool registration,
`needsApproval`, cell-id rejection, valid input, PUT body shape, and the
returned id — all passing
- [x] Typecheck clean
- [x] Lint clean (no new warnings)

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

* **New Features**
* Added AI-assisted notebook creation for saving multi-step
investigations.
* Added support for database and log SQL cells in newly created
notebooks.
* Notebook creation requires approval before saving and returns the
notebook’s name and identifier.
* Added support for custom request headers during notebook and content
operations.
* Added guidance for choosing between one-time SQL execution and
reusable notebooks when Explorer is enabled.

* **Improvements**
* Improved validation and normalization of notebook content before
saving.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-11 11:54:49 -04:00
Charis 4587d177c3 Add optional title field to notebook cells (#48937)
## Summary

- Adds optional `title` field to `databaseCellSchema` and
`logCellSchema` in notebook schema
- Allows database and logs notebook cells to carry descriptive titles
- Field automatically propagates through derived schemas (wire,
writable, agent, domain) via Zod inheritance

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

## Summary by CodeRabbit

* **New Features**
  * Added optional titles to database and log notebook cells.
* Cell titles are now preserved across notebook editing, viewing, and
agent workflows.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-11 09:21:33 -04:00
Charis 1296a1c745 feat(studio): notebook query and mutation hooks (#48907)
## Summary

Implements the "notebook query and mutation hooks" step of the notebooks
data layer:

- `data/content/notebooks/notebook-query.ts` —
`getNotebook`/`useNotebookQuery`, wrapping the existing `getContentById`
and narrowing to `type: 'notebook'`.
- `data/content/notebooks/notebooks-infinite-query.ts` —
`useNotebooksInfiniteQuery`, a typed wrapper over
`useContentInfiniteQuery` narrowing pages to notebook rows.
- `data/content/notebooks/notebook-upsert-mutation.ts` —
`createNotebook`/`updateNotebook` + their mutation hooks, PUTting
through the existing `upsertContent`.

Write-path correctness, worked out while building the mutation hooks:

- Cell `id`s are always backend-generated, never client-supplied — a
brand-new cell has no `id` at all; an existing cell being kept/edited in
an update keeps its real id so the backend can diff it against the
previous version. `notebook-schema.ts` gains
`writableCellSchema`/`writableNotebookSchema` (ids optional per cell)
and `WritableCell`/`WritableNotebook` types, derived from `z.infer` of
those schemas rather than hand-duplicated, with only the `sql` field
re-branded per cell type via a small distributive conditional type.
- Cell SQL at this write boundary must already be
`SafeSqlFragment`/`SafeLogSqlFragment` (proven user-authored at a
save/run event handler), not `unchecked_sql` — matching the
`safe-sql-execution` skill's provenance model.
- `content-remap.ts`'s notebook `unmapSqlContentField` branch is
simplified to a passthrough: notebook writes only ever arrive already
wire-shaped via `createNotebook`/`updateNotebook`, so there's nothing
left to unmap.

Note: this was originally stacked on
`feature/notebooks-types-convergence`, but that branch merged into
`master` (#48905) while this PR was in progress, so it's rebased
directly onto `master` now.

## Test plan

- [x] `pnpm --filter studio run typecheck` passes
- [x] `pnpm --filter studio exec vitest run data/content/notebooks
data/content/content-remap.test.ts` — 38/38 passing
- [x] `pnpm --filter studio exec eslint` clean on all touched files

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

## Summary by CodeRabbit

* **New Features**
* Added notebook listing with pagination, filtering, sorting, and
project-specific queries.
  * Added notebook retrieval for viewing individual notebooks.
  * Added notebook creation and editing with automatic content refresh.
* Added support for preserving cell IDs and safely handling SQL content.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-10 15:32:46 -04:00
CharisandJoshen Lim 0b97e37ccf feat: notebook content schema (#48813)
Related to FE-4109.

## Summary

- **API codegen workaround**: Platform API's `notebook` content type
hasn't shipped to the OpenAPI spec yet, so `pnpm api:codegen` can't be
run. Locally widened `ContentBase.type` to include `'notebook'` (marked
with TODO for removal once spec publishes).
- **Notebook schema & type system**: Introduced Zod schemas mirroring
RFC-defined notebook shape (`schema_version: 1, cells: Cell[]`).
Maintains wire/domain boundary (cell `sql` → `unchecked_sql` branded for
security). Agent-writable schema for `create_notebook` tool omits cell
IDs (backend-generated); future update operations will require them. All
TypeScript types are `z.infer`'d from schemas (no hand-written parallel
interfaces).
- **IsoDateTimeString moved**: Extracted ISO datetime validator from
`querySource.ts` to `lib/iso-datetime.ts` (data layer shouldn't import
from components layer). Needed by notebook `time_range` fields.

## Test plan

- [x] Unit tests: `notebook-schema.test.ts` (9 tests),
`iso-datetime.test.ts` (3 tests), `querySource.test.ts` updated and
passing (26 tests)
- [x] Typecheck: no new errors
- [x] Prettier: formatting clean

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

## Summary by CodeRabbit

- **New Features**
- Added support for validating and processing notebook content,
including markdown, database, log cells, time ranges, and chart
configurations.
  - Added compatibility for notebook content types in content handling.
- Added reliable ISO date-time validation for notebook data and related
features.

- **Tests**
- Expanded coverage for valid and invalid notebook structures, cell
requirements, time ranges, chart settings, and date-time values.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-08-07 13:40:18 +07:00