Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(notebooks): let mcp agents pick a chart for a sql cell (#109259)

Sinan Kucukkoselerd24c80f7db33
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index cb815d85dfa0..f9bfb7ecccfc 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -13074,6 +13074,14 @@ snapshots:
hash: v1.k794b7964.236c0485a9150c930638669fc0e9e894f5957a2ac2745f29b73ed558ffcd1cdc.yeGKlhnvYq8b01QMsu190pnW-nQwU4cGKsf7aH0Ck8k
scenes-app-notebooks-run-all-banner--starting--light:
hash: v1.k794b7964.6c7bd37efe1d58d68070782d7d1d0ce20be5abfebe1f829feb0376b584ad1158.CVBhfDqMZqLLuxmDgkiTAS9Vn2SANiX9cOWDF1Ui8hk
+ scenes-app-notebooks-sql-cell-chart--bar-chart--dark:
+ hash: v1.k794b7964.4b9763fbf9a227bfd8011e77ffdebc555dd84159bc3555e64cbc772a3f577b97.rV9Q2LerkU-4gFGqjyuUtqJfa5Eg7IWIfxq5pTijeAs
+ scenes-app-notebooks-sql-cell-chart--bar-chart--light:
+ hash: v1.k794b7964.75cb272b247dfe1d0d751ac76a9bbf602fc122a7dcdee14d1dc58fc0bf776664.C-l8o8t6DAWzgk0V3gjTaUXq8fh0oLfAKx41SpxmzQ0
+ scenes-app-notebooks-sql-cell-chart--line-chart--dark:
+ hash: v1.k794b7964.acd1ca0ffe9b2ca1b475f2ada98c2d852640f533cd8cee18adfbbb0d1a1271b0.EcUH90S95-XdsPZFEFml6IyvfJtJJotSgQsgmyMg5Pc
+ scenes-app-notebooks-sql-cell-chart--line-chart--light:
+ hash: v1.k794b7964.48a35e5d510ee5bb815299d814acc467016199b559833ecc66418f23cd1b0732.xiZOqKnalZ7mv20MlRJSPfRXI7WxZ9kLLvDxQ4KQBQA
scenes-app-notebooks-widget-generation-cost--less-than-one-cent--dark:
hash: v1.k794b7964.3d7ab4ed80e86dee207323ed0baf83d86a9c0b53c868f64769ddc708b4ab5881.RKwiZJnBL8K4kWfRM3MV6Aruoqr20twxVmepMy_SU6Y
scenes-app-notebooks-widget-generation-cost--less-than-one-cent--light:
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookSQLCellChart.stories.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookSQLCellChart.stories.tsx
new file mode 100644
index 000000000000..8946cee74351
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookSQLCellChart.stories.tsx
@@ -0,0 +1,115 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { notebookTestTemplate } from './__mocks__/notebook-template-for-snapshot'
+import { buildMarkdownNotebookContent } from './markdownNotebookV2'
+
+const RESULT = {
+ columns: ['month', 'orgs'],
+ types: [
+ ['month', 'Date'],
+ ['orgs', 'UInt64'],
+ ],
+ row_count: 6,
+ first_page: [
+ ['2023-01-01', 120],
+ ['2023-02-01', 180],
+ ['2023-03-01', 150],
+ ['2023-04-01', 240],
+ ['2023-05-01', 310],
+ ['2023-06-01', 290],
+ ],
+ has_more: false,
+}
+
+// The tag exactly as the MCP notebooks-add-cell tool writes it for a cell with a visualization.
+const sqlCellTag = (display: string): string =>
+ `<SQLV2 nodeId="0d3f7a52-9c1e-4d7b-a8f0-5b2c6e1d9a44" title="Orgs by month" code="select month, orgs from monthly_orgs" returnVariable="sql_df" outputTab="visualization" vizQuery={${JSON.stringify(
+ {
+ kind: 'DataVisualizationNode',
+ display,
+ chartSettings: { xAxis: { column: 'month' }, yAxis: [{ column: 'orgs' }] },
+ }
+ )}} runId="run-1" result={${JSON.stringify(RESULT)}} />`
+
+const notebooks = {
+ 'sql-cell-bar-chart': {
+ ...notebookTestTemplate('SQL cell bar chart', []),
+ content: buildMarkdownNotebookContent(`# SQL cell bar chart\n\n${sqlCellTag('ActionsBar')}`),
+ },
+ 'sql-cell-line-chart': {
+ ...notebookTestTemplate('SQL cell line chart', []),
+ content: buildMarkdownNotebookContent(`# SQL cell line chart\n\n${sqlCellTag('ActionsLineGraph')}`),
+ },
+}
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/Notebooks/SQL cell chart',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2023-07-04',
+ featureFlags: [FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS],
+ testOptions: {
+ waitForSelector: '[data-attr="notebook-node-sql-v2"] canvas',
+ },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/notebooks/:short_id/sql_v2/runs/:run_id': {
+ status: 'done',
+ result: RESULT,
+ error: null,
+ },
+ '/api/projects/:team_id/notebooks/kernel/compute_options': {
+ currency: 'USD',
+ cpu_rate_per_core_hour: 0.2,
+ memory_rate_per_gb_hour: 0.025,
+ default_preset_key: 'small',
+ presets: [
+ {
+ key: 'small',
+ name: 'Small',
+ description: 'Exploring data and working with small dataframes.',
+ cpu_cores: 1,
+ memory_gb: 2,
+ hourly_price: 0.25,
+ },
+ ],
+ allowed_cpu_cores: [1],
+ allowed_memory_gb: [2],
+ allowed_idle_timeout_seconds: [3600],
+ },
+ '/api/projects/:team_id/notebooks/:short_id': ({ params }) => [
+ 200,
+ { ...notebooks[params.short_id as keyof typeof notebooks], short_id: params.short_id },
+ ],
+ },
+ post: {
+ '/api/projects/:team_id/notebooks/:short_id/collab/markdown_save': async ({ params, request }) => {
+ const body = (await request.json()) as Record<string, unknown> & { version: number }
+ return {
+ ...notebooks[params.short_id as keyof typeof notebooks],
+ short_id: params.short_id,
+ ...body,
+ version: body.version + 1,
+ }
+ },
+ },
+ }),
+ ],
+}
+
+export default meta
+
+type Story = StoryObj<{}>
+
+export const BarChart: Story = { parameters: { pageUrl: urls.notebook('sql-cell-bar-chart') } }
+export const LineChart: Story = { parameters: { pageUrl: urls.notebook('sql-cell-line-chart') } }
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index a8671305e855..26d72da0c77b 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10032,7 +10032,7 @@
}
},
"notebooks-add-cell": {
- "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. Run analysis Python here rather than in a runtime the user can't see — dataframe work, statistics, clustering, forecasting, plotting — so the code and its output stay visible and re-runnable beside the result; the sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code. Cells can read the notebook's variables (see notebooks-get, set with notebooks-set-variables): a SQL cell as a bare `{name}` placeholder, a Python cell as a plain global. A SQL cell reading an undeclared `{name}` fails to run, so declare the variable first. A notebook holds at most 50 cells; past that the call fails, so start a new notebook rather than retrying. A Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one. notebooks-list-frames reports that rate, and notebooks-compute-options lists the presets.",
+ "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. To chart a SQL cell, set visualization: a display type plus optional chartSettings axes. The cell then opens on the chart instead of the table. Inside a notebook, chart a SQL result this way instead of saving a separate SQL insight. The response lists visualization_warnings when an axis names a column the query does not return, when a Y column is not numeric, or when the chart cannot plot every row. The first Python cell can take longer while the notebook's sandbox kernel starts. Run analysis Python here rather than in a runtime the user can't see — dataframe work, statistics, clustering, forecasting, plotting — so the code and its output stay visible and re-runnable beside the result; the sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code. Cells can read the notebook's variables (see notebooks-get, set with notebooks-set-variables): a SQL cell as a bare `{name}` placeholder, a Python cell as a plain global. A SQL cell reading an undeclared `{name}` fails to run, so declare the variable first. A notebook holds at most 50 cells; past that the call fails, so start a new notebook rather than retrying. A Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one. notebooks-list-frames reports that rate, and notebooks-compute-options lists the presets.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Add a cell to a notebook; SQL/Python cells run immediately.",
@@ -10291,7 +10291,7 @@
}
},
"notebooks-update-cell": {
- "description": "Update a cell by node_id. For a SQL or Python cell pass `code` to replace its source and re-run it, or omit code to re-run it unchanged (how you refresh a stale cell). For a markdown cell (cell_type 'markdown' in notebooks-get: prose, a heading, a table, a fenced block) pass `markdown` instead: it replaces that block only, runs nothing, and leaves every other cell untouched. That is how you fix wording in a notebook you already shared, instead of appending a correction or recreating it under a new URL. Read the ids with notebooks-get and edit against that same read, because a markdown cell's id is derived from its text and changes once the text changes. Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code) or fix it first, walking the graph one hop at a time. To refresh the whole notebook in one call instead, use notebooks-run. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.",
+ "description": "Update a cell by node_id. For a SQL or Python cell pass `code` to replace its source and re-run it, or omit code to re-run it unchanged (how you refresh a stale cell). For a SQL cell, pass `visualization` to change its chart. Without code, only the chart changes and the cell does not re-run. Pass null to show the results table again. For a markdown cell (cell_type 'markdown' in notebooks-get: prose, a heading, a table, a fenced block) pass `markdown` instead: it replaces that block only, runs nothing, and leaves every other cell untouched. That is how you fix wording in a notebook you already shared, instead of appending a correction or recreating it under a new URL. Read the ids with notebooks-get and edit against that same read, because a markdown cell's id is derived from its text and changes once the text changes. Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code, no visualization) or fix it first, walking the graph one hop at a time. To refresh the whole notebook in one call instead, use notebooks-run. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Update a cell's code and re-run it.",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index 4957edc1b91d..3bf2b8d68557 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -304,7 +304,7 @@
}
},
"notebooks-add-cell": {
- "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. Run analysis Python here rather than in a runtime the user can't see — dataframe work, statistics, clustering, forecasting, plotting — so the code and its output stay visible and re-runnable beside the result; the sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code. Cells can read the notebook's variables (see notebooks-get, set with notebooks-set-variables): a SQL cell as a bare `{name}` placeholder, a Python cell as a plain global. A SQL cell reading an undeclared `{name}` fails to run, so declare the variable first. A notebook holds at most 50 cells; past that the call fails, so start a new notebook rather than retrying. A Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one. notebooks-list-frames reports that rate, and notebooks-compute-options lists the presets.",
+ "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. To chart a SQL cell, set visualization: a display type plus optional chartSettings axes. The cell then opens on the chart instead of the table. Inside a notebook, chart a SQL result this way instead of saving a separate SQL insight. The response lists visualization_warnings when an axis names a column the query does not return, when a Y column is not numeric, or when the chart cannot plot every row. The first Python cell can take longer while the notebook's sandbox kernel starts. Run analysis Python here rather than in a runtime the user can't see — dataframe work, statistics, clustering, forecasting, plotting — so the code and its output stay visible and re-runnable beside the result; the sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code. Cells can read the notebook's variables (see notebooks-get, set with notebooks-set-variables): a SQL cell as a bare `{name}` placeholder, a Python cell as a plain global. A SQL cell reading an undeclared `{name}` fails to run, so declare the variable first. A notebook holds at most 50 cells; past that the call fails, so start a new notebook rather than retrying. A Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one. notebooks-list-frames reports that rate, and notebooks-compute-options lists the presets.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Add a cell to a notebook; SQL/Python cells run immediately.",
@@ -319,7 +319,7 @@
}
},
"notebooks-update-cell": {
- "description": "Update a cell by node_id. For a SQL or Python cell pass `code` to replace its source and re-run it, or omit code to re-run it unchanged (how you refresh a stale cell). For a markdown cell (cell_type 'markdown' in notebooks-get: prose, a heading, a table, a fenced block) pass `markdown` instead: it replaces that block only, runs nothing, and leaves every other cell untouched. That is how you fix wording in a notebook you already shared, instead of appending a correction or recreating it under a new URL. Read the ids with notebooks-get and edit against that same read, because a markdown cell's id is derived from its text and changes once the text changes. Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code) or fix it first, walking the graph one hop at a time. To refresh the whole notebook in one call instead, use notebooks-run. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.",
+ "description": "Update a cell by node_id. For a SQL or Python cell pass `code` to replace its source and re-run it, or omit code to re-run it unchanged (how you refresh a stale cell). For a SQL cell, pass `visualization` to change its chart. Without code, only the chart changes and the cell does not re-run. Pass null to show the results table again. For a markdown cell (cell_type 'markdown' in notebooks-get: prose, a heading, a table, a fenced block) pass `markdown` instead: it replaces that block only, runs nothing, and leaves every other cell untouched. That is how you fix wording in a notebook you already shared, instead of appending a correction or recreating it under a new URL. Read the ids with notebooks-get and edit against that same read, because a markdown cell's id is derived from its text and changes once the text changes. Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code, no visualization) or fix it first, walking the graph one hop at a time. To refresh the whole notebook in one call instead, use notebooks-run. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Update a cell's code and re-run it.",
diff --git a/services/mcp/src/tools/notebooks/addCell.ts b/services/mcp/src/tools/notebooks/addCell.ts
index f24bc5bc490b..cae36c7ff539 100644
--- a/services/mcp/src/tools/notebooks/addCell.ts
+++ b/services/mcp/src/tools/notebooks/addCell.ts
@@ -24,6 +24,12 @@ import {
upsertProp,
type CellTagBlock,
} from './cellTags'
+import {
+ applyVisualization,
+ CellVisualizationSchema,
+ VISUALIZATION_PARAM_DESCRIPTION,
+ visualizationWarnings,
+} from './cellVisualization'
import { applyMarkdownEdit, fetchMarkdownNotebook, notebookPathFor } from './markdownDoc'
import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'
import { getNotebookWidgetTagNames, getNotebookWidgetViewError } from './widgetCatalog'
@@ -56,7 +62,7 @@ const AddCellInputSchema = z
.record(z.string(), z.unknown())
.optional()
.describe(
- 'Component cells: the props for the tag, matching what the notebook UI stores for that component. Object widgets take their identity prop plus an optional view, for example {"id": 123, "view": "summary"}. For Query: {"query": {"kind": "InsightVizNode", "source": <TrendsQuery|FunnelsQuery|RetentionQuery|PathsQuery|StickinessQuery|LifecycleQuery>}} for insights, or {"query": {"kind": "DataTableNode", "source": {"kind": "EventsQuery", …}}} for event tables. HogQLQuery sources are not accepted here — use cell_type sql, which charts its result too.'
+ 'Component cells: the props for the tag, matching what the notebook UI stores for that component. Object widgets take their identity prop plus an optional view, for example {"id": 123, "view": "summary"}. For Query: {"query": {"kind": "InsightVizNode", "source": <TrendsQuery|FunnelsQuery|RetentionQuery|PathsQuery|StickinessQuery|LifecycleQuery>}} for insights, or {"query": {"kind": "DataTableNode", "source": {"kind": "EventsQuery", …}}} for event tables. HogQLQuery sources are not accepted here: use cell_type sql, and set visualization to chart its result.'
),
dataframe_name: z
.string()
@@ -78,6 +84,7 @@ const AddCellInputSchema = z
.describe(
'Insert after this block: any node_id notebooks-get returns, a markdown block included. Defaults to the end of the document. A markdown block id comes from the text, so pass one from the read you are acting on.'
),
+ visualization: CellVisualizationSchema.optional().describe(VISUALIZATION_PARAM_DESCRIPTION),
})
.strict()
@@ -87,6 +94,7 @@ export interface AddCellResult {
node_id?: string
dataframe_name?: string
run?: ShapedRunResult
+ visualization_warnings?: string[]
}
/**
@@ -305,7 +313,7 @@ async function runAndWriteBack(
outputName: string,
cells: CellTagBlock[],
variables: Schemas.NotebookVariable[] | undefined
-): Promise<ShapedRunResult> {
+): Promise<{ run: ShapedRunResult; warnings: string[] }> {
const projectId = await context.stateManager.getProjectId()
const notebookPath = notebookPathFor(projectId, notebookId)
const refs = collectRunRefs(cells, nodeId)
@@ -318,6 +326,7 @@ async function runAndWriteBack(
variables,
})
const outcome = await awaitRun(context, notebookPath, runId)
+ let warnings: string[] = []
// Mirror the editor's write-back so humans opening the notebook see the result: runId
// always, the envelope once terminal. Anchored on nodeId, so concurrent edits to other
// parts of the document survive the retry inside applyMarkdownEdit.
@@ -329,10 +338,11 @@ async function runAndWriteBack(
let source = upsertProp(block.source, 'runId', runId)
if (outcome.envelope && (outcome.status === 'done' || outcome.status === 'interrupted')) {
source = upsertProp(source, 'result', buildResultProp(outcome.envelope))
+ warnings = visualizationWarnings(source, outcome.envelope)
}
return replaceCellTag(markdown, block, source)
})
- return shapeRunForModel(outcome)
+ return { run: shapeRunForModel(outcome), warnings }
}
/**
@@ -364,6 +374,11 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResu
if (params.cell_type === 'markdown' && !params.markdown?.trim()) {
throw new Error('A markdown cell requires non-empty markdown.')
}
+ if (params.visualization && params.cell_type !== 'sql') {
+ throw new Error(
+ `visualization applies to sql cells only, not ${params.cell_type} cells. A python cell plots with matplotlib.`
+ )
+ }
if (params.cell_type === 'saved_insight' && !params.insight_short_id?.trim()) {
throw new Error('A saved_insight cell requires insight_short_id.')
}
@@ -380,7 +395,7 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResu
}
if (hasHogQLQuerySource(params.props)) {
throw new Error(
- "Use cell_type 'sql' for SQL instead of a component with a HogQLQuery source. A sql cell runs the query, names a dataframe other cells can reference, and charts its result."
+ "Use cell_type 'sql' for SQL instead of a component with a HogQLQuery source. A sql cell runs the query, names a dataframe other cells can reference, and charts its result when you set visualization."
)
}
const widgetViewError = getNotebookWidgetViewError(params.tag_name, params.props?.view)
@@ -445,7 +460,8 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResu
parseCellTags(initial.markdown),
(initial.notebook.variables ?? []).map((variable) => variable.name)
)
- const tag = buildCellTag(tagName, { nodeId, title, code: params.code, returnVariable: dataframeName })
+ const plainTag = buildCellTag(tagName, { nodeId, title, code: params.code, returnVariable: dataframeName })
+ const tag = params.visualization ? applyVisualization(plainTag, params.visualization) : plainTag
// The save response carries the notebook as it stood when the save committed, so it holds a
// variable edit that landed after the read above. The run binds those values to stay in step
@@ -453,7 +469,7 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResu
const { notebook, markdown } = await applyMarkdownEdit(context, params.notebook_id, (current, version) =>
insertBlock(current, tag, params.after_node_id, proseAnchor, version)
)
- const run = await runAndWriteBack(
+ const { run, warnings } = await runAndWriteBack(
context,
params.notebook_id,
nodeId,
@@ -463,7 +479,12 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResu
parseCellTags(markdown),
notebook.variables
)
- return wrapRunResultAsInformational({ node_id: nodeId, dataframe_name: dataframeName, run })
+ return wrapRunResultAsInformational({
+ node_id: nodeId,
+ dataframe_name: dataframeName,
+ run,
+ ...(warnings.length ? { visualization_warnings: warnings } : {}),
+ })
}
const tool = (): ToolBase<typeof NotebooksAddCellSchema, AddCellResult> => ({
diff --git a/services/mcp/src/tools/notebooks/cellTags.ts b/services/mcp/src/tools/notebooks/cellTags.ts
index 6e4f31f1aeb0..e7d4aecaa66b 100644
--- a/services/mcp/src/tools/notebooks/cellTags.ts
+++ b/services/mcp/src/tools/notebooks/cellTags.ts
@@ -81,6 +81,19 @@ function findExpressionProp(tagSource: string, name: string): { start: number; e
return null
}
+export function readExpressionProp(tagSource: string, name: string): unknown {
+ const expression = findExpressionProp(tagSource, name)
+ if (!expression) {
+ return null
+ }
+ const segment = tagSource.slice(expression.start, expression.end)
+ try {
+ return JSON.parse(segment.slice(`${name}={`.length, -1))
+ } catch {
+ return null
+ }
+}
+
export function serializePropValue(value: unknown): string {
if (typeof value === 'string') {
return JSON.stringify(value)
@@ -128,6 +141,52 @@ export function removeProp(tagSource: string, name: string): string {
return tagSource.slice(0, start) + tagSource.slice(expression.end)
}
+/**
+ * The props the editor derives for a SQL cell that holds its SQL in `query` and has no `code`. Keep in
+ * sync with `getSqlV2PropsFromQueryProp` (markdownNotebookV2.ts) and `_code_from_query_prop` (sql_v2_state.py).
+ */
+export function legacySqlProps(tagSource: string): { code: string; vizQuery?: Record<string, unknown> } | null {
+ if (readStringProp(tagSource, 'code')?.trim()) {
+ return null
+ }
+ let query: unknown = readStringProp(tagSource, 'query') ?? readExpressionProp(tagSource, 'query')
+ if (typeof query === 'string') {
+ if (!query.trim().startsWith('{')) {
+ return query.trim() ? { code: query } : null
+ }
+ try {
+ query = JSON.parse(query)
+ } catch {
+ return null
+ }
+ }
+ if (!query || typeof query !== 'object' || Array.isArray(query)) {
+ return null
+ }
+ const node = query as Record<string, unknown>
+ const source = (node.kind === 'HogQLQuery' ? node : node.source) as Record<string, unknown> | null | undefined
+ const code = source?.kind === 'HogQLQuery' && typeof source.query === 'string' ? source.query : ''
+ if (!code.trim()) {
+ return null
+ }
+ return node.kind === 'DataVisualizationNode' ? { code, vizQuery: node } : { code }
+}
+
+/**
+ * While `code` is empty, a chart in `query` overrides `outputTab` and `vizQuery` in the editor. A chart
+ * edit would not show, and new `code` would drop the chart, unless the tag holds the derived props first.
+ */
+export function materializeLegacySqlProps(tagSource: string): string {
+ const legacy = legacySqlProps(tagSource)
+ if (!legacy) {
+ return tagSource
+ }
+ const source = upsertProp(tagSource, 'code', legacy.code)
+ return legacy.vizQuery
+ ? upsertProp(upsertProp(source, 'outputTab', 'visualization'), 'vizQuery', legacy.vizQuery)
+ : source
+}
+
export function buildCellTag(tagName: string, props: Record<string, unknown>): string {
const serialized = Object.entries(props)
.filter(([, value]) => value !== undefined)
@@ -204,7 +263,10 @@ export function parseCellTags(markdown: string): CellTagBlock[] {
source,
nodeId: readStringProp(source, 'nodeId'),
returnVariable: (readStringProp(source, 'returnVariable') ?? '').trim(),
- code: readStringProp(source, 'code') ?? '',
+ code:
+ (tagName === 'SQLV2' ? legacySqlProps(source)?.code : undefined) ??
+ readStringProp(source, 'code') ??
+ '',
})
offset += blockLines.reduce((sum, blockLine) => sum + blockLine.length + 1, 0)
index = cursor + 1
diff --git a/services/mcp/src/tools/notebooks/cellVisualization.ts b/services/mcp/src/tools/notebooks/cellVisualization.ts
new file mode 100644
index 000000000000..73612d6b54a9
--- /dev/null
+++ b/services/mcp/src/tools/notebooks/cellVisualization.ts
@@ -0,0 +1,132 @@
+import { z } from 'zod'
+
+import { ChartDisplayType, ChartSettings, TableSettings } from '@/schema/query'
+
+import { readExpressionProp, removeProp, upsertProp } from './cellTags'
+
+// The SQL chart has no renderer for WorldMap, and TwoDimensionalHeatmap needs heatmap column
+// settings this schema does not carry, so either one opens the cell on an empty chart.
+const SqlCellDisplayType = ChartDisplayType.exclude(['WorldMap', 'TwoDimensionalHeatmap'])
+
+export const CellVisualizationSchema = z
+ .object({
+ display: SqlCellDisplayType.describe(
+ 'Chart type. Use ActionsLineGraph or ActionsAreaGraph for a time series, ActionsBar for categories, ActionsPie for shares of a total, BoldNumber for one headline value, and ActionsTable for a formatted table.'
+ ),
+ chartSettings: ChartSettings.optional().describe(
+ 'Axes and chart options. Omit an axis to let the chart pick it: the first date column for X, and every numeric column for Y. Every column named here must be a column the query returns, and a Y column must be numeric.'
+ ),
+ tableSettings: TableSettings.optional(),
+ })
+ .strict()
+
+export type CellVisualization = z.infer<typeof CellVisualizationSchema>
+
+export const VISUALIZATION_PARAM_DESCRIPTION =
+ 'SQL cells only: show the result as a chart instead of the table, like the Visualization tab in the editor. The chart draws from the rows the run returns, so aggregate in SQL to the points you want plotted.'
+
+interface ResultColumns {
+ columns?: string[] | null
+ types?: unknown[] | null
+ row_count?: number | null
+ first_page?: unknown[] | null
+ has_more?: boolean | null
+ previewOnly?: boolean | null
+}
+
+// `vizQuery.source` is left out because the node always rebuilds it from the cell's current
+// `code`, so a stored copy could only drift from the code.
+export function applyVisualization(tagSource: string, visualization: CellVisualization | null): string {
+ if (visualization === null) {
+ return removeProp(upsertProp(tagSource, 'outputTab', 'results'), 'vizQuery')
+ }
+ const vizQuery = { kind: 'DataVisualizationNode', ...visualization }
+ return upsertProp(upsertProp(tagSource, 'outputTab', 'visualization'), 'vizQuery', vizQuery)
+}
+
+function storedVisualization(tagSource: string): CellVisualization | null {
+ const vizQuery = readExpressionProp(tagSource, 'vizQuery')
+ if (!vizQuery || typeof vizQuery !== 'object') {
+ return null
+ }
+ const parsed = CellVisualizationSchema.safeParse({
+ display: (vizQuery as { display?: unknown }).display,
+ chartSettings: (vizQuery as { chartSettings?: unknown }).chartSettings,
+ tableSettings: (vizQuery as { tableSettings?: unknown }).tableSettings,
+ })
+ return parsed.success ? parsed.data : null
+}
+
+export function storedVisualizationWarnings(tagSource: string): string[] {
+ const result = readExpressionProp(tagSource, 'result')
+ if (!result || typeof result !== 'object' || !Array.isArray((result as ResultColumns).columns)) {
+ return []
+ }
+ return visualizationWarnings(tagSource, result as ResultColumns)
+}
+
+/**
+ * Mirrors `toFriendlyClickhouseTypeName` and `isNumericalType` in the frontend
+ * dataVisualizationLogic.ts, which decide whether the chart accepts a column as a Y series.
+ */
+function isNumericClickhouseType(type: string | undefined): boolean {
+ if (!type || type.includes('Array') || type.includes('Tuple')) {
+ return false
+ }
+ return type.includes('Int') || type.includes('Float') || type.includes('Decimal')
+}
+
+function columnType(result: ResultColumns, column: string): string | undefined {
+ const entry = (result.types ?? []).find((type) => Array.isArray(type) && type[0] === column)
+ return Array.isArray(entry) && typeof entry[1] === 'string' ? entry[1] : undefined
+}
+
+/**
+ * Problems that make the chart draw nothing, or less than the agent expects, while the call
+ * itself succeeds. The chart drops both axes when one names a missing or non-numeric column, and
+ * it plots only the first page of the run, so the agent cannot see either failure otherwise.
+ */
+export function visualizationWarnings(tagSource: string, result: ResultColumns | null): string[] {
+ const visualization = storedVisualization(tagSource)
+ if (!visualization || !result?.columns) {
+ return []
+ }
+ const columns = result.columns
+ const known = new Set(columns)
+ const listed = columns.join(', ')
+ const warnings: string[] = []
+ const settings = visualization.chartSettings
+
+ const xColumn = settings?.xAxis?.column
+ if (xColumn !== undefined && !known.has(xColumn)) {
+ warnings.push(`xAxis column '${xColumn}' is not in the result columns: ${listed}.`)
+ }
+ for (const series of settings?.yAxis ?? []) {
+ if (!known.has(series.column)) {
+ warnings.push(`yAxis column '${series.column}' is not in the result columns: ${listed}.`)
+ } else if (!isNumericClickhouseType(columnType(result, series.column))) {
+ warnings.push(
+ `yAxis column '${series.column}' is not numeric (${columnType(result, series.column) ?? 'unknown type'}), so the chart cannot plot it.`
+ )
+ }
+ }
+ const breakdown = settings?.seriesBreakdownColumn
+ if (breakdown && !known.has(breakdown)) {
+ warnings.push(`seriesBreakdownColumn '${breakdown}' is not in the result columns: ${listed}.`)
+ }
+ if (warnings.length > 0) {
+ warnings.push('The chart ignores both axes when one of them is invalid. Fix the column names or the query.')
+ }
+
+ const plotted = result.first_page?.length ?? 0
+ const truncated = !!result.has_more || (result.row_count ?? 0) > plotted
+ // A table pages through the rows, and a bold number shows one value, so only a plot loses points.
+ // A stored preview keeps fewer rows than the run result the chart restores, so its count proves
+ // nothing about the chart. The run that stored it already reported this from the full result.
+ if (!['ActionsTable', 'BoldNumber'].includes(visualization.display) && truncated && !result.previewOnly) {
+ warnings.push(
+ `The chart plots only the first ${plotted} rows of ${result.row_count ?? 'more'}. Aggregate in SQL so the result fits.`
+ )
+ }
+ return warnings
+}
diff --git a/services/mcp/src/tools/notebooks/updateCell.ts b/services/mcp/src/tools/notebooks/updateCell.ts
index cf5730469f5d..997df353f6f3 100644
--- a/services/mcp/src/tools/notebooks/updateCell.ts
+++ b/services/mcp/src/tools/notebooks/updateCell.ts
@@ -14,12 +14,20 @@ import {
collectRunRefs,
directDependents,
findCellTag,
+ materializeLegacySqlProps,
parseCellTags,
replaceCellTag,
normalizeForTagScan,
startsComponentTag,
upsertProp,
} from './cellTags'
+import {
+ applyVisualization,
+ CellVisualizationSchema,
+ storedVisualizationWarnings,
+ VISUALIZATION_PARAM_DESCRIPTION,
+ visualizationWarnings,
+} from './cellVisualization'
import { applyMarkdownEdit, fetchMarkdownNotebook, notebookPathFor, replaceMarkdownCell } from './markdownDoc'
import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'
@@ -40,13 +48,20 @@ const UpdateCellInputSchema = z
code: z
.string()
.optional()
- .describe('New SQL or Python source. Omit to re-run the cell as-is (e.g. a stale cell).'),
+ .describe(
+ 'New SQL or Python source. Omit code and visualization to re-run the cell as-is (e.g. a stale cell).'
+ ),
markdown: z
.string()
.optional()
.describe(
'New markdown for a markdown cell: prose, a heading, a table, or a fenced block. Use this instead of `code` when notebooks-get reports the cell as cell_type "markdown". Pass the replacement only; the surrounding cells are untouched.'
),
+ visualization: CellVisualizationSchema.nullable()
+ .optional()
+ .describe(
+ `${VISUALIZATION_PARAM_DESCRIPTION} Pass null to show the results table again. Without code, the chart changes and the cell does not re-run.`
+ ),
})
.strict()
@@ -56,6 +71,13 @@ export interface UpdateCellResult {
node_id: string
run: ShapedRunResult
stale_dependents: { node_id: string; dataframe_name?: string }[]
+ visualization_warnings?: string[]
+}
+
+export interface UpdateVisualizationResult {
+ node_id: string
+ updated: true
+ visualization_warnings?: string[]
}
export interface UpdateProseCellResult {
@@ -97,6 +119,9 @@ async function updateProseCell(
context: Context,
params: z.infer<typeof NotebooksUpdateCellSchema>
): Promise<UpdateProseCellResult> {
+ if (params.visualization !== undefined) {
+ throw new Error(`Cell ${params.node_id} is a markdown cell. visualization applies to sql cells only.`)
+ }
if (params.code !== undefined) {
throw new Error(
`Cell ${params.node_id} is a markdown cell. Pass its replacement as \`markdown\`, not \`code\`.`
@@ -114,8 +139,11 @@ async function updateProseCell(
export const updateCellHandler: ToolBase<
typeof NotebooksUpdateCellSchema,
- UpdateCellResult | UpdateProseCellResult
+ UpdateCellResult | UpdateProseCellResult | UpdateVisualizationResult
>['handler'] = async (context: Context, params: z.infer<typeof NotebooksUpdateCellSchema>) => {
+ if (params.visualization !== undefined && params.markdown !== undefined) {
+ throw new Error('visualization applies to sql cells only. A markdown cell has no chart.')
+ }
if (params.code !== undefined && params.markdown !== undefined) {
throw new Error(
'Pass either code (a SQL or Python cell) or markdown (a markdown cell), not both. The cell type follows from node_id; read it from notebooks-get.'
@@ -124,7 +152,7 @@ export const updateCellHandler: ToolBase<
// A prefix only hints at the cell type. A tag holds its id in a prop, and nothing stops that
// prop from reading like a markdown block id, so the document decides when the two disagree.
const looksLikeProse = PROSE_NODE_ID_PREFIXES.some((prefix) => params.node_id.startsWith(prefix))
- if (looksLikeProse && params.code !== undefined) {
+ if (looksLikeProse && (params.code !== undefined || params.visualization !== undefined)) {
const { markdown } = await fetchMarkdownNotebook(context, params.notebook_id)
if (!findCellTag(markdown, params.node_id)) {
return await updateProseCell(context, params)
@@ -146,17 +174,39 @@ export const updateCellHandler: ToolBase<
`Cell ${params.node_id} is a ${existing.tagName} cell and cannot be updated with this tool — delete and re-add it instead.`
)
}
+ if (params.visualization !== undefined && existing.tagName !== 'SQLV2') {
+ throw new Error(
+ `visualization applies to sql cells only, and ${params.node_id} is a python cell. A python cell plots with matplotlib.`
+ )
+ }
let markdown = initial.markdown
let notebook = initial.notebook
- if (params.code !== undefined && params.code !== existing.code) {
+ const codeChanged = params.code !== undefined && params.code !== existing.code
+ if (codeChanged || params.visualization !== undefined) {
const applied = await applyMarkdownEdit(context, params.notebook_id, (current) => {
const block = findCellTag(current, params.node_id)
if (!block) {
throw new Error(`No cell with node_id ${params.node_id} in notebook ${params.notebook_id}.`)
}
- return replaceCellTag(current, block, upsertProp(block.source, 'code', params.code))
+ let source = block.tagName === 'SQLV2' ? materializeLegacySqlProps(block.source) : block.source
+ if (codeChanged) {
+ source = upsertProp(source, 'code', params.code)
+ }
+ if (params.visualization !== undefined) {
+ source = applyVisualization(source, params.visualization)
+ }
+ return replaceCellTag(current, block, source)
})
+ if (params.code === undefined) {
+ const updated = findCellTag(applied.markdown, params.node_id)
+ const warnings = updated ? storedVisualizationWarnings(updated.source) : []
+ return wrapRunResultAsInformational({
+ node_id: params.node_id,
+ updated: true as const,
+ ...(warnings.length ? { visualization_warnings: warnings } : {}),
+ })
+ }
markdown = applied.markdown
// The save response carries the notebook as it stood when the save committed, so it holds a
// variable edit that landed after the read above.
@@ -180,6 +230,7 @@ export const updateCellHandler: ToolBase<
variables: notebook.variables,
})
const outcome = await awaitRun(context, notebookPath, runId)
+ let warnings: string[] = []
await applyMarkdownEdit(context, params.notebook_id, (current) => {
const block = findCellTag(current, params.node_id)
if (!block) {
@@ -188,6 +239,8 @@ export const updateCellHandler: ToolBase<
let source = upsertProp(block.source, 'runId', runId)
if (outcome.envelope && (outcome.status === 'done' || outcome.status === 'interrupted')) {
source = upsertProp(source, 'result', buildResultProp(outcome.envelope))
+ // New code can drop a column the stored chart plots, so every run re-checks the chart.
+ warnings = visualizationWarnings(source, outcome.envelope)
}
return replaceCellTag(current, block, source)
})
@@ -197,10 +250,14 @@ export const updateCellHandler: ToolBase<
run: shapeRunForModel(outcome),
stale_dependents:
outcome.status === 'done' ? directDependents(cells, existing.returnVariable, params.node_id) : [],
+ ...(warnings.length ? { visualization_warnings: warnings } : {}),
})
}
-const tool = (): ToolBase<typeof NotebooksUpdateCellSchema, UpdateCellResult | UpdateProseCellResult> => ({
+const tool = (): ToolBase<
+ typeof NotebooksUpdateCellSchema,
+ UpdateCellResult | UpdateProseCellResult | UpdateVisualizationResult
+> => ({
name: 'notebooks-update-cell',
schema: NotebooksUpdateCellSchema,
handler: updateCellHandler,
diff --git a/services/mcp/tests/unit/notebook-cell-tools.test.ts b/services/mcp/tests/unit/notebook-cell-tools.test.ts
index dfff8ba4e133..1f9c92da3704 100644
--- a/services/mcp/tests/unit/notebook-cell-tools.test.ts
+++ b/services/mcp/tests/unit/notebook-cell-tools.test.ts
@@ -2,7 +2,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { buildToolResultPayload } from '@/lib/build-tool-result'
import { GENERATED_TOOLS } from '@/tools/generated/notebooks'
-import { addCellHandler } from '@/tools/notebooks/addCell'
+import { addCellHandler, NotebooksAddCellSchema } from '@/tools/notebooks/addCell'
+import { findCellTag, readExpressionProp, readStringProp } from '@/tools/notebooks/cellTags'
import { createMarkdownHandler } from '@/tools/notebooks/createMarkdown'
import { deleteCellHandler } from '@/tools/notebooks/deleteCell'
import { runNotebookHandler } from '@/tools/notebooks/runNotebook'
@@ -321,6 +322,193 @@ describe('notebook cell tools', () => {
expect(writtenBack).not.toContain('result={')
})
+ describe('sql cell charts', () => {
+ const doneWith = (result: Record<string, unknown>): Record<string, unknown> => ({
+ status: 'done',
+ result: { status: 'ok', has_more: false, ...result },
+ error: null,
+ })
+
+ it('add sql cell with a visualization opens the chart tab and stores the chart without its source', async () => {
+ const state = makeState('# Doc\n')
+ state.runStatusResponses.push(DONE_STATUS)
+ const context = createMockContext(state)
+
+ const result = await addCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ cell_type: 'sql',
+ code: 'select 1 as x',
+ visualization: { display: 'ActionsBar', chartSettings: { yAxis: [{ column: 'x' }] } },
+ })
+
+ const inserted = state.saveBodies[0].content.content[0].attrs.markdown
+ expect(inserted).toContain('outputTab="visualization"')
+ expect(inserted).toContain(
+ 'vizQuery={{"kind":"DataVisualizationNode","display":"ActionsBar","chartSettings":{"yAxis":[{"column":"x"}]}}}'
+ )
+ expect(inserted).not.toContain('"source"')
+ expect(result).not.toHaveProperty('visualization_warnings')
+ })
+
+ it.each([
+ {
+ label: 'an axis column the query does not return',
+ chartSettings: { xAxis: { column: 'month' } },
+ run: doneWith({ columns: ['x'], types: [['x', 'Int64']], row_count: 1, first_page: [[1]] }),
+ warning: "xAxis column 'month' is not in the result columns: x.",
+ },
+ {
+ label: 'a Y column that is not numeric',
+ chartSettings: { xAxis: { column: 'month' }, yAxis: [{ column: 'orgs' }] },
+ run: doneWith({
+ columns: ['month', 'orgs'],
+ types: [
+ ['month', 'Date'],
+ ['orgs', 'String'],
+ ],
+ row_count: 1,
+ first_page: [['2026-09-01', '12']],
+ }),
+ warning: "yAxis column 'orgs' is not numeric (String), so the chart cannot plot it.",
+ },
+ {
+ label: 'more rows than the chart plots',
+ chartSettings: { yAxis: [{ column: 'x' }] },
+ run: doneWith({
+ columns: ['x'],
+ types: [['x', 'Int64']],
+ row_count: 120,
+ first_page: Array.from({ length: 50 }, (_, index) => [index]),
+ has_more: true,
+ }),
+ warning: 'The chart plots only the first 50 rows of 120. Aggregate in SQL so the result fits.',
+ },
+ ])('add sql cell warns about $label', async ({ chartSettings, run, warning }) => {
+ const state = makeState('# Doc\n')
+ state.runStatusResponses.push(run)
+ const context = createMockContext(state)
+
+ const result = await addCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ cell_type: 'sql',
+ code: 'select 1',
+ visualization: { display: 'ActionsLineGraph', chartSettings },
+ })
+
+ expect(result.visualization_warnings).toContain(warning)
+ })
+
+ const STORED_PREVIEW =
+ 'runId="old" result={{"columns":["x"],"types":[["x","Int64"]],"row_count":20,"first_page":[[1]],"has_more":true,"previewOnly":true}}'
+ const LEGACY_PIE_QUERY =
+ 'query={{"kind":"DataVisualizationNode","display":"ActionsPie","source":{"kind":"HogQLQuery","query":"select 1 as x"}}}'
+ const targetProp = (state: MockState, name: string): unknown => {
+ const source = findCellTag(state.markdown, 'target')!.source
+ return readStringProp(source, name) ?? readExpressionProp(source, name)
+ }
+
+ it.each([
+ { label: 'a cell that holds its SQL in code', sql: 'code="select 1 as x"' },
+ { label: 'a legacy cell that holds its SQL and a pie chart in query', sql: LEGACY_PIE_QUERY },
+ ])(
+ 'update cell with only a visualization changes the chart of $label without re-running, and null restores the table',
+ async ({ sql }) => {
+ const state = makeState(
+ `# Doc\n\n<SQLV2 nodeId="target" ${sql} returnVariable="df" ${STORED_PREVIEW} />\n`
+ )
+ const context = createMockContext(state)
+
+ const charted = await updateCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ node_id: 'target',
+ visualization: { display: 'ActionsLineGraph', chartSettings: { yAxis: [{ column: 'y' }] } },
+ })
+
+ expect(state.runBodies).toHaveLength(0)
+ expect(targetProp(state, 'code')).toBe('select 1 as x')
+ expect(targetProp(state, 'outputTab')).toBe('visualization')
+ expect(targetProp(state, 'vizQuery')).toMatchObject({ display: 'ActionsLineGraph' })
+ expect(charted).toMatchObject({
+ updated: true,
+ visualization_warnings: expect.arrayContaining([
+ "yAxis column 'y' is not in the result columns: x.",
+ ]),
+ })
+ // The stored preview holds fewer rows than the chart restores, so it must not claim truncation.
+ expect(JSON.stringify(charted)).not.toContain('plots only')
+
+ await updateCellHandler(context, { notebook_id: 'aBcD1234', node_id: 'target', visualization: null })
+
+ expect(state.runBodies).toHaveLength(0)
+ expect(targetProp(state, 'code')).toBe('select 1 as x')
+ expect(targetProp(state, 'outputTab')).toBe('results')
+ expect(targetProp(state, 'vizQuery')).toBeNull()
+ expect(targetProp(state, 'runId')).toBe('old')
+ }
+ )
+
+ it('update cell with new code keeps the chart a legacy cell holds in query', async () => {
+ const state = makeState(`# Doc\n\n<SQLV2 nodeId="target" ${LEGACY_PIE_QUERY} returnVariable="df" />\n`)
+ state.runStatusResponses.push(DONE_STATUS)
+ const context = createMockContext(state)
+
+ await updateCellHandler(context, { notebook_id: 'aBcD1234', node_id: 'target', code: 'select 2 as x' })
+
+ expect(state.runBodies[0]).toMatchObject({ code: 'select 2 as x' })
+ expect(targetProp(state, 'code')).toBe('select 2 as x')
+ expect(targetProp(state, 'outputTab')).toBe('visualization')
+ expect(targetProp(state, 'vizQuery')).toMatchObject({ display: 'ActionsPie' })
+ })
+
+ it.each(['WorldMap', 'TwoDimensionalHeatmap'])(
+ 'refuses the %s display, which opens a sql cell on an empty chart',
+ (display) => {
+ expect(
+ NotebooksAddCellSchema.safeParse({
+ notebook_id: 'aBcD1234',
+ cell_type: 'sql',
+ code: 'select 1',
+ visualization: { display },
+ }).success
+ ).toBe(false)
+ }
+ )
+
+ it.each([
+ {
+ label: 'add a python cell',
+ markdown: '# Doc\n',
+ run: (context: Context) =>
+ addCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ cell_type: 'python',
+ code: 'df.plot()',
+ visualization: { display: 'ActionsBar' },
+ }),
+ },
+ {
+ label: 'update a python cell',
+ markdown: '# Doc\n\n<PythonV2 nodeId="py" code="x = 1" returnVariable="out" />\n',
+ run: (context: Context) =>
+ updateCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ node_id: 'py',
+ visualization: { display: 'ActionsBar' },
+ }),
+ },
+ ] as { label: string; markdown: string; run: (context: Context) => Promise<unknown> }[])(
+ 'refuses a visualization to $label without saving or running',
+ async ({ markdown, run }) => {
+ const state = makeState(markdown)
+ const context = createMockContext(state)
+
+ await expect(run(context)).rejects.toThrow(/sql cells only/)
+ expect(state.saveBodies).toHaveLength(0)
+ expect(state.runBodies).toHaveLength(0)
+ }
+ )
+ })
+
it('add markdown cell appends prose without dispatching a run', async () => {
const state = makeState('# Doc\n')
const context = createMockContext(state)