The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
refactor(studio): drop notebook type widening now that the API supports it (#49272)
Charis8bdfe03fe765
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsxindex adc39e12076..b0fb890f53a 100644--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx@@ -41,7 +41,7 @@ export const ExplorerNotebookTab = () => {const currentNotebook = useCurrentNotebook()const { name, content } = currentNotebook?.notebook ?? {}const cells = content?.cells ?? []- const queryCellIds = cells.filter(isQueryCell).map((cell) => cell.id)+ const queryCellIds = cells.filter(isQueryCell).map((cell) => cell._id)const [isRunningNotebook, setIsRunningNotebook] = useState(false)const queryCellRefs = useRef(new Map<string, QueryEditorHandle>())@@ -82,7 +82,7 @@ export const ExplorerNotebookTab = () => {if (!notebookId) returnconst cell = type === 'markdown' ? createMarkdownCellSkeleton() : createQueryCellSkeleton()- const lastCellId = cells[cells.length - 1]?.id+ const lastCellId = cells[cells.length - 1]?._idsnap.insertCellAfter({ id: notebookId, cellId: lastCellId, cell })}@@ -133,22 +133,22 @@ export const ExplorerNotebookTab = () => {<><DndContext sensors={sensors} onDragEnd={handleDragEnd}><SortableContext- items={cells.map((cell) => cell.id)}+ items={cells.map((cell) => cell._id)}strategy={verticalListSortingStrategy}><div className="flex flex-col gap-y-4">{cells.map((cell) =>isQueryCell(cell) ? (<QueryCell- key={cell.id}+ key={cell._id}cell={cell}ref={(instance) => {- if (instance) queryCellRefs.current.set(cell.id, instance)- else queryCellRefs.current.delete(cell.id)+ if (instance) queryCellRefs.current.set(cell._id, instance)+ else queryCellRefs.current.delete(cell._id)}}/>) : (- <MarkdownCell key={cell.id} cell={cell} />+ <MarkdownCell key={cell._id} cell={cell} />))}</div>diff --git a/apps/studio/components/interfaces/Explorer/MarkdownCell.tsx b/apps/studio/components/interfaces/Explorer/MarkdownCell.tsxindex 3cbf89238be..df8dc8860f8 100644--- a/apps/studio/components/interfaces/Explorer/MarkdownCell.tsx+++ b/apps/studio/components/interfaces/Explorer/MarkdownCell.tsx@@ -41,7 +41,7 @@ export const MarkdownCell = ({ cell }: MarkdownCellProps) => {const notebookId = currentNotebook?.notebook.idif (!notebookId) return- const nextCells = cells.map((c) => (c.id === cellId ? { ...c, text } : c))+ const nextCells = cells.map((c) => (c._id === cellId ? { ...c, text } : c))snap.updateCells({ id: notebookId, cells: nextCells })setIsEditing(false)}@@ -50,9 +50,9 @@ export const MarkdownCell = ({ cell }: MarkdownCellProps) => {return (<SortableSection- id={cell.id}- actions={<AddCellDropdown cellId={cell.id} />}- gripDropdownContent={<MoveCellDropdownContent cellId={cell.id} />}+ id={cell._id}+ actions={<AddCellDropdown cellId={cell._id} />}+ gripDropdownContent={<MoveCellDropdownContent cellId={cell._id} />}gripClassName="mt-1.5 opacity-0 group-hover:opacity-100 has-[[data-state=open]]:opacity-100 transition">{isEditing ? (@@ -84,10 +84,10 @@ export const MarkdownCell = ({ cell }: MarkdownCellProps) => {].join(' && '))editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter, () =>- handleUpdateMarkdownRef.current(cell.id, valueRef.current)+ handleUpdateMarkdownRef.current(cell._id, valueRef.current))editor.onDidBlurEditorWidget(() =>- handleUpdateMarkdownRef.current(cell.id, valueRef.current)+ handleUpdateMarkdownRef.current(cell._id, valueRef.current))}}/>@@ -100,7 +100,7 @@ export const MarkdownCell = ({ cell }: MarkdownCellProps) => {<Buttonvariant="text"onMouseDown={(e) => e.preventDefault()}- onClick={() => handleUpdateMarkdown(cell.id, value)}+ onClick={() => handleUpdateMarkdown(cell._id, value)}>Done</Button>diff --git a/apps/studio/components/interfaces/Explorer/MoveCellDropdownContent.tsx b/apps/studio/components/interfaces/Explorer/MoveCellDropdownContent.tsxindex 5fb0e392ba7..9cc1632a111 100644--- a/apps/studio/components/interfaces/Explorer/MoveCellDropdownContent.tsx+++ b/apps/studio/components/interfaces/Explorer/MoveCellDropdownContent.tsx@@ -12,7 +12,7 @@ export const MoveCellDropdownContent = ({ cellId }: MoveCellDropdownContentPropsconst currentNotebook = useCurrentNotebook()const cells = currentNotebook?.notebook.content?.cells ?? []- const currentIndex = cells.findIndex((c) => c.id === cellId)+ const currentIndex = cells.findIndex((c) => c._id === cellId)const isFirstCell = currentIndex <= 0const isLastCell = currentIndex === -1 || currentIndex === cells.length - 1diff --git a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.test.tsx b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.test.tsxindex e12d35d52b1..a1f9e8622f8 100644--- a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.test.tsx+++ b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.test.tsx@@ -8,7 +8,7 @@ import { customRender as render } from '@/tests/lib/custom-render'const wireMarkdownCell = (id: string, text: string): CellWire => ({_tag: 'markdown_cell',- id,+ _id: id,text,})@@ -16,7 +16,7 @@ const agentMarkdownCell = (text: string): AgentCell => ({ _tag: 'markdown_cell',const wireDatabaseCell = (id: string, database_identifier?: string): CellWire => ({_tag: 'database_cell',- id,+ _id: id,sql: 'select 1',row_limit: 100,database_identifier,diff --git a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.test.ts b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.test.tsindex 5f4523daea5..f9ca459fa5e 100644--- a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.test.ts+++ b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.test.ts@@ -15,7 +15,7 @@ import { isoDateTimeString } from '@/lib/iso-datetime'const wireMarkdownCell = (id: string, text = 'hello'): CellWire => ({_tag: 'markdown_cell',- id,+ _id: id,text,})@@ -23,7 +23,7 @@ const agentMarkdownCell = (text = 'hello'): AgentCell => ({ _tag: 'markdown_cellconst wireDatabaseCell = (id: string, title?: string, database_identifier?: string): CellWire => ({_tag: 'database_cell',- id,+ _id: id,title,sql: 'select 1',row_limit: 100,@@ -32,7 +32,7 @@ const wireDatabaseCell = (id: string, title?: string, database_identifier?: striconst wireLogCell = (id: string): CellWire => ({_tag: 'log_cell',- id,+ _id: id,sql: 'select 1',time_range: { _tag: 'relative_time_range', unit: 'day', amount: 7 },})diff --git a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.ts b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.tsindex 3d40260a6e8..11959be18c8 100644--- a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.ts+++ b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.ts@@ -1,16 +1,19 @@import dayjs from 'dayjs'import type { CodeBlockLang } from 'ui-patterns/CodeBlock'-import type { NotebookCellDiffEntry } from '@/data/content/notebooks/notebook-operations'-import type { AgentCell, CellWire, TimeRange } from '@/data/content/notebooks/notebook-schema'+import type {+ NotebookCellDiffEntry,+ OperationResultCell,+} from '@/data/content/notebooks/notebook-operations'+import type { TimeRange } from '@/data/content/notebooks/notebook-schema'-/** React key for a diff entry. Added/replaced cells have no `id`, so they key off the operation. */+/** React key for a diff entry. Added/replaced cells have no `_id`, so they key off the operation. */export function getEntryKey(entry: NotebookCellDiffEntry): string {switch (entry._tag) {case 'unchanged':case 'removed':case 'moved':- return entry.cell.id+ return entry.cell._idcase 'added':case 'replaced':return `op-${entry.operationIndex}`@@ -27,7 +30,7 @@ export function isEntryExpandedByDefault(entry: NotebookCellDiffEntry): boolean}/** Human label for a collapsed/badge row. */-export function getCellLabel(cell: CellWire | AgentCell): string {+export function getCellLabel(cell: OperationResultCell): string {switch (cell._tag) {case 'markdown_cell':return 'Markdown cell'@@ -38,7 +41,7 @@ export function getCellLabel(cell: CellWire | AgentCell): string {}/** The cell's underlying source text, regardless of backend. */-export function getCellSourceText(cell: CellWire | AgentCell): string {+export function getCellSourceText(cell: OperationResultCell): string {switch (cell._tag) {case 'markdown_cell':return cell.text@@ -49,7 +52,7 @@ export function getCellSourceText(cell: CellWire | AgentCell): string {}/** Language for rendering the cell's source via `CodeBlock`. */-export function getCellCodeBlockLanguage(cell: CellWire | AgentCell): CodeBlockLang {+export function getCellCodeBlockLanguage(cell: OperationResultCell): CodeBlockLang {switch (cell._tag) {case 'markdown_cell':return 'markdown'@@ -60,7 +63,7 @@ export function getCellCodeBlockLanguage(cell: CellWire | AgentCell): CodeBlockL}/** Monaco language id for rendering the cell's source via `DiffEditor`. */-export function getCellMonacoLanguage(cell: CellWire | AgentCell): string {+export function getCellMonacoLanguage(cell: OperationResultCell): string {switch (cell._tag) {case 'markdown_cell':return 'markdown'@@ -85,7 +88,7 @@ export function formatTimeRange(range: TimeRange): string {* when the cell has none. A `replace_cell` can change only this and leave `sql` identical,* so it's compared independently of the source text rather than folded into it.*/-export function getCellMetadataLine(cell: CellWire | AgentCell): string | null {+export function getCellMetadataLine(cell: OperationResultCell): string | null {switch (cell._tag) {case 'markdown_cell':return nulldiff --git a/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.ts b/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.tsindex 1d11993ee23..2480bdc709a 100644--- a/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.ts+++ b/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.ts@@ -16,7 +16,7 @@ import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'const CHART: ChartConfig = {type: 'bar',x_column: 'day',- y_columns: ['signups'],+ y_series: ['signups'],cumulative: false,scale: 'linear',show_labels: true,@@ -24,7 +24,7 @@ const CHART: ChartConfig = {const DATABASE_CELL: QueryCell = {_tag: 'database_cell',- id: 'cell-1',+ _id: 'cell-1',title: 'Signups',view: 'chart',chart: CHART,@@ -35,7 +35,7 @@ const DATABASE_CELL: QueryCell = {const LOG_CELL: QueryCell = {_tag: 'log_cell',- id: 'cell-2',+ _id: 'cell-2',title: 'Edge errors',view: 'table',chart: CHART,@@ -66,7 +66,7 @@ describe('changeCellSource', () => {expect(next).toEqual({_tag: 'log_cell',- id: 'cell-1',+ _id: 'cell-1',title: 'Signups',view: 'chart',chart: CHART,@@ -80,7 +80,7 @@ describe('changeCellSource', () => {expect(next).toEqual({_tag: 'database_cell',- id: 'cell-2',+ _id: 'cell-2',title: 'Edge errors',view: 'table',chart: CHART,@@ -138,7 +138,7 @@ describe('cloneQueryCell', () => {const clone = cloneQueryCell(DATABASE_CELL)expect(clone).toEqual(DATABASE_CELL)- expect(clone.chart?.y_columns).not.toBe(DATABASE_CELL.chart?.y_columns)+ expect(clone.chart?.y_series).not.toBe(DATABASE_CELL.chart?.y_series)})})diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.ts b/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.tsindex ca6cb3edb57..5eabf93bd83 100644--- a/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.ts+++ b/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.ts@@ -17,13 +17,13 @@ export const DEFAULT_CELL_ROW_LIMIT = 100* Valtio snapshots are deep-readonly. Readonly properties assign to mutable ones, so only* the array needs rebuilding to turn a snapshot's chart back into a writable config.*/-type ReadonlyChartConfig = Omit<ChartConfig, 'y_columns'> & {- readonly y_columns: readonly string[]+type ReadonlyChartConfig = Omit<ChartConfig, 'y_series'> & {+ readonly y_series: readonly string[]}export const cloneChartConfig = (chart: ReadonlyChartConfig | undefined-): ChartConfig | undefined => (chart ? { ...chart, y_columns: [...chart.y_columns] } : undefined)+): ChartConfig | undefined => (chart ? { ...chart, y_series: [...chart.y_series] } : undefined)/** The display state a query cell hands the shared editor. */// `view` is already defaulted to 'table' by the domain transform, so there is nothing to@@ -35,7 +35,7 @@ export const getCellDisplay = (cell: Snapshot<QueryCell>): QueryDisplay => ({/** Fields every query cell carries, copied out of a snapshot so the result is writable. */const copyQueryCellBase = (cell: Snapshot<QueryCell>) => ({- id: cell.id,+ _id: cell._id,title: cell.title,view: cell.view,chart: cloneChartConfig(cell.chart),diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsxindex dec95340133..5293f0f3ecc 100644--- a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx+++ b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx@@ -53,7 +53,7 @@ export const QueryCell = forwardRef<QueryEditorHandle, QueryCellProps>(functionsnap.updateCell({id: notebookId,- cellId: cell.id,+ cellId: cell._id,updater: (candidate) => (isQueryCell(candidate) ? updater(candidate) : candidate),})}@@ -89,14 +89,14 @@ export const QueryCell = forwardRef<QueryEditorHandle, QueryCellProps>(functionreturn (<SortableSection- id={cell.id}- actions={<AddCellDropdown cellId={cell.id} />}- gripDropdownContent={<MoveCellDropdownContent cellId={cell.id} />}+ id={cell._id}+ actions={<AddCellDropdown cellId={cell._id} />}+ gripDropdownContent={<MoveCellDropdownContent cellId={cell._id} />}gripClassName="mt-2 opacity-0 group-hover:opacity-100 has-[[data-state=open]]:opacity-100 transition"><QueryEditorref={ref}- id={cell.id}+ id={cell._id}variant="embedded"title={title}query={toQueryModel(cell, sql)}diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/DisplaySettingsButton.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/DisplaySettingsButton.tsxindex e093b3c2ddc..6704864b680 100644--- a/apps/studio/components/interfaces/Explorer/QueryEditor/DisplaySettingsButton.tsx+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/DisplaySettingsButton.tsx@@ -29,7 +29,7 @@ import {import { ExplorerToolbarAction } from '../ExplorerToolbar'import { type QueryDisplay, type QueryResult } from '../types'import { checkHasNonPositiveValues } from '@/components/ui/QueryBlock/QueryBlock.utils'-import { MAX_CHART_Y_COLUMNS, type ChartConfig } from '@/data/content/notebooks/notebook-schema'+import { MAX_CHART_Y_SERIES, type ChartConfig } from '@/data/content/notebooks/notebook-schema'interface DisplaySettingsButtonProps {display: QueryDisplay@@ -39,9 +39,9 @@ interface DisplaySettingsButtonProps {onChange: (display: QueryDisplay) => void}-const getLogScaleDisabledReason = (y_columns: string[]) => {- if (y_columns.length === 0) return 'Select a column for the Y axis first'- if (y_columns.length > 1) return 'Only available with a single Y axis column'+const getLogScaleDisabledReason = (y_series: string[]) => {+ if (y_series.length === 0) return 'Select a column for the Y axis first'+ if (y_series.length > 1) return 'Only available with a single Y axis column'return 'Data contains zero or negative values'}@@ -56,22 +56,22 @@ export const DisplaySettingsButton = ({const {type = 'bar',x_column,- y_columns = [],+ y_series = [],cumulative = false,show_labels = false,scale = 'linear',} = chart ?? {}const hasNonPositiveValues = useMemo(- () => checkHasNonPositiveValues(result?.rows ?? [], y_columns[0]),- [result, y_columns]+ () => checkHasNonPositiveValues(result?.rows ?? [], y_series[0]),+ [result, y_series])// Logarithmic scale only applies to a single series.const canToggleLogScale = useMemo(() => {- if (y_columns.length !== 1 || !result || (result.rows ?? []).length === 0) return false+ if (y_series.length !== 1 || !result || (result.rows ?? []).length === 0) return falsereturn !hasNonPositiveValues- }, [hasNonPositiveValues, result, y_columns.length])+ }, [hasNonPositiveValues, result, y_series.length])const onChangeView = (view: 'table' | 'chart') => {onChange({ ...display, view })@@ -83,7 +83,7 @@ export const DisplaySettingsButton = ({chart: {type: chart?.type ?? 'bar',x_column: chart?.x_column ?? '',- y_columns: chart?.y_columns ?? [],+ y_series: chart?.y_series ?? [],cumulative: chart?.cumulative ?? false,scale: chart?.scale ?? 'linear',show_labels: chart?.show_labels ?? false,@@ -97,10 +97,10 @@ export const DisplaySettingsButton = ({})useEffect(() => {- if (scale === 'log' && (hasNonPositiveValues || y_columns.length > 1)) {+ if (scale === 'log' && (hasNonPositiveValues || y_series.length > 1)) {resetToLinearScale()}- }, [hasNonPositiveValues, scale, y_columns.length])+ }, [hasNonPositiveValues, scale, y_series.length])return (<Popover>@@ -187,16 +187,16 @@ export const DisplaySettingsButton = ({className="[&>div:first-child]:xl:w-3/5"><MultiSelector- values={y_columns}+ values={y_series}onValuesChange={(values) => {- if (values.length > MAX_CHART_Y_COLUMNS) return- onUpdateChartConfig({ y_columns: values })+ if (values.length > MAX_CHART_Y_SERIES) return+ onUpdateChartConfig({ y_series: values })}}className="w-full"><MultiSelectorTriggermode="inline-combobox"- label={`Select up to ${MAX_CHART_Y_COLUMNS} columns`}+ label={`Select up to ${MAX_CHART_Y_SERIES} columns`}deletableBadgebadgeLimit="wrap"showIcon={false}@@ -208,9 +208,7 @@ export const DisplaySettingsButton = ({<MultiSelectorItemkey={x}value={x}- disabled={- y_columns.length >= MAX_CHART_Y_COLUMNS && !y_columns.includes(x)- }+ disabled={y_series.length >= MAX_CHART_Y_SERIES && !y_series.includes(x)}>{x}</MultiSelectorItem>@@ -249,7 +247,7 @@ export const DisplaySettingsButton = ({</TooltipTrigger>{!canToggleLogScale && (<TooltipContent side="left">- {getLogScaleDisabledReason(y_columns)}+ {getLogScaleDisabledReason(y_series)}</TooltipContent>)}</Tooltip>diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsxindex 52958c120b7..09787e596c7 100644--- a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx@@ -12,7 +12,7 @@ interface QueryResultChartProps {result?: QueryResult}-const Y_COLUMN_COLORS = [+const Y_SERIES_COLORS = ['hsl(var(--brand-default))','hsl(var(--chart-blue))','hsl(var(--chart-3))',@@ -25,36 +25,36 @@ const toChartValue = (value: unknown): string | number => {}export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {- const { type, x_column, y_columns = [], cumulative, show_labels, scale } = chart ?? {}+ const { type, x_column, y_series = [], cumulative, show_labels, scale } = chart ?? {}- const hasConfig = !!x_column && y_columns.length > 0+ const hasConfig = !!x_column && y_series.length > 0// Logarithmic scale only makes sense for a single series — DisplaySettingsButton// resets `scale` to linear once a second Y column is added- const effectiveScale = y_columns.length > 1 ? 'linear' : scale+ const effectiveScale = y_series.length > 1 ? 'linear' : scaleconst chartConfig: ChartSeriesConfig = useMemo(() =>- y_columns.reduce((acc, key, index) => {- acc[key] = { label: key, color: Y_COLUMN_COLORS[index] }+ y_series.reduce((acc, key, index) => {+ acc[key] = { label: key, color: Y_SERIES_COLORS[index] }return acc}, {} as ChartSeriesConfig),- [y_columns]+ [y_series])const chartRows = useMemo(() => {const xKey = x_column ?? ''return (result?.rows ?? []).map((row) => {const chartRow: Record<string, string | number> = { [xKey]: toChartValue(row[xKey]) }- y_columns.forEach((yKey) => {+ y_series.forEach((yKey) => {chartRow[yKey] = toChartValue(row[yKey])})return chartRow})- }, [result, x_column, y_columns])+ }, [result, x_column, y_series])const cumulativeResults = useMemo(- () => getCumulativeResults({ rows: chartRows }, { yKey: y_columns }),- [chartRows, y_columns]+ () => getCumulativeResults({ rows: chartRows }, { yKey: y_series }),+ [chartRows, y_series])const resultToRender = cumulative ? cumulativeResults : chartRows@@ -81,43 +81,45 @@ export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {}return (- <Chart className="flex h-full min-h-0 flex-col">- <ChartCard className="flex h-full min-h-0 flex-col rounded-none border-0">- <ChartContent className="flex h-full min-h-0 flex-1 flex-col">- {type === 'bar' && (- <ChartBar- isFullHeight- xKey={x_column}- dataKey={y_columns[0]}- dataKeys={y_columns}- config={chartConfig}- showXAxis={show_labels}- showYAxis={show_labels}- data={resultToRender}- YAxisProps={{- scale: effectiveScale === 'log' ? 'log' : 'auto',- domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,- tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,- }}- />- )}- {type === 'line' && (- <ChartLine- isFullHeight- xKey={x_column}- dataKey={y_columns[0]}- dataKeys={y_columns}- config={chartConfig}- showXAxis={show_labels}- showYAxis={show_labels}- data={resultToRender}- YAxisProps={{- scale: effectiveScale === 'log' ? 'log' : 'auto',- domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,- tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,- }}- />- )}+ <Chart>+ <ChartCard className="rounded-none border-0">+ <ChartContent>+ <div className="h-40">+ {type === 'bar' && (+ <ChartBar+ isFullHeight+ xKey={x_column}+ dataKey={y_series[0]}+ dataKeys={y_series}+ config={chartConfig}+ showXAxis={show_labels}+ showYAxis={show_labels}+ data={resultToRender}+ YAxisProps={{+ scale: effectiveScale === 'log' ? 'log' : 'auto',+ domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,+ tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,+ }}+ />+ )}+ {type === 'line' && (+ <ChartLine+ isFullHeight+ xKey={x_column}+ dataKey={y_series[0]}+ dataKeys={y_series}+ config={chartConfig}+ showXAxis={show_labels}+ showYAxis={show_labels}+ data={resultToRender}+ YAxisProps={{+ scale: effectiveScale === 'log' ? 'log' : 'auto',+ domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,+ tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,+ }}+ />+ )}+ </div></ChartContent></ChartCard></Chart>diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsxindex 882d79dfb94..71425a3fb5e 100644--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx@@ -43,7 +43,7 @@ const NOTEBOOK_ID = 'notebook-test'const databaseCell = createQueryCellSkeleton({ sql: 'select 1' })const logCell = {_tag: 'log_cell' as const,- id: 'log-cell-1',+ _id: 'log-cell-1',view: 'table' as const,chart: undefined,unchecked_sql: untrustedLogSql('select * from edge_logs limit 1'),diff --git a/apps/studio/components/interfaces/Explorer/utils.ts b/apps/studio/components/interfaces/Explorer/utils.tsindex 70caeba255f..92a4cc2dcdb 100644--- a/apps/studio/components/interfaces/Explorer/utils.ts+++ b/apps/studio/components/interfaces/Explorer/utils.ts@@ -1,12 +1,12 @@import { untrustedSql } from '@supabase/pg-meta'import { DEFAULT_CELL_ROW_LIMIT } from './QueryCell/QueryCell.utils'-import { generateUuid } from '@/lib/api/snippets.browser'+import { generateDraftId } from '@/data/content/notebooks/notebook-schema'export const createQueryCellSkeleton = ({ sql }: { sql?: string } = {}) => {return {_tag: 'database_cell' as const,- id: generateUuid(),+ _id: generateDraftId(),view: 'table' as const,chart: undefined,unchecked_sql: untrustedSql(sql ?? ''),@@ -26,7 +26,7 @@ export const createMarkdownCellSkeleton = ({} = {}) => {return {_tag: 'markdown_cell' as const,- id: generateUuid(),+ _id: generateDraftId(),text: content,}}diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.test.ts b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.test.tsindex b64eddf7e3e..f5fc067f602 100644--- a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.test.ts+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.test.ts@@ -22,7 +22,7 @@ describe('getAssistantQueryDisplay', () => {chart: {type: 'bar',x_column: 'day',- y_columns: ['signups'],+ y_series: ['signups'],cumulative: false,scale: 'linear',show_labels: false,@@ -31,7 +31,7 @@ describe('getAssistantQueryDisplay', () => {})it('keeps an empty y-axis list when only the x-axis is provided', () => {- expect(getAssistantQueryDisplay({ xAxis: 'day' }).chart?.y_columns).toEqual([])+ expect(getAssistantQueryDisplay({ xAxis: 'day' }).chart?.y_series).toEqual([])})})diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.ts b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.tsindex a09fc6fba58..930134aea12 100644--- a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.ts+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.ts@@ -25,7 +25,7 @@ export function getAssistantQueryDisplay({? {type: 'bar',x_column: xAxis ?? '',- y_columns: yAxis ? [yAxis] : [],+ y_series: yAxis ? [yAxis] : [],cumulative: false,scale: 'linear',show_labels: false,diff --git a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsxindex ba4d765cc17..61f5de48c25 100644--- a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx@@ -25,8 +25,8 @@ const mockNotebookRow = (overrides: Partial<Record<string, unknown>> = {}) => ({content: {schema_version: 1,cells: [- { _tag: 'markdown_cell', id: 'cell-1', text: 'hello' },- { _tag: 'markdown_cell', id: 'cell-2', text: 'world' },+ { _tag: 'markdown_cell', _id: 'cell-1', text: 'hello' },+ { _tag: 'markdown_cell', _id: 'cell-2', text: 'world' },],},...overrides,diff --git a/apps/studio/data/content/content-infinite-query.ts b/apps/studio/data/content/content-infinite-query.tsindex 706a897eff7..5e148cc3f01 100644--- a/apps/studio/data/content/content-infinite-query.ts+++ b/apps/studio/data/content/content-infinite-query.ts@@ -28,10 +28,7 @@ export async function getContent(params: {path: { ref: projectRef },query: {- // TODO — Charis 2026-08-06- // Cast until the generated query param type picks up 'notebook' (see ContentBase in- // content-query.ts)- type: type as 'sql' | 'report' | 'log_sql',+ type,name,sort_by: sort,limit: limit.toString(),diff --git a/apps/studio/data/content/content-query.ts b/apps/studio/data/content/content-query.tsindex b555f21cdf7..385a15073bc 100644--- a/apps/studio/data/content/content-query.ts+++ b/apps/studio/data/content/content-query.ts@@ -12,12 +12,7 @@ import type {UseCustomQueryOptions,} from '@/types'-// TODO — Charis 2026-08-06-// Temporary widening until we have API support for notebooks-export type ContentBase = Omit<- components['schemas']['GetUserContentResponse']['data'][number],- 'type'-> & { type: components['schemas']['GetUserContentResponse']['data'][number]['type'] | 'notebook' }+export type ContentBase = components['schemas']['GetUserContentResponse']['data'][number]export type Content = Omit<ContentBase, 'content' | 'type'> &(@@ -65,9 +60,7 @@ export async function getContent(const { data, error } = await get('/platform/projects/{ref}/content', {params: {path: { ref: projectRef },- // TODO — Charis 2026-08-06- // Cast until the generated query param type picks up 'notebook' (see ContentBase above)- query: { type: type as 'sql' | 'report' | 'log_sql', name, limit: limit.toString() },+ query: { type, name, limit: limit.toString() },},headers,signal,diff --git a/apps/studio/data/content/content-remap.test.ts b/apps/studio/data/content/content-remap.test.tsindex 36f46481571..fabb0d08db9 100644--- a/apps/studio/data/content/content-remap.test.ts+++ b/apps/studio/data/content/content-remap.test.ts@@ -6,20 +6,20 @@ import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'const MARKDOWN_CELL = {_tag: 'markdown_cell' as const,- id: 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11',+ _id: 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11',text: '# Signup funnel',}const DATABASE_CELL = {_tag: 'database_cell' as const,- id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',+ _id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',sql: 'select * from auth.users limit 100',row_limit: 100,}const LOG_CELL = {_tag: 'log_cell' as const,- id: 'c2001199-1e2b-4ef8-bb6d-6bb9bd380a33',+ _id: 'c2001199-1e2b-4ef8-bb6d-6bb9bd380a33',sql: "select timestamp, event_message from edge_logs where source = 'edge_logs' limit 10",time_range: {_tag: 'relative_time_range' as const,@@ -113,10 +113,14 @@ describe('remapSqlContentField', () => {const result = remapSqlContentField(NOTEBOOK)const [markdownCell, databaseCell, logCell] = result.content.cells- expect(markdownCell).toEqual(MARKDOWN_CELL)+ expect(markdownCell).toEqual({+ _tag: 'markdown_cell',+ _id: MARKDOWN_CELL._id,+ text: MARKDOWN_CELL.text,+ })expect(databaseCell).toEqual({_tag: 'database_cell',- id: DATABASE_CELL.id,+ _id: DATABASE_CELL._id,row_limit: 100,view: 'table',unchecked_sql: untrustedSql(DATABASE_CELL.sql),@@ -124,7 +128,7 @@ describe('remapSqlContentField', () => {expect(databaseCell).not.toHaveProperty('sql')expect(logCell).toEqual({_tag: 'log_cell',- id: LOG_CELL.id,+ _id: LOG_CELL._id,time_range: LOG_CELL.time_range,view: 'table',unchecked_sql: untrustedLogSql(LOG_CELL.sql),@@ -138,7 +142,7 @@ describe('remapSqlContentField', () => {type: 'notebook' as const,content: {schema_version: 1 as const,- cells: [{ _tag: 'database_cell' as const, id: '1', sql: 'select 1' }],+ cells: [{ _tag: 'database_cell' as const, _id: '1', sql: 'select 1' }],},}@@ -235,9 +239,9 @@ describe('unmapSqlContentField', () => {describe('unmapSqlContentField (notebooks)', () => {// Notebook content only ever reaches `unmapSqlContentField` via createNotebook/updateNotebook,- // which always hand it a WritableNotebook — plain `sql` per cell, `id` present only for- // existing cells. That's already wire-shaped, so this is a pure passthrough.- it('returns notebook content completely unchanged', () => {+ // which always hand it a WritableNotebook already keyed on the wire's `_id` — present for+ // an existing cell, omitted for a new one.+ it('passes a real _id through, and leaves a cell with none without one', () => {const writableNotebook = {id: 'e4bbee88-8d2b-4de7-aa5c-5aa8ac270b55',type: 'notebook' as const,@@ -247,7 +251,7 @@ describe('unmapSqlContentField (notebooks)', () => {{ _tag: 'markdown_cell' as const, text: '# New cell' },{_tag: 'database_cell' as const,- id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',+ _id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',sql: 'select * from auth.users limit 100',row_limit: 100,},@@ -266,7 +270,31 @@ describe('unmapSqlContentField (notebooks)', () => {const result = unmapSqlContentField(writableNotebook)- expect(result).toBe(writableNotebook)+ const [markdownCell, databaseCell, logCell] = result.content.cells+ expect(markdownCell).not.toHaveProperty('_id')+ expect(databaseCell).toMatchObject({ _id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22' })+ expect(logCell).not.toHaveProperty('_id')+ })++ it('drops a client-fabricated draft id rather than sending it back as _id', () => {+ const writableNotebook = {+ id: 'e4bbee88-8d2b-4de7-aa5c-5aa8ac270b55',+ type: 'notebook' as const,+ content: {+ schema_version: 1 as const,+ cells: [+ {+ _tag: 'markdown_cell' as const,+ _id: 'draft-b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',+ text: '# New cell',+ },+ ],+ },+ }++ const result = unmapSqlContentField(writableNotebook)++ expect(result.content.cells[0]).not.toHaveProperty('_id')})})diff --git a/apps/studio/data/content/content-remap.ts b/apps/studio/data/content/content-remap.tsindex a01b09d7e3b..c164b9ea63e 100644--- a/apps/studio/data/content/content-remap.ts+++ b/apps/studio/data/content/content-remap.ts@@ -11,7 +11,8 @@// (data/content/notebooks/notebook-schema.ts) instead of the single-field swap below.import { untrustedSql } from '@supabase/pg-meta'-import { notebookDomainSchema } from './notebooks/notebook-schema'+import type { WritableNotebook } from './notebooks/notebook-schema'+import { notebookDomainSchema, toWireWritableNotebook } from './notebooks/notebook-schema'import type { SnippetStatus } from './snippet-status'import type { SnippetWithContent } from './sql-folders-query'import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'@@ -58,10 +59,9 @@ export function remapWireSnippet(row: unknown, status: SnippetStatus): SnippetWi// Reverse remap: `unchecked_sql` → `sql` before sending to the API.export function unmapSqlContentField<T extends { type: string }>(item: T): T {if (isNotebookContentType(item.type)) {- // Notebook content only ever reaches this function via createNotebook/updateNotebook,- // which always hand it a WritableNotebook — plain `sql` per cell, `id` present only- // for existing cells. That's already wire-shaped, so there's nothing to unmap.- return item+ if (!('content' in item)) return item+ const content = toWireWritableNotebook(item.content as WritableNotebook)+ return { ...item, content } as T}if (!isSqlContentType(item.type)) return itemif (!('content' in item)) return itemdiff --git a/apps/studio/data/content/notebooks/notebook-operations.test.ts b/apps/studio/data/content/notebooks/notebook-operations.test.tsindex e77b1d6b56b..77a5ba0a804 100644--- a/apps/studio/data/content/notebooks/notebook-operations.test.ts+++ b/apps/studio/data/content/notebooks/notebook-operations.test.ts@@ -10,9 +10,9 @@ import type { NotebookWire } from './notebook-schema'const NOTEBOOK: NotebookWire = {schema_version: 1,cells: [- { _tag: 'markdown_cell', id: 'cell-1', text: '# Intro' },- { _tag: 'database_cell', id: 'cell-2', sql: 'select 1', row_limit: 100 },- { _tag: 'markdown_cell', id: 'cell-3', text: '# Outro' },+ { _tag: 'markdown_cell', _id: 'cell-1', text: '# Intro' },+ { _tag: 'database_cell', _id: 'cell-2', sql: 'select 1', row_limit: 100 },+ { _tag: 'markdown_cell', _id: 'cell-3', text: '# Outro' },],}@@ -29,7 +29,7 @@ describe('applyNotebookOperations', () => {expect(result.success).toBe(true)if (!result.success) returnexpect(- result.notebook.cells.map((cell) => ('id' in cell ? cell.id : 'text' in cell && cell.text))+ result.notebook.cells.map((cell) => ('_id' in cell ? cell._id : 'text' in cell && cell.text))).toEqual(['cell-1', '# New', 'cell-2', 'cell-3'])})@@ -98,7 +98,7 @@ describe('applyNotebookOperations', () => {expect(result.success).toBe(true)if (!result.success) return- expect(result.notebook.cells.map((cell) => ('id' in cell ? cell.id : undefined))).toEqual([+ expect(result.notebook.cells.map((cell) => ('_id' in cell ? cell._id : undefined))).toEqual(['cell-2','cell-3','cell-1',@@ -114,7 +114,7 @@ describe('applyNotebookOperations', () => {expect(result.success).toBe(true)if (!result.success) return- expect(result.notebook.cells.map((cell) => ('id' in cell ? cell.id : undefined))).toEqual([+ expect(result.notebook.cells.map((cell) => ('_id' in cell ? cell._id : undefined))).toEqual(['cell-3','cell-1','cell-2',@@ -133,7 +133,7 @@ describe('applyNotebookOperations', () => {expect(result.success).toBe(true)if (!result.success) return- expect(result.notebook.cells.map((cell) => ('id' in cell ? cell.id : undefined))).toEqual([+ expect(result.notebook.cells.map((cell) => ('_id' in cell ? cell._id : undefined))).toEqual(['cell-3','cell-1','cell-2',@@ -152,7 +152,7 @@ describe('applyNotebookOperations', () => {expect(result.success).toBe(true)if (!result.success) return- expect(result.notebook.cells.map((cell) => ('id' in cell ? cell.id : undefined))).toEqual([+ expect(result.notebook.cells.map((cell) => ('_id' in cell ? cell._id : undefined))).toEqual(['cell-2','cell-3','cell-1',@@ -169,7 +169,7 @@ describe('applyNotebookOperations', () => {expect(result.success).toBe(true)if (!result.success) return- expect(result.notebook.cells.map((cell) => ('id' in cell ? cell.id : undefined))).toEqual([+ expect(result.notebook.cells.map((cell) => ('_id' in cell ? cell._id : undefined))).toEqual(['cell-1','cell-2','cell-3',diff --git a/apps/studio/data/content/notebooks/notebook-operations.ts b/apps/studio/data/content/notebooks/notebook-operations.tsindex 2e4391e07dd..60d2dcb27d2 100644--- a/apps/studio/data/content/notebooks/notebook-operations.ts+++ b/apps/studio/data/content/notebooks/notebook-operations.ts@@ -110,9 +110,9 @@ function findAnchorIndex(entries: NotebookCellDiffEntry[], cellId: string): numbswitch (entry._tag) {case 'unchanged':case 'moved':- return entry.cell.id === cellId+ return entry.cell._id === cellIdcase 'replaced':- return entry.before.id === cellId+ return entry.before._id === cellIdcase 'added':case 'removed':return false@@ -127,7 +127,7 @@ function findTargetCell(for (let index = 0; index < entries.length; index++) {const entry = entries[index]if (entry._tag !== 'unchanged' && entry._tag !== 'moved') continue- if (entry.cell.id === cellId) return { index, cell: entry.cell }+ if (entry.cell._id === cellId) return { index, cell: entry.cell }}return undefined}@@ -139,11 +139,11 @@ function downgradeNoOpMoves(if (!entries.some((entry) => entry._tag === 'moved')) return entriesconst finalOrder = entries.flatMap((entry) =>- entry._tag === 'unchanged' || entry._tag === 'moved' ? [entry.cell.id] : []+ entry._tag === 'unchanged' || entry._tag === 'moved' ? [entry.cell._id] : [])const survivingIds = new Set(finalOrder)const originalOrder = notebook.cells- .map((cell) => cell.id)+ .map((cell) => cell._id).filter((cellId) => survivingIds.has(cellId))const hasSamePredecessors = (cellId: string) => {@@ -156,7 +156,7 @@ function downgradeNoOpMoves(}return entries.map((entry) =>- entry._tag === 'moved' && hasSamePredecessors(entry.cell.id)+ entry._tag === 'moved' && hasSamePredecessors(entry.cell._id)? { _tag: 'unchanged', cell: entry.cell }: entry)@@ -177,7 +177,7 @@ export function deriveNotebookDiff(targetedIds.add(cellId)}- const originalIndexById = new Map(notebook.cells.map((cell, index) => [cell.id, index]))+ const originalIndexById = new Map(notebook.cells.map((cell, index) => [cell._id, index]))const entries: NotebookCellDiffEntry[] = notebook.cells.map((cell) => ({_tag: 'unchanged',cell,@@ -259,7 +259,7 @@ export function deriveNotebookDiff(const error = insertAfter(operation.after_cell_id, {_tag: 'moved',cell: found.cell,- fromIndex: originalIndexById.get(found.cell.id) ?? found.index,+ fromIndex: originalIndexById.get(found.cell._id) ?? found.index,operationIndex,})if (error) return { success: false, error }diff --git a/apps/studio/data/content/notebooks/notebook-query.test.ts b/apps/studio/data/content/notebooks/notebook-query.test.tsindex cabd96fb6d6..46ccd458eda 100644--- a/apps/studio/data/content/notebooks/notebook-query.test.ts+++ b/apps/studio/data/content/notebooks/notebook-query.test.ts@@ -7,9 +7,7 @@ import { addAPIMock } from '@/tests/lib/msw'const NOTEBOOK_ID = 'd3aadd77-7c3c-4de7-aa5c-5aa8ac270b44'-// `type: 'notebook'` isn't in the generated GetUserContentByIdResponse['type'] enum yet (same-// gap tracked by the ContentBase TODO in content-query.ts), so the mock body needs a cast.-const NOTEBOOK_ROW = {+const NOTEBOOK_ROW: components['schemas']['GetUserContentByIdResponse'] = {id: NOTEBOOK_ID,type: 'notebook',name: 'Signup funnel',@@ -33,9 +31,7 @@ describe('getNotebook', () => {method: 'get',path: '/platform/projects/:ref/content/item/:id',response: () =>- HttpResponse.json<components['schemas']['GetUserContentByIdResponse']>(- NOTEBOOK_ROW as unknown as components['schemas']['GetUserContentByIdResponse']- ),+ HttpResponse.json<components['schemas']['GetUserContentByIdResponse']>(NOTEBOOK_ROW),})const result = await getNotebook({ projectRef: 'default', id: NOTEBOOK_ID })diff --git a/apps/studio/data/content/notebooks/notebook-query.ts b/apps/studio/data/content/notebooks/notebook-query.tsindex 66d62839cca..3e64aef8f35 100644--- a/apps/studio/data/content/notebooks/notebook-query.ts+++ b/apps/studio/data/content/notebooks/notebook-query.ts@@ -14,14 +14,11 @@ export async function getNotebook() {const data = await getContentById({ projectRef, id }, signal, headers)- // api-types doesn't have 'notebook' in GetUserContentByIdResponse['type'] yet — same gap- // tracked by the ContentBase TODO in content-query.ts — so this narrowing can't be static.- if ((data.type as string) !== 'notebook') {+ if (data.type !== 'notebook') {throw new Error(`Content ${id} is not a notebook (got type: ${data.type})`)}- return data as unknown as Omit<typeof data, 'type' | 'content'> & {- type: 'notebook'+ return data as Omit<typeof data, 'content'> & {content: Notebooks.Content}}diff --git a/apps/studio/data/content/notebooks/notebook-schema.test.ts b/apps/studio/data/content/notebooks/notebook-schema.test.tsindex 2f1615ba0e8..a459382cbe0 100644--- a/apps/studio/data/content/notebooks/notebook-schema.test.ts+++ b/apps/studio/data/content/notebooks/notebook-schema.test.ts@@ -1,33 +1,35 @@-import { untrustedSql } from '@supabase/pg-meta'+import { safeSql, untrustedSql } from '@supabase/pg-meta'import { describe, expect, it } from 'vitest'import {agentNotebookSchema,+ isDraftId,isQueryCell,notebookDomainSchema,notebookSchema,timeRangeSchema,+ toWireWritableNotebook,writableNotebookSchema,} from './notebook-schema'-import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'+import { safeSql as safeLogSql, untrustedLogSql } from '@/data/logs/safe-analytics-sql'const FULL_NOTEBOOK = {schema_version: 1 as const,cells: [{_tag: 'markdown_cell' as const,- id: 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11',+ _id: 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11',text: '# Signup funnel',},{_tag: 'database_cell' as const,- id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',+ _id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',sql: 'select * from auth.users limit 100',row_limit: 100,},{_tag: 'log_cell' as const,- id: 'c2001199-1e2b-4ef8-bb6d-6bb9bd380a33',+ _id: 'c2001199-1e2b-4ef8-bb6d-6bb9bd380a33',sql: "select timestamp, event_message from edge_logs where source = 'edge_logs' limit 10",time_range: {_tag: 'relative_time_range' as const,@@ -46,7 +48,7 @@ describe('notebookSchema', () => {it('rejects an unknown cell _tag', () => {const result = notebookSchema.safeParse({schema_version: 1,- cells: [{ _tag: 'chart_cell', id: '1', text: 'hi' }],+ cells: [{ _tag: 'chart_cell', _id: '1', text: 'hi' }],})expect(result.success).toBe(false)@@ -55,7 +57,7 @@ describe('notebookSchema', () => {it('rejects a database_cell missing row_limit', () => {const result = notebookSchema.safeParse({schema_version: 1,- cells: [{ _tag: 'database_cell', id: '1', sql: 'select 1' }],+ cells: [{ _tag: 'database_cell', _id: '1', sql: 'select 1' }],})expect(result.success).toBe(false)@@ -67,7 +69,7 @@ describe('notebookSchema', () => {cells: [{_tag: 'log_cell',- id: '1',+ _id: '1',sql: 'select 1',time_range: {_tag: 'absolute_time_range',@@ -87,7 +89,7 @@ describe('notebookSchema', () => {cells: [{_tag: 'log_cell',- id: '1',+ _id: '1',sql: 'select 1',time_range: {_tag: 'absolute_time_range',@@ -107,7 +109,7 @@ describe('notebookSchema', () => {cells: [{_tag: 'log_cell',- id: '1',+ _id: '1',sql: 'select 1',time_range: { _tag: 'relative_time_range', unit: 'fortnight', amount: 1 },},@@ -123,7 +125,7 @@ describe('notebookSchema', () => {cells: [{_tag: 'database_cell',- id: '1',+ _id: '1',sql: 'select 1',row_limit: 100,database_identifier: 'replica-1',@@ -134,20 +136,29 @@ describe('notebookSchema', () => {expect(result.success).toBe(true)})+ it('rejects a cell with no _id — the backend always assigns one on save', () => {+ const result = notebookSchema.safeParse({+ schema_version: 1,+ cells: [{ _tag: 'markdown_cell', text: 'hi' }],+ })++ expect(result.success).toBe(false)+ })+it('keeps a chart configured while the table view is selected', () => {const result = notebookSchema.safeParse({schema_version: 1,cells: [{_tag: 'database_cell',- id: '1',+ _id: '1',sql: 'select 1',row_limit: 100,view: 'table',chart: {type: 'bar',x_column: 'day',- y_columns: ['signups'],+ y_series: ['signups'],cumulative: false,show_labels: true,},@@ -164,7 +175,7 @@ describe('notebookSchema', () => {describe('timeRangeSchema', () => {const logCell = (time_range: unknown) => ({schema_version: 1,- cells: [{ _tag: 'log_cell', id: '1', sql: 'select 1', time_range }],+ cells: [{ _tag: 'log_cell', _id: '1', sql: 'select 1', time_range }],})it('rejects a relative_time_range with a non-positive or fractional amount', () => {@@ -275,7 +286,7 @@ describe('writableNotebookSchema', () => {cells: [{_tag: 'database_cell',- id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',+ _id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',sql: 'select * from auth.users limit 100',row_limit: 100,},@@ -346,10 +357,14 @@ describe('notebookDomainSchema', () => {if (!result.success) returnconst [markdownCell, databaseCell, logCell] = result.data.cells- expect(markdownCell).toEqual(FULL_NOTEBOOK.cells[0])+ expect(markdownCell).toEqual({+ _tag: 'markdown_cell',+ _id: FULL_NOTEBOOK.cells[0]._id,+ text: FULL_NOTEBOOK.cells[0].text,+ })expect(databaseCell).toEqual({_tag: 'database_cell',- id: FULL_NOTEBOOK.cells[1].id,+ _id: FULL_NOTEBOOK.cells[1]._id,row_limit: 100,view: 'table',unchecked_sql: untrustedSql('select * from auth.users limit 100'),@@ -364,3 +379,65 @@ describe('notebookDomainSchema', () => {expect(logCell).not.toHaveProperty('sql')})})++describe('toWireWritableNotebook', () => {+ it('sends a real id through as _id', () => {+ const wire = toWireWritableNotebook({+ schema_version: 1,+ cells: [{ _tag: 'markdown_cell', _id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22', text: 'hi' }],+ })++ expect(wire.cells[0]).toMatchObject({ _id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22' })+ })++ it('drops a draft id rather than sending it back as _id', () => {+ expect(isDraftId('draft-b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22')).toBe(true)++ const wire = toWireWritableNotebook({+ schema_version: 1,+ cells: [+ { _tag: 'markdown_cell', _id: 'draft-b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22', text: 'hi' },+ ],+ })++ expect(wire.cells[0]).not.toHaveProperty('_id')+ })++ it('leaves a cell with no id at all without an _id', () => {+ const wire = toWireWritableNotebook({+ schema_version: 1,+ cells: [{ _tag: 'markdown_cell', text: 'hi' }],+ })++ expect(wire.cells[0]).not.toHaveProperty('_id')+ })++ it('carries a query cell (database_cell, log_cell) sql through as plain text, never unchecked_sql', () => {+ const wire = toWireWritableNotebook({+ schema_version: 1,+ cells: [+ {+ _tag: 'database_cell',+ _id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',+ sql: safeSql`select 1`,+ row_limit: 100,+ },+ {+ _tag: 'log_cell',+ sql: safeLogSql`select 1`,+ time_range: { _tag: 'relative_time_range', unit: 'hour', amount: 1 },+ },+ ],+ })++ const [databaseCell, logCell] = wire.cells+ expect(databaseCell).toMatchObject({+ _id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',+ sql: 'select 1',+ })+ expect(databaseCell).not.toHaveProperty('unchecked_sql')+ expect(logCell).toMatchObject({ sql: 'select 1' })+ expect(logCell).not.toHaveProperty('_id')+ expect(logCell).not.toHaveProperty('unchecked_sql')+ })+})diff --git a/apps/studio/data/content/notebooks/notebook-schema.ts b/apps/studio/data/content/notebooks/notebook-schema.tsindex 65c2539cfc5..7d4b058ea76 100644--- a/apps/studio/data/content/notebooks/notebook-schema.ts+++ b/apps/studio/data/content/notebooks/notebook-schema.ts@@ -14,12 +14,12 @@ const isoDateTimeSchema = z.string().transform((raw, ctx) => {return parsed})-export const MAX_CHART_Y_COLUMNS = 3+export const MAX_CHART_Y_SERIES = 3const chartConfigSchema = z.object({type: z.enum(['bar', 'line']),x_column: z.string(),- y_columns: z.array(z.string()).max(MAX_CHART_Y_COLUMNS),+ y_series: z.array(z.string()).max(MAX_CHART_Y_SERIES),cumulative: z.boolean(),scale: z.enum(['linear', 'log']).default('linear'),show_labels: z.boolean(),@@ -54,17 +54,10 @@ export const timeRangeSchema = z{ message: 'must be later than the start of the range', path: ['end'] })-// Source parameters — the per-backend values a query needs beyond its SQL. Declared-// here, in the wire contract, because this schema is the shape shared with the API and-// the agent tool surface, so it is where the validation has to be authoritative. The-// runtime registry (data/query-sources/query-source-registry.ts) borrows these rather-// than redeclaring them. Each is spread flat into its cell — no `source` wrapper — to-// keep the JSON an agent has to author as shallow as possible.export const databaseSourceSchema = z.object({/*** Which database the query runs against: the read-replica `identifier`, or absent- * for the project's primary. Named `database_identifier` rather than `identifier`- * because every cell already carries an `id`.+ * for the project's primary.*/database_identifier: z.string().optional(),})@@ -73,14 +66,11 @@ export const logsSourceSchema = z.object({time_range: timeRangeSchema,})-const cellBaseSchema = z.object({- id: z.string(),+const markdownFieldsSchema = z.object({+ text: z.string(),})-// Fields every runnable cell shares, regardless of backend. `sql` is deliberately NOT-// here: it stays on each member so the domain transform can brand it per dialect and-// generic code holding a `QueryCell` can't hand it to the wrong wire boundary.-const queryCellBaseSchema = cellBaseSchema.extend({+const queryFieldsBaseSchema = z.object({title: z.string().optional(),view: z.enum(['table', 'chart']).optional(),// Persisted independently of `view` so a user who switches to the table and back@@ -88,32 +78,40 @@ const queryCellBaseSchema = cellBaseSchema.extend({chart: chartConfigSchema.optional(),})-const markdownCellSchema = cellBaseSchema.extend({- _tag: z.literal('markdown_cell'),- text: z.string(),-})--const databaseCellSchema = queryCellBaseSchema.extend({- _tag: z.literal('database_cell'),+const databaseFieldsSchema = queryFieldsBaseSchema.extend({sql: z.string(),row_limit: z.number(),...databaseSourceSchema.shape,})-const logCellSchema = queryCellBaseSchema.extend({- _tag: z.literal('log_cell'),+const logFieldsSchema = queryFieldsBaseSchema.extend({sql: z.string(),...logsSourceSchema.shape,})+// The wire shape: a cell that's been saved always carries the backend's real `_id` — the+// backend assigns one on every write and returns it on every subsequent read.+const markdownCellSchema = markdownFieldsSchema.extend({+ _tag: z.literal('markdown_cell'),+ _id: z.string(),+})++const databaseCellSchema = databaseFieldsSchema.extend({+ _tag: z.literal('database_cell'),+ _id: z.string(),+})++const logCellSchema = logFieldsSchema.extend({+ _tag: z.literal('log_cell'),+ _id: z.string(),+})+const cellSchema = z.discriminatedUnion('_tag', [markdownCellSchema,databaseCellSchema,logCellSchema,])-// The wire shape: every notebook fetched from the API has this shape, with backend--// generated cell `id`s and plaintext `sql`.export const notebookSchema = z.object({schema_version: z.literal(1),cells: z.array(cellSchema),@@ -123,16 +121,14 @@ export type NotebookWire = z.infer<typeof notebookSchema>export type CellWire = z.infer<typeof cellSchema>// Cells for the create/update PUT body (data/content/notebooks/notebook-upsert-mutation.ts).-// An existing cell being kept or edited carries its real backend-assigned `id` so the-// backend can diff it against the previous version; a newly inserted cell has no `id` at-// all — the backend generates one on write. `sql` must already be a SafeSqlFragment /-// SafeLogSqlFragment — i.e. promoted at the point of user action per the-// safe-sql-execution skill — never a raw string or an UntrustedSqlFragment/unchecked_sql,-// since neither proves this specific save was user-authored.+// An existing cell being kept or edited carries its real backend-assigned `_id` so the+// backend can diff it against the previous version; a newly inserted cell — or one whose+// `_id` is a client-fabricated draft id (see DRAFT_ID_PREFIX below) — has no `_id` at all+// once it reaches the wire, so the backend generates one on write.const writableCellSchema = z.discriminatedUnion('_tag', [- markdownCellSchema.extend({ id: z.string().optional() }),- databaseCellSchema.extend({ id: z.string().optional() }),- logCellSchema.extend({ id: z.string().optional() }),+ markdownFieldsSchema.extend({ _tag: z.literal('markdown_cell'), _id: z.string().optional() }),+ databaseFieldsSchema.extend({ _tag: z.literal('database_cell'), _id: z.string().optional() }),+ logFieldsSchema.extend({ _tag: z.literal('log_cell'), _id: z.string().optional() }),])export const writableNotebookSchema = z.object({@@ -152,12 +148,18 @@ export type WritableNotebook = Omit<z.infer<typeof writableNotebookSchema>, 'celcells: Array<WritableCell>}+// Same shape as WritableCell/WritableNotebook but with `sql` left as a plain, unbranded+// string — the actual write-body wire shape (`_id` optional, unlike the required `_id` on+// CellWire/NotebookWire above, since a cell being created for the first time has none yet).+type WritableCellWire = z.infer<typeof writableCellSchema>+type WritableNotebookWire = z.infer<typeof writableNotebookSchema>+// Agents have restrictions on writing IDs to preserve guarantees about ID-// uniqueness.+// uniquenessexport const agentCellSchema = z.discriminatedUnion('_tag', [- markdownCellSchema.omit({ id: true }).strict(),- databaseCellSchema.omit({ id: true }).strict(),- logCellSchema.omit({ id: true }).strict(),+ markdownFieldsSchema.extend({ _tag: z.literal('markdown_cell') }).strict(),+ databaseFieldsSchema.extend({ _tag: z.literal('database_cell') }).strict(),+ logFieldsSchema.extend({ _tag: z.literal('log_cell') }).strict(),])export const agentNotebookSchema = z.object({@@ -168,8 +170,28 @@ export const agentNotebookSchema = z.object({export type AgentNotebook = z.infer<typeof agentNotebookSchema>export type AgentCell = z.infer<typeof agentCellSchema>-// The domain shape: parses the same wire cell (`cellSchema`), transforms `sql` into a-// branded `unchecked_sql`, and defaults `view` to 'table'+// A backend-recognized `_id` is required once a cell is saved (see cellSchema above), but a+// cell can exist client-side before that first save — created fresh in the editor (see+// components/interfaces/Explorer/utils.ts) — and needs *some* stable identity in the+// meantime for React keys and state lookups. A draft id fills that gap. It's never sent to+// the backend as a real `_id` (see wireId below): a cell with a draft id reaches the wire+// exactly like a brand-new one, so the backend assigns its own.+const DRAFT_ID_PREFIX = 'draft-'++export function generateDraftId(): string {+ return `${DRAFT_ID_PREFIX}${crypto.randomUUID()}`+}++export function isDraftId(id: string): boolean {+ return id.startsWith(DRAFT_ID_PREFIX)+}++function wireId(id: string | undefined): { _id: string } | Record<string, never> {+ return id !== undefined && !isDraftId(id) ? { _id: id } : {}+}++// The domain shape: parses the wire cell (`cellSchema`), transforms `sql` into a branded+// `unchecked_sql`, and defaults `view` to 'table'.const cellDomainSchema = cellSchema.transform((cell) => {switch (cell._tag) {case 'markdown_cell':@@ -193,9 +215,6 @@ export const notebookDomainSchema = z.object({export type NotebookContent = z.infer<typeof notebookDomainSchema>export type Cell = z.infer<typeof cellDomainSchema>-// Reverse of cellDomainSchema's transform, for display-only conversions (e.g. deriving a-// diff preview client-side). Never promoted or executed — writes still go through-// acceptUntrustedSql/acceptUntrustedLogsSql at the point of user action.export function toWireCell(cell: Cell): CellWire {switch (cell._tag) {case 'markdown_cell':@@ -215,6 +234,27 @@ export function toWireNotebook(content: NotebookContent): NotebookWire {return { schema_version: content.schema_version, cells: content.cells.map(toWireCell) }}+export function toWireWritableCell(cell: WritableCell): WritableCellWire {+ switch (cell._tag) {+ case 'markdown_cell': {+ const { _id, ...rest } = cell+ return { ...rest, ...wireId(_id) }+ }+ case 'database_cell': {+ const { _id, ...rest } = cell+ return { ...rest, ...wireId(_id) }+ }+ case 'log_cell': {+ const { _id, ...rest } = cell+ return { ...rest, ...wireId(_id) }+ }+ }+}++export function toWireWritableNotebook(content: WritableNotebook): WritableNotebookWire {+ return { schema_version: content.schema_version, cells: content.cells.map(toWireWritableCell) }+}+export type MarkdownCell = Extract<Cell, { _tag: 'markdown_cell' }>export type DatabaseCell = Extract<Cell, { _tag: 'database_cell' }>export type LogCell = Extract<Cell, { _tag: 'log_cell' }>diff --git a/apps/studio/data/content/notebooks/notebook-upsert-mutation.test.ts b/apps/studio/data/content/notebooks/notebook-upsert-mutation.test.tsindex c32ff0df315..55f5a0eb1fd 100644--- a/apps/studio/data/content/notebooks/notebook-upsert-mutation.test.ts+++ b/apps/studio/data/content/notebooks/notebook-upsert-mutation.test.ts@@ -12,7 +12,7 @@ const LOG_SQL = "select timestamp, event_message from edge_logs where source = 'const EXISTING_CELL_ID = 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22'-// Create-shaped: no cell carries an `id` — the notebook is brand new, so no cell has a+// Create-shaped: no cell carries an `_id` — the notebook is brand new, so no cell has a// prior version for the backend to diff against; ids are backend-generated on write.const VALID_CONTENT: WritableNotebook = {schema_version: 1,@@ -27,7 +27,7 @@ const VALID_CONTENT: WritableNotebook = {],}-// Update-shaped: mixes an existing cell (kept, carries its real backend-assigned id so the+// Update-shaped: mixes an existing cell (kept, carries its real backend-assigned _id so the// backend can diff it against the previous version) with a newly inserted cell (no id —// same as create, the backend assigns one on write).const UPDATE_CONTENT: WritableNotebook = {@@ -35,7 +35,7 @@ const UPDATE_CONTENT: WritableNotebook = {cells: [{_tag: 'database_cell',- id: EXISTING_CELL_ID,+ _id: EXISTING_CELL_ID,sql: DATABASE_SQL,row_limit: 100,},@@ -85,6 +85,7 @@ describe('createNotebook', () => {const content = sentBody?.content as WritableNotebookfor (const cell of content.cells) {expect(cell).not.toHaveProperty('id')+ expect(cell).not.toHaveProperty('_id')}const [, databaseCell, logCell] = content.cells as Array<Record<string, unknown>>@@ -125,9 +126,11 @@ describe('updateNotebook', () => {const content = sentBody?.content as WritableNotebookconst [databaseCell, logCell] = content.cells as Array<Record<string, unknown>>- expect(databaseCell.id).toBe(EXISTING_CELL_ID)+ expect(databaseCell._id).toBe(EXISTING_CELL_ID)+ expect(databaseCell).not.toHaveProperty('id')expect(databaseCell.sql).toBe(DATABASE_SQL)expect(logCell).not.toHaveProperty('id')+ expect(logCell).not.toHaveProperty('_id')expect(logCell.sql).toBe(LOG_SQL)})diff --git a/apps/studio/data/content/notebooks/notebook-upsert-mutation.ts b/apps/studio/data/content/notebooks/notebook-upsert-mutation.tsindex 39155ee8d49..e234a2f505f 100644--- a/apps/studio/data/content/notebooks/notebook-upsert-mutation.ts+++ b/apps/studio/data/content/notebooks/notebook-upsert-mutation.ts@@ -6,15 +6,6 @@ import { contentKeys } from '../keys'import { writableNotebookSchema, type WritableNotebook } from './notebook-schema'import type { ResponseError, UseCustomMutationOptions } from '@/types'-// TODO — Charis 2026-08-06-// UpsertContentPayload['type'] (generated from api-types) doesn't have 'notebook' yet — same-// gap tracked by the ContentBase TODO in content-query.ts. Widen locally and cast at the-// upsertContent call site until the generated type picks it up.-type NotebookUpsertPayload = Omit<UpsertContentPayload, 'type' | 'content'> & {- type: 'notebook'- content: WritableNotebook-}-function buildNotebookUpsertPayload({id,name,@@ -25,7 +16,7 @@ function buildNotebookUpsertPayload({name: stringdescription?: stringcontent: WritableNotebook-}): NotebookUpsertPayload {+}): UpsertContentPayload {writableNotebookSchema.parse(content)return {@@ -53,11 +44,7 @@ export async function createNotebook(const id = crypto.randomUUID()const payload = buildNotebookUpsertPayload({ id, name, description, content })- await upsertContent(- { projectRef, payload: payload as unknown as UpsertContentPayload },- signal,- headersInit- )+ await upsertContent({ projectRef, payload }, signal, headersInit)return { id }}@@ -73,11 +60,7 @@ export async function updateNotebook() {const payload = buildNotebookUpsertPayload({ id, name, description, content })- return upsertContent(- { projectRef, payload: payload as unknown as UpsertContentPayload },- signal,- headersInit- )+ return upsertContent({ projectRef, payload }, signal, headersInit)}export type UpdateNotebookData = Awaited<ReturnType<typeof updateNotebook>>diff --git a/apps/studio/data/content/notebooks/notebooks-infinite-query.test.ts b/apps/studio/data/content/notebooks/notebooks-infinite-query.test.tsindex e9a54dc3435..e256ce7e309 100644--- a/apps/studio/data/content/notebooks/notebooks-infinite-query.test.ts+++ b/apps/studio/data/content/notebooks/notebooks-infinite-query.test.ts@@ -7,7 +7,7 @@ import type { components } from '@/data/api'import { customRenderHook } from '@/tests/lib/custom-render'import { addAPIMock } from '@/tests/lib/msw'-const NOTEBOOK_ROW = {+const NOTEBOOK_ROW: components['schemas']['GetUserContentResponse']['data'][number] = {id: 'd3aadd77-7c3c-4de7-aa5c-5aa8ac270b44',type: 'notebook',name: 'Signup funnel',@@ -36,7 +36,7 @@ describe('useNotebooksInfiniteQuery', () => {HttpResponse.json<components['schemas']['GetUserContentResponse']>({cursor: undefined,data: [NOTEBOOK_ROW],- } as unknown as components['schemas']['GetUserContentResponse']),+ }),})const { result } = customRenderHook(() => useNotebooksInfiniteQuery({ projectRef: 'default' }))diff --git a/apps/studio/data/content/sql-folders-query.ts b/apps/studio/data/content/sql-folders-query.tsindex 85d2ec4b5b1..3027722faec 100644--- a/apps/studio/data/content/sql-folders-query.ts+++ b/apps/studio/data/content/sql-folders-query.ts@@ -24,17 +24,11 @@ export type Snippet =// brand to narrow on `type` first. The shared field names (`content_id`,// `unchecked_sql`, `schema_version`) keep the many read sites that only need the// SQL text compiling unchanged.-//-// `report` is included because the content endpoints' wire type carries it, but-// it deliberately has NO SQL content (`content?: never`): report bodies are-// `Dashboards.Content` and are loaded through the separate `Content` union-// (data/content/content-query.ts), never with SQL here. Modelling it as `never`-// (rather than reusing `SqlSnippets.Content`) keeps that honest while letting the-// broadly-typed rows the content/folder queries return assign without a cast.export type SnippetWithContent = Omit<Snippet, 'type'> & { status: SnippetStatus } & (| { type: 'sql'; content?: SqlSnippets.Content }| { type: 'log_sql'; content?: LogSqlSnippets.Content }| { type: 'report'; content?: never }+ | { type: 'notebook'; content?: never })// Attaches the 'saved' lifecycle status to a snippet as it crosses from thediff --git a/apps/studio/lib/ai/tools/mock-tools.test.ts b/apps/studio/lib/ai/tools/mock-tools.test.tsindex 1cd7f5ee101..803cf8233f7 100644--- a/apps/studio/lib/ai/tools/mock-tools.test.ts+++ b/apps/studio/lib/ai/tools/mock-tools.test.ts@@ -149,7 +149,7 @@ describe('ai/tools/mock-tools getMockTools', () => {{ toolCallId: 'test', messages: [], context: {} })expect(fetched.cells).toHaveLength(2)- expect(fetched.cells.every((cell) => typeof cell.id === 'string')).toBe(true)+ expect(fetched.cells.every((cell) => typeof cell._id === 'string')).toBe(true)const listed = await mockTools.list_notebooks.execute({ limit: 20 },@@ -186,10 +186,10 @@ describe('ai/tools/mock-tools getMockTools', () => {operations: [{_tag: 'insert_cell',- after_cell_id: markdownCell.id,+ after_cell_id: markdownCell._id,cell: { _tag: 'database_cell', sql: 'select 1', row_limit: 10 },},- { _tag: 'delete_cell', cell_id: logCell.id },+ { _tag: 'delete_cell', cell_id: logCell._id },],},{ toolCallId: 'test', messages: [], context: {} }diff --git a/apps/studio/lib/ai/tools/mock-tools.ts b/apps/studio/lib/ai/tools/mock-tools.tsindex 69b959e0337..d288e17744f 100644--- a/apps/studio/lib/ai/tools/mock-tools.ts+++ b/apps/studio/lib/ai/tools/mock-tools.ts@@ -178,18 +178,18 @@ export const MOCK_NOTEBOOKS_DATA: MockNotebook[] = [cells: [{_tag: 'markdown_cell',- id: 'c1a0b8e2-3f47-4a52-9d18-6b0c4e2f7a91',+ _id: 'c1a0b8e2-3f47-4a52-9d18-6b0c4e2f7a91',text: '# Auth health\n\nRun this daily: signup volume, then anything the auth service logged as an error.',},{_tag: 'database_cell',- id: 'd2b1c9f3-4a58-4b63-8e29-7c1d5f3a8b02',+ _id: 'd2b1c9f3-4a58-4b63-8e29-7c1d5f3a8b02',title: 'Signups per day',sql: "select date_trunc('day', created_at) as day, count(*) as signups\nfrom auth.users\ngroup by day\norder by day desc",row_limit: 30,chart: {x_column: 'day',- y_columns: ['signups'],+ y_series: ['signups'],cumulative: false,type: 'line',scale: 'log',@@ -198,7 +198,7 @@ export const MOCK_NOTEBOOKS_DATA: MockNotebook[] = [},{_tag: 'log_cell',- id: 'e3c2d0a4-5b69-4c74-9f3a-8d2e6a4b9c13',+ _id: 'e3c2d0a4-5b69-4c74-9f3a-8d2e6a4b9c13',title: 'Auth errors',sql: "select timestamp, event_message\nfrom auth_logs\nwhere event_message like '%error%'\norder by timestamp desc",time_range: { _tag: 'relative_time_range', unit: 'hour', amount: 1 },@@ -216,12 +216,12 @@ export const MOCK_NOTEBOOKS_DATA: MockNotebook[] = [cells: [{_tag: 'markdown_cell',- id: 'f4d3e1b5-7c80-4d85-8a4b-9e3f7b5c0d24',+ _id: 'f4d3e1b5-7c80-4d85-8a4b-9e3f7b5c0d24',text: '# Edge function errors\n\nFailures from the last day, newest first.',},{_tag: 'log_cell',- id: '0a5e4f2c-8d91-4e96-9b5c-af408c6d1e35',+ _id: '0a5e4f2c-8d91-4e96-9b5c-af408c6d1e35',title: 'hello-world failures',sql: "select timestamp, event_message\nfrom function_edge_logs\nwhere event_message like '%TypeError%'\norder by timestamp desc",time_range: { _tag: 'relative_time_range', unit: 'day', amount: 1 },@@ -363,15 +363,15 @@ function createMockNotebookStore() {const assignCellIds = (cells: OperationResultCell[]): CellWire[] =>cells.map((cell): CellWire => {- if ('id' in cell) return cell- const id = `mock-cell-${++cellCount}`+ if ('_id' in cell) return cell+ const _id = `mock-cell-${++cellCount}`switch (cell._tag) {case 'markdown_cell':- return { ...cell, id }+ return { ...cell, _id }case 'database_cell':- return { ...cell, id }+ return { ...cell, _id }case 'log_cell':- return { ...cell, id }+ return { ...cell, _id }}})diff --git a/apps/studio/lib/ai/tools/notebook-tools.test.ts b/apps/studio/lib/ai/tools/notebook-tools.test.tsindex 81f080b4c89..2650d326ca0 100644--- a/apps/studio/lib/ai/tools/notebook-tools.test.ts+++ b/apps/studio/lib/ai/tools/notebook-tools.test.ts@@ -29,16 +29,16 @@ type GetUserContentResponse = components['schemas']['GetUserContentResponse']const NOTEBOOK_CONTENT = {schema_version: 1,cells: [- { _tag: 'markdown_cell', id: 'cell-1', text: '# Signup funnel' },+ { _tag: 'markdown_cell', _id: 'cell-1', text: '# Signup funnel' },{_tag: 'database_cell',- id: 'cell-2',+ _id: 'cell-2',sql: 'select * from auth.users limit 100',row_limit: 100,},{_tag: 'log_cell',- id: 'cell-3',+ _id: 'cell-3',sql: 'select timestamp, event_message from edge_logs limit 10',time_range: { _tag: 'relative_time_range', unit: 'hour', amount: 1 },},@@ -204,17 +204,17 @@ describe('ai/tools/notebook-tools', () => {visibility: 'project',updated_at: '2026-01-01T00:00:00.000Z',cells: [- { _tag: 'markdown_cell', id: 'cell-1', text: '# Signup funnel' },+ { _tag: 'markdown_cell', _id: 'cell-1', text: '# Signup funnel' },{_tag: 'database_cell',- id: 'cell-2',+ _id: 'cell-2',row_limit: 100,view: 'table',sql: 'select * from auth.users limit 100',},{_tag: 'log_cell',- id: 'cell-3',+ _id: 'cell-3',time_range: { _tag: 'relative_time_range', unit: 'hour', amount: 1 },view: 'table',sql: 'select timestamp, event_message from edge_logs limit 10',@@ -423,7 +423,7 @@ describe('ai/tools/notebook-tools', () => {expect(sentBody?.type).toBe('notebook')const content = sentBody?.content as { cells: Array<Record<string, unknown>> }- expect(content.cells.map((cell) => cell.id ?? cell.text)).toEqual([+ expect(content.cells.map((cell) => cell._id ?? cell.text)).toEqual(['cell-1','# New section','cell-2',diff --git a/apps/studio/lib/ai/tools/notebook-tools.ts b/apps/studio/lib/ai/tools/notebook-tools.tsindex a0d62f1adc8..3383816b4f7 100644--- a/apps/studio/lib/ai/tools/notebook-tools.ts+++ b/apps/studio/lib/ai/tools/notebook-tools.ts@@ -11,8 +11,7 @@ import {import { getNotebook } from '@/data/content/notebooks/notebook-query'import {agentNotebookSchema,- type CellWire,- type NotebookWire,+ toWireNotebook,type WritableCell,type WritableNotebook,} from '@/data/content/notebooks/notebook-schema'@@ -80,28 +79,15 @@ export const getNotebookTools = (ctx: NotebookToolsContext = {}) => {execute: async ({ id }) => {const notebook = await getNotebook({ projectRef, id }, undefined, authHeaders)+ // toWireNotebook discards the `unchecked_sql` brand for display purposes only — the+ // result is returned to the agent, never written back.return {id: notebook.id,name: notebook.name,description: notebook.description,visibility: notebook.visibility,updated_at: notebook.updated_at,- // Inlined rather than a shared helper: this discards the `unchecked_sql` brand for- // display purposes only — the result is returned to the agent, never written back.- cells: notebook.content.cells.map((cell) => {- switch (cell._tag) {- case 'markdown_cell':- return cell- case 'database_cell': {- const { unchecked_sql, ...rest } = cell- return { ...rest, sql: unchecked_sql }- }- case 'log_cell': {- const { unchecked_sql, ...rest } = cell- return { ...rest, sql: unchecked_sql }- }- }- }),+ cells: toWireNotebook(notebook.content).cells,}},}),@@ -172,29 +158,10 @@ export const getNotebookTools = (ctx: NotebookToolsContext = {}) => {)}- // Inlined rather than a shared helper, right beside this tool's own- // `needsApproval: true`: this discards each cell's `unchecked_sql` brand so- // applyNotebookOperations can splice cells as plain data. The result is never- // written or executed as-is — every cell is re-promoted via- // acceptUntrustedSql/acceptUntrustedLogsSql further down in this same execute,- // right before the PUT.- const wireNotebook: NotebookWire = {- schema_version: notebook.content.schema_version,- cells: notebook.content.cells.map((cell): CellWire => {- switch (cell._tag) {- case 'markdown_cell':- return cell- case 'database_cell': {- const { unchecked_sql, ...rest } = cell- return { ...rest, sql: unchecked_sql }- }- case 'log_cell': {- const { unchecked_sql, ...rest } = cell- return { ...rest, sql: unchecked_sql }- }- }- }),- }+ // The result of applyNotebookOperations is never written or executed as-is — every+ // cell is re-promoted via acceptUntrustedSql/acceptUntrustedLogsSql further down in+ // this same execute, right before the PUT.+ const wireNotebook = toWireNotebook(notebook.content)const result = applyNotebookOperations(wireNotebook, operations)if (!result.success) {diff --git a/apps/studio/state/notebooks/notebooks-state.test.ts b/apps/studio/state/notebooks/notebooks-state.test.tsindex c7316c8aa7d..7619736810f 100644--- a/apps/studio/state/notebooks/notebooks-state.test.ts+++ b/apps/studio/state/notebooks/notebooks-state.test.ts@@ -44,7 +44,7 @@ describe('notebooksState', () => {notebooksState.updateCells({id: 'notebook-1',- cells: [{ _tag: 'markdown_cell', id: 'cell-1', text: 'hello' }],+ cells: [{ _tag: 'markdown_cell', _id: 'cell-1', text: 'hello' }],})expect(notebooksState.notebooks['notebook-1'].status).toBe('unsaved')@@ -56,7 +56,7 @@ describe('notebooksState', () => {notebooksState.updateCells({id: 'notebook-1',- cells: [{ _tag: 'markdown_cell', id: 'cell-1', text: 'hello' }],+ cells: [{ _tag: 'markdown_cell', _id: 'cell-1', text: 'hello' }],})expect(notebooksState.notebooks['notebook-1'].status).toBe('new')@@ -66,7 +66,7 @@ describe('notebooksState', () => {notebooksState.setNotebook({ projectRef: 'ref', notebook: makeNotebook('notebook-1') })notebooksState.updateCells({id: 'notebook-1',- cells: [{ _tag: 'markdown_cell', id: 'cell-1', text: 'hello' }],+ cells: [{ _tag: 'markdown_cell', _id: 'cell-1', text: 'hello' }],})expect(notebooksState.notebooks['notebook-1'].status).toBe('unsaved')diff --git a/apps/studio/state/notebooks/notebooks-state.ts b/apps/studio/state/notebooks/notebooks-state.tsindex 14449cf9279..486129e4607 100644--- a/apps/studio/state/notebooks/notebooks-state.ts+++ b/apps/studio/state/notebooks/notebooks-state.ts@@ -114,7 +114,7 @@ export const notebooksState = proxy({if (!stateNotebook?.notebook.content) returnconst cells = stateNotebook.notebook.content.cells- const insertAt = cellId ? cells.findIndex((c) => c.id === cellId) : -1+ const insertAt = cellId ? cells.findIndex((c) => c._id === cellId) : -1const nextCells = [...cells]nextCells.splice(insertAt === -1 ? cells.length : insertAt + 1, 0, cell)@@ -140,7 +140,7 @@ export const notebooksState = proxy({if (!stateNotebook?.notebook.content) returnconst nextCells = stateNotebook.notebook.content.cells.map((cell) =>- cell.id === cellId ? updater(cell) : cell+ cell._id === cellId ? updater(cell) : cell)notebooksState.updateCells({ id, cells: nextCells })},@@ -152,7 +152,7 @@ export const notebooksState = proxy({const stateNotebook = notebooksState.notebooks[id]if (!stateNotebook?.notebook.content) return- const nextCells = stateNotebook.notebook.content.cells.filter((c) => c.id !== cellId)+ const nextCells = stateNotebook.notebook.content.cells.filter((c) => c._id !== cellId)notebooksState.updateCells({ id, cells: nextCells })},@@ -173,7 +173,7 @@ export const notebooksState = proxy({if (!stateNotebook?.notebook.content) returnconst cells = stateNotebook.notebook.content.cells- const currentIndex = cells.findIndex((c) => c.id === cellId)+ const currentIndex = cells.findIndex((c) => c._id === cellId)if (currentIndex === -1) returnconst nextIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1@@ -199,8 +199,8 @@ export const notebooksState = proxy({if (!stateNotebook?.notebook.content) returnconst cells = stateNotebook.notebook.content.cells- const oldIndex = cells.findIndex((c) => c.id === activeCellId)- const newIndex = cells.findIndex((c) => c.id === overCellId)+ const oldIndex = cells.findIndex((c) => c._id === activeCellId)+ const newIndex = cells.findIndex((c) => c._id === overCellId)if (oldIndex === -1 || newIndex === -1) returnnotebooksState.updateCells({ id, cells: arrayMove([...cells], oldIndex, newIndex) })diff --git a/packages/api-types/types/platform.d.ts b/packages/api-types/types/platform.d.tsindex 5b5b673b495..2cc15ae84dc 100644--- a/packages/api-types/types/platform.d.ts+++ b/packages/api-types/types/platform.d.ts@@ -8088,7 +8088,7 @@ export interface components {owner_id: numberproject_id: number/** @enum {string} */- type: 'sql' | 'report' | 'log_sql'+ type: 'sql' | 'report' | 'log_sql' | 'notebook'updated_at: string/** @enum {string} */visibility: 'user' | 'project' | 'org' | 'public'@@ -8107,7 +8107,7 @@ export interface components {owner_id: numberproject_id: number/** @enum {string} */- type: 'sql' | 'report' | 'log_sql'+ type: 'sql' | 'report' | 'log_sql' | 'notebook'updated_at: string/** @enum {string} */visibility: 'user' | 'project' | 'org' | 'public'@@ -8141,7 +8141,7 @@ export interface components {owner_id: numberproject_id: number/** @enum {string} */- type: 'sql' | 'report' | 'log_sql'+ type: 'sql' | 'report' | 'log_sql' | 'notebook'updated_at: stringupdated_by: {id: number@@ -13663,22 +13663,88 @@ export interface components {enabled: boolean}UpsertContentBody: {- content?: {- [key: string]: unknown- }+ content?:+ | {+ [key: string]: unknown+ }+ | {+ cells: (+ | {+ _id?: string+ /** @enum {string} */+ _tag: 'database_cell'+ chart?: {+ cumulative: boolean+ /** @enum {string} */+ scale: 'linear' | 'log'+ show_labels: boolean+ /** @enum {string} */+ type: 'bar' | 'line'+ x_column: string+ y_series: string[]+ }+ row_limit: number+ sql: string+ title?: string+ /** @enum {string} */+ view?: 'table' | 'chart'+ }+ | {+ _id?: string+ /** @enum {string} */+ _tag: 'log_cell'+ chart?: {+ cumulative: boolean+ /** @enum {string} */+ scale: 'linear' | 'log'+ show_labels: boolean+ /** @enum {string} */+ type: 'bar' | 'line'+ x_column: string+ y_series: string[]+ }+ sql: string+ time_range:+ | {+ /** @enum {string} */+ _tag: 'absolute_time_range'+ end: string+ start: string+ }+ | {+ /** @enum {string} */+ _tag: 'relative_time_range'+ amount: number+ /** @enum {string} */+ unit: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'+ }+ title?: string+ /** @enum {string} */+ view?: 'table' | 'chart'+ }+ | {+ _id?: string+ /** @enum {string} */+ _tag: 'markdown_cell'+ text: string+ }+ )[]+ schema_version: number+ }description?: string/*** @description A missing `favorite` value means that the value will remained unchanged for updates. Defaults to `false` for inserts.* @default false*/favorite?: boolean- folder_id?: (null | (string | null)) | null+ /** Format: uuid */+ folder_id?: string | nullid?: stringname: stringowner_id?: numberproject_id?: number/** @enum {string} */- type: 'sql' | 'report' | 'log_sql'+ type: 'sql' | 'report' | 'log_sql' | 'notebook'/** @enum {string} */visibility: 'user' | 'project' | 'org' | 'public'}@@ -25421,7 +25487,7 @@ export interface operations {name?: stringsort_by?: 'name' | 'inserted_at'sort_order?: 'asc' | 'desc'- type?: 'sql' | 'report' | 'log_sql'+ type?: 'sql' | 'report' | 'log_sql' | 'notebook'visibility?: string}header?: never@@ -25579,7 +25645,7 @@ export interface operations {parameters: {query?: {name?: string- type?: 'sql' | 'report' | 'log_sql'+ type?: 'sql' | 'report' | 'log_sql' | 'notebook'}header?: neverpath: {@@ -25636,7 +25702,7 @@ export interface operations {name?: stringsort_by?: 'name' | 'inserted_at'sort_order?: 'asc' | 'desc'- type?: 'sql' | 'report' | 'log_sql'+ type?: 'sql' | 'report' | 'log_sql' | 'notebook'visibility?: string}header?: never