Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(studio): notebook cell operations (#48940)

Charis810d292121a6
diff --git a/apps/studio/data/content/notebooks/notebook-operations.test.ts b/apps/studio/data/content/notebooks/notebook-operations.test.ts
new file mode 100644
index 00000000000..3fafc6f7431
--- /dev/null
+++ b/apps/studio/data/content/notebooks/notebook-operations.test.ts
@@ -0,0 +1,259 @@
+import { describe, expect, it } from 'vitest'
+
+import { applyNotebookOperations, type NotebookOperation } from './notebook-operations'
+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' },
+ ],
+}
+
+const NEW_MARKDOWN_CELL = { _tag: 'markdown_cell' as const, text: '# New' }
+
+describe('applyNotebookOperations', () => {
+ it('inserts a cell after an existing cell', () => {
+ const ops: NotebookOperation[] = [
+ { _tag: 'insert_cell', after_cell_id: 'cell-1', cell: NEW_MARKDOWN_CELL },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ expect(
+ result.notebook.cells.map((cell) => ('id' in cell ? cell.id : 'text' in cell && cell.text))
+ ).toEqual(['cell-1', '# New', 'cell-2', 'cell-3'])
+ })
+
+ it('inserts a cell at the start', () => {
+ const ops: NotebookOperation[] = [
+ { _tag: 'insert_cell', after_cell_id: 'start', cell: NEW_MARKDOWN_CELL },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ expect(result.notebook.cells[0]).toEqual(NEW_MARKDOWN_CELL)
+ })
+
+ it('preserves insertion order for multiple inserts anchored at the same cell', () => {
+ const ops: NotebookOperation[] = [
+ {
+ _tag: 'insert_cell',
+ after_cell_id: 'cell-1',
+ cell: { _tag: 'markdown_cell', text: 'first' },
+ },
+ {
+ _tag: 'insert_cell',
+ after_cell_id: 'cell-1',
+ cell: { _tag: 'markdown_cell', text: 'second' },
+ },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ const texts = result.notebook.cells.map((cell) => ('text' in cell ? cell.text : undefined))
+ expect(texts).toEqual(['# Intro', 'first', 'second', undefined, '# Outro'])
+ })
+
+ it('replaces a cell in place and drops its id', () => {
+ const ops: NotebookOperation[] = [
+ { _tag: 'replace_cell', cell_id: 'cell-2', cell: NEW_MARKDOWN_CELL },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ expect(result.notebook.cells).toEqual([NOTEBOOK.cells[0], NEW_MARKDOWN_CELL, NOTEBOOK.cells[2]])
+ })
+
+ it('deletes a cell', () => {
+ const ops: NotebookOperation[] = [{ _tag: 'delete_cell', cell_id: 'cell-2' }]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ expect(result.notebook.cells).toEqual([NOTEBOOK.cells[0], NOTEBOOK.cells[2]])
+ })
+
+ it('moves a cell after another cell', () => {
+ const ops: NotebookOperation[] = [
+ { _tag: 'move_cell', cell_id: 'cell-1', after_cell_id: 'cell-3' },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ expect(result.notebook.cells.map((cell) => ('id' in cell ? cell.id : undefined))).toEqual([
+ 'cell-2',
+ 'cell-3',
+ 'cell-1',
+ ])
+ })
+
+ it('moves a cell to the start', () => {
+ const ops: NotebookOperation[] = [
+ { _tag: 'move_cell', cell_id: 'cell-3', after_cell_id: 'start' },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ expect(result.notebook.cells.map((cell) => ('id' in cell ? cell.id : undefined))).toEqual([
+ 'cell-3',
+ 'cell-1',
+ 'cell-2',
+ ])
+ })
+
+ it('resolves a move anchored on another moved cell using its new position', () => {
+ // cell-1 moves after cell-3 first, landing at [cell-2, cell-3, cell-1]; cell-2 then moves
+ // after cell-1's *new* position, giving [cell-3, cell-1, cell-2].
+ const ops: NotebookOperation[] = [
+ { _tag: 'move_cell', cell_id: 'cell-1', after_cell_id: 'cell-3' },
+ { _tag: 'move_cell', cell_id: 'cell-2', after_cell_id: 'cell-1' },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ expect(result.notebook.cells.map((cell) => ('id' in cell ? cell.id : undefined))).toEqual([
+ 'cell-3',
+ 'cell-1',
+ 'cell-2',
+ ])
+ })
+
+ it('produces a different result when the same two moves are given in the opposite order', () => {
+ // cell-2 moves after cell-1 first — a no-op, since it's already there — landing at
+ // [cell-1, cell-2, cell-3]; cell-1 then moves after cell-3, giving [cell-2, cell-3, cell-1].
+ const ops: NotebookOperation[] = [
+ { _tag: 'move_cell', cell_id: 'cell-2', after_cell_id: 'cell-1' },
+ { _tag: 'move_cell', cell_id: 'cell-1', after_cell_id: 'cell-3' },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ expect(result.notebook.cells.map((cell) => ('id' in cell ? cell.id : undefined))).toEqual([
+ 'cell-2',
+ 'cell-3',
+ 'cell-1',
+ ])
+ })
+
+ it('resolves two moves that anchor on each other back to the original order', () => {
+ const ops: NotebookOperation[] = [
+ { _tag: 'move_cell', cell_id: 'cell-1', after_cell_id: 'cell-2' },
+ { _tag: 'move_cell', cell_id: 'cell-2', after_cell_id: 'cell-1' },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ expect(result.notebook.cells.map((cell) => ('id' in cell ? cell.id : undefined))).toEqual([
+ 'cell-1',
+ 'cell-2',
+ 'cell-3',
+ ])
+ })
+
+ it('applies an insert, a replace, and a delete together', () => {
+ const ops: NotebookOperation[] = [
+ { _tag: 'delete_cell', cell_id: 'cell-1' },
+ { _tag: 'replace_cell', cell_id: 'cell-2', cell: NEW_MARKDOWN_CELL },
+ {
+ _tag: 'insert_cell',
+ after_cell_id: 'cell-3',
+ cell: { _tag: 'markdown_cell', text: 'end' },
+ },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ expect(result.notebook.cells).toEqual([
+ NEW_MARKDOWN_CELL,
+ NOTEBOOK.cells[2],
+ { _tag: 'markdown_cell', text: 'end' },
+ ])
+ })
+
+ it('returns unknown_cell_id when after_cell_id does not exist', () => {
+ const ops: NotebookOperation[] = [
+ { _tag: 'insert_cell', after_cell_id: 'missing', cell: NEW_MARKDOWN_CELL },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result).toEqual({
+ success: false,
+ error: { _tag: 'unknown_cell_id', cell_id: 'missing' },
+ })
+ })
+
+ it('returns unknown_cell_id when a targeted cell_id does not exist', () => {
+ const ops: NotebookOperation[] = [{ _tag: 'delete_cell', cell_id: 'missing' }]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result).toEqual({
+ success: false,
+ error: { _tag: 'unknown_cell_id', cell_id: 'missing' },
+ })
+ })
+
+ it('returns conflicting_operations when two ops target the same cell', () => {
+ const ops: NotebookOperation[] = [
+ { _tag: 'delete_cell', cell_id: 'cell-2' },
+ { _tag: 'replace_cell', cell_id: 'cell-2', cell: NEW_MARKDOWN_CELL },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result).toEqual({
+ success: false,
+ error: { _tag: 'conflicting_operations', cell_id: 'cell-2' },
+ })
+ })
+
+ it('returns conflicting_operations when a move targets its own anchor', () => {
+ const ops: NotebookOperation[] = [
+ { _tag: 'move_cell', cell_id: 'cell-2', after_cell_id: 'cell-2' },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result).toEqual({
+ success: false,
+ error: { _tag: 'conflicting_operations', cell_id: 'cell-2' },
+ })
+ })
+
+ it('returns empty_result when every cell is deleted', () => {
+ const ops: NotebookOperation[] = [
+ { _tag: 'delete_cell', cell_id: 'cell-1' },
+ { _tag: 'delete_cell', cell_id: 'cell-2' },
+ { _tag: 'delete_cell', cell_id: 'cell-3' },
+ ]
+
+ const result = applyNotebookOperations(NOTEBOOK, ops)
+
+ expect(result).toEqual({ success: false, error: { _tag: 'empty_result' } })
+ })
+})
diff --git a/apps/studio/data/content/notebooks/notebook-operations.ts b/apps/studio/data/content/notebooks/notebook-operations.ts
new file mode 100644
index 00000000000..8b9ba411ddc
--- /dev/null
+++ b/apps/studio/data/content/notebooks/notebook-operations.ts
@@ -0,0 +1,177 @@
+import * as z from 'zod'
+
+import {
+ agentCellSchema,
+ type AgentCell,
+ type CellWire,
+ type NotebookWire,
+} from './notebook-schema'
+
+export const CELL_ANCHOR_START = 'start'
+
+const cellAnchorSchema = z
+ .string()
+ .describe(`The id of the cell to insert after, or "${CELL_ANCHOR_START}" for the beginning.`)
+
+export const insertCellOperationSchema = z.object({
+ _tag: z.literal('insert_cell'),
+ after_cell_id: cellAnchorSchema,
+ cell: agentCellSchema,
+})
+
+export const replaceCellOperationSchema = z.object({
+ _tag: z.literal('replace_cell'),
+ cell_id: z.string().describe('The id of the existing cell to replace.'),
+ cell: agentCellSchema,
+})
+
+export const deleteCellOperationSchema = z.object({
+ _tag: z.literal('delete_cell'),
+ cell_id: z.string().describe('The id of the existing cell to delete.'),
+})
+
+export const moveCellOperationSchema = z.object({
+ _tag: z.literal('move_cell'),
+ cell_id: z.string().describe('The id of the existing cell to move.'),
+ after_cell_id: cellAnchorSchema,
+})
+
+export const notebookOperationSchema = z.discriminatedUnion('_tag', [
+ insertCellOperationSchema,
+ replaceCellOperationSchema,
+ deleteCellOperationSchema,
+ moveCellOperationSchema,
+])
+
+export const notebookOperationsSchema = z.array(notebookOperationSchema)
+
+export type InsertCellOperation = z.infer<typeof insertCellOperationSchema>
+export type ReplaceCellOperation = z.infer<typeof replaceCellOperationSchema>
+export type DeleteCellOperation = z.infer<typeof deleteCellOperationSchema>
+export type MoveCellOperation = z.infer<typeof moveCellOperationSchema>
+export type NotebookOperation = z.infer<typeof notebookOperationSchema>
+
+export type OperationResultCell = CellWire | AgentCell
+
+export type NotebookOperationsResult = {
+ schema_version: NotebookWire['schema_version']
+ cells: OperationResultCell[]
+}
+
+export type NotebookOperationError =
+ | { _tag: 'unknown_cell_id'; cell_id: string }
+ | { _tag: 'conflicting_operations'; cell_id: string }
+ | { _tag: 'empty_result' }
+
+export type ApplyNotebookOperationsResult =
+ | { success: true; notebook: NotebookOperationsResult }
+ | { success: false; error: NotebookOperationError }
+
+function targetCellId(operation: NotebookOperation): string | undefined {
+ switch (operation._tag) {
+ case 'insert_cell':
+ return undefined
+ case 'replace_cell':
+ case 'delete_cell':
+ case 'move_cell':
+ return operation.cell_id
+ }
+}
+
+export function applyNotebookOperations(
+ notebook: NotebookWire,
+ operations: NotebookOperation[]
+): ApplyNotebookOperationsResult {
+ const targetedIds = new Set<string>()
+ for (const operation of operations) {
+ const cellId = targetCellId(operation)
+ if (cellId === undefined) continue
+
+ if (targetedIds.has(cellId)) {
+ return { success: false, error: { _tag: 'conflicting_operations', cell_id: cellId } }
+ }
+ targetedIds.add(cellId)
+ }
+
+ const cells: OperationResultCell[] = [...notebook.cells]
+ const indexOfCellId = (cellId: string) =>
+ cells.findIndex((cell) => 'id' in cell && cell.id === cellId)
+
+ const insertedAfter = new Map<string, number>()
+ const insertAfter = (
+ anchor: string,
+ item: OperationResultCell
+ ): NotebookOperationError | undefined => {
+ const anchorIndex = anchor === CELL_ANCHOR_START ? -1 : indexOfCellId(anchor)
+ if (anchor !== CELL_ANCHOR_START && anchorIndex === -1) {
+ return { _tag: 'unknown_cell_id', cell_id: anchor }
+ }
+
+ const offset = insertedAfter.get(anchor) ?? 0
+ cells.splice(anchorIndex + 1 + offset, 0, item)
+ insertedAfter.set(anchor, offset + 1)
+ return undefined
+ }
+
+ for (const operation of operations) {
+ switch (operation._tag) {
+ case 'insert_cell': {
+ const error = insertAfter(operation.after_cell_id, operation.cell)
+ if (error) return { success: false, error }
+ break
+ }
+ case 'replace_cell': {
+ const index = indexOfCellId(operation.cell_id)
+ if (index === -1) {
+ return {
+ success: false,
+ error: { _tag: 'unknown_cell_id', cell_id: operation.cell_id },
+ }
+ }
+ cells[index] = operation.cell
+ break
+ }
+ case 'delete_cell': {
+ const index = indexOfCellId(operation.cell_id)
+ if (index === -1) {
+ return {
+ success: false,
+ error: { _tag: 'unknown_cell_id', cell_id: operation.cell_id },
+ }
+ }
+ cells.splice(index, 1)
+ break
+ }
+ case 'move_cell': {
+ if (operation.after_cell_id === operation.cell_id) {
+ return {
+ success: false,
+ error: { _tag: 'conflicting_operations', cell_id: operation.cell_id },
+ }
+ }
+
+ const fromIndex = indexOfCellId(operation.cell_id)
+ if (fromIndex === -1) {
+ return {
+ success: false,
+ error: { _tag: 'unknown_cell_id', cell_id: operation.cell_id },
+ }
+ }
+
+ const [movedCell] = cells.splice(fromIndex, 1)
+ const error = insertAfter(operation.after_cell_id, movedCell)
+ if (error) return { success: false, error }
+ break
+ }
+ }
+ }
+
+ if (cells.length === 0) {
+ return { success: false, error: { _tag: 'empty_result' } }
+ }
+
+ return {
+ success: true,
+ notebook: { schema_version: notebook.schema_version, cells },
+ }
+}