The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): render assistant notebook runs (#49362)
Saxon Fletcher1a013ea2c83a
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.test.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.test.tsxindex 1515ba15418..e084e1b7ff2 100644--- a/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.test.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.test.tsx@@ -92,4 +92,55 @@ describe('AssistantNotebookPreview', () => {expect(screen.getByText('Show 2 more cells')).toBeInTheDocument()})++ it('renders run results inside their matching minified notebook cell', () => {+ const entries: NotebookCellDiffEntry[] = [+ { _tag: 'unchanged', cell: wireDatabaseCell('cell-1') },+ ]++ const { container } = render(+ <AssistantNotebookPreview+ entries={entries}+ mode="run"+ title="Signup funnel"+ results={{ 'cell-1': { rows: [] } }}+ />+ )++ expect(screen.getByText('Signup funnel')).toBeInTheDocument()+ expect(screen.getByText('1 cell')).toBeInTheDocument()+ expect(screen.getByText('Success. No rows returned')).toBeInTheDocument()+ expect(screen.getByText('0 rows')).toBeInTheDocument()+ expect(container.querySelector('[data-slot="explorer-query-results"]')).toBeInTheDocument()+ })++ it('bases result rendering and layout on supplied results rather than preview mode', () => {+ const entries: NotebookCellDiffEntry[] = [+ { _tag: 'unchanged', cell: wireDatabaseCell('cell-1') },+ ]++ const { container } = render(+ <AssistantNotebookPreview+ entries={entries}+ mode="create"+ results={{ 'cell-1': { rows: [{ value: 1 }] } }}+ />+ )++ expect(screen.getByText('1 row')).toBeInTheDocument()+ expect(container.querySelector('[data-slot="explorer-query-results"]')).toBeInTheDocument()+ expect(container.querySelector('.flex.flex-col.gap-2')).toBeInTheDocument()+ expect(container.querySelector('.divide-y.divide-border')).not.toBeInTheDocument()+ })++ it('keeps a run preview without results in the grouped cell layout', () => {+ const entries: NotebookCellDiffEntry[] = [+ { _tag: 'unchanged', cell: wireDatabaseCell('cell-1') },+ ]++ const { container } = render(<AssistantNotebookPreview entries={entries} mode="run" />)++ expect(container.querySelector('[data-slot="explorer-query-results"]')).not.toBeInTheDocument()+ expect(container.querySelector('.divide-y.divide-border')).toBeInTheDocument()+ })})diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.tsxindex 26c243b6c53..360a475fac6 100644--- a/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.tsx@@ -14,13 +14,16 @@ import {ExplorerToolbarIcon,ExplorerToolbarTitle,} from '@/components/interfaces/Explorer/ExplorerToolbar'+import type { QueryResult } from '@/components/interfaces/Explorer/types'import type { NotebookCellDiffEntry } from '@/data/content/notebooks/notebook-operations'export interface AssistantNotebookPreviewProps {entries: NotebookCellDiffEntry[]- mode: 'create' | 'update'+ mode: 'create' | 'update' | 'run'/** The notebook's name, shown in the toolbar. Falls back to a generic label. */title?: string+ /** Query results keyed by persisted cell id. */+ results?: Record<string, QueryResult>className?: string}@@ -29,18 +32,20 @@ const VISIBLE_ENTRY_LIMIT = 5const FALLBACK_TITLE = {create: 'New notebook',update: 'Notebook changes',+ run: 'Notebook run',} as const/**- * Read-only minified notebook for assistant create/update previews. Composes the same- * Explorer toolbar as notebook tabs; the surrounding `Confirm` card owns the frame.- * Pure presentational: no data fetching, no approval or notebook-editor state — see- * `deriveNotebookDiff` for how `entries` is produced.+ * Read-only minified notebook for assistant create/update proposals and notebook runs.+ * Composes the same Explorer toolbar and query-result surfaces as notebook tabs; the+ * surrounding `Confirm` card owns the frame. Pure presentational: no data fetching,+ * approval, or notebook-editor state — callers adapt those concerns into entries/results.*/export const AssistantNotebookPreview = ({entries,mode,title,+ results,className,}: AssistantNotebookPreviewProps) => {const [isShowingAllEntries, setIsShowingAllEntries] = useState(false)@@ -49,6 +54,7 @@ export const AssistantNotebookPreview = ({const summary = summarizeNotebookDiff(entries, mode)const visibleEntries = isShowingAllEntries ? entries : entries.slice(0, VISIBLE_ENTRY_LIMIT)const hiddenCount = entries.length - visibleEntries.length+ const hasResults = results !== undefinedconst isExpanded = (entry: NotebookCellDiffEntry) =>expandedOverrides[getEntryKey(entry)] === true@@ -67,20 +73,29 @@ export const AssistantNotebookPreview = ({</ExplorerToolbarActions></ExplorerToolbar><div className="p-2">- <div className="overflow-hidden rounded-md border bg-surface-100">- <div className="divide-y divide-border">+ <div+ className={cn(+ hasResults ? 'flex flex-col gap-2' : 'overflow-hidden rounded-md border bg-surface-100'+ )}+ >+ <div className={cn(hasResults ? 'contents' : 'divide-y divide-border')}>{visibleEntries.map((entry) => {const key = getEntryKey(entry)return (- <AssistantNotebookPreviewCell+ <divkey={key}- entry={entry}- mode={mode}- isExpanded={isExpanded(entry)}- onExpandedChange={(open) =>- setExpandedOverrides((prev) => ({ ...prev, [key]: open }))- }- />+ className={cn(hasResults && 'overflow-hidden rounded-md border bg-surface-100')}+ >+ <AssistantNotebookPreviewCell+ entry={entry}+ mode={mode}+ result={results?.[key]}+ isExpanded={isExpanded(entry)}+ onExpandedChange={(open) =>+ setExpandedOverrides((prev) => ({ ...prev, [key]: open }))+ }+ />+ </div>)})}</div>@@ -88,7 +103,10 @@ export const AssistantNotebookPreview = ({<Buttonvariant="text"size="tiny"- className="w-full rounded-none border-0 border-t border-default text-foreground-light"+ className={cn(+ 'w-full text-foreground-light',+ !hasResults && 'rounded-none border-0 border-t border-default'+ )}onClick={() => setIsShowingAllEntries(true)}>Show {hiddenCount} more cell{hiddenCount === 1 ? '' : 's'}diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils.ts b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils.tsindex b8aefa9bd82..97ba1141100 100644--- a/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils.ts+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils.ts@@ -104,15 +104,16 @@ export function getEntryMetadataLine(entry: NotebookCellDiffEntry): string | nulexport type NotebookDiffSummary =| { mode: 'create'; cellCount: number }+ | { mode: 'run'; cellCount: number }| { mode: 'update'; counts: { added: number; removed: number; replaced: number; moved: number } }/** Summarizes a set of diff entries into counts suitable for a header line. */export function summarizeNotebookDiff(entries: NotebookCellDiffEntry[],- mode: 'create' | 'update'+ mode: 'create' | 'update' | 'run'): NotebookDiffSummary {- if (mode === 'create') {- return { mode: 'create', cellCount: entries.length }+ if (mode === 'create' || mode === 'run') {+ return { mode, cellCount: entries.length }}const counts = { added: 0, removed: 0, replaced: 0, moved: 0 }@@ -140,7 +141,7 @@ export function summarizeNotebookDiff(/** Formats a `NotebookDiffSummary` into the header string. */export function formatNotebookDiffSummary(summary: NotebookDiffSummary): string {- if (summary.mode === 'create') {+ if (summary.mode === 'create' || summary.mode === 'run') {const { cellCount } = summaryreturn `${cellCount} cell${cellCount === 1 ? '' : 's'}`}diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreviewCell.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreviewCell.tsxindex 908bd0be124..174f72ff699 100644--- a/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreviewCell.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreviewCell.tsx@@ -17,6 +17,12 @@ import {getCellSourceText,getEntryMetadataLine,} from './AssistantNotebookPreview.utils'+import {+ ExplorerQueryFooter,+ ExplorerQueryResults,+} from '@/components/interfaces/Explorer/ExplorerQuery'+import { QueryResultRenderer } from '@/components/interfaces/Explorer/QueryEditor/QueryResultRenderer'+import type { QueryResult } from '@/components/interfaces/Explorer/types'import { DiffEditor } from '@/components/ui/DiffEditor'import type { NotebookCellDiffEntry } from '@/data/content/notebooks/notebook-operations'import type { AgentCell, CellWire } from '@/data/content/notebooks/notebook-schema'@@ -25,8 +31,9 @@ export interface AssistantNotebookPreviewCellProps {entry: NotebookCellDiffEntryisExpanded: booleanonExpandedChange: (isExpanded: boolean) => void- /** Create previews omit per-row change glyphs — every cell is an add. */- mode: 'create' | 'update'+ /** Create and run previews omit per-row change glyphs. */+ mode: 'create' | 'update' | 'run'+ result?: QueryResult}/**@@ -54,6 +61,7 @@ export const AssistantNotebookPreviewCell = ({isExpanded,onExpandedChange,mode,+ result,}: AssistantNotebookPreviewCellProps) => {const marker = CHANGE_MARKERS[entry._tag]const isRemoved = entry._tag === 'removed'@@ -92,10 +100,48 @@ export const AssistantNotebookPreviewCell = ({<CellBody entry={entry} /></div></CollapsibleContent>+ {result !== undefined && cell._tag !== 'markdown_cell' && (+ <QueryCellResult cell={cell} result={result} />+ )}</Collapsible>)}+const QueryCellResult = ({+ cell,+ result,+}: {+ cell: Extract<CellWire | AgentCell, { _tag: 'database_cell' | 'log_cell' }>+ result: QueryResult+}) => {+ const rowCount = result.rows?.length ?? 0+ const rowLimit = cell._tag === 'database_cell' ? cell.row_limit : undefined++ return (+ <>+ <ExplorerQueryResults+ className={cn(+ 'border-t',+ rowCount === 0 ? 'min-h-20 items-center justify-center' : 'h-56 overflow-x-auto'+ )}+ >+ <QueryResultRenderer view={cell.view ?? 'table'} result={result} chart={cell.chart} />+ </ExplorerQueryResults>+ <ExplorerQueryFooter className="flex items-center gap-x-2">+ <p>+ {rowCount.toLocaleString()} {rowCount === 1 ? 'row' : 'rows'}+ </p>+ {rowLimit !== undefined && (+ <>+ <p>·</p>+ <p>{rowLimit < 0 ? 'No row limit' : `Limit ${rowLimit} rows`}</p>+ </>+ )}+ </ExplorerQueryFooter>+ </>+ )+}+/*** The gutter glyph, with a tooltip naming the change type it stands for. The glyph stays* `aria-hidden` — the row's `aria-label` already carries the same word — so the tooltip is adiff --git a/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsxindex a5ba61a2398..86bf4c88214 100644--- a/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx@@ -18,6 +18,7 @@ import {import { MessageMarkdown } from './MessageMarkdown'import { MessagePartQueryLogs } from './MessagePartQueryLogs'import { NotebookProposalRenderer, type NotebookProposalMode } from './NotebookProposalRenderer'+import { NotebookRunRenderer } from './NotebookRunRenderer'import { parseSupportRequestMessage, SupportRequestMessage } from './SupportRequestMessage'function MessagePartText({ textPart }: { textPart: TextUIPart }) {@@ -262,6 +263,32 @@ function MessagePartNotebookProposal({)}+function MessagePartNotebookRun({ toolPart }: { toolPart: ToolUIPart }) {+ const { state, input: submittedInput, output } = toolPart+ const input = state === 'output-error' ? (submittedInput ?? toolPart.rawInput) : submittedInput+ const { addToolApprovalResponse } = useMessageActionsContext()++ if (state === 'input-streaming')+ return <ToolDisplayExecuteSqlLoading label="Preparing notebook..." />++ const { confirmState, onApprove, onDeny } = getManualToolApprovalHandlers({+ state,+ approval: toolPart.approval,+ addToolApprovalResponse,+ })++ return (+ <NotebookRunRenderer+ state={state}+ input={input}+ output={output}+ confirmState={confirmState}+ onApprove={onApprove}+ onDeny={onDeny}+ />+ )+}+const MessagePart = {Text: MessagePartText,Dynamic: MessagePartDynamicTool,@@ -271,6 +298,7 @@ const MessagePart = {QueryLogs: MessagePartQueryLogs,DeployEdgeFunction: MessagePartDeployEdgeFunction,NotebookProposal: MessagePartNotebookProposal,+ NotebookRun: MessagePartNotebookRun,} as constfunction MessagePartContainer({@@ -288,6 +316,7 @@ const isWideMessagePart = (part: NonNullable<VercelMessage['parts']>[number]) =>part.type === 'tool-query_logs' ||part.type === 'tool-create_notebook' ||part.type === 'tool-update_notebook' ||+ part.type === 'tool-run_notebook' ||(part.type === 'dynamic-tool' && part.toolName === 'query_logs') ||// Unlabelled code fences resolve to SQL in MessageMarkdown, too.(part.type === 'text' && /```(?:sql)?(?:\s|$)/i.test(part.text))@@ -342,6 +371,9 @@ export function MessagePartSwitcher({case 'tool-delete_notebook': {return <MessagePart.NotebookProposal toolPart={part} mode="delete" />}+ case 'tool-run_notebook': {+ return <MessagePart.NotebookRun toolPart={part} />+ }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.tsindex e3a1542aebc..82a9d2e8cd9 100644--- a/apps/studio/components/ui/AIAssistantPanel/Message.utils.ts+++ b/apps/studio/components/ui/AIAssistantPanel/Message.utils.ts@@ -145,6 +145,11 @@ export const deleteNotebookInputSchema = z.object({id: z.string(),})+export const runNotebookInputSchema = z.object({+ id: z.string(),+ expected_updated_at: z.string(),+})+export const notebookToolOutputSchema = z.object({ id: z.string(), name: z.string() })export const updateNotebookToolOutputSchema = notebookToolOutputSchema.extend({diff --git a/apps/studio/components/ui/AIAssistantPanel/NotebookRunRenderer.test.tsx b/apps/studio/components/ui/AIAssistantPanel/NotebookRunRenderer.test.tsxnew file mode 100644index 00000000000..b6745c632b7--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/NotebookRunRenderer.test.tsx@@ -0,0 +1,211 @@+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 { NotebookRunRenderer } from './NotebookRunRenderer'+import type { components } from '@/data/api'+import { customRender as render } from '@/tests/lib/custom-render'+import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'++const NOTEBOOK_ID = 'd3aadd77-7c3c-4de7-aa5c-5aa8ac270b44'+const UPDATED_AT = '2026-01-01T00:00:00.000Z'++const mockNotebook = (updatedAt = UPDATED_AT) =>+ addAPIMock({+ method: 'get',+ path: '/platform/projects/:ref/content/item/:id',+ response: () =>+ HttpResponse.json<components['schemas']['GetUserContentByIdResponse']>({+ id: NOTEBOOK_ID,+ type: 'notebook',+ name: 'Signup funnel',+ description: '',+ favorite: false,+ folder_id: null,+ inserted_at: UPDATED_AT,+ updated_at: updatedAt,+ visibility: 'project',+ owner_id: 1,+ project_id: 1,+ content: {+ schema_version: 1,+ cells: [+ {+ _tag: 'database_cell',+ _id: 'cell-1',+ title: 'Recent signups',+ sql: 'select email from auth.users',+ row_limit: 100,+ },+ ],+ },+ }),+ })++const mockNotebookError = () => {+ addAPIMock({+ method: 'get',+ path: '/platform/projects/:ref',+ response: {+ id: 1,+ ref: 'default',+ organization_id: 1,+ name: 'Test Project',+ status: 'ACTIVE_HEALTHY',+ cloud_provider: 'AWS',+ region: 'us-east-1',+ db_host: 'db.default.supabase.co',+ restUrl: 'https://default.supabase.co/rest/v1/',+ inserted_at: UPDATED_AT,+ updated_at: UPDATED_AT,+ subscription_id: 'sub-1',+ is_branch_enabled: false,+ is_physical_backups_enabled: false,+ high_availability: false,+ integration_source: null,+ connectionString: 'postgresql://postgres@localhost:5432/postgres',+ is_hibernating: false,+ },+ })+ addAPIMock({+ method: 'get',+ path: '/platform/projects/:ref/content/item/:id',+ response: () =>+ HttpResponse.json<APIErrorBody>({ message: 'Notebook unavailable' }, { status: 500 }),+ })+}++describe('NotebookRunRenderer', () => {+ it('previews the notebook and requests one Run notebook approval', async () => {+ const user = userEvent.setup()+ const onApprove = vi.fn()+ mockNotebook()++ const { container } = render(+ <NotebookRunRenderer+ state="approval-requested"+ confirmState="approval-requested"+ input={{ id: NOTEBOOK_ID, expected_updated_at: UPDATED_AT }}+ output={undefined}+ onApprove={onApprove}+ onDeny={vi.fn()}+ />+ )++ const loadingStatus = container.querySelector('[aria-live="polite"]')+ expect(loadingStatus).toHaveTextContent('Loading notebook...')+ expect(loadingStatus?.querySelector('svg')).toHaveClass('motion-reduce:animate-none')+ expect(await screen.findByText('Assistant wants to run "Signup funnel"')).toBeInTheDocument()+ expect(container.querySelector('[aria-live="polite"]')).toBe(loadingStatus)+ expect(loadingStatus).toHaveClass('sr-only')+ expect(screen.getByText('1 cell')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'Run notebook' }))+ expect(onApprove).toHaveBeenCalledTimes(1)+ })++ it('keeps raw results visible to the user after execution', async () => {+ mockNotebook()++ render(+ <NotebookRunRenderer+ state="output-available"+ confirmState="success"+ input={{ id: NOTEBOOK_ID, expected_updated_at: UPDATED_AT }}+ output={{+ id: NOTEBOOK_ID,+ name: 'Signup funnel',+ updated_at: UPDATED_AT,+ cells: [+ {+ cell_id: 'cell-1',+ title: 'Recent signups',+ source: 'database',+ status: 'success',+ rows: [{ email: '[email protected]' }],+ },+ ],+ }}+ />+ )++ expect(await screen.findByText('Notebook executed')).toBeInTheDocument()+ expect(screen.getByText('1 row')).toBeInTheDocument()+ expect(screen.getByText(/person@example\.com/)).toBeInTheDocument()+ })++ it('warns before approval when the notebook changed since the Assistant read it', async () => {+ mockNotebook('2026-01-02T00:00:00.000Z')++ render(+ <NotebookRunRenderer+ state="approval-requested"+ confirmState="approval-requested"+ input={{ id: NOTEBOOK_ID, expected_updated_at: UPDATED_AT }}+ output={undefined}+ onApprove={vi.fn()}+ onDeny={vi.fn()}+ />+ )++ expect(+ await screen.findByText('Notebook changed since the Assistant read it')+ ).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Run notebook' })).toBeInTheDocument()+ })++ it('keeps a failed approval request denyable without allowing the run', async () => {+ const user = userEvent.setup()+ const onApprove = vi.fn()+ const onDeny = vi.fn()+ mockNotebookError()++ const { container } = render(+ <NotebookRunRenderer+ state="approval-requested"+ confirmState="approval-requested"+ input={{ id: NOTEBOOK_ID, expected_updated_at: UPDATED_AT }}+ output={undefined}+ onApprove={onApprove}+ onDeny={onDeny}+ />+ )++ expect(await screen.findByText('Failed to load notebook')).toBeInTheDocument()+ expect(container.querySelector('[data-slot="assistant-confirm"]')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Run notebook' })).not.toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: 'Skip' }))+ expect(onDeny).toHaveBeenCalledTimes(1)+ expect(onApprove).not.toHaveBeenCalled()+ })++ it('warns when historical results are shown with a newer notebook', async () => {+ mockNotebook('2026-01-02T00:00:00.000Z')++ render(+ <NotebookRunRenderer+ state="output-available"+ confirmState="success"+ input={{ id: NOTEBOOK_ID, expected_updated_at: UPDATED_AT }}+ output={{+ id: NOTEBOOK_ID,+ name: 'Signup funnel',+ updated_at: UPDATED_AT,+ cells: [+ {+ cell_id: 'cell-1',+ title: 'Recent signups',+ source: 'database',+ status: 'success',+ rows: [{ email: '[email protected]' }],+ },+ ],+ }}+ />+ )++ expect(await screen.findByText('Notebook changed since this run')).toBeInTheDocument()+ expect(screen.getByText(/preview shows the current notebook/i)).toBeInTheDocument()+ })+})diff --git a/apps/studio/components/ui/AIAssistantPanel/NotebookRunRenderer.tsx b/apps/studio/components/ui/AIAssistantPanel/NotebookRunRenderer.tsxnew file mode 100644index 00000000000..cc4d893ff1b--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/NotebookRunRenderer.tsx@@ -0,0 +1,202 @@+import { useParams } from 'common'+import { Loader2 } from 'lucide-react'+import { Button, cn } from 'ui'+import { Admonition } from 'ui-patterns/Admonition'+import { CodeBlock } from 'ui-patterns/CodeBlock'++import { AssistantNotebookPreview } from './AssistantNotebookPreview'+import { toAssistantQueryResult } from './AssistantQueryCell.utils'+import { Confirm } from './Confirm'+import type { ConfirmFooterApprovalState } from './Confirm.utils'+import { runNotebookInputSchema } from './Message.utils'+import { AlertError } from '@/components/ui/AlertError'+import { useNotebookQuery } from '@/data/content/notebooks/notebook-query'+import { toWireNotebook } from '@/data/content/notebooks/notebook-schema'+import { notebookRunOutputSchema } from '@/lib/ai/tools/notebook-run-output'++export type NotebookRunState =+ | 'input-available'+ | 'approval-requested'+ | 'approval-responded'+ | 'output-denied'+ | 'output-available'+ | 'output-error'++export interface NotebookRunRendererProps {+ state: NotebookRunState+ input: unknown+ output: unknown+ confirmState?: ConfirmFooterApprovalState+ onApprove?: () => void+ onDeny?: () => void+}++export const NotebookRunRenderer = ({+ state,+ input,+ output,+ confirmState,+ onApprove,+ onDeny,+}: NotebookRunRendererProps) => {+ const { ref } = useParams()+ const parsedInput = runNotebookInputSchema.safeParse(input)+ const {+ data: notebook,+ isLoading,+ isError,+ error,+ } = useNotebookQuery(+ { projectRef: ref, id: parsedInput.success ? parsedInput.data.id : undefined },+ { enabled: parsedInput.success }+ )++ if (!parsedInput.success) {+ return (+ <Confirm+ className="my-4"+ state={confirmState}+ message="Assistant wants to run a notebook"+ denyOnly+ onCancel={onDeny}+ >+ <div className="flex flex-col gap-2 p-3">+ <Admonition+ type="warning"+ title="Couldn't render this notebook run"+ description="The assistant's input didn't match the expected shape. You can review the raw input below."+ />+ <CodeBlock+ language="json"+ value={JSON.stringify(input, null, 2)}+ hideLineNumbers+ className="text-xs"+ wrapperClassName="max-h-56"+ />+ </div>+ </Confirm>+ )+ }++ const loadingStatus = (+ <div+ aria-live="polite"+ className={cn(+ isLoading+ ? 'my-4 rounded-lg border bg-surface-75 heading-meta h-9 px-3 text-foreground-light flex items-center gap-2'+ : 'sr-only'+ )}+ >+ {isLoading && (+ <>+ <Loader2 className="w-4 h-4 animate-spin motion-reduce:animate-none" />+ Loading notebook...+ </>+ )}+ </div>+ )++ if (isLoading) {+ return <>{loadingStatus}</>+ }++ if (isError || !notebook) {+ const loadError = <AlertError error={error} subject="Failed to load notebook" />++ if (confirmState === 'approval-requested') {+ return (+ <>+ {loadingStatus}+ <Confirm+ className="my-4"+ state={confirmState}+ message="Assistant wants to run a notebook"+ denyOnly+ onCancel={onDeny}+ >+ <div className="p-3">{loadError}</div>+ </Confirm>+ </>+ )+ }++ return (+ <>+ {loadingStatus}+ <div className="my-4 flex flex-col gap-2">+ {loadError}+ {confirmState !== undefined && (+ <Button variant="outline" size="tiny" className="w-fit" disabled onClick={onDeny}>+ Skip+ </Button>+ )}+ </div>+ </>+ )+ }++ const entries = toWireNotebook(notebook.content).cells.map((cell) => ({+ _tag: 'unchanged' as const,+ cell,+ }))+ const parsedOutput = notebookRunOutputSchema.safeParse(output)+ const isHistoricalRun = state === 'output-available' || state === 'output-error'+ const referencedUpdatedAt =+ state === 'output-available' && parsedOutput.success+ ? parsedOutput.data.updated_at+ : parsedInput.data.expected_updated_at+ const hasNotebookChanged = notebook.updated_at !== referencedUpdatedAt+ const results = parsedOutput.success+ ? Object.fromEntries(+ parsedOutput.data.cells.map((cell) => [+ cell.cell_id,+ cell.status === 'error'+ ? { error: { message: cell.error?.message ?? 'Failed to run query' } }+ : (toAssistantQueryResult(cell.rows ?? []) ?? { rows: [] }),+ ])+ )+ : undefined++ return (+ <>+ {loadingStatus}+ <Confirm+ className="my-4"+ state={confirmState}+ message={`Assistant wants to run "${notebook.name}"`}+ cancelLabel="Skip"+ confirmLabel="Run notebook"+ confirmLabelLoading="Running..."+ successMessage="Notebook executed"+ errorMessage="Failed to run notebook"+ deniedMessage="Skipped notebook run"+ onCancel={onDeny}+ onConfirm={onApprove}+ >+ {hasNotebookChanged && (+ <div className="px-2 pt-2">+ <Admonition+ type="warning"+ title={+ isHistoricalRun+ ? 'Notebook changed since this run'+ : 'Notebook changed since the Assistant read it'+ }+ description={+ isHistoricalRun+ ? 'This preview shows the current notebook. Its cells may not match the saved results from this run.'+ : 'Review the current cells below. The run will be rejected until the Assistant reads the latest notebook version.'+ }+ />+ </div>+ )}+ <AssistantNotebookPreview+ entries={entries}+ mode="run"+ title={notebook.name}+ results={state === 'output-available' ? results : undefined}+ />+ </Confirm>+ </>+ )+}