Skip to content

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

feat(studio): wire notebook create/update proposals into assistant panel (#49159)

Charis79fbe467ba4b
diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx
index 047b51b6356..fc3132f9b5e 100644
--- a/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx
@@ -13,6 +13,7 @@ import {
parseExecuteSqlChartResult,
} from './Message.utils'
import { MessageMarkdown } from './MessageMarkdown'
+import { NotebookProposalRenderer, type NotebookProposalMode } from './NotebookProposalRenderer'
import { parseSupportRequestMessage, SupportRequestMessage } from './SupportRequestMessage'
function MessagePartText({ textPart }: { textPart: TextUIPart }) {
@@ -232,6 +233,59 @@ function MessagePartDeployEdgeFunction({ toolPart }: { toolPart: ToolUIPart }) {
)
}
+const NOTEBOOK_DRAFTING_LABEL: Record<NotebookProposalMode, string> = {
+ create: 'Drafting notebook...',
+ update: 'Drafting notebook update...',
+}
+
+const NOTEBOOK_FAILED_LABEL: Record<NotebookProposalMode, string> = {
+ create: 'Failed to create notebook.',
+ update: 'Failed to update notebook.',
+}
+
+function MessagePartNotebookProposal({
+ toolPart,
+ mode,
+}: {
+ toolPart: ToolUIPart
+ mode: NotebookProposalMode
+}) {
+ const { state, input, output } = toolPart
+ const { addToolApprovalResponse } = useMessageActionsContext()
+
+ if (state === 'input-streaming') {
+ return (
+ <div className="my-4 mx-4 rounded-lg border bg-surface-75 heading-meta h-9 px-3 text-foreground-light flex items-center gap-2">
+ <Loader2 className="w-4 h-4 animate-spin" />
+ {NOTEBOOK_DRAFTING_LABEL[mode]}
+ </div>
+ )
+ }
+
+ if (state === 'output-error') {
+ return <p className="text-xs text-danger px-4">{NOTEBOOK_FAILED_LABEL[mode]}</p>
+ }
+
+ const approvalId = state === 'approval-requested' ? toolPart.approval?.id : undefined
+
+ return (
+ <NotebookProposalRenderer
+ mode={mode}
+ state={state}
+ input={input}
+ output={output}
+ onApprove={
+ approvalId ? () => addToolApprovalResponse?.({ id: approvalId, approved: true }) : undefined
+ }
+ onDeny={
+ approvalId
+ ? () => addToolApprovalResponse?.({ id: approvalId, approved: false })
+ : undefined
+ }
+ />
+ )
+}
+
const MessagePart = {
Text: MessagePartText,
Dynamic: MessagePartDynamicTool,
@@ -239,6 +293,7 @@ const MessagePart = {
Reasoning: MessagePartReasoning,
ExecuteSql: MessagePartExecuteSql,
DeployEdgeFunction: MessagePartDeployEdgeFunction,
+ NotebookProposal: MessagePartNotebookProposal,
} as const
export function MessagePartSwitcher({
@@ -269,6 +324,12 @@ export function MessagePartSwitcher({
case 'tool-deploy_edge_function': {
return <MessagePart.DeployEdgeFunction toolPart={part} />
}
+ case 'tool-create_notebook': {
+ return <MessagePart.NotebookProposal toolPart={part} mode="create" />
+ }
+ case 'tool-update_notebook': {
+ return <MessagePart.NotebookProposal toolPart={part} mode="update" />
+ }
case 'source-url':
case 'source-document':
diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.utils.ts b/apps/studio/components/ui/AIAssistantPanel/Message.utils.ts
index 932864198f7..9867cc27511 100644
--- a/apps/studio/components/ui/AIAssistantPanel/Message.utils.ts
+++ b/apps/studio/components/ui/AIAssistantPanel/Message.utils.ts
@@ -1,6 +1,9 @@
import { untrustedSql } from '@supabase/pg-meta'
import { z, type SafeParseReturnType } from 'zod'
+import { notebookOperationsSchema } from '@/data/content/notebooks/notebook-operations'
+import { agentNotebookSchema } from '@/data/content/notebooks/notebook-schema'
+
// Splits markdown into alternating [plain, code, plain, code, ...] segments.
// Odd-indexed segments are already inside code spans/fences and should be left alone.
const CODE_SEGMENT_REGEX = /(```[\s\S]*?```|`[^`]*`)/g
@@ -126,6 +129,20 @@ export const deployEdgeFunctionOutputSchema = z
.object({ success: z.boolean().optional() })
.passthrough()
+export const createNotebookInputSchema = z.object({
+ name: z.string(),
+ description: z.string().optional(),
+ content: agentNotebookSchema,
+})
+
+export const updateNotebookInputSchema = z.object({
+ id: z.string(),
+ expected_updated_at: z.string(),
+ operations: notebookOperationsSchema,
+})
+
+export const notebookToolOutputSchema = z.object({ id: z.string(), name: z.string() })
+
export const rateMessageResponseSchema = z.object({
category: z.enum([
'sql_generation',
diff --git a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx
new file mode 100644
index 00000000000..ba4d765cc17
--- /dev/null
+++ b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx
@@ -0,0 +1,164 @@
+import { screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { HttpResponse } from 'msw'
+import { describe, expect, it, vi } from 'vitest'
+
+import { NotebookProposalRenderer } from './NotebookProposalRenderer'
+import type { components } from '@/data/api'
+import { customRender as render } from '@/tests/lib/custom-render'
+import { addAPIMock } from '@/tests/lib/msw'
+
+const NOTEBOOK_ID = 'd3aadd77-7c3c-4de7-aa5c-5aa8ac270b44'
+
+const mockNotebookRow = (overrides: Partial<Record<string, unknown>> = {}) => ({
+ id: NOTEBOOK_ID,
+ type: 'notebook',
+ name: 'Signup funnel',
+ description: '',
+ favorite: false,
+ folder_id: null,
+ inserted_at: '2024-01-01T00:00:00.000Z',
+ updated_at: '2024-01-01T00:00:00.000Z',
+ visibility: 'project',
+ owner_id: 1,
+ project_id: 1,
+ content: {
+ schema_version: 1,
+ cells: [
+ { _tag: 'markdown_cell', id: 'cell-1', text: 'hello' },
+ { _tag: 'markdown_cell', id: 'cell-2', text: 'world' },
+ ],
+ },
+ ...overrides,
+})
+
+const mockContentItem = (row: ReturnType<typeof mockNotebookRow>) =>
+ addAPIMock({
+ method: 'get',
+ path: '/platform/projects/:ref/content/item/:id',
+ response: () =>
+ HttpResponse.json<components['schemas']['GetUserContentByIdResponse']>(
+ row as unknown as components['schemas']['GetUserContentByIdResponse']
+ ),
+ })
+
+describe('NotebookProposalRenderer', () => {
+ it('renders the create-mode preview and approves on confirm', async () => {
+ const user = userEvent.setup()
+ const onApprove = vi.fn()
+
+ render(
+ <NotebookProposalRenderer
+ mode="create"
+ state="approval-requested"
+ input={{
+ name: 'New notebook',
+ content: {
+ schema_version: 1,
+ cells: [{ _tag: 'markdown_cell', text: 'hello' }],
+ },
+ }}
+ output={undefined}
+ onApprove={onApprove}
+ onDeny={vi.fn()}
+ />
+ )
+
+ expect(screen.getByText('1 cell')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Create' }))
+ expect(onApprove).toHaveBeenCalledTimes(1)
+ })
+
+ it('renders the update-mode diff once the notebook is fetched and approves on confirm', async () => {
+ const user = userEvent.setup()
+ const onApprove = vi.fn()
+ mockContentItem(mockNotebookRow())
+
+ render(
+ <NotebookProposalRenderer
+ mode="update"
+ state="approval-requested"
+ input={{
+ id: NOTEBOOK_ID,
+ expected_updated_at: '2024-01-01T00:00:00.000Z',
+ operations: [{ _tag: 'delete_cell', cell_id: 'cell-1' }],
+ }}
+ output={undefined}
+ onApprove={onApprove}
+ onDeny={vi.fn()}
+ />
+ )
+
+ expect(await screen.findByText('−1')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Apply changes' }))
+ expect(onApprove).toHaveBeenCalledTimes(1)
+ })
+
+ it('warns and withholds the diff when the notebook changed since expected_updated_at', async () => {
+ const onApprove = vi.fn()
+ mockContentItem(mockNotebookRow({ updated_at: '2024-06-01T00:00:00.000Z' }))
+
+ render(
+ <NotebookProposalRenderer
+ mode="update"
+ state="approval-requested"
+ input={{
+ id: NOTEBOOK_ID,
+ expected_updated_at: '2024-01-01T00:00:00.000Z',
+ operations: [{ _tag: 'delete_cell', cell_id: 'cell-1' }],
+ }}
+ output={undefined}
+ onApprove={onApprove}
+ onDeny={vi.fn()}
+ />
+ )
+
+ expect(
+ await screen.findByText('This notebook changed since the assistant planned this update')
+ ).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Refresh' })).toBeInTheDocument()
+ expect(onApprove).not.toHaveBeenCalled()
+ })
+
+ it('falls back to a raw-input admonition without dropping the confirm footer on a parse failure', async () => {
+ const user = userEvent.setup()
+ const onDeny = vi.fn()
+
+ render(
+ <NotebookProposalRenderer
+ mode="create"
+ state="approval-requested"
+ input={{ nonsense: true }}
+ output={undefined}
+ onApprove={vi.fn()}
+ onDeny={onDeny}
+ />
+ )
+
+ expect(screen.getByText("Couldn't render a preview for this notebook")).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Skip' }))
+ expect(onDeny).toHaveBeenCalledTimes(1)
+ })
+
+ it('renders an Open notebook link once output is available', () => {
+ render(
+ <NotebookProposalRenderer
+ mode="create"
+ state="output-available"
+ input={{}}
+ output={{ id: NOTEBOOK_ID, name: 'Signup funnel' }}
+ />
+ )
+
+ const link = screen.getByRole('link', { name: 'Open notebook' })
+ expect(link).toHaveAttribute('href', `/project/default/explorer/notebook/${NOTEBOOK_ID}`)
+ })
+
+ it('renders a muted skipped summary when output-denied', () => {
+ render(
+ <NotebookProposalRenderer mode="update" state="output-denied" input={{}} output={undefined} />
+ )
+
+ expect(screen.getByText('Skipped notebook update')).toBeInTheDocument()
+ })
+})
diff --git a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx
new file mode 100644
index 00000000000..b644d8aeafb
--- /dev/null
+++ b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx
@@ -0,0 +1,308 @@
+import { useParams } from 'common'
+import { Loader2 } from 'lucide-react'
+import Link from 'next/link'
+import { Button } from 'ui'
+import { Admonition } from 'ui-patterns/Admonition'
+import { CodeBlock } from 'ui-patterns/CodeBlock'
+
+import { ConfirmFooter } from './ConfirmFooter'
+import {
+ createNotebookInputSchema,
+ notebookToolOutputSchema,
+ updateNotebookInputSchema,
+} from './Message.utils'
+import { NotebookPreview } from '@/components/interfaces/Explorer/NotebookPreview/NotebookPreview'
+import { AlertError } from '@/components/ui/AlertError'
+import {
+ deriveNotebookDiff,
+ describeNotebookOperationError,
+ type NotebookCellDiffEntry,
+} from '@/data/content/notebooks/notebook-operations'
+import { useNotebookQuery } from '@/data/content/notebooks/notebook-query'
+import { toWireNotebook } from '@/data/content/notebooks/notebook-schema'
+
+export type NotebookProposalMode = 'create' | 'update'
+
+// input-streaming and output-error are handled by the caller before this component is
+// rendered — see MessagePartCreateNotebook / MessagePartUpdateNotebook in Message.Parts.tsx.
+export type NotebookProposalState =
+ | 'input-available'
+ | 'approval-requested'
+ | 'approval-responded'
+ | 'output-denied'
+ | 'output-available'
+
+export interface NotebookProposalRendererProps {
+ mode: NotebookProposalMode
+ state: NotebookProposalState
+ input: unknown
+ output: unknown
+ onApprove?: () => void
+ onDeny?: () => void
+}
+
+type NotebookProposalStepProps = Omit<NotebookProposalRendererProps, 'mode' | 'output'>
+
+const MODE_COPY = {
+ create: {
+ confirmMessage: 'Assistant wants to create this notebook',
+ confirmLabel: 'Create',
+ confirmLabelLoading: 'Creating...',
+ skippedLabel: 'Skipped notebook creation',
+ outputLabel: 'Notebook created',
+ },
+ update: {
+ confirmMessage: 'Assistant wants to update this notebook',
+ confirmLabel: 'Apply changes',
+ confirmLabelLoading: 'Applying changes...',
+ skippedLabel: 'Skipped notebook update',
+ outputLabel: 'Notebook updated',
+ },
+} as const
+
+/**
+ * Renders the create/update notebook tool across all approval states. Owns input parsing
+ * (via the shared `agentNotebookSchema` / `notebookOperationsSchema`), the update-mode diff
+ * fetch, and the `expected_updated_at` version check.
+ */
+export const NotebookProposalRenderer = (props: NotebookProposalRendererProps) => {
+ const { mode, state, output } = props
+
+ if (state === 'output-denied') {
+ return (
+ <p className="text-xs text-foreground-lighter my-2 px-4">{MODE_COPY[mode].skippedLabel}</p>
+ )
+ }
+
+ if (state === 'output-available') {
+ return <NotebookOutputSummary mode={mode} output={output} />
+ }
+
+ const { input, onApprove, onDeny } = props
+ return mode === 'create' ? (
+ <CreateNotebookProposal state={state} input={input} onApprove={onApprove} onDeny={onDeny} />
+ ) : (
+ <UpdateNotebookProposal state={state} input={input} onApprove={onApprove} onDeny={onDeny} />
+ )
+}
+
+function NotebookOutputSummary({ mode, output }: { mode: NotebookProposalMode; output: unknown }) {
+ const { ref } = useParams()
+ const parsedOutput = notebookToolOutputSchema.safeParse(output)
+ const label = MODE_COPY[mode].outputLabel
+
+ return (
+ <div className="flex items-center justify-between gap-2 my-2 mx-4 px-3 py-1.5 text-sm border rounded-md bg-surface-75">
+ <span className="text-foreground-light truncate">
+ {parsedOutput.success ? `${label}: ${parsedOutput.data.name}` : label}
+ </span>
+ {parsedOutput.success && ref && (
+ <Button asChild variant="default" size="tiny">
+ <Link href={`/project/${ref}/explorer/notebook/${parsedOutput.data.id}`}>
+ Open notebook
+ </Link>
+ </Button>
+ )}
+ </div>
+ )
+}
+
+interface NotebookConfirmFooterProps {
+ mode: NotebookProposalMode
+ state: NotebookProposalState
+ message?: string
+ confirmLabel?: string
+ confirmLabelLoading?: string
+ extraLoading?: boolean
+ onApprove?: () => void
+ onDeny?: () => void
+}
+
+/** The footer morphs (label + disabled) across approval-requested/approval-responded and is absent otherwise. */
+function NotebookConfirmFooter({
+ mode,
+ state,
+ message,
+ confirmLabel,
+ confirmLabelLoading,
+ extraLoading = false,
+ onApprove,
+ onDeny,
+}: NotebookConfirmFooterProps) {
+ if (state !== 'approval-requested' && state !== 'approval-responded') return null
+
+ const copy = MODE_COPY[mode]
+ const isApprovalRequested = state === 'approval-requested'
+
+ return (
+ <ConfirmFooter
+ message={message ?? copy.confirmMessage}
+ cancelLabel="Skip"
+ confirmLabel={confirmLabel ?? copy.confirmLabel}
+ confirmLabelLoading={confirmLabelLoading ?? copy.confirmLabelLoading}
+ isLoading={!isApprovalRequested || extraLoading}
+ onCancel={isApprovalRequested ? onDeny : undefined}
+ onConfirm={isApprovalRequested ? onApprove : undefined}
+ />
+ )
+}
+
+function NotebookParseFailure({
+ mode,
+ state,
+ input,
+ onApprove,
+ onDeny,
+}: Pick<NotebookProposalRendererProps, 'mode' | 'state' | 'input' | 'onApprove' | 'onDeny'>) {
+ return (
+ <div className="w-auto overflow-x-hidden my-4 px-4 flex flex-col gap-2">
+ <Admonition
+ type="warning"
+ title="Couldn't render a preview for this notebook"
+ description="The assistant's proposed input didn't match the expected shape. You can still review the raw input below."
+ />
+ <CodeBlock
+ language="json"
+ value={JSON.stringify(input, null, 2)}
+ hideLineNumbers
+ className="text-xs"
+ wrapperClassName="max-h-56"
+ />
+ <NotebookConfirmFooter mode={mode} state={state} onApprove={onApprove} onDeny={onDeny} />
+ </div>
+ )
+}
+
+function CreateNotebookProposal({ state, input, onApprove, onDeny }: NotebookProposalStepProps) {
+ const parsedInput = createNotebookInputSchema.safeParse(input)
+
+ if (!parsedInput.success) {
+ return (
+ <NotebookParseFailure
+ mode="create"
+ state={state}
+ input={input}
+ onApprove={onApprove}
+ onDeny={onDeny}
+ />
+ )
+ }
+
+ const entries: NotebookCellDiffEntry[] = parsedInput.data.content.cells.map(
+ (cell, operationIndex) => ({
+ _tag: 'added',
+ cell,
+ operationIndex,
+ })
+ )
+
+ return (
+ <div className="w-auto overflow-x-hidden my-4 px-4 flex flex-col gap-2">
+ <NotebookPreview entries={entries} mode="create" />
+ <NotebookConfirmFooter mode="create" state={state} onApprove={onApprove} onDeny={onDeny} />
+ </div>
+ )
+}
+
+function UpdateNotebookProposal({ state, input, onApprove, onDeny }: NotebookProposalStepProps) {
+ const { ref } = useParams()
+ const parsedInput = updateNotebookInputSchema.safeParse(input)
+
+ const {
+ data: notebook,
+ isLoading,
+ isError,
+ error,
+ refetch,
+ isFetching,
+ } = useNotebookQuery(
+ { projectRef: ref, id: parsedInput.success ? parsedInput.data.id : undefined },
+ { enabled: parsedInput.success }
+ )
+
+ if (!parsedInput.success) {
+ return (
+ <NotebookParseFailure
+ mode="update"
+ state={state}
+ input={input}
+ onApprove={onApprove}
+ onDeny={onDeny}
+ />
+ )
+ }
+
+ if (isLoading) {
+ return (
+ <div className="my-4 mx-4 rounded-lg border bg-surface-75 heading-meta h-9 px-3 text-foreground-light flex items-center gap-2">
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Loading notebook...
+ </div>
+ )
+ }
+
+ if (isError || !notebook) {
+ return (
+ <div className="w-auto overflow-x-hidden my-4 px-4 flex flex-col gap-2">
+ <AlertError error={error} subject="Failed to load notebook" />
+ {(state === 'approval-requested' || state === 'approval-responded') && (
+ <Button
+ variant="outline"
+ size="tiny"
+ className="w-fit"
+ disabled={state === 'approval-responded'}
+ onClick={onDeny}
+ >
+ Skip
+ </Button>
+ )}
+ </div>
+ )
+ }
+
+ const isStale = notebook.updated_at !== parsedInput.data.expected_updated_at
+
+ if (isStale) {
+ return (
+ <div className="w-auto overflow-x-hidden my-4 px-4 flex flex-col gap-2">
+ <Admonition
+ type="warning"
+ title="This notebook changed since the assistant planned this update"
+ description={`"${notebook.name}" was updated after the assistant read it. Refresh to see the latest version before deciding.`}
+ />
+ <NotebookConfirmFooter
+ mode="update"
+ state={state}
+ confirmLabel="Refresh"
+ confirmLabelLoading="Refreshing..."
+ extraLoading={isFetching}
+ onDeny={onDeny}
+ onApprove={() => refetch()}
+ />
+ </div>
+ )
+ }
+
+ const diff = deriveNotebookDiff(toWireNotebook(notebook.content), parsedInput.data.operations)
+
+ return (
+ <div className="w-auto overflow-x-hidden my-4 px-4 flex flex-col gap-2">
+ {diff.success ? (
+ <NotebookPreview entries={diff.entries} mode="update" />
+ ) : (
+ <Admonition
+ type="warning"
+ title="This update can't be applied as written"
+ description={describeNotebookOperationError(diff.error)}
+ />
+ )}
+ <NotebookConfirmFooter
+ mode="update"
+ state={state}
+ message={`Assistant wants to update "${notebook.name}"`}
+ onApprove={onApprove}
+ onDeny={onDeny}
+ />
+ </div>
+ )
+}
diff --git a/apps/studio/data/content/notebooks/notebook-schema.ts b/apps/studio/data/content/notebooks/notebook-schema.ts
index 6e563a6ae15..8a1e1332ed6 100644
--- a/apps/studio/data/content/notebooks/notebook-schema.ts
+++ b/apps/studio/data/content/notebooks/notebook-schema.ts
@@ -190,6 +190,29 @@ 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':
+ 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 }
+ }
+ }
+}
+
+export function toWireNotebook(content: NotebookContent): NotebookWire {
+ return { schema_version: content.schema_version, cells: content.cells.map(toWireCell) }
+}
+
export type MarkdownCell = Extract<Cell, { _tag: 'markdown_cell' }>
export type DatabaseCell = Extract<Cell, { _tag: 'database_cell' }>
export type LogCell = Extract<Cell, { _tag: 'log_cell' }>