Commit Graph

79 Commits

Author SHA1 Message Date
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
Charis
89b4f1aca4 feat(studio): add delete_notebook tool to AI assistant (#49413)
## Summary

* Adds a `delete_notebook` AI assistant tool (`needsApproval: true`)
that lets the assistant delete a notebook with explicit user approval,
mirroring the existing `create_notebook`/`update_notebook` tools.
* Wires up a destructive-styled approval card in the AI Assistant Panel
(fetches the notebook to show its name, warns the deletion is permanent)
using the same `Confirm`/tool-approval plumbing as the other notebook
tools.
* Updates `tool-filter.ts` opt-in gating, the assistant system prompt,
the eval-harness mock tools, and the eval dataset with `delete_notebook`
coverage.
* Adds test coverage in `notebook-tools.test.ts`, `mock-tools.test.ts`,
and `NotebookProposalRenderer.test.tsx`.

Closes
[FE-4242](https://linear.app/supabase/issue/FE-4242/assistant-delete-notebook-tool).

## Test plan

- [X] `pnpm typecheck --filter=studio` passes
- [X] `pnpm --filter studio exec vitest run` for the touched files
(notebook-tools, mock-tools, NotebookProposalRenderer,
[Message.Parts](<http://Message.Parts>), and existing consumers of
`content-delete-mutation`) — all passing
- [X] `eslint` and `prettier --check` clean on all touched files
- [X] Manual verification of the approval UI in a running Studio
instance (not done in this session)

## Summary by CodeRabbit

* **New Features**
* Added AI-assisted notebook deletion with explicit confirmation and
irreversible-action warnings.
* Added safeguards to distinguish deleting an entire notebook from
removing individual panels.
* Completed deletions now display the deleted notebook’s name without an
option to reopen it.
* **Bug Fixes**
* Improved handling of missing notebooks and invalid deletion requests.
* **Tests**
* Added coverage for deletion approval, denial, errors, and successful
completion.

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

* **New Features**
* Added AI-assisted notebook deletion with explicit approval and
irreversible-action warnings.
* Added confirmation, loading, error, and completion states for notebook
deletion.
* Prevented accidental full-notebook deletion when only a panel or
section should be removed.
* Improved notebook update results by showing applied changes when
available.

* **Bug Fixes**
  * Notebook deletion now uses the required API version.
* Improved handling and validation of missing notebooks during deletion.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-08-24 13:18:12 -04:00
Saxon Fletcher
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
Charis
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
Charis
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
Ivan Vasilov
b5477a89a3 chore: Update API types (#48981)
Update the API types by running `api:codegen`. Some of the changes are
fixed in code, some of the type changes had to be reverted (JIT Access,
SSO features).

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

* **Billing**
  * Updated subscription messaging to reflect AWS Marketplace billing.
  * Removed outdated partner-billing downgrade notices.

* **Bug Fixes**
* Improved request handling for API keys, custom domains, SQL snippets,
branches, and storage operations.
  * Improved legacy signing-key compatibility.
  * Refined temporary database access availability messaging.

* **Updates**
  * Removed Fly as an available cloud provider for region selection.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-13 09:48:13 +02: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
7798e42435 feat(studio): notebook read tools (#48908)
## Summary
- Adds `list_notebooks` (cursor-paginated) and `get_notebook` AI tools
in `lib/ai/tools/notebook-tools.ts`, modeled directly on
`report-tools.ts`: server-side `getContent`/`getNotebook` with the
`authorization` header forwarded, zod-validated input.
- `get_notebook` resolves every cell and exposes `unchecked_sql` as a
plain `sql` field for the agent to read — display only, per the
`safe-sql-execution` skill; nothing here executes SQL.
- Registers both tools in `lib/ai/tools/index.ts` (same platform branch
as reports) and in `lib/ai/tool-filter.ts`'s `toolSetValidationSchema` +
`TOOL_CATEGORY_MAP` (`SCHEMA` tier).
- Adds an optional `headers` param to `content-infinite-query.ts`'s
`getContent`, mirroring the sibling `content-query.ts`, so the
cursor-paginated fetch can carry the `Authorization` header from a
server context.
- New tools are behind the Explorer feature flag.

Stacked on #48907 (1.4 — notebook query and mutation hooks), per the
Notebooks implementation plan (stack 2.1).

Resolves FE-4081
Resolves FE-4080

## Test plan
- [x] `pnpm exec tsc --noEmit` — no new errors
- [x] `pnpm exec vitest run lib/ai/tools/notebook-tools.test.ts
lib/ai/tools/index.test.ts lib/ai/tools/report-tools.test.ts
data/content/notebooks` — 36/36 passing
- [x] `pnpm --filter studio run lint` — no new warnings
- [x] `pnpm exec prettier --check` on changed files — clean

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

* **New Features**
  * Added AI tools to list project notebooks with pagination.
* Added AI support for retrieving notebook markdown and resolved SQL
cell content.
  * Notebook tools now respect project and authorization context.
* Notebook features are available only when Explorer access is enabled.
  * Content requests can forward custom request headers.

* **Tests**
* Added coverage for notebook tools, Explorer access, feature flags,
authorization, pagination, and error handling.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-11 08:40:51 -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
Charis
957e9fec67 feat(studio): notebook content at the API boundary (#48815)
## Summary

Stacked on #48813 (1.2: notebook content schema). Part of
[FE-4109](https://linear.app/supabase/issue/FE-4109/notebooks-data-model)
— see that issue for the rest of the notebooks data-model stack.

- Teach `content-remap.ts`'s wire↔domain dispatcher about the `notebook`
content type, branding each cell's `sql` per `_tag` via the notebook
schemas added in 1.2 (parses through `notebookDomainSchema` on the way
in, unbrands per cell on the way out).
- Add `{ type: 'notebook'; content: Notebooks.Content }` to the
`Content` union in `content-query.ts`, plus a `ContentOfType<T>` helper
for narrowing it.
- Fix the resulting narrowing fallout at call sites that assumed
`Content` only ever meant `sql`/`report`/`log_sql`: two
generated-query-param casts, and four report/logs call sites now
narrowed via `ContentOfType<'report'>` / `ContentOfType<'log_sql'>`.

## Test plan

- [x] `pnpm --filter studio vitest run data/content/` — 35 tests pass,
including new notebook coverage in `content-remap.test.ts` (per-cell
brand separation, missing-field throw, remap↔unmap round-trip)
- [x] `pnpm typecheck` — clean (pre-existing unrelated `ui-patterns`
error aside)
- [x] `pnpm --filter studio lint` — no new warnings/errors on changed
files
- [x] `pnpm format` — clean

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-08-10 10:15:24 -04:00
Charis
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
Charis
b3c5c9fc04 feat(studio): logs snippets in SQL editor nav, search, and tabs (#48457)
## What

PR 7 of the SQL-editor query-source (Database vs Logs) stack. Surfaces
`log_sql` snippets as a distinct query source across the SQL editor
sidebar. Stacked on **`charislam/toolbar-ui-creation-flow`** (PR 6 —
toolbar UI + creation flow); review/merge that first.

Nothing is user-visible until the flags roll out — every entry point
requires **both** `sqlEditorLogsSource` **and** `otelLegacyLogs`.

## Changes

- **Nav** — a flag-gated **Logs** section (`LogsSnippetsSection`) backed
by its own single-type `log_sql` query. The active snippet is injected
only into the section it belongs to, via a shared
`withActiveSnippet(snippets, active, belongsPredicate)` helper (also
DRYs the private/favorites/shared injections).
- **Search** (`SearchList`) — a **Logs** result group with a shared,
extracted `SqlSnippetTree`; the "N results found" count now sums
database + logs, with loading/empty states covering both queries.
- **Tabs** — an immutable `sqlSource` field on tab/recent-item metadata
(set at tab creation, lazily backfilled once the snippet loads via
`useEffectEvent`), and a distinct `ScrollText` icon via a shared
`LogsSnippetIcon`. Tab cleanup treats `log_sql` tabs as live and only
prunes them when logs data is authoritative (`canPruneLogsTabs`), so a
disabled/erroring logs query never wrongly deletes logs tabs or blocks
database-tab cleanup.
- **Data layer** — `useSqlSnippetsQuery` gains an optional `type` param
so logs reuse the same `SnippetWithContent` shape as the other sections
(no casts).

## Tests

- `state/tabs.test.ts` — `sqlSource` backfill + creation-time
carry-through.
- `components/layouts/Tabs/Tabs.utils.test.tsx` — cleanup prunes stale
database/logs snippets, keeps live ones, and preserves logs tabs when
logs data isn't authoritative.

## Verification

- `pnpm --filter studio typecheck` ✓
- `pnpm --filter studio run lint:ratchet` ✓
- `pnpm test:studio` (affected suites) ✓

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

* **New Features**
* Added a collapsible Logs section to the SQL editor sidebar for
browsing, sorting, selecting, renaming, and deleting log queries.
* Expanded SQL search with separate, paginated results for database and
log queries.
* Added dedicated log-query icons across navigation, tabs, previews, and
recent items.
* **Bug Fixes**
* Improved tab and recent-item cleanup while preserving active log
queries and accurate source metadata.
* **Tests**
* Added coverage for log tab cleanup and SQL source metadata
synchronization.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-04 09:02:39 -04:00
Joshen Lim
2c53ca4a79 Support listing and reading custom reports from Assistant (#48530)
## Context

This is pre-requisite work for adding support to managing custom reports
from the Assistant. Planning to break this into a number of PRs, briefly
- Adding read support for custom reports
- Adding write support for custom reports
- Adding run support for custom reports
  - Should be able to infer data from the results then

This PR starts with adding support for listing and reading custom
reports from the Assistant

## Other changes involved
- Updates setting up of the home page report to have better title and
description
- Swaps the variant of the ToggleGroup in the SQL block for custom
reports as the default variant blends into the background color of the
PopoverContent

## To test
- [ ] Assistant should be able to list custom reports + read its
contents
<img width="428" height="755" alt="image"
src="https://github.com/user-attachments/assets/6a15b660-c0ee-4a06-984c-87eff3943eec"
/>


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

- **New Features**
- Added AI-assisted tools to list reports and retrieve report details,
including chart counts, layouts, configurations, and SQL-backed chart
information.
  - Added clearer empty-state messaging when no snippets are available.

- **Improvements**
- New homepage reports now use the name “Homepage Report” and include a
descriptive project-home summary.
  - Updated query controls with refreshed visual styling.
  - Improved content requests to support additional request context.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-03 13:59:50 +07:00
Charis
fa5eb17277 feat(studio): discriminated snippet union + source-aware writes (#48313)
Stacked on #48305.

## What

PR 3 of the stacked SQL-editor query-source series (Database vs Logs).
Stacked on the PR 2 branch `charislam/log-sql-content-shape`.

Turns `SnippetWithContent` into a discriminated union on `type` and
makes all snippet writes source-aware:

- `data/content/sql-folders-query.ts`: `SnippetWithContent` is now `{
type: 'sql'; content?: SqlSnippets.Content } | { type: 'log_sql';
content?: LogSqlSnippets.Content } | { type: 'report'; content?: never
}`. `report` is kept (the content endpoints' wire type carries it) but
has no SQL content — its body is `Dashboards.Content`, loaded through
the separate `Content` union.
- `setSql` brands per type (`untrustedLogSql` vs `untrustedSql`).
- `buildUpsertPayload` persists `snippet.type` (no longer hardcoded
`'sql'`).
- `createSqlSnippetSkeletonV2({ source })` emits the matching type +
content shape with the `as any` cast removed.
- New `components/interfaces/SQLEditor/querySource.ts`:
`SqlSnippetSource` + `getSnippetSource`.
- `seedSnippet` test helper gains a `source` arg.
- New `remapWireSnippet` boundary helper in `content-remap.ts`
concentrates the single wire->domain assertion, so `content-id-query` /
`content-upsert-mutation` call sites are cast-free (no `as unknown as`).
- Collateral: query result types aligned to the union; `updateSnippet`
no longer accepts `type` (source is immutable); db-only editor read
paths narrow away `log_sql`.

## Why

Impossible-states-impossible typing: a snippet's brand follows its
content type, so logs SQL and database SQL can never cross execution
paths. No behavior change for existing database snippets.

## Testing

- \`pnpm typecheck\` — clean
- \`pnpm --filter studio run lint:ratchet\` — no new warnings
- \`pnpm test:studio\` (data/content, SQLEditor, state/sql-editor) —
passing, including new tests for \`getSnippetSource\`, source-aware
\`setSql\`, type-aware \`buildUpsertPayload\`, and both skeleton shapes.

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

* **New Features**
* Added source-aware creation for SQL editor snippets, including
log-based SQL snippets.
* Introduced backend source mapping so log snippets are treated as
log_sql.
* **Bug Fixes**
* Improved SQL retrieval/prettification so log snippets no longer use
the wrong fallback content.
* Ensured log snippets are sanitized and preserve correct type, content,
identifiers, and statuses during save/upsert flows.
* **Tests**
* Expanded unit and integration coverage for log snippet creation,
source mapping, editing, prettification, and upsert payloads.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-28 12:28:36 -04:00
Charis
7743fee3ab feat(studio): log_sql content shape + remap content.sql to unchecked_sql (#48305)
## What

PR **2 of 9** in the SQL-editor query-source (Database vs Logs) stack.

**Base:** `charislam/snippet-source-typing` (#48301) — this is a stacked
PR; review/merge that one first.

Client-side rename only — **the wire format is unchanged** (the platform
API still stores and returns `content.sql`). This moves the frontend
`LogSqlSnippets.Content` field to the branded `unchecked_sql`, matching
`SqlSnippets.Content`, and hardens the remap boundary so the rename
can't silently drop saved query text.

## Changes

- **`types/userContent.ts`** — `LogSqlSnippets.Content`'s plain `sql:
string` becomes `unchecked_sql: UntrustedLogSqlFragment` (the brand
added in PR 1). Shape kept minimal: `{ content_id, unchecked_sql,
schema_version }`.
- **`data/content/content-remap.ts`** — extend
`remapSqlContentField`/`unmapSqlContentField` to `log_sql`, branding
**per type** (`untrustedLogSql` for logs, `untrustedSql` for database)
and never mixing brands. **Defensive unmap**: content missing
`unchecked_sql` is never clobbered with `sql: undefined`; a residual raw
`sql` field (a missed save-path rename) throws in development to surface
the bug loudly, while production no-ops safely.
- **Legacy Logs Explorer consumers** updated to the branded field: the
explorer save/update paths, `SavedQueriesItem`, `RecentQueriesItem`, and
the recent-queries page.
- **Two db-only write sites** that leaned on
`LogSqlSnippets.Content.sql`: `EditorPanel` now saves `unchecked_sql`,
and `MoveQueryModal` switches to the SQL-editor-specific
`getSqlSnippetById` so its content is typed as `SqlSnippets.Content` —
no narrowing or casting.

## Tests

- **content-remap**: `log_sql` remap/unmap round-trip with the logs
brand; the defensive-unmap no-op (prod) and dev throw.
- **content-upsert-mutation**: a `log_sql` payload reaches the wire as a
plain `content.sql` and the response remaps back to `unchecked_sql` (the
data-loss-critical round-trip shared by both explorer save-new and
`SavedQueriesItem` update).

## Verification

- `pnpm --filter studio run typecheck` ✓
- `pnpm --filter studio run lint:ratchet` ✓ (no new warnings)
- `pnpm test:studio` for `data/content` + `Settings/Logs` — 139 passing
✓
- Prettier ✓

Nothing is user-visible yet — logs snippet entry points arrive later in
the stack behind the `sqlEditorLogsSource` flag.

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

- **Bug Fixes**
- Improved handling of saved and recent log queries across the SQL
editor and Logs Explorer.
- Log SQL now uses `unchecked_sql` (branded as untrusted) consistently
when creating, editing, moving, and reopening queries, with correct
remapping to/from the API boundary.
- Fixed saved-query update payloads to preserve the right query content
and omit legacy fields.

- **Tests**
- Added/expanded Vitest coverage for saved log query editing, recent-log
normalization, and `log_sql` remap/upsert request/response behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-28 10:47:43 -04:00
Andrey A.
4562af27c2 test(studio): cover SQL content remap and upsert response remap (#47445) 2026-06-30 15:36:39 +02:00
Charis
b34a9a027f fix: snippet content missing after move or rename (#47409)
Snippet content was wiped blank after a move or rename (until dashboard
refreshed) because it depended on the API returning the new content, but
the API returns under the `content` field, not the `unchecked_sql` field
that is expected. Added a `remapSqlContentField` remap to fix.

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

## Summary by CodeRabbit

* **Bug Fixes**
* Improved the saved content response so snippet fields are mapped
consistently before being returned.
* Kept the saved status unchanged while updating the returned data shape
for better accuracy.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-06-29 19:14:56 +00:00
Charis
d5653f1f92 refactor(studio): unify snippet save + persistence into SnippetStatus (3/9) (#47251)
## What

PR 3 of a stacked refactor of the SQL editor snippet state. Replaces the
two overlapping pieces of snippet lifecycle state — the `savingStates`
map (`IDLE|UPDATING|UPDATING_FAILED`) and the `isNotSavedInDatabaseYet`
boolean — with a single `SnippetStatus` enum.

## Status is attached at the data layer (never absent)

- `SnippetStatus` + `SnippetWithContent` now live in `data/content`. The
snippet queries attach `status: 'saved'` via a typed `withSavedStatus()`
helper, and `upsertContent` returns `SnippetWithContent` so move/rename
responses carry status too.
- A SQL-typed `getSqlSnippetById`/`useSqlSnippetByIdQuery` returns
`SnippetWithContent` (the generic `useContentIdQuery` stays for Reports,
which use it). `[id].tsx` loads content with **no casting**.
- `'new'` is attached on local creation (`createSqlSnippetSkeletonV2`).

## Behavior

Behavior-preserving for the existing auto-save flow (faithful mapping of
both old fields, including the replication-lag swallow). One incidental
fix: the read-only/saving indicator now also covers a brand-new
snippet's first save (previously only re-saves of persisted snippets had
distinct saving/failed states in some paths).

## Tests

New `sql-editor-lifecycle.test.ts` (29 tests) covering every predicate
and transition; existing rules tests updated. `pnpm --filter studio
typecheck` clean; 52 state/sql-editor unit tests pass.

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

## Summary by CodeRabbit

## Release Notes

* **Refactor**
* Restructured SQL snippet persistence tracking, replacing boolean flags
with a comprehensive status system for clearer visibility into save
progress.
* Enhanced saving indicator UI to reflect accurate snippet save states.

* **Tests**
* Added test coverage for snippet persistence state transitions and
lifecycle scenarios.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-06-24 08:56:39 -04:00
Jordi Enric
4c011cf9c0 feat(reports): add optimistic delete for custom reports (#46803)
## Problem

Deleting a custom report waited for the API round trip before updating
the UI. The confirmation modal showed a loading spinner, the report
stayed visible in the sidebar until the request resolved, and the
interaction felt sluggish.

## Fix

The delete now applies optimistically. On confirm, the report is removed
from the sidebar immediately and the user is navigated away. The actual
delete runs in the background. If it fails, the cached list is rolled
back to its previous state and an error toast is shown.

The optimistic behavior lives inside `useContentDeleteMutation` (via
`onMutate` snapshot + `onError` rollback), so any current or future
caller of that hook gets it for free, no per-call wiring required.

## How to test

- Open a project with at least one custom report
- Click the kebab menu on a report and choose Delete report, then
confirm
- Expected result: the report disappears from the sidebar instantly and
a success toast appears
- To test rollback: throttle/offline the network or force the delete
endpoint to fail, then delete again
- Expected result: the report reappears in the sidebar and an error
toast is shown

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

* **Improvements**
* Deletion flows now provide explicit loading, success and error
feedback; UI updates immediately on delete and will restore if the
action fails.

* **Removals**
* Removed the reports menu and individual report menu item UI components
(affects report-level rename/delete dropdowns and related menu
navigation).

* **Tests**
* Added tests covering content deletion behavior, multiple-deletion
cases, and data integrity after removals.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 09:57:19 +02:00
Charis
0433eeb5f5 feat(studio): mark sql provenance for safety (#45336)
Mark provenance of SQL via the branded types SafeSqlFragment and
UntrustedSqlFragment. Only SafeSqlFragment should be executed;
UntrustedSqlFragments require some kind of implicit user approval (show
on screen + user has to click something) before they are promoted to
SafeSqlFragment.

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

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

* **Refactor**
* Platform-wide SQL handling tightened: snippets and AI-generated SQL
are treated as untrusted/display-only until promoted, improving safety
and consistency.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-05-04 13:08:06 -04:00
Charis
3b7052b5a9 cleanup: fix import order and prefixes for studio/data (#44501) 2026-04-03 09:15:57 +02:00
Ivan Vasilov
5fb5acc0b9 chore: Refactor the generation of ids for snippets (#41264)
* Add a generateDeterministicUuid function and tests for it.

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

* Clean up extra code.

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

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

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

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

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

* Save the snippet to the API when adding it.

* Minor fixes from CodeRabbit review.

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

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

* UpsertContentPayload always has an id.

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2025-12-16 09:43:59 +01:00
Ivan Vasilov
581ae07120 fix: Hide favourites and share snippets on self-hosted variant (#41227)
* Hide favorite and share actions for self-hosted version.

* Rename the query on save only on platform.

* Simplify useCheckOpenAiKeyQuery.

* Rename with AI now depends if the OPENAI_API_KEY is set.

* Minor fixes.

* Fix the tests to use .skip for skipping tests. Remove extra port params.

* Make the test for favourites work only on platform variant.
2025-12-10 10:12:15 -07:00
Ivan Vasilov
0d5be306ef chore: Bump React Query to v5 (#40174)
* Bump the deps, refactor deprecated code.

* Migrate keepPreviousData usage.

* Migrate all uses of InfiniteQuery.

* Fix refetchInterval in queries.

* Migrate all use of isLoading to isPending in mutations.

* Fix accessing location in claim-project.

* Fix a bug in duplicate query keys.

* Migrate all queries to use isPending.

* Revert "Fix accessing location in claim-project."

This reverts commit 2a07df64b5.

* Revert the rss.xml file to master.
2025-12-10 10:10:29 +01:00
Kamil Ogórek
762bdfa741 ref: Remove unused queries/mutations (#41163) 2025-12-08 18:39:05 +01:00
Luca Forstner
e063783f76 refactor: Send favorite as top level value for user content (#40556)
Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2025-11-19 15:16:58 +01:00
Ivan Vasilov
c83d7255a4 chore: Migrate leftover query keys (#40573)
* Fix queryKey to be compatible with RQ 5.

* Revert .find usage of queryKey.
2025-11-18 10:27:17 -07:00
Ivan Vasilov
8b657165b5 chore: Migrate to use custom type for ReactQuery queries and mutations (#40073)
* Add custom types for queries, mutations and infinite queries.

* Migrate all queries to use the new type.

* Migrate all infinite queries to useCustomInfiniteQueryOptions.

* Migrate all mutations to use useCustomMutationOptions.

* Add type to all imports in `types` folder.
2025-11-03 13:18:13 +01:00
Joshen Lim
64e3e047eb Final final cleaning up barrel files (#40018)
* Final final cleaning up barrel files

* Fix merge conflict
2025-10-31 14:02:59 +08:00
Ivan Vasilov
da4a40e308 chore: Migrate RQ functions to use object syntax style (#39895)
* Migrate all uses of invalidateQueries to use object syntax.

* Migrate the remainder of useInfiniteQuery.

* Migrate all setQueriesData.

* Migrate all fetchQuery uses.

* Migrate some leftover functions from RQ.

* Fix issues found by Charis.
2025-10-28 10:43:14 +01:00
Alaister Young
8855d05803 chore(studio): swap react-query to object syntax (#39842)
* chore(studio): swap react-query to object syntax

* Fix small issues found

* Fix realtime settings

* Nit

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2025-10-27 09:38:27 +01:00
Kevin Grüneberg
312259b704 chore: user v2 content count query for search (#39869)
* chore: user v2 content count query for search

Instead of using two different endpoint versions, we can rely on v2 for all cases.

* Update SearchList.tsx
2025-10-26 13:49:33 +08:00
Joshen Lim
426fda2ebc Address circular dependencies across multiple files (#39231)
* Address circular dependencies across multiple files

* Fix TS
2025-10-06 11:01:56 +08:00
Riccardo Busetti
77356bf946 feat(replication): Significantly improve the replication UI behavior (#38237) 2025-08-29 12:20:51 +02:00
Joshen Lim
c153df20c8 Refactor search list in sql editor to have context menu (#37945)
* Refactor search list in sql editor to have context menu

* Add visibility to snippet item in search list tree view

* Address feedback

* Attempt to fix unit test for edit secret modal

* REvert changes to edit secret modal test
2025-08-18 11:26:33 +08:00