Files
supabase/apps/studio/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils.ts
Saxon Fletcher 1a013ea2c8 feat(studio): render assistant notebook runs (#49362)
<img width="1944" height="1053" alt="image"
src="https://github.com/user-attachments/assets/74c6968b-5ad4-46f7-adcc-a144221877b2"
/>


## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

Assistant notebook-run UI, reusable result previews, and approval flow.

## Stack context

This stack is based on #49352 (`chore/assistant-tool-outcomes`) and
assumes #49350–#49352 merge first.

Review bottom to top:

1. #49361 — assistant notebook run tool
2. #49362 — assistant notebook run UI
3. #49364 — terminal-state polish

## What is the current behavior?

The `run_notebook` tool has no dedicated Assistant renderer, and the
shared notebook preview cannot display saved query results.

## What is the new behavior?

- Adds a run mode to the shared minified notebook preview.
- Adds a dedicated renderer for notebook-run tool parts and wires it
into `Message.Parts.tsx`.
- Loads the current notebook and presents all cells behind one **Run
notebook** approval.
- Renders database and Logs results inside their matching notebook cells
using the existing Explorer table/chart renderer and row-limit metadata.
- Gives cells with results separate bordered surfaces while preserving
the existing create/update layouts.
- Warns when the notebook changed before approval or since a historical
run.
- Preserves raw run results for the user while the model receives
separately sanitized output.
- Handles malformed input and notebook-loading failures without hiding
the approval state.

## How to test manually

This PR now contains both the reusable result preview and the
`tool-run_notebook` Assistant wiring, so it can be tested directly from
this branch. #49364 is not required for the notebook-run UI path.

1. Create and save a notebook with at least six cells. Include:
   - a markdown cell
   - a database query that returns rows
   - a query that returns no rows
   - a query that fails
   - a Logs query
   - a database query with a row limit
2. Ask the AI Assistant: **Read this notebook and analyze it using its
current results.**
3. Confirm the approval card displays the notebook name and current
cells, with one **Run notebook** button and one **Skip** action.
4. Click **Skip** and confirm the card remains visible with **Skipped
notebook run**.
5. Ask again and click **Run notebook**. Confirm the card enters a
running state, then shows **Notebook executed** with each result under
the cell that produced it.
6. Confirm the successful empty query says **Success. No rows returned**
and shows **0 rows**.
7. Confirm the failed query shows its error without hiding the other
cell results.
8. Confirm row counts and database row-limit copy appear below the
corresponding results.
9. Confirm only the first five cells are initially visible, then click
**Show more cells** and verify the remaining cells appear.
10. Refresh or reopen the conversation and confirm the completed
notebook preview and results remain visible.
11. Start another run but leave it awaiting approval. Edit and save the
notebook in another tab, then return and confirm the card warns
**Notebook changed since the Assistant read it**.
12. Complete a run, then edit and save the notebook. Reopen the
conversation and confirm the historical card warns **Notebook changed
since this run**.
13. Ask the Assistant to create or update a notebook and confirm those
proposal previews retain their grouped layout.

## Automated test

`mise exec node@22 -- pnpm --dir apps/studio exec vitest --run
components/ui/AIAssistantPanel/AssistantNotebookPreview.test.tsx
components/ui/AIAssistantPanel/NotebookRunRenderer.test.tsx`

12 tests pass at this stack boundary.
2026-08-25 18:16:34 +10:00

158 lines
4.9 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import dayjs from 'dayjs'
import type { CodeBlockLang } from 'ui-patterns/CodeBlock'
import type {
NotebookCellDiffEntry,
OperationResultCell,
} from '@/data/content/notebooks/notebook-operations'
import type { TimeRange } from '@/data/content/notebooks/notebook-schema'
/** React key for a diff entry. Added/replaced cells have no `_id`, so they key off the operation. */
export function getEntryKey(entry: NotebookCellDiffEntry): string {
switch (entry._tag) {
case 'unchanged':
case 'removed':
case 'moved':
return entry.cell._id
case 'added':
case 'replaced':
return `op-${entry.operationIndex}`
}
}
/** Human label for a collapsed/badge row. */
export function getCellLabel(cell: OperationResultCell): string {
switch (cell._tag) {
case 'markdown_cell':
return 'Markdown cell'
case 'database_cell':
case 'log_cell':
return `Query: ${cell.title ?? 'Untitled query'}`
}
}
/** The cell's underlying source text, regardless of backend. */
export function getCellSourceText(cell: OperationResultCell): string {
switch (cell._tag) {
case 'markdown_cell':
return cell.text
case 'database_cell':
case 'log_cell':
return cell.sql
}
}
/** Language for rendering the cell's source via `CodeBlock`. */
export function getCellCodeBlockLanguage(cell: OperationResultCell): CodeBlockLang {
switch (cell._tag) {
case 'markdown_cell':
return 'markdown'
case 'database_cell':
case 'log_cell':
return 'sql'
}
}
/** Monaco language id for rendering the cell's source via `DiffEditor`. */
export function getCellMonacoLanguage(cell: OperationResultCell): string {
switch (cell._tag) {
case 'markdown_cell':
return 'markdown'
case 'database_cell':
case 'log_cell':
return 'pgsql'
}
}
/** Formats a `TimeRange` as plain text, e.g. "Last 7 days" or an absolute bound pair. */
export function formatTimeRange(range: TimeRange): string {
if (range._tag === 'relative_time_range') {
return `Last ${range.amount} ${range.unit}${range.amount === 1 ? '' : 's'}`
}
const format = (value: string) => dayjs(value).format('MMM D, YYYY h:mm A')
return `${format(range.start)} → ${format(range.end)}`
}
/**
* Plain-text metadata line for a query cell (its source parameters, not its SQL) — `null`
* when the cell has none. A `replace_cell` can change only this and leave `sql` identical,
* so it's compared independently of the source text rather than folded into it.
*/
export function getCellMetadataLine(cell: OperationResultCell): string | null {
switch (cell._tag) {
case 'markdown_cell':
return null
case 'database_cell':
return cell.database_identifier ? `Database: ${cell.database_identifier}` : null
case 'log_cell':
return `Time range: ${formatTimeRange(cell.time_range)}`
}
}
/** 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: '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' | 'run'
): NotebookDiffSummary {
if (mode === 'create' || mode === 'run') {
return { mode, cellCount: entries.length }
}
const counts = { added: 0, removed: 0, replaced: 0, moved: 0 }
for (const entry of entries) {
switch (entry._tag) {
case 'added':
counts.added++
break
case 'removed':
counts.removed++
break
case 'replaced':
counts.replaced++
break
case 'moved':
counts.moved++
break
case 'unchanged':
break
}
}
return { mode: 'update', counts }
}
/** Formats a `NotebookDiffSummary` into the header string. */
export function formatNotebookDiffSummary(summary: NotebookDiffSummary): string {
if (summary.mode === 'create' || summary.mode === 'run') {
const { cellCount } = summary
return `${cellCount} cell${cellCount === 1 ? '' : 's'}`
}
const { added, removed, replaced, moved } = summary.counts
const parts: string[] = []
if (added > 0) parts.push(`+${added}`)
if (removed > 0) parts.push(`−${removed}`)
if (replaced > 0) parts.push(`~${replaced}`)
if (moved > 0) parts.push(`↕${moved}`)
return parts.length > 0 ? parts.join(' ') : 'No changes'
}