Skip to content

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

notebook preview refine (#49288)

Saxon Fletcher81bccd68622c
diff --git a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.tsx b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.tsx
deleted file mode 100644
index 5d79e016bef..00000000000
--- a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-import { NotebookPen } from 'lucide-react'
-import { useState } from 'react'
-import { Button, cn } from 'ui'
-
-import {
- formatNotebookDiffSummary,
- getEntryKey,
- isEntryExpandedByDefault,
- summarizeNotebookDiff,
-} from './NotebookPreview.utils'
-import { NotebookPreviewCell } from './NotebookPreviewCell'
-import type { NotebookCellDiffEntry } from '@/data/content/notebooks/notebook-operations'
-
-export interface NotebookPreviewProps {
- entries: NotebookCellDiffEntry[]
- mode: 'create' | 'update'
- /** The notebook's name, shown in the card header. Falls back to a generic label. */
- title?: string
- className?: string
-}
-
-const VISIBLE_ENTRY_LIMIT = 5
-
-const FALLBACK_TITLE = {
- create: 'New notebook',
- update: 'Notebook changes',
-} as const
-
-/**
- * Read-only preview of a proposed notebook create/update, rendered from a pre-computed diff.
- * Pure presentational component: no data fetching, no approval or notebook-editor state — see
- * `deriveNotebookDiff` for how `entries` is produced.
- */
-export const NotebookPreview = ({ entries, mode, title, className }: NotebookPreviewProps) => {
- const [isShowingAllEntries, setIsShowingAllEntries] = useState(false)
- const [expandedOverrides, setExpandedOverrides] = useState<Record<string, boolean>>({})
-
- const summary = summarizeNotebookDiff(entries, mode)
- const visibleEntries = isShowingAllEntries ? entries : entries.slice(0, VISIBLE_ENTRY_LIMIT)
- const hiddenCount = entries.length - visibleEntries.length
-
- const isExpanded = (entry: NotebookCellDiffEntry) =>
- expandedOverrides[getEntryKey(entry)] ?? isEntryExpandedByDefault(entry)
-
- const hasEntries = entries.length > 0
- const areAllExpanded = visibleEntries.every(isExpanded)
-
- const toggleAll = () =>
- setExpandedOverrides(
- Object.fromEntries(entries.map((entry) => [getEntryKey(entry), !areAllExpanded]))
- )
-
- return (
- <div
- className={cn('overflow-hidden rounded-lg border border-default bg-surface-100', className)}
- >
- <div className="flex items-center gap-2 border-b border-default bg-surface-200 px-3 py-1.5">
- <NotebookPen
- aria-hidden={true}
- size={13}
- strokeWidth={1.5}
- className="shrink-0 text-foreground-lighter"
- />
- <span className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">
- {title ?? FALLBACK_TITLE[mode]}
- </span>
- <span className="heading-meta shrink-0 text-foreground-light">
- {formatNotebookDiffSummary(summary)}
- </span>
- {hasEntries && (
- <Button
- variant="text"
- size="tiny"
- className="-mr-1.5 shrink-0 px-1.5 text-foreground-lighter hover:text-foreground"
- onClick={toggleAll}
- >
- {areAllExpanded ? 'Collapse all' : 'Expand all'}
- </Button>
- )}
- </div>
- <div className="divide-y divide-border">
- {visibleEntries.map((entry) => {
- const key = getEntryKey(entry)
- return (
- <NotebookPreviewCell
- key={key}
- entry={entry}
- isExpanded={isExpanded(entry)}
- onExpandedChange={(open) =>
- setExpandedOverrides((prev) => ({ ...prev, [key]: open }))
- }
- />
- )
- })}
- </div>
- {hiddenCount > 0 && (
- <Button
- variant="text"
- size="tiny"
- className="w-full rounded-none border-0 border-t border-default text-foreground-light"
- onClick={() => setIsShowingAllEntries(true)}
- >
- Show {hiddenCount} more cell{hiddenCount === 1 ? '' : 's'}
- </Button>
- )}
- </div>
- )
-}
diff --git a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.test.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.test.tsx
similarity index 74%
rename from apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.test.tsx
rename to apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.test.tsx
index a1f9e8622f8..b796ea2e5e0 100644
--- a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.test.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.test.tsx
@@ -1,7 +1,8 @@
import { screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { describe, expect, it } from 'vitest'
-import { NotebookPreview } from './NotebookPreview'
+import { AssistantNotebookPreview } from './AssistantNotebookPreview'
import type { NotebookCellDiffEntry } from '@/data/content/notebooks/notebook-operations'
import type { AgentCell, CellWire } from '@/data/content/notebooks/notebook-schema'
import { customRender as render } from '@/tests/lib/custom-render'
@@ -29,18 +30,20 @@ const agentDatabaseCell = (database_identifier?: string): AgentCell => ({
database_identifier,
})
-describe('NotebookPreview', () => {
+describe('AssistantNotebookPreview', () => {
// The whole safety argument for this feature reduces to this: agent-authored markdown text
// is rendered as literal source (via CodeBlock), never interpreted into real DOM nodes. A
// future refactor that swaps in <Markdown> would break this silently.
- it('never renders agent-authored cell content as real img/link/src DOM nodes', () => {
+ it('never renders agent-authored cell content as real img/link/src DOM nodes', async () => {
+ const user = userEvent.setup()
const adversarialText =
'![x](https://evil.example/) [y](https://evil.example/) <img src=x onerror=1>'
const entries: NotebookCellDiffEntry[] = [
{ _tag: 'added', cell: agentMarkdownCell(adversarialText), operationIndex: 0 },
]
- const { container } = render(<NotebookPreview entries={entries} mode="update" />)
+ const { container } = render(<AssistantNotebookPreview entries={entries} mode="update" />)
+ await user.click(screen.getByRole('button', { name: 'Added Markdown cell' }))
expect(container.querySelectorAll('img')).toHaveLength(0)
expect(container.querySelectorAll('[href]')).toHaveLength(0)
@@ -53,9 +56,11 @@ describe('NotebookPreview', () => {
{ _tag: 'unchanged', cell: wireMarkdownCell('b', 'two') },
]
- render(<NotebookPreview entries={entries} mode="create" />)
+ render(<AssistantNotebookPreview entries={entries} mode="create" />)
+ expect(screen.getByRole('toolbar', { name: 'Notebook toolbar' })).toBeInTheDocument()
expect(screen.getByText('2 cells')).toBeInTheDocument()
+ expect(screen.getByText('New notebook')).toBeInTheDocument()
})
it('surfaces a metadata-only change on a replaced cell even when the sql is unchanged', () => {
@@ -68,9 +73,12 @@ describe('NotebookPreview', () => {
},
]
- render(<NotebookPreview entries={entries} mode="update" />)
+ render(<AssistantNotebookPreview entries={entries} mode="update" />)
expect(screen.getByText('Database: primary → Database: replica-3')).toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'Replaced Query: Untitled query' })
+ ).toHaveTextContent('Database: primary → Database: replica-3')
})
it('hides entries past the limit behind a "Show N more" button', async () => {
@@ -79,7 +87,7 @@ describe('NotebookPreview', () => {
cell: wireMarkdownCell(`cell-${index}`, `text-${index}`),
}))
- render(<NotebookPreview entries={entries} mode="create" />)
+ render(<AssistantNotebookPreview entries={entries} mode="create" />)
expect(screen.getByText('Show 2 more cells')).toBeInTheDocument()
})
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.tsx
new file mode 100644
index 00000000000..959378d65e5
--- /dev/null
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.tsx
@@ -0,0 +1,101 @@
+import { NotebookText } from 'lucide-react'
+import { useState } from 'react'
+import { Button, cn } from 'ui'
+
+import {
+ formatNotebookDiffSummary,
+ getEntryKey,
+ summarizeNotebookDiff,
+} from './AssistantNotebookPreview.utils'
+import { AssistantNotebookPreviewCell } from './AssistantNotebookPreviewCell'
+import {
+ ExplorerToolbar,
+ ExplorerToolbarActions,
+ ExplorerToolbarIcon,
+ ExplorerToolbarTitle,
+} from '@/components/interfaces/Explorer/ExplorerToolbar'
+import type { NotebookCellDiffEntry } from '@/data/content/notebooks/notebook-operations'
+
+export interface AssistantNotebookPreviewProps {
+ entries: NotebookCellDiffEntry[]
+ mode: 'create' | 'update'
+ /** The notebook's name, shown in the toolbar. Falls back to a generic label. */
+ title?: string
+ className?: string
+}
+
+const VISIBLE_ENTRY_LIMIT = 5
+
+const FALLBACK_TITLE = {
+ create: 'New notebook',
+ update: 'Notebook changes',
+} 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.
+ */
+export const AssistantNotebookPreview = ({
+ entries,
+ mode,
+ title,
+ className,
+}: AssistantNotebookPreviewProps) => {
+ const [isShowingAllEntries, setIsShowingAllEntries] = useState(false)
+ const [expandedOverrides, setExpandedOverrides] = useState<Record<string, boolean>>({})
+
+ const summary = summarizeNotebookDiff(entries, mode)
+ const visibleEntries = isShowingAllEntries ? entries : entries.slice(0, VISIBLE_ENTRY_LIMIT)
+ const hiddenCount = entries.length - visibleEntries.length
+
+ const isExpanded = (entry: NotebookCellDiffEntry) =>
+ expandedOverrides[getEntryKey(entry)] === true
+
+ return (
+ <div className={cn('flex min-w-0 flex-col', className)}>
+ <ExplorerToolbar aria-label="Notebook toolbar">
+ <ExplorerToolbarIcon>
+ <NotebookText />
+ </ExplorerToolbarIcon>
+ <ExplorerToolbarTitle>{title ?? FALLBACK_TITLE[mode]}</ExplorerToolbarTitle>
+ <ExplorerToolbarActions>
+ <span className="shrink-0 text-sm text-muted-foreground">
+ {formatNotebookDiffSummary(summary)}
+ </span>
+ </ExplorerToolbarActions>
+ </ExplorerToolbar>
+ <div className="p-2">
+ <div className="overflow-hidden rounded-md border bg-surface-100">
+ <div className="divide-y divide-border">
+ {visibleEntries.map((entry) => {
+ const key = getEntryKey(entry)
+ return (
+ <AssistantNotebookPreviewCell
+ key={key}
+ entry={entry}
+ mode={mode}
+ isExpanded={isExpanded(entry)}
+ onExpandedChange={(open) =>
+ setExpandedOverrides((prev) => ({ ...prev, [key]: open }))
+ }
+ />
+ )
+ })}
+ </div>
+ {hiddenCount > 0 && (
+ <Button
+ variant="text"
+ size="tiny"
+ className="w-full rounded-none border-0 border-t border-default text-foreground-light"
+ onClick={() => setIsShowingAllEntries(true)}
+ >
+ Show {hiddenCount} more cell{hiddenCount === 1 ? '' : 's'}
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.test.ts b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils.test.ts
similarity index 83%
rename from apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.test.ts
rename to apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils.test.ts
index f9ca459fa5e..9a7536d73bf 100644
--- a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.test.ts
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils.test.ts
@@ -7,8 +7,9 @@ import {
getCellLabel,
getCellMetadataLine,
getEntryKey,
+ getEntryMetadataLine,
summarizeNotebookDiff,
-} from './NotebookPreview.utils'
+} from './AssistantNotebookPreview.utils'
import type { NotebookCellDiffEntry } from '@/data/content/notebooks/notebook-operations'
import type { AgentCell, CellWire } from '@/data/content/notebooks/notebook-schema'
import { isoDateTimeString } from '@/lib/iso-datetime'
@@ -37,6 +38,13 @@ const wireLogCell = (id: string): CellWire => ({
time_range: { _tag: 'relative_time_range', unit: 'day', amount: 7 },
})
+const agentDatabaseCell = (database_identifier?: string): AgentCell => ({
+ _tag: 'database_cell',
+ sql: 'select 1',
+ row_limit: 100,
+ database_identifier,
+})
+
describe('getEntryKey', () => {
it('keys unchanged, removed, and moved entries off the cell id', () => {
expect(getEntryKey({ _tag: 'unchanged', cell: wireMarkdownCell('cell-1') })).toBe('cell-1')
@@ -128,6 +136,39 @@ describe('getCellMetadataLine', () => {
})
})
+describe('getEntryMetadataLine', () => {
+ it('uses the cell metadata for non-replaced entries', () => {
+ expect(
+ getEntryMetadataLine({
+ _tag: 'unchanged',
+ cell: wireDatabaseCell('cell-1', 'Signups', 'replica-3'),
+ })
+ ).toBe('Database: replica-3')
+ })
+
+ it('returns a before → after pair when a replacement changes only metadata', () => {
+ expect(
+ getEntryMetadataLine({
+ _tag: 'replaced',
+ before: wireDatabaseCell('cell-1', 'Signups', 'primary'),
+ after: agentDatabaseCell('replica-3'),
+ operationIndex: 0,
+ })
+ ).toBe('Database: primary → Database: replica-3')
+ })
+
+ it('returns a single line when replacement metadata is unchanged', () => {
+ expect(
+ getEntryMetadataLine({
+ _tag: 'replaced',
+ before: wireDatabaseCell('cell-1', 'Signups', 'primary'),
+ after: agentDatabaseCell('primary'),
+ operationIndex: 0,
+ })
+ ).toBe('Database: primary')
+ })
+})
+
describe('summarizeNotebookDiff / formatNotebookDiffSummary', () => {
it('formats create mode with pluralized cell count', () => {
const entries: NotebookCellDiffEntry[] = [
diff --git a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.ts b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils.ts
similarity index 89%
rename from apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.ts
rename to apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils.ts
index 11959be18c8..b8aefa9bd82 100644
--- a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.ts
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils.ts
@@ -20,15 +20,6 @@ export function getEntryKey(entry: NotebookCellDiffEntry): string {
}
}
-/**
- * Whether a diff entry starts expanded. Only the entries the user has to actually read to
- * decide — the ones whose content the assistant is proposing — open on their own; unchanged,
- * moved, and removed cells stay as single rows until asked for.
- */
-export function isEntryExpandedByDefault(entry: NotebookCellDiffEntry): boolean {
- return entry._tag === 'added' || entry._tag === 'replaced'
-}
-
/** Human label for a collapsed/badge row. */
export function getCellLabel(cell: OperationResultCell): string {
switch (cell._tag) {
@@ -99,6 +90,18 @@ export function getCellMetadataLine(cell: OperationResultCell): string | null {
}
}
+/** Header metadata for a diff row, including a before → after pair on replacements. */
+export function getEntryMetadataLine(entry: NotebookCellDiffEntry): string | null {
+ if (entry._tag !== 'replaced') {
+ return getCellMetadataLine(entry.cell)
+ }
+
+ const beforeMetadata = getCellMetadataLine(entry.before)
+ const afterMetadata = getCellMetadataLine(entry.after)
+ if (beforeMetadata === afterMetadata) return afterMetadata
+ return `${beforeMetadata ?? 'No metadata'} → ${afterMetadata ?? 'No metadata'}`
+}
+
export type NotebookDiffSummary =
| { mode: 'create'; cellCount: number }
| { mode: 'update'; counts: { added: number; removed: number; replaced: number; moved: number } }
diff --git a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreviewCell.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreviewCell.tsx
similarity index 67%
rename from apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreviewCell.tsx
rename to apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreviewCell.tsx
index 67153618e7b..908bd0be124 100644
--- a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreviewCell.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreviewCell.tsx
@@ -1,4 +1,4 @@
-import { ChevronRight } from 'lucide-react'
+import { ChevronRight, FileText, SquareCode } from 'lucide-react'
import {
cn,
Collapsible,
@@ -13,18 +13,20 @@ import { CodeBlock } from 'ui-patterns/CodeBlock'
import {
getCellCodeBlockLanguage,
getCellLabel,
- getCellMetadataLine,
getCellMonacoLanguage,
getCellSourceText,
-} from './NotebookPreview.utils'
+ getEntryMetadataLine,
+} from './AssistantNotebookPreview.utils'
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'
-export interface NotebookPreviewCellProps {
+export interface AssistantNotebookPreviewCellProps {
entry: NotebookCellDiffEntry
isExpanded: boolean
onExpandedChange: (isExpanded: boolean) => void
+ /** Create previews omit per-row change glyphs — every cell is an add. */
+ mode: 'create' | 'update'
}
/**
@@ -47,37 +49,46 @@ function getEntryCell(entry: NotebookCellDiffEntry): CellWire | AgentCell {
}
/** One row of the diff card: a header line that collapses to a single row, plus its content. */
-export const NotebookPreviewCell = ({
+export const AssistantNotebookPreviewCell = ({
entry,
isExpanded,
onExpandedChange,
-}: NotebookPreviewCellProps) => {
+ mode,
+}: AssistantNotebookPreviewCellProps) => {
const marker = CHANGE_MARKERS[entry._tag]
const isRemoved = entry._tag === 'removed'
- const label = getCellLabel(getEntryCell(entry))
+ const cell = getEntryCell(entry)
+ const label = getCellLabel(cell)
+ const metadata = getEntryMetadataLine(entry)
return (
<Collapsible open={isExpanded} onOpenChange={onExpandedChange}>
<CollapsibleTrigger
aria-label={`${marker.changeLabel} ${label}`}
- className="group flex w-full items-center gap-2 px-3 py-1.5 text-left transition-colors hover:bg-surface-200"
+ className="group flex w-full items-center gap-2 bg-muted px-3 py-2 text-left transition-colors hover:bg-accent"
>
- <ChangeGlyph marker={marker} />
+ {mode === 'update' && <ChangeGlyph marker={marker} />}
<ChevronRight
size={12}
className="shrink-0 text-foreground-lighter transition-transform group-data-[state=open]:rotate-90"
/>
+ <CellTypeIcon cell={cell} />
<span
className={cn(
- 'truncate text-sm text-foreground-light',
+ 'min-w-0 flex-1 truncate text-sm text-foreground',
isRemoved && 'text-foreground-lighter line-through'
)}
>
{label}
</span>
+ {metadata && (
+ <span className="min-w-0 max-w-[45%] shrink truncate text-sm text-muted-foreground">
+ {metadata}
+ </span>
+ )}
</CollapsibleTrigger>
<CollapsibleContent>
- <div className="flex flex-col gap-1.5 px-3 pb-2.5">
+ <div className="border-t">
<CellBody entry={entry} />
</div>
</CollapsibleContent>
@@ -108,44 +119,27 @@ const ChangeGlyph = ({ marker }: { marker: ChangeMarker }) => {
)
}
+/** Same icons the notebook tab uses for query vs markdown cells. */
+const CellTypeIcon = ({ cell }: { cell: CellWire | AgentCell }) => {
+ const Icon = cell._tag === 'markdown_cell' ? FileText : SquareCode
+ return <Icon aria-hidden size={14} className="shrink-0 text-foreground-muted" />
+}
+
const CellBody = ({ entry }: { entry: NotebookCellDiffEntry }) =>
entry._tag === 'replaced' ? (
<ReplacedCellBody before={entry.before} after={entry.after} />
) : (
- <>
- <CellSource cell={entry.cell} />
- <MetadataLine text={getCellMetadataLine(entry.cell)} />
- </>
+ <CellSource cell={entry.cell} />
)
-/**
- * A `replace_cell` can change only the source parameters (`database_identifier`,
- * `time_range`) and leave `sql`/`text` identical — the `DiffEditor` above would then show no
- * change at all, so the metadata is compared independently and rendered as its own
- * before → after line whenever it differs.
- */
-const ReplacedCellBody = ({ before, after }: { before: CellWire; after: AgentCell }) => {
- const beforeMetadata = getCellMetadataLine(before)
- const afterMetadata = getCellMetadataLine(after)
-
- return (
- <>
- <DiffEditor
- original={getCellSourceText(before)}
- modified={getCellSourceText(after)}
- language={getCellMonacoLanguage(after)}
- height={240}
- />
- {beforeMetadata !== afterMetadata ? (
- <MetadataLine
- text={`${beforeMetadata ?? 'No metadata'} → ${afterMetadata ?? 'No metadata'}`}
- />
- ) : (
- <MetadataLine text={afterMetadata} />
- )}
- </>
- )
-}
+const ReplacedCellBody = ({ before, after }: { before: CellWire; after: AgentCell }) => (
+ <DiffEditor
+ original={getCellSourceText(before)}
+ modified={getCellSourceText(after)}
+ language={getCellMonacoLanguage(after)}
+ height={240}
+ />
+)
/**
* The cell's source, always rendered as literal text via `CodeBlock` — agent-authored markdown
@@ -154,14 +148,11 @@ const ReplacedCellBody = ({ before, after }: { before: CellWire; after: AgentCel
const CellSource = ({ cell }: { cell: CellWire | AgentCell }) => (
<CodeBlock
hideCopy
+ hideLineNumbers
language={getCellCodeBlockLanguage(cell)}
value={getCellSourceText(cell)}
- hideLineNumbers
wrapLongLines
- className="wrap-break-word rounded-none border-0 p-0 text-xs"
+ className="wrap-break-word rounded-none border-0 px-3! py-2! text-xs"
+ wrapperClassName="max-w-none"
/>
)
-
-/** A plain-text metadata line for a query cell — never rendered as a link or attribute. */
-const MetadataLine = ({ text }: { text: string | null }) =>
- text ? <p className="text-xs text-foreground-lighter">{text}</p> : null
diff --git a/apps/studio/components/ui/AIAssistantPanel/Confirm.tsx b/apps/studio/components/ui/AIAssistantPanel/Confirm.tsx
index 8282bdce2ae..a3a7d26c975 100644
--- a/apps/studio/components/ui/AIAssistantPanel/Confirm.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/Confirm.tsx
@@ -10,6 +10,8 @@ interface ConfirmFooterProps {
confirmLabelLoading?: string
isLoading?: boolean
isDisabled?: boolean
+ /** Omit the confirm button so only Skip remains (unparseable / unapplyable previews). */
+ denyOnly?: boolean
/** Escape hatch for consumers that attach the bar directly under their own frame. */
className?: string
onCancel?: () => void | Promise<void>
@@ -24,6 +26,7 @@ export const ConfirmFooter = ({
confirmLabelLoading = 'Working...',
isLoading = false,
isDisabled = false,
+ denyOnly = false,
className,
onCancel,
onConfirm,
@@ -33,20 +36,21 @@ export const ConfirmFooter = ({
return (
<div
className={cn(
- 'flex items-center justify-between py-2 pr-2 pl-4 text-xs text-foreground gap-3 shrink-0',
- 'relative overflow-hidden border-t bg-border shadow-inset',
- 'bg-linear-to-r from-background-surface-75 to-background-surface-200',
+ 'mx-3 flex shrink-0 items-center justify-between gap-3 rounded-b-md py-2 pr-2 pl-3',
+ 'border-x border-b bg-surface-200 text-xs text-foreground-light',
className
)}
>
- <div className="flex-1 relative z-10">{message}</div>
- <div className="flex items-center gap-2 relative z-10">
+ <div className="min-w-0 flex-1">{message}</div>
+ <div className="flex shrink-0 items-center gap-2">
<Button size="tiny" variant="outline" onClick={onCancel} disabled={isInactive}>
{cancelLabel}
</Button>
- <Button size="tiny" variant="primary" onClick={onConfirm} disabled={isInactive}>
- {isLoading ? confirmLabelLoading : confirmLabel}
- </Button>
+ {!denyOnly && (
+ <Button size="tiny" variant="primary" onClick={onConfirm} disabled={isInactive}>
+ {isLoading ? confirmLabelLoading : confirmLabel}
+ </Button>
+ )}
</div>
</div>
)
@@ -66,18 +70,21 @@ interface ConfirmProps {
isLoading?: boolean
/**
* Children fill the remaining height of the card (e.g. `QueryEditor` in viewport
- * mode). Omit for content-sized bodies like notebook previews.
+ * mode). Omit for content-sized bodies like notebook previews and Edge Function blocks.
*/
fill?: boolean
className?: string
+ /** Omit the confirm button so only Skip remains. */
+ denyOnly?: boolean
onCancel?: () => void | Promise<void>
onConfirm?: () => void | Promise<void>
}
/**
* Card that wraps an assistant tool preview and optionally attaches a confirm footer
- * below it. The card owns the frame; nested surfaces (QueryEditor viewport, unframed
- * edge-function blocks) fill the body.
+ * below it. The card owns the frame; the footer hangs inset from the sides so it reads
+ * as tucked under the card. Nested surfaces (QueryEditor viewport, unframed notebook
+ * previews, Edge Function blocks) fill the body.
*/
export const Confirm = ({
children,
@@ -90,6 +97,7 @@ export const Confirm = ({
isLoading = false,
fill = false,
className,
+ denyOnly = false,
onCancel,
onConfirm,
}: PropsWithChildren<ConfirmProps>) => {
@@ -100,13 +108,14 @@ export const Confirm = ({
return (
<div
data-slot="assistant-confirm"
- className={cn(
- 'flex flex-col overflow-hidden rounded-md border shadow-xs bg-muted',
- fill && 'min-h-64',
- className
- )}
+ className={cn('flex flex-col', fill && 'min-h-64', className)}
>
- <div className={cn('min-w-0', fill && 'flex min-h-0 flex-1 flex-col overflow-hidden')}>
+ <div
+ className={cn(
+ 'min-w-0 overflow-hidden rounded-md border shadow-xs bg-muted',
+ fill && 'flex min-h-0 flex-1 flex-col overflow-hidden'
+ )}
+ >
{children}
</div>
{bar.show && (
@@ -117,6 +126,7 @@ export const Confirm = ({
confirmLabelLoading={confirmLabelLoading}
isLoading={showLoading}
isDisabled={!isApprovalRequested}
+ denyOnly={denyOnly}
onCancel={onCancel}
onConfirm={onConfirm}
/>
diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx
index 62cd84b4ba2..e6ea99e7623 100644
--- a/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx
@@ -249,7 +249,11 @@ function MessagePartNotebookProposal({
return <p className="text-xs text-danger px-4">{NOTEBOOK_FAILED_LABEL[mode]}</p>
}
- const approvalId = state === 'approval-requested' ? toolPart.approval?.id : undefined
+ const { confirmState, onApprove, onDeny } = getManualToolApprovalHandlers({
+ state,
+ approval: toolPart.approval,
+ addToolApprovalResponse,
+ })
return (
<NotebookProposalRenderer
@@ -257,14 +261,9 @@ function MessagePartNotebookProposal({
state={state}
input={input}
output={output}
- onApprove={
- approvalId ? () => addToolApprovalResponse?.({ id: approvalId, approved: true }) : undefined
- }
- onDeny={
- approvalId
- ? () => addToolApprovalResponse?.({ id: approvalId, approved: false })
- : undefined
- }
+ confirmState={confirmState}
+ onApprove={onApprove}
+ onDeny={onDeny}
/>
)
}
diff --git a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx
index 61f5de48c25..5d591f90644 100644
--- a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx
@@ -51,6 +51,7 @@ describe('NotebookProposalRenderer', () => {
<NotebookProposalRenderer
mode="create"
state="approval-requested"
+ confirmState="approval-requested"
input={{
name: 'New notebook',
content: {
@@ -64,7 +65,9 @@ describe('NotebookProposalRenderer', () => {
/>
)
+ expect(screen.getByRole('toolbar', { name: 'Notebook toolbar' })).toBeInTheDocument()
expect(screen.getByText('1 cell')).toBeInTheDocument()
+ expect(screen.getByText('Assistant wants to create this notebook')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Create' }))
expect(onApprove).toHaveBeenCalledTimes(1)
})
@@ -78,6 +81,7 @@ describe('NotebookProposalRenderer', () => {
<NotebookProposalRenderer
mode="update"
state="approval-requested"
+ confirmState="approval-requested"
input={{
id: NOTEBOOK_ID,
expected_updated_at: '2024-01-01T00:00:00.000Z',
@@ -102,6 +106,7 @@ describe('NotebookProposalRenderer', () => {
<NotebookProposalRenderer
mode="update"
state="approval-requested"
+ confirmState="approval-requested"
input={{
id: NOTEBOOK_ID,
expected_updated_at: '2024-01-01T00:00:00.000Z',
@@ -122,22 +127,55 @@ describe('NotebookProposalRenderer', () => {
it('falls back to a raw-input admonition without dropping the confirm footer on a parse failure', async () => {
const user = userEvent.setup()
+ const onApprove = vi.fn()
const onDeny = vi.fn()
render(
<NotebookProposalRenderer
mode="create"
state="approval-requested"
+ confirmState="approval-requested"
input={{ nonsense: true }}
output={undefined}
- onApprove={vi.fn()}
+ onApprove={onApprove}
onDeny={onDeny}
/>
)
expect(screen.getByText("Couldn't render a preview for this notebook")).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Create' })).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Skip' }))
+ expect(onDeny).toHaveBeenCalledTimes(1)
+ expect(onApprove).not.toHaveBeenCalled()
+ })
+
+ it('withholds Apply changes when the update cannot be applied as written', async () => {
+ const user = userEvent.setup()
+ const onApprove = vi.fn()
+ const onDeny = vi.fn()
+ mockContentItem(mockNotebookRow())
+
+ render(
+ <NotebookProposalRenderer
+ mode="update"
+ state="approval-requested"
+ confirmState="approval-requested"
+ input={{
+ id: NOTEBOOK_ID,
+ expected_updated_at: '2024-01-01T00:00:00.000Z',
+ operations: [{ _tag: 'delete_cell', cell_id: 'missing' }],
+ }}
+ output={undefined}
+ onApprove={onApprove}
+ onDeny={onDeny}
+ />
+ )
+
+ expect(await screen.findByText("This update can't be applied as written")).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Apply changes' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Skip' }))
expect(onDeny).toHaveBeenCalledTimes(1)
+ expect(onApprove).not.toHaveBeenCalled()
})
it('renders an Open notebook link once output is available', () => {
@@ -154,11 +192,25 @@ describe('NotebookProposalRenderer', () => {
expect(link).toHaveAttribute('href', `/project/default/explorer/notebook/${NOTEBOOK_ID}`)
})
- it('renders a muted skipped summary when output-denied', () => {
+ it('keeps the preview in the message after skip', () => {
render(
- <NotebookProposalRenderer mode="update" state="output-denied" input={{}} output={undefined} />
+ <NotebookProposalRenderer
+ mode="create"
+ state="output-denied"
+ input={{
+ name: 'New notebook',
+ content: {
+ schema_version: 1,
+ cells: [{ _tag: 'markdown_cell', text: 'hello' }],
+ },
+ }}
+ output={undefined}
+ />
)
- expect(screen.getByText('Skipped notebook update')).toBeInTheDocument()
+ expect(screen.getByRole('toolbar', { name: 'Notebook toolbar' })).toBeInTheDocument()
+ expect(screen.getByText('New notebook')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Create' })).not.toBeInTheDocument()
+ expect(screen.queryByText('Skipped notebook creation')).not.toBeInTheDocument()
})
})
diff --git a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx
index 9a9ea604551..0f2c665de51 100644
--- a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx
@@ -1,17 +1,19 @@
import { useParams } from 'common'
import { Loader2 } from 'lucide-react'
import Link from 'next/link'
-import { Button, cn } from 'ui'
+import { type PropsWithChildren } from 'react'
+import { Button } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { CodeBlock } from 'ui-patterns/CodeBlock'
-import { ConfirmFooter } from './Confirm'
+import { AssistantNotebookPreview } from './AssistantNotebookPreview'
+import { Confirm } from './Confirm'
+import { type ConfirmFooterApprovalState } from './Confirm.utils'
import {
createNotebookInputSchema,
notebookToolOutputSchema,
updateNotebookInputSchema,
} from './Message.utils'
-import { NotebookPreview } from '@/components/interfaces/Explorer/NotebookPreview/NotebookPreview'
import { AlertError } from '@/components/ui/AlertError'
import {
deriveNotebookDiff,
@@ -24,7 +26,7 @@ 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.
+// rendered — see MessagePartNotebookProposal in Message.Parts.tsx.
export type NotebookProposalState =
| 'input-available'
| 'approval-requested'
@@ -37,25 +39,25 @@ export interface NotebookProposalRendererProps {
state: NotebookProposalState
input: unknown
output: unknown
+ /** Result of `getManualToolApprovalConfirmState`. Drives the Confirm footer. */
+ confirmState?: ConfirmFooterApprovalState
onApprove?: () => void
onDeny?: () => void
}
-type NotebookProposalStepProps = Omit<NotebookProposalRendererProps, 'mode' | 'output'>
+type NotebookProposalStepProps = Omit<NotebookProposalRendererProps, 'mode' | 'output' | 'state'>
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
@@ -63,26 +65,31 @@ const MODE_COPY = {
/**
* 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.
+ * fetch, and the `expected_updated_at` version check. Wraps the preview in `Confirm` the
+ * same way `AssistantQueryCell` wraps `QueryEditor`.
*/
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
+ const { input, confirmState, onApprove, onDeny } = props
return mode === 'create' ? (
- <CreateNotebookProposal state={state} input={input} onApprove={onApprove} onDeny={onDeny} />
+ <CreateNotebookProposal
+ input={input}
+ confirmState={confirmState}
+ onApprove={onApprove}
+ onDeny={onDeny}
+ />
) : (
- <UpdateNotebookProposal state={state} input={input} onApprove={onApprove} onDeny={onDeny} />
+ <UpdateNotebookProposal
+ input={input}
+ confirmState={confirmState}
+ onApprove={onApprove}
+ onDeny={onDeny}
+ />
)
}
@@ -107,95 +114,91 @@ function NotebookOutputSummary({ mode, output }: { mode: NotebookProposalMode; o
)
}
-interface NotebookConfirmFooterProps {
+interface NotebookConfirmProps {
mode: NotebookProposalMode
- state: NotebookProposalState
+ confirmState?: ConfirmFooterApprovalState
message?: string
confirmLabel?: string
confirmLabelLoading?: string
extraLoading?: boolean
+ denyOnly?: boolean
onApprove?: () => void
onDeny?: () => void
}
-/**
- * `ConfirmFooter` now ships bare so the `Confirm` card can own the frame, so this renderer
- * supplies its own flush-under-block border. The block above still has to square off its
- * bottom corners and the two must not be gapped apart.
- */
-const GLUED_TO_FOOTER = 'rounded-b-none'
-const FLUSH_UNDER_BLOCK = 'border border-t-0 rounded-b-lg'
-
-function hasConfirmFooter(state: NotebookProposalState) {
- return state === 'approval-requested' || state === 'approval-responded'
-}
-
-/** The footer morphs (label + disabled) across approval-requested/approval-responded and is absent otherwise. */
-function NotebookConfirmFooter({
+/** Confirm card around a notebook preview, matching AssistantQueryCell / EdgeFunctionRenderer. */
+function NotebookConfirm({
mode,
- state,
+ confirmState,
message,
confirmLabel,
confirmLabelLoading,
- extraLoading = false,
+ extraLoading,
+ denyOnly,
onApprove,
onDeny,
-}: NotebookConfirmFooterProps) {
- if (!hasConfirmFooter(state)) return null
-
+ children,
+}: PropsWithChildren<NotebookConfirmProps>) {
const copy = MODE_COPY[mode]
- const isApprovalRequested = state === 'approval-requested'
return (
- <ConfirmFooter
- className={FLUSH_UNDER_BLOCK}
+ <Confirm
+ className="my-4"
+ state={confirmState}
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}
- />
+ extraLoading={extraLoading}
+ denyOnly={denyOnly}
+ onCancel={onDeny}
+ onConfirm={denyOnly ? undefined : onApprove}
+ >
+ {children}
+ </Confirm>
)
}
function NotebookParseFailure({
mode,
- state,
+ confirmState,
input,
- onApprove,
onDeny,
-}: Pick<NotebookProposalRendererProps, 'mode' | 'state' | 'input' | 'onApprove' | 'onDeny'>) {
+}: Pick<NotebookProposalRendererProps, 'mode' | 'confirmState' | 'input' | 'onDeny'>) {
return (
- <div className="w-auto overflow-x-hidden my-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>
+ <NotebookConfirm mode={mode} confirmState={confirmState} denyOnly onDeny={onDeny}>
+ <div className="flex flex-col gap-2 p-3">
+ <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"
+ />
+ </div>
+ </NotebookConfirm>
)
}
-function CreateNotebookProposal({ state, input, onApprove, onDeny }: NotebookProposalStepProps) {
+function CreateNotebookProposal({
+ input,
+ confirmState,
+ onApprove,
+ onDeny,
+}: NotebookProposalStepProps) {
const parsedInput = createNotebookInputSchema.safeParse(input)
if (!parsedInput.success) {
return (
<NotebookParseFailure
mode="create"
- state={state}
+ confirmState={confirmState}
input={input}
- onApprove={onApprove}
onDeny={onDeny}
/>
)
@@ -210,19 +213,23 @@ function CreateNotebookProposal({ state, input, onApprove, onDeny }: NotebookPro
)
return (
- <div className="w-auto overflow-x-hidden my-4 flex flex-col">
- <NotebookPreview
- entries={entries}
- mode="create"
- title={parsedInput.data.name}
- className={cn(hasConfirmFooter(state) && GLUED_TO_FOOTER)}
- />
- <NotebookConfirmFooter mode="create" state={state} onApprove={onApprove} onDeny={onDeny} />
- </div>
+ <NotebookConfirm
+ mode="create"
+ confirmState={confirmState}
+ onApprove={onApprove}
+ onDeny={onDeny}
+ >
+ <AssistantNotebookPreview entries={entries} mode="create" title={parsedInput.data.name} />
+ </NotebookConfirm>
)
}
-function UpdateNotebookProposal({ state, input, onApprove, onDeny }: NotebookProposalStepProps) {
+function UpdateNotebookProposal({
+ input,
+ confirmState,
+ onApprove,
+ onDeny,
+}: NotebookProposalStepProps) {
const { ref } = useParams()
const parsedInput = updateNotebookInputSchema.safeParse(input)
@@ -242,9 +249,8 @@ function UpdateNotebookProposal({ state, input, onApprove, onDeny }: NotebookPro
return (
<NotebookParseFailure
mode="update"
- state={state}
+ confirmState={confirmState}
input={input}
- onApprove={onApprove}
onDeny={onDeny}
/>
)
@@ -263,12 +269,12 @@ function UpdateNotebookProposal({ state, input, onApprove, onDeny }: NotebookPro
return (
<div className="w-auto overflow-x-hidden my-4 flex flex-col gap-2">
<AlertError error={error} subject="Failed to load notebook" />
- {(state === 'approval-requested' || state === 'approval-responded') && (
+ {confirmState !== undefined && (
<Button
variant="outline"
size="tiny"
className="w-fit"
- disabled={state === 'approval-responded'}
+ disabled={confirmState !== 'approval-requested'}
onClick={onDeny}
>
Skip
@@ -282,52 +288,57 @@ function UpdateNotebookProposal({ state, input, onApprove, onDeny }: NotebookPro
if (isStale) {
return (
- <div className="w-auto overflow-x-hidden my-4 flex flex-col">
- <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.`}
- className={cn(hasConfirmFooter(state) && GLUED_TO_FOOTER)}
- />
- <NotebookConfirmFooter
- mode="update"
- state={state}
- confirmLabel="Refresh"
- confirmLabelLoading="Refreshing..."
- extraLoading={isFetching}
- onDeny={onDeny}
- onApprove={() => refetch()}
- />
- </div>
+ <NotebookConfirm
+ mode="update"
+ confirmState={confirmState}
+ confirmLabel="Refresh"
+ confirmLabelLoading="Refreshing..."
+ extraLoading={isFetching}
+ onDeny={onDeny}
+ onApprove={() => refetch()}
+ >
+ <div className="p-3">
+ <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.`}
+ />
+ </div>
+ </NotebookConfirm>
)
}
const diff = deriveNotebookDiff(toWireNotebook(notebook.content), parsedInput.data.operations)
- return (
- <div className="w-auto overflow-x-hidden my-4 flex flex-col">
- {diff.success ? (
- <NotebookPreview
- entries={diff.entries}
- mode="update"
- title={notebook.name}
- className={cn(hasConfirmFooter(state) && GLUED_TO_FOOTER)}
- />
- ) : (
- <Admonition
- type="warning"
- title="This update can't be applied as written"
- description={describeNotebookOperationError(diff.error)}
- className={cn(hasConfirmFooter(state) && GLUED_TO_FOOTER)}
- />
- )}
- <NotebookConfirmFooter
+ if (!diff.success) {
+ return (
+ <NotebookConfirm
mode="update"
- state={state}
+ confirmState={confirmState}
message={`Assistant wants to update "${notebook.name}"`}
- onApprove={onApprove}
+ denyOnly
onDeny={onDeny}
- />
- </div>
+ >
+ <div className="p-3">
+ <Admonition
+ type="warning"
+ title="This update can't be applied as written"
+ description={describeNotebookOperationError(diff.error)}
+ />
+ </div>
+ </NotebookConfirm>
+ )
+ }
+
+ return (
+ <NotebookConfirm
+ mode="update"
+ confirmState={confirmState}
+ message={`Assistant wants to update "${notebook.name}"`}
+ onApprove={onApprove}
+ onDeny={onDeny}
+ >
+ <AssistantNotebookPreview entries={diff.entries} mode="update" title={notebook.name} />
+ </NotebookConfirm>
)
}