Skip to content

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

feat(studio): tighten the notebook diff preview (#49218)

Charis4343e21da031
diff --git a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.tsx b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.tsx
index 62b8754e1e1..5d79e016bef 100644
--- a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.tsx
+++ b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.tsx
@@ -1,9 +1,11 @@
+import { NotebookPen } from 'lucide-react'
import { useState } from 'react'
-import { Button } from 'ui'
+import { Button, cn } from 'ui'
import {
formatNotebookDiffSummary,
getEntryKey,
+ isEntryExpandedByDefault,
summarizeNotebookDiff,
} from './NotebookPreview.utils'
import { NotebookPreviewCell } from './NotebookPreviewCell'
@@ -12,34 +14,92 @@ import type { NotebookCellDiffEntry } from '@/data/content/notebooks/notebook-op
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 }: NotebookPreviewProps) => {
- const [isExpanded, setIsExpanded] = useState(false)
+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 = isExpanded ? entries : entries.slice(0, VISIBLE_ENTRY_LIMIT)
+ 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="flex flex-col gap-2">
- <p className="text-xs text-foreground-light font-mono">
- {formatNotebookDiffSummary(summary)}
- </p>
- <div className="flex flex-col gap-1.5">
- {visibleEntries.map((entry) => (
- <NotebookPreviewCell key={getEntryKey(entry)} entry={entry} />
- ))}
+ <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" className="w-full" onClick={() => setIsExpanded(true)}>
+ <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>
)}
diff --git a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.ts b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.ts
index 4dd3087ffc8..3d40260a6e8 100644
--- a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.ts
+++ b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreview.utils.ts
@@ -17,6 +17,15 @@ 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: CellWire | AgentCell): string {
switch (cell._tag) {
diff --git a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreviewCell.tsx b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreviewCell.tsx
index ddac9ae9e1c..67153618e7b 100644
--- a/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreviewCell.tsx
+++ b/apps/studio/components/interfaces/Explorer/NotebookPreview/NotebookPreviewCell.tsx
@@ -1,6 +1,14 @@
-import { useState, type ReactNode } from 'react'
-import { Badge, Button, cn } from 'ui'
-import { CodeBlock, type CodeBlockLang } from 'ui-patterns/CodeBlock'
+import { ChevronRight } from 'lucide-react'
+import {
+ cn,
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from 'ui'
+import { CodeBlock } from 'ui-patterns/CodeBlock'
import {
getCellCodeBlockLanguage,
@@ -15,77 +23,100 @@ import type { AgentCell, CellWire } from '@/data/content/notebooks/notebook-sche
export interface NotebookPreviewCellProps {
entry: NotebookCellDiffEntry
+ isExpanded: boolean
+ onExpandedChange: (isExpanded: boolean) => void
}
-/** Renders a single diff entry, dispatching on its tag. */
-export const NotebookPreviewCell = ({ entry }: NotebookPreviewCellProps) => {
- switch (entry._tag) {
- case 'unchanged':
- return <CollapsedRow label={getCellLabel(entry.cell)} />
- case 'removed':
- return (
- <CollapsedRow
- label={getCellLabel(entry.cell)}
- strikethrough
- badge={{ variant: 'destructive', label: 'Removed' }}
- />
- )
- case 'moved':
- return (
- <CollapsedRow
- label={getCellLabel(entry.cell)}
- badge={{ variant: 'secondary', label: 'Moved' }}
- />
- )
- case 'added':
- return <AddedCell cell={entry.cell} />
- case 'replaced':
- return <ReplacedCell before={entry.before} after={entry.after} />
- }
-}
+/**
+ * A single-character gutter marker per change type The glyph is decorative —
+ * `changeLabel` carries the same information into the row's accessible name and its tooltip.
+ */
+const CHANGE_MARKERS = {
+ added: { glyph: '+', changeLabel: 'Added', className: 'text-brand-600' },
+ removed: { glyph: '−', changeLabel: 'Removed', className: 'text-destructive' },
+ replaced: { glyph: '~', changeLabel: 'Replaced', className: 'text-warning-600' },
+ moved: { glyph: '↕', changeLabel: 'Moved', className: 'text-foreground-lighter' },
+ unchanged: { glyph: '', changeLabel: 'Unchanged', className: '' },
+} as const
+
+type ChangeMarker = (typeof CHANGE_MARKERS)[keyof typeof CHANGE_MARKERS]
-interface CollapsedRowProps {
- label: string
- strikethrough?: boolean
- badge?: { variant: 'destructive' | 'secondary'; label: string }
+/** The cell a row is labelled by — for a replacement, the proposed cell rather than the current one. */
+function getEntryCell(entry: NotebookCellDiffEntry): CellWire | AgentCell {
+ return entry._tag === 'replaced' ? entry.after : entry.cell
}
-/** A single muted row with no content — used for unchanged, removed, and moved entries. */
-const CollapsedRow = ({ label, strikethrough, badge }: CollapsedRowProps) => (
- <div className="flex items-center gap-2 px-3 py-1.5 text-sm text-foreground-light">
- {badge && <Badge variant={badge.variant}>{badge.label}</Badge>}
- <span className={cn('truncate', strikethrough && 'line-through text-foreground-lighter')}>
- {label}
- </span>
- </div>
-)
+/** One row of the diff card: a header line that collapses to a single row, plus its content. */
+export const NotebookPreviewCell = ({
+ entry,
+ isExpanded,
+ onExpandedChange,
+}: NotebookPreviewCellProps) => {
+ const marker = CHANGE_MARKERS[entry._tag]
+ const isRemoved = entry._tag === 'removed'
+ const label = getCellLabel(getEntryCell(entry))
-interface ContentCellProps {
- badge: { variant: 'success' | 'warning'; label: string }
- label: string
- children: ReactNode
+ 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"
+ >
+ <ChangeGlyph marker={marker} />
+ <ChevronRight
+ size={12}
+ className="shrink-0 text-foreground-lighter transition-transform group-data-[state=open]:rotate-90"
+ />
+ <span
+ className={cn(
+ 'truncate text-sm text-foreground-light',
+ isRemoved && 'text-foreground-lighter line-through'
+ )}
+ >
+ {label}
+ </span>
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <div className="flex flex-col gap-1.5 px-3 pb-2.5">
+ <CellBody entry={entry} />
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ )
}
-/** Shared frame for entries that show full cell content — added and replaced cells. */
-const ContentCell = ({ badge, label, children }: ContentCellProps) => (
- <div className="flex flex-col gap-2 px-3 py-2 border rounded-md bg-surface-75">
- <div className="flex items-center gap-2 text-sm">
- <Badge variant={badge.variant}>{badge.label}</Badge>
- <span className="text-foreground truncate">{label}</span>
- </div>
- {children}
- </div>
-)
+/**
+ * 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 a
+ * pointer affordance rather than a second announcement.
+ */
+const ChangeGlyph = ({ marker }: { marker: ChangeMarker }) => {
+ const className = cn('w-3 shrink-0 text-center font-mono text-xs leading-none', marker.className)
-const AddedCell = ({ cell }: { cell: AgentCell }) => (
- <ContentCell badge={{ variant: 'success', label: 'Added' }} label={getCellLabel(cell)}>
- <ExpandableCodeBlock
- language={getCellCodeBlockLanguage(cell)}
- value={getCellSourceText(cell)}
- />
- <MetadataLine text={getCellMetadataLine(cell)} />
- </ContentCell>
-)
+ // An unchanged cell has no glyph, so there is nothing to explain — render the spacer alone.
+ if (!marker.glyph) return <span aria-hidden className={className} />
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span aria-hidden className={className}>
+ {marker.glyph}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="left">{marker.changeLabel}</TooltipContent>
+ </Tooltip>
+ )
+}
+
+const CellBody = ({ entry }: { entry: NotebookCellDiffEntry }) =>
+ entry._tag === 'replaced' ? (
+ <ReplacedCellBody before={entry.before} after={entry.after} />
+ ) : (
+ <>
+ <CellSource cell={entry.cell} />
+ <MetadataLine text={getCellMetadataLine(entry.cell)} />
+ </>
+ )
/**
* A `replace_cell` can change only the source parameters (`database_identifier`,
@@ -93,12 +124,12 @@ const AddedCell = ({ cell }: { cell: AgentCell }) => (
* change at all, so the metadata is compared independently and rendered as its own
* before → after line whenever it differs.
*/
-const ReplacedCell = ({ before, after }: { before: CellWire; after: AgentCell }) => {
+const ReplacedCellBody = ({ before, after }: { before: CellWire; after: AgentCell }) => {
const beforeMetadata = getCellMetadataLine(before)
const afterMetadata = getCellMetadataLine(after)
return (
- <ContentCell badge={{ variant: 'warning', label: 'Replaced' }} label={getCellLabel(after)}>
+ <>
<DiffEditor
original={getCellSourceText(before)}
modified={getCellSourceText(after)}
@@ -112,43 +143,25 @@ const ReplacedCell = ({ before, after }: { before: CellWire; after: AgentCell })
) : (
<MetadataLine text={afterMetadata} />
)}
- </ContentCell>
+ </>
)
}
-/** 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
-
-interface ExpandableCodeBlockProps {
- language: CodeBlockLang
- value: string
-}
-
/**
- * `CodeBlock` clipped to a fixed height with a "Show more/less" toggle. `CodeBlock`'s
- * wrapper already scrolls (`overflow-auto`), so clipping just changes what's visible.
+ * The cell's source, always rendered as literal text via `CodeBlock` — agent-authored markdown
+ * must never be interpreted into real DOM nodes.
*/
-const ExpandableCodeBlock = ({ language, value }: ExpandableCodeBlockProps) => {
- const [isExpanded, setIsExpanded] = useState(false)
+const CellSource = ({ cell }: { cell: CellWire | AgentCell }) => (
+ <CodeBlock
+ hideCopy
+ language={getCellCodeBlockLanguage(cell)}
+ value={getCellSourceText(cell)}
+ hideLineNumbers
+ wrapLongLines
+ className="wrap-break-word rounded-none border-0 p-0 text-xs"
+ />
+)
- return (
- <div>
- <CodeBlock
- language={language}
- value={value}
- hideLineNumbers
- className="text-xs"
- wrapperClassName={cn(!isExpanded && 'max-h-56')}
- />
- <Button
- variant="text"
- size="tiny"
- className="mt-1"
- onClick={() => setIsExpanded((prev) => !prev)}
- >
- {isExpanded ? 'Show less' : 'Show more'}
- </Button>
- </div>
- )
-}
+/** 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/NotebookProposalRenderer.tsx b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx
index b644d8aeafb..18a38634a89 100644
--- a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.tsx
@@ -1,7 +1,7 @@
import { useParams } from 'common'
import { Loader2 } from 'lucide-react'
import Link from 'next/link'
-import { Button } from 'ui'
+import { Button, cn } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { CodeBlock } from 'ui-patterns/CodeBlock'
@@ -118,6 +118,16 @@ interface NotebookConfirmFooterProps {
onDeny?: () => void
}
+/**
+ * `ConfirmFooter` is built to sit flush under the block it confirms (`border-t-0 rounded-b-lg`),
+ * so that block has to square off its own bottom corners and the two must not be gapped apart.
+ */
+const GLUED_TO_FOOTER = 'rounded-b-none'
+
+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({
mode,
@@ -129,7 +139,7 @@ function NotebookConfirmFooter({
onApprove,
onDeny,
}: NotebookConfirmFooterProps) {
- if (state !== 'approval-requested' && state !== 'approval-responded') return null
+ if (!hasConfirmFooter(state)) return null
const copy = MODE_COPY[mode]
const isApprovalRequested = state === 'approval-requested'
@@ -155,7 +165,7 @@ function NotebookParseFailure({
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">
+ <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"
@@ -197,8 +207,13 @@ function CreateNotebookProposal({ state, input, onApprove, onDeny }: NotebookPro
)
return (
- <div className="w-auto overflow-x-hidden my-4 px-4 flex flex-col gap-2">
- <NotebookPreview entries={entries} mode="create" />
+ <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>
)
@@ -243,7 +258,7 @@ function UpdateNotebookProposal({ state, input, onApprove, onDeny }: NotebookPro
if (isError || !notebook) {
return (
- <div className="w-auto overflow-x-hidden my-4 px-4 flex flex-col gap-2">
+ <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') && (
<Button
@@ -264,11 +279,12 @@ function UpdateNotebookProposal({ state, input, onApprove, onDeny }: NotebookPro
if (isStale) {
return (
- <div className="w-auto overflow-x-hidden my-4 px-4 flex flex-col gap-2">
+ <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"
@@ -286,14 +302,20 @@ function UpdateNotebookProposal({ state, input, onApprove, onDeny }: NotebookPro
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">
+ <div className="w-auto overflow-x-hidden my-4 flex flex-col">
{diff.success ? (
- <NotebookPreview entries={diff.entries} mode="update" />
+ <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
diff --git a/packages/ui-patterns/src/CodeBlock/CodeBlock.tsx b/packages/ui-patterns/src/CodeBlock/CodeBlock.tsx
index 0b2848a48aa..fbd3345554e 100644
--- a/packages/ui-patterns/src/CodeBlock/CodeBlock.tsx
+++ b/packages/ui-patterns/src/CodeBlock/CodeBlock.tsx
@@ -80,6 +80,7 @@ export interface CodeBlockProps {
theme?: any
children?: string
wrapLines?: boolean
+ wrapLongLines?: boolean
focusable?: boolean
renderer?: SyntaxHighlighterProps['renderer']
handleCopy?: (value?: string) => void
@@ -100,6 +101,7 @@ export interface CodeBlockProps {
* @param {string} [props.children] - The code content as children.
* @param {boolean} [props.hideCopy=false] - Whether to hide the copy button.
* @param {boolean} [props.hideLineNumbers=false] - Whether to hide line numbers.
+ * @param {boolean} [props.wrapLongLines=false] - Whether long lines soft-wrap instead of scrolling horizontally.
* @param {SyntaxHighlighterProps['renderer']} [props.renderer] - Custom renderer for syntax highlighting.
* @param {boolean} [props.focusable=true] - Whether the code block is focusable. When true, users can focus the code block to select text or use ⌘A (Cmd+A) to select all. This is so we don't need to load Monaco Editor.
* @param {function} [props.handleCopy] - Optional override behaviour for copying value. For e.g if the code block contains obfuscated values, but the copy behaviour should reveal those values instead.
@@ -118,6 +120,7 @@ export const CodeBlock = ({
hideCopy = false,
hideLineNumbers = false,
wrapLines = true,
+ wrapLongLines = false,
renderer,
focusable = true,
onCopyCallback = noop,
@@ -203,6 +206,7 @@ export const CodeBlock = ({
suppressContentEditableWarning
language={lang}
wrapLines={wrapLines}
+ wrapLongLines={wrapLongLines}
style={monokaiTheme}
className={cn(
'code-block border border-surface p-4 w-full my-0! !bg-surface-100 outline-hidden focus:border-foreground-lighter/50',