The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): wire update_notebook tool (#48949)
Charis4da8bfe469b3
diff --git a/apps/studio/lib/ai/prompts.ts b/apps/studio/lib/ai/prompts.tsindex 9aeb7b460e4..cdd1cd93603 100644--- a/apps/studio/lib/ai/prompts.ts+++ b/apps/studio/lib/ai/prompts.ts@@ -763,8 +763,10 @@ DO NOT start searching for recovery docs before checking deletion docsexport const NOTEBOOKS_PROMPT = `## Notebooks- Use \`create_notebook\` for a saved, shareable, multi-step investigation or dashboard the user will revisit — e.g. "build me a signup funnel notebook" or "create a notebook to track auth errors".+- Use \`update_notebook\` to edit an existing notebook — insert, replace, delete, or move cells — instead of recreating it from scratch.- Use \`execute_sql\` for a single ad-hoc question with no need to persist it.-- When the request clearly calls for a notebook, call \`create_notebook\` directly; the tool handles user approval.+- When the request clearly calls for a notebook, call \`create_notebook\` or \`update_notebook\` directly; both tools handle user approval.+- \`update_notebook\` re-fetches the notebook right before applying edits, so the latest save always wins — it cannot detect edits made by someone else in between.`export const OUTPUT_ONLY_PROMPT = `diff --git a/apps/studio/lib/ai/tool-filter.ts b/apps/studio/lib/ai/tool-filter.tsindex b818829fffa..a2256aa5e24 100644--- a/apps/studio/lib/ai/tool-filter.ts+++ b/apps/studio/lib/ai/tool-filter.ts@@ -40,6 +40,7 @@ export const toolSetValidationSchema = z.record('list_notebooks','get_notebook','create_notebook',+ 'update_notebook',// Fallback tools for self-hosted'getSchemaTables',@@ -94,6 +95,7 @@ export const TOOL_CATEGORY_MAP: Record<string, ToolCategory> = {list_notebooks: TOOL_CATEGORIES.SCHEMA,get_notebook: TOOL_CATEGORIES.SCHEMA,create_notebook: TOOL_CATEGORIES.SCHEMA,+ update_notebook: TOOL_CATEGORIES.SCHEMA,getSchemaTables: TOOL_CATEGORIES.SCHEMA,getRlsKnowledge: TOOL_CATEGORIES.SCHEMA,getFunctions: TOOL_CATEGORIES.SCHEMA,diff --git a/apps/studio/lib/ai/tools/notebook-tools.test.ts b/apps/studio/lib/ai/tools/notebook-tools.test.tsindex 371b7543963..475409dc91d 100644--- a/apps/studio/lib/ai/tools/notebook-tools.test.ts+++ b/apps/studio/lib/ai/tools/notebook-tools.test.ts@@ -47,10 +47,15 @@ const NOTEBOOK_CONTENT = {describe('ai/tools/notebook-tools', () => {describe('getNotebookTools', () => {- it('should return list_notebooks, get_notebook, and create_notebook tools', () => {+ it('should return list_notebooks, get_notebook, create_notebook, and update_notebook tools', () => {const tools = getNotebookTools()- expect(Object.keys(tools)).toEqual(['list_notebooks', 'get_notebook', 'create_notebook'])+ expect(Object.keys(tools)).toEqual([+ 'list_notebooks',+ 'get_notebook',+ 'create_notebook',+ 'update_notebook',+ ])})it('should not require approval to read notebooks', () => {@@ -60,10 +65,11 @@ describe('ai/tools/notebook-tools', () => {expect(tools.get_notebook.needsApproval).toBeUndefined()})- it('should require approval to create a notebook', () => {+ it('should require approval to create or update a notebook', () => {const tools = getNotebookTools()expect(tools.create_notebook.needsApproval).toBe(true)+ expect(tools.update_notebook.needsApproval).toBe(true)})})@@ -322,4 +328,85 @@ describe('ai/tools/notebook-tools', () => {expect(result).toEqual({ id: sentBody?.id, name: 'Signup funnel' })})})++ describe('update_notebook', () => {+ function mockGetNotebook() {+ addAPIMock({+ method: 'get',+ path: '/platform/projects/:ref/content/item/:id',+ response: () =>+ HttpResponse.json<GetUserContentByIdResponse>({+ id: 'notebook-1',+ name: 'Signup funnel',+ description: undefined,+ visibility: 'project',+ favorite: false,+ folder_id: null,+ inserted_at: '2026-01-01T00:00:00.000Z',+ updated_at: '2026-01-01T00:00:00.000Z',+ owner_id: 1,+ project_id: 1,+ type: 'notebook',+ content: NOTEBOOK_CONTENT,+ } as unknown as GetUserContentByIdResponse),+ })+ }++ it('should re-fetch the notebook, apply the operations, and PUT the resolved content', async () => {+ mockGetNotebook()+ let sentBody: Record<string, unknown> | undefined+ addAPIMock({+ method: 'put',+ path: '/platform/projects/:ref/content',+ response: async ({ request }) => {+ sentBody = (await request.json()) as Record<string, unknown>+ return new HttpResponse(null)+ },+ })++ const tools = getNotebookTools({ projectRef: 'test-project' })+ if (!tools.update_notebook.execute) throw new Error('execute is undefined')++ const result = await tools.update_notebook.execute(+ {+ id: 'notebook-1',+ operations: [+ { _tag: 'delete_cell', cell_id: 'cell-3' },+ {+ _tag: 'insert_cell',+ after_cell_id: 'cell-1',+ cell: { _tag: 'markdown_cell', text: '# New section' },+ },+ ],+ },+ { toolCallId: 'test', messages: [] }+ )++ expect(sentBody?.id).toBe('notebook-1')+ 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([+ 'cell-1',+ '# New section',+ 'cell-2',+ ])+ expect(content.cells[2].sql).toBe('select * from auth.users limit 100')+ expect(result).toEqual({ id: 'notebook-1', name: 'Signup funnel' })+ })++ it('should throw a descriptive error instead of PUTting when an operation targets an unknown cell id', async () => {+ mockGetNotebook()++ const tools = getNotebookTools({ projectRef: 'test-project' })+ if (!tools.update_notebook.execute) throw new Error('execute is undefined')++ await expect(+ tools.update_notebook.execute(+ { id: 'notebook-1', operations: [{ _tag: 'delete_cell', cell_id: 'missing-cell' }] },+ { toolCallId: 'test', messages: [] }+ )+ ).rejects.toThrow('No cell with id "missing-cell"')+ })+ })})diff --git a/apps/studio/lib/ai/tools/notebook-tools.ts b/apps/studio/lib/ai/tools/notebook-tools.tsindex 88556cf5f12..64ae842fd24 100644--- a/apps/studio/lib/ai/tools/notebook-tools.ts+++ b/apps/studio/lib/ai/tools/notebook-tools.ts@@ -3,16 +3,34 @@ import { tool } from 'ai'import { z } from 'zod'import { getContent } from '@/data/content/content-infinite-query'+import {+ applyNotebookOperations,+ notebookOperationsSchema,+ type NotebookOperationError,+} from '@/data/content/notebooks/notebook-operations'import { getNotebook } from '@/data/content/notebooks/notebook-query'import {agentNotebookSchema,+ type CellWire,+ type NotebookWire,type WritableCell,type WritableNotebook,} from '@/data/content/notebooks/notebook-schema'-import { createNotebook } from '@/data/content/notebooks/notebook-upsert-mutation'+import { createNotebook, updateNotebook } from '@/data/content/notebooks/notebook-upsert-mutation'import { acceptUntrustedLogsSql, untrustedLogSql } from '@/data/logs/safe-analytics-sql'import type { Notebooks } from '@/types'+function describeOperationError(error: NotebookOperationError): string {+ switch (error._tag) {+ case 'unknown_cell_id':+ return `No cell with id "${error.cell_id}" exists in this notebook.`+ case 'conflicting_operations':+ return `More than one operation targets cell "${error.cell_id}".`+ case 'empty_result':+ return 'This update would leave the notebook with no cells.'+ }+}+export type NotebookToolsContext = {projectRef?: stringauthorization?: string@@ -72,6 +90,8 @@ export const getNotebookTools = (ctx: NotebookToolsContext = {}) => {name: notebook.name,description: notebook.description,visibility: notebook.visibility,+ // 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':@@ -104,12 +124,14 @@ export const getNotebookTools = (ctx: NotebookToolsContext = {}) => {}),needsApproval: true,execute: async ({ name, description, content }) => {+ // This approval gate is the user gesture that promotes each cell's SQL from+ // untrusted to safe — keep the promotion here, not in a shared helper, so it's+ // auditable directly alongside the `needsApproval: true` above.const cells: WritableNotebook['cells'] = content.cells.map((cell): WritableCell => {switch (cell._tag) {case 'markdown_cell':return cellcase 'database_cell':- // The `needsApproval: true` gate above is the user gesture that promotes this SQL from untrusted to safe.return { ...cell, sql: acceptUntrustedSql(untrustedSql(cell.sql)) }case 'log_cell':return { ...cell, sql: acceptUntrustedLogsSql(untrustedLogSql(cell.sql)) }@@ -130,5 +152,75 @@ export const getNotebookTools = (ctx: NotebookToolsContext = {}) => {return { id: result.id, name }},}),+ update_notebook: tool({+ description:+ 'Asks the user to apply an ordered list of cell operations (insert, replace, delete, move) to an existing notebook. Requires user approval before updating. Re-fetches the notebook right before applying the operations; concurrent edits are last-write-wins.',+ inputSchema: z.object({+ id: z.string().describe('The id of the notebook to update.'),+ operations: notebookOperationsSchema.describe(+ 'An ordered list of operations to apply to the notebook, addressing existing cells by id.'+ ),+ }),+ needsApproval: true,+ execute: async ({ id, operations }) => {+ const notebook = await getNotebook({ projectRef, id }, undefined, authHeaders)++ // 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 }+ }+ }+ }),+ }++ const result = applyNotebookOperations(wireNotebook, operations)+ if (!result.success) {+ throw new Error(describeOperationError(result.error))+ }++ // Same promotion as create_notebook above, inlined here for the same auditability+ // reason: it must stay visible next to this tool's own `needsApproval: true`.+ const cells: WritableNotebook['cells'] = result.notebook.cells.map((cell): WritableCell => {+ switch (cell._tag) {+ case 'markdown_cell':+ return cell+ case 'database_cell':+ return { ...cell, sql: acceptUntrustedSql(untrustedSql(cell.sql)) }+ case 'log_cell':+ return { ...cell, sql: acceptUntrustedLogsSql(untrustedLogSql(cell.sql)) }+ }+ })++ await updateNotebook(+ {+ projectRef: projectRef ?? '',+ id,+ name: notebook.name,+ description: notebook.description,+ content: { schema_version: result.notebook.schema_version, cells },+ },+ undefined,+ authHeaders+ )++ return { id, name: notebook.name }+ },+ }),}}