: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(notebooks): generate widgets with available dataframes (#101587)
Marius Andra4bfcd858de9a
diff --git a/docs/internal/generated-notebook-widgets.md b/docs/internal/generated-notebook-widgets.mdindex 0b4c265d8721..7cbd5d434aa6 100644--- a/docs/internal/generated-notebook-widgets.md+++ b/docs/internal/generated-notebook-widgets.md@@ -13,7 +13,8 @@ Notebooks can generate interactive widgets from instructions and the notebook's- A preview without dataframe inputs runs immediately when its automated review found no potential issues. Previews with dataframe access, flagged reviews, and legacy unreviewed versions require exact-build consent at a gate that links to the source.- Every ready build exposes the SHA-256 of its frozen Canvas artifact manifest. Choosing “Run widget” at a gate records consent for that exact hash. A later gated build with different artifact contents requires a new decision. A build with identical contents reuses the earlier consent.- “View source” remains available before a widget runs and reads the source belonging to the selected historical version.-- Every dataframe must have a completed run before generation. Each preview load pins permission-checked pages to one run and reads at most 5,000 rows per connected dataframe without sending values to the model. Across all its dataframes, one preview reads at most 200 pages and 32 MiB of response data.+- Generation uses dataframes with completed runs and skips cells that have not run. Each preview load pins permission-checked pages to one run and reads at most 5,000 rows per connected dataframe without sending values to the model. Across all its dataframes, one preview reads at most 200 pages and 32 MiB of response data.+- Improving a notebook widget requires completed results for its existing inputs, including renamed connections, and preserves their slots and schemas. Unrelated cells without completed results are still skipped.- Notebook-managed Canvas artifacts use a restricted source policy. Signed artifact URLs can render them, but the ordinary Canvas API cannot list or edit them.- `<Widget>` is the only notebook markdown tag for generated widgets.- Widget previews allow pointer lock for interactive controls such as games. Both the iframe and artifact CSP permit `allow-pointer-lock`; the preview URL varies to refresh previously cached CSP headers.@@ -89,6 +90,9 @@ The SQL and insight dataframe name rows are visible when either `revamped-py-notThe widget flag enables HogQL dataframe preparation. Python, kernel-backed SQL, and direct connections require `revamped-py-notebooks`.Insights that expose SQL have the same dataframe name field below their results, starting with `insight_df` (with a numeric suffix when needed).An editor prepares the insight's dataframe when a SQL or Python cell first references it, before generating a widget, or when rerunning a widget's data dependencies.+Widget generation continues with the available dataframes if an embedded insight cannot be prepared.+Refreshing a widget prepares only its connected insight dataframes; SQL and Python cells prepare any insights they reference when they run.+An insight preparation failure still stops a cell or widget refresh that depends on that insight.Widgets that use only insight dataframes refresh after preparation without requiring a SQL or Python cell.Opening a notebook, renaming a dataframe, or refreshing an insight's display does not prepare dataframes or save preparation metadata.Preparation uses the insight query cache and saves the run reference and column metadata only after the SQL run completes.@@ -123,7 +127,7 @@ Generation also requires the organization's AI data processing consent and the `An agent inserts a `Widget` component through `notebooks-add-cell`, then calls `notebooks-widget-generate` with its returned `node_id`.Markdown editing can also insert `<Widget nodeId="widget-example" prompt="Show an interactive chart" />` into a saved notebook.-All notebook SQL and Python dataframes must have completed runs before generation.+Only notebook SQL and Python dataframes with completed runs are available to generation; unrun cells do not block it.Inserting the tag does not start a generation job.The agent polls status and directs the user to the notebook for review and execution consent.MCP responses for widget generation, status, and attachment omit the preview URL so previews open through the notebook's existing consent flow.diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex 4552d47346bb..1fea31ca2672 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -845,6 +845,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDinput_candidates,self._authorize_widget_run,node_id=node_id,+ skip_unready=True,)result = start_widget_generation(notebook=notebook,diff --git a/products/notebooks/backend/test/test_widgets.py b/products/notebooks/backend/test/test_widgets.pyindex 040fcfd4602a..4470e53f7ddb 100644--- a/products/notebooks/backend/test/test_widgets.py+++ b/products/notebooks/backend/test/test_widgets.py@@ -610,14 +610,25 @@ class TestWidgetData(APIBaseTest):assert version is not Nonereturn version- def test_inspection_uses_latest_successful_run_and_authorizes_it(self) -> None:+ @parameterized.expand([("all_ready", False), ("unrun_sibling", True)])+ def test_inspection_uses_latest_successful_run_and_authorizes_it(self, _name: str, unrun_sibling: bool) -> None:self._run(value=1)latest = self._run(value=2)authorize = MagicMock()+ inputs = [self.INPUT_NAME]+ if unrun_sibling:+ self.notebook.content = markdown_content(+ f'<PythonV2 nodeId="source" returnVariable="{self.INPUT_NAME}" />\n\n'+ '<SQLV2 nodeId="unrun" code="SELECT 1" returnVariable="unrun_df" />'+ )+ inputs.append("unrun_df")+ with self.assertRaises(WidgetError) as error:+ inspect_widget_inputs(self.notebook, inputs, authorize)+ assert error.exception.code == "input_not_ready"- inspection = inspect_widget_inputs(self.notebook, [self.INPUT_NAME], authorize)+ inspection = inspect_widget_inputs(self.notebook, inputs, authorize, skip_unready=unrun_sibling)- assert inspection.resolved_inputs[0].run == latest+ assert [(item.name, item.run) for item in inspection.resolved_inputs] == [(self.INPUT_NAME, latest)]assert inspection.contract[0]["columns"] == [{"name": "lat", "type": "float64"},{"name": "label", "type": "string"},@@ -1015,8 +1026,16 @@ class TestWidgetData(APIBaseTest):version_id=version.canvas_source_version_id,)- def test_generate_endpoint_infers_available_dataframes(self) -> None:+ @parameterized.expand([("all_ready", False), ("unrun_sibling", True)])+ def test_generate_endpoint_infers_available_dataframes(self, _name: str, unrun_sibling: bool) -> None:latest = self._run()+ if unrun_sibling:+ self.notebook.content = markdown_content(+ f'<PythonV2 nodeId="source" returnVariable="{self.INPUT_NAME}" />\n\n'+ f'<Widget nodeId="{self.NODE_ID}" prompt="Render a globe" />\n\n'+ '<SQLV2 nodeId="unrun" code="SELECT 1" returnVariable="unrun_df" />'+ )+ self.notebook.save(update_fields=["content"])url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/widgets/{self.NODE_ID}/generate/"result = WidgetStatus(lifecycle_status="building",@@ -1045,7 +1064,8 @@ class TestWidgetData(APIBaseTest):)assert response.status_code == 202- assert generate.call_args.kwargs["inspection"].resolved_inputs[0].run == latest+ inputs = generate.call_args.kwargs["inspection"].resolved_inputs+ assert [(item.name, item.run) for item in inputs] == [(self.INPUT_NAME, latest)]assert generate.call_args.kwargs["operation"] == "regenerate"@parameterized.expand(@@ -1143,6 +1163,56 @@ class TestWidgetData(APIBaseTest):assert job.status == GeneratedWidgetGenerationJob.Status.QUEUEDassert job.error_code is None+ @parameterized.expand([("direct", False), ("bound", True)])+ def test_improvement_requires_existing_inputs_and_preserves_slots(self, _name: str, bound: bool) -> None:+ instance = self._mapping()+ version = self._pinned_version(instance)+ slot = "points" if bound else self.INPUT_NAME+ version.input_contract[0]["slot"] = slot+ if bound:+ version.input_contract[0]["sourceName"] = "original_df"+ instance.input_bindings = {slot: {"source": self.INPUT_NAME}}+ instance.save(update_fields=["input_bindings"])+ version.save(update_fields=["input_contract"])+ self.notebook.content = markdown_content(+ f'<PythonV2 nodeId="source" returnVariable="{self.INPUT_NAME}" />\n\n'+ '<SQLV2 nodeId="unrun" returnVariable="unrun_df" code="SELECT 1" />\n\n'+ f'<Widget nodeId="{self.NODE_ID}" />'+ )+ self.notebook.save(update_fields=["content"])+ url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/widgets/{self.NODE_ID}/generate/"+ request = {+ "prompt": "Use a darker background",+ "generation_id": str(uuid4()),+ "generation_operation": "improve",+ "expected_current_version_id": str(version.id),+ }+ with (+ patch("products.notebooks.backend.widgets._is_ai_usage_limited", return_value=False),+ patch("products.notebooks.backend.widgets.start_widget_generation_workflow") as workflow,+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self.client.post(url, data=request, format="json")+ assert response.status_code == 409+ assert response.json()["code"] == "input_not_ready"+ assert not GeneratedWidgetGenerationJob.objects.for_team(self.team.id).exists()+ workflow.assert_not_called()++ run = self._run()+ response = self.client.post(url, data=request, format="json")++ assert response.status_code == 202+ job = GeneratedWidgetGenerationJob.objects.for_team(self.team.id).get()+ required = next(item for item in job.input_contract if item["slot"] == slot)+ assert required == {+ **version.input_contract[0],+ "sourceName": self.INPUT_NAME,+ "runId": str(run.id),+ "totalRowCount": 150,+ }+ assert "unrun_df" not in [item["slot"] for item in job.input_contract]+ workflow.assert_called_once()+def test_improvement_rejects_a_stale_current_version_before_creating_a_job(self) -> None:self._mapping()@@ -1335,6 +1405,8 @@ class TestWidgetData(APIBaseTest):assert error.exception.code == "generation_id_conflict"def test_generation_identifier_is_scoped_to_the_team(self) -> None:+ self._run()+ inspection = inspect_widget_inputs(self.notebook, [self.INPUT_NAME], authorize_run=lambda _run: None)generation_id = uuid4()other_team = Team.objects.create(organization=self.organization)other_notebook = Notebook.objects.create(@@ -1379,7 +1451,7 @@ class TestWidgetData(APIBaseTest):node_id=self.NODE_ID,prompt="Make it lighter",user_id=self.user.id,- inspection=WidgetInputInspection(resolved_inputs=[]),+ inspection=inspection,model="claude-sonnet-4-6",generation_id=generation_id,operation=GeneratedWidgetVersion.Operation.IMPROVE,diff --git a/products/notebooks/backend/widgets.py b/products/notebooks/backend/widgets.pyindex e7fe5b971e38..da1a0f79fea2 100644--- a/products/notebooks/backend/widgets.py+++ b/products/notebooks/backend/widgets.py@@ -329,6 +329,8 @@ def inspect_widget_inputs(inputs: list[str],authorize_run: Callable[[NotebookNodeRun], None],node_id: str | None = None,+ *,+ skip_unready: bool = False,) -> WidgetInputInspection:normalized_inputs = normalize_widget_inputs(inputs)if node_id is not None:@@ -347,7 +349,7 @@ def inspect_widget_inputs()runs = {run.node_id: run for run in run_queryset.defer("envelope")}unresolved = [name for name in normalized_inputs if owners[name] not in runs]- if unresolved:+ if unresolved and not skip_unready:raise WidgetConflictError(f'Run the cell that creates "{unresolved[0]}" before generating this widget.',"input_not_ready",@@ -641,6 +643,33 @@ def _reconcile_stale_generation_job(job: GeneratedWidgetGenerationJob) -> None:job.refresh_from_db()+def _improvement_input_contract(+ instance: NotebookWidgetInstance,+ base_version: GeneratedWidgetVersion,+ inspection: WidgetInputInspection,+) -> list[dict[str, object]]:+ available = {item.name: item.contract for item in inspection.resolved_inputs}+ bindings = instance.input_bindings if isinstance(instance.input_bindings, dict) else {}+ required: list[dict[str, object]] = []+ for item in base_version.input_contract:+ slot = str(item["slot"])+ binding = bindings.get(slot)+ source = (+ str(binding["source"])+ if isinstance(binding, dict) and isinstance(binding.get("source"), str)+ else str(item.get("sourceName") or slot)+ )+ if source not in available:+ raise WidgetConflictError(+ f'Run the cell that creates "{source}" before improving this widget.',+ "input_not_ready",+ )+ # Existing source still uses these slots, including schemas supplied by input transformations.+ required.append({**available[source], **item, "sourceName": source})+ slots = {item["slot"] for item in required}+ return required + [item for item in inspection.contract if item["slot"] not in slots]++def start_widget_generation(*,notebook: Notebook,@@ -769,6 +798,9 @@ def start_widget_generation(elif operation == GeneratedWidgetVersion.Operation.INITIAL:resolved_operation = GeneratedWidgetVersion.Operation.REGENERATEinput_contract = input_contract_override if input_contract_override is not None else inspection.contract+ if operation == GeneratedWidgetVersion.Operation.IMPROVE and input_contract_override is None:+ assert base_version is not None+ input_contract = _improvement_input_contract(locked_instance, base_version, inspection)job = GeneratedWidgetGenerationJob.objects.for_team(notebook.team_id).create(idempotency_key=generation_id,team_id=notebook.team_id,diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsxindex c7858ca6b1bb..6530d730b4f2 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx@@ -56,7 +56,7 @@ function EditableNotebookGeneratedWidgetRunButton({prompt: typeof node.props.prompt === 'string' ? node.props.prompt : '',model,isEditable: canEditNotebook,- prepareInsightDataframes: () => prepareNotebookInsightDataframes(mountedNotebookLogic),+ prepareInsightDataframes: (names?: string[]) => prepareNotebookInsightDataframes(mountedNotebookLogic, names),persistNotebook: async (): Promise<void> => {await mountedNotebookLogic.asyncActions.saveNotebook({content: mountedNotebookLogic.values.content,diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsxindex 18477d90a463..7815822000fe 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx@@ -82,7 +82,7 @@ function ExpandedWidget({prompt,model,isEditable,- prepareInsightDataframes: () => prepareNotebookInsightDataframes(notebookLogic),+ prepareInsightDataframes: (names?: string[]) => prepareNotebookInsightDataframes(notebookLogic, names),persistNotebook: async (): Promise<void> => {await notebookLogic.asyncActions.saveNotebook({content: notebookLogic.values.content,diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsxindex 20fb34672d57..05577c186d7f 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx@@ -47,7 +47,7 @@ export function NotebookNodeGeneratedWidgetSettings({prompt: attributes.prompt ?? '',model: attributes.model ?? DEFAULT_WIDGET_MODEL,isEditable,- prepareInsightDataframes: () => prepareNotebookInsightDataframes(notebookLogic),+ prepareInsightDataframes: (names) => prepareNotebookInsightDataframes(notebookLogic, names),persistNotebook: async (): Promise<void> => {await notebookLogic.asyncActions.saveNotebook({content: notebookLogic.values.content,@@ -186,8 +186,8 @@ export function NotebookNodeGeneratedWidgetSettings({/></div><div className="text-xs text-muted">- Run every SQL and Python cell before generating. The widget can use their latest completed- results automatically.+ Run the SQL and Python cells the widget should use. The widget uses their latest completed+ results and skips cells that haven't run.</div><div><LemonLabel htmlFor={modelId}>Model</LemonLabel>diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.ts b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.tsindex 16a2a92f051e..a58cf6db9d53 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.ts+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.ts@@ -971,6 +971,7 @@ describe('notebookNodeGeneratedWidgetLogic', () => {logic.actions.runDataDependencies()expect(logic.values.dataRefreshInFlight).toBe(true)expect(prepareInsightDataframes).toHaveBeenCalledTimes(1)+ expect(prepareInsightDataframes).toHaveBeenCalledWith(['insight_df'])expect(notebooksWidgetStatus).toHaveBeenCalledTimes(1)finishPreparation()@@ -1039,8 +1040,15 @@ describe('notebookNodeGeneratedWidgetLogic', () => {it('loads the selected version source and queues an improvement from it', async () => {const versionId = '00000000-0000-0000-0000-000000000009'+ const prepareInsightDataframes = jest.fn().mockResolvedValue(undefined)jest.mocked(notebooksWidgetStatus).mockResolvedValue(- status({ lifecycle_status: 'ready', current_version_id: versionId, has_versions: true })+ status({+ lifecycle_status: 'ready',+ current_version_id: versionId,+ has_versions: true,+ frame_names: ['points'],+ input_bindings: { points: { source: 'insight_df' } },+ }))jest.mocked(notebooksWidgetVersions).mockResolvedValue({results: [@@ -1066,7 +1074,7 @@ describe('notebookNodeGeneratedWidgetLogic', () => {})jest.mocked(notebooksWidgetSource).mockResolvedValue({ source: 'export default function Widget() {}' })jest.mocked(notebooksWidgetGenerate).mockResolvedValue(status({ lifecycle_status: 'generating' }))- logic = notebookNodeGeneratedWidgetLogic(props)+ logic = notebookNodeGeneratedWidgetLogic({ ...props, prepareInsightDataframes })logic.mount()await expectLogic(logic).toFinishAllListeners()@@ -1100,6 +1108,25 @@ describe('notebookNodeGeneratedWidgetLogic', () => {expect.objectContaining({ signal: expect.anything() }))expect(logic.values.sourceModalOpen).toBe(false)+ expect(prepareInsightDataframes.mock.calls).toEqual([[['insight_df']], []])+ })++ it('stops an improvement when a required insight cannot be prepared', async () => {+ const versionId = '00000000-0000-0000-0000-000000000009'+ const prepareInsightDataframes = jest.fn().mockRejectedValue(new Error('Preparation failed. Try again.'))+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({ current_version_id: versionId, frame_names: ['insight_df'], has_versions: true })+ )+ logic = notebookNodeGeneratedWidgetLogic({ ...props, prepareInsightDataframes })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await logic.asyncActions.generateWidget('Use a darker background', 'claude-sonnet-4-6', 'improve', versionId)++ expect(prepareInsightDataframes).toHaveBeenCalledWith(['insight_df'])+ expect(notebooksWidgetGenerate).not.toHaveBeenCalled()+ expect(logic.values.generationRequestLoading).toBe(false)+ expect(logic.values.generationError).toBe('Preparation failed. Try again.')})it('waits for immutable version metadata before improving source', async () => {diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.ts b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.tsindex f4258869ff0c..2497dc7aa208 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.ts+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.ts@@ -84,7 +84,7 @@ export type NotebookNodeGeneratedWidgetLogicProps = {prompt: stringmodel: WidgetModelisEditable: boolean- prepareInsightDataframes?: () => Promise<void>+ prepareInsightDataframes?: (names?: string[]) => Promise<void>persistNotebook: () => Promise<void>getContent: () => JSONContent | nullreusableWidgetId?: string@@ -1123,6 +1123,14 @@ export const notebookNodeGeneratedWidgetLogic: LogicWrapper<notebookNodeGenerateconst generationId = uuidv4()let aborted = falsetry {+ if (operation === 'improve') {+ await props.prepareInsightDataframes?.(+ getWidgetSourceFrameNames(+ values.status?.frame_names ?? [],+ values.status?.input_bindings ?? {}+ )+ )+ }await props.prepareInsightDataframes?.()await props.persistNotebook()const requestGeneration = async (): Promise<WidgetStatusApi> =>@@ -1416,15 +1424,15 @@ export const notebookNodeGeneratedWidgetLogic: LogicWrapper<notebookNodeGenerateactions.setRuntimeError(null)actions.dataRefreshStarted()try {- await props.prepareInsightDataframes?.()- if (props.prepareInsightDataframes) {- await props.persistNotebook()- }- const content = props.getContent()const sourceFrameNames = getWidgetSourceFrameNames(values.activeFrameNames,values.status?.input_bindings ?? {})+ await props.prepareInsightDataframes?.(sourceFrameNames)+ if (props.prepareInsightDataframes) {+ await props.persistNotebook()+ }+ const content = props.getContent()const { missingFrameNames, nodeIds } = getWidgetDataDependencies(content, sourceFrameNames)if (missingFrameNames.length) {throw new Error(diff --git a/products/notebooks/frontend/notebookInsightDataframe.test.ts b/products/notebooks/frontend/notebookInsightDataframe.test.tsindex 19ee60a4525a..191910980afd 100644--- a/products/notebooks/frontend/notebookInsightDataframe.test.ts+++ b/products/notebooks/frontend/notebookInsightDataframe.test.ts@@ -1,7 +1,9 @@import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import api from 'lib/api'import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { insightsApi } from 'scenes/insights/utils/api'import { collectNotebookFrameNodes } from 'scenes/notebooks/Nodes/notebookNodeContent'import { collectSqlV2Refs } from 'scenes/notebooks/Nodes/notebookNodeSQLV2Logic'import { buildMarkdownNotebookContent } from 'scenes/notebooks/Notebook/markdownNotebookV2'@@ -16,6 +18,7 @@ import type { InsightLogicProps } from '~/types'import { notebookCodeCellLogic } from './notebookCodeCellLogic'import { InsightDataframeAttributes, notebookInsightDataframeLogic } from './notebookInsightDataframeLogic'+import { prepareNotebookInsightDataframes } from './prepareNotebookInsightDataframes'describe('insight dataframes', () => {let notebook: ReturnType<typeof notebookLogic.build>@@ -143,6 +146,46 @@ describe('insight dataframes', () => {])})+ it.each(['missing', 'failed'])(+ 'continues discovering widget dataframes after a %s insight, but rejects an explicit dependency',+ async (failure) => {+ const captureException = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined)+ const lookup = jest.spyOn(insightsApi, 'getByShortId')+ if (failure === 'missing') {+ lookup.mockResolvedValue(null)+ } else {+ lookup.mockRejectedValue(new Error('Could not load insight'))+ }+ jest.spyOn(queries, 'performQuery').mockResolvedValue(response)+ notebook.actions.setLocalContent(+ buildMarkdownNotebookContent(+ '<Insight nodeId="unavailable" id="missing-insight" returnVariable="unavailable_df" />\n\n' ++ `<Query nodeId="source" query={${JSON.stringify(insightProps.query)}} returnVariable="available_df" />\n\n` ++ '<SQLV2 nodeId="sql" code="SELECT 1" returnVariable="sql_df" runId="sql-run" result={{"columns":["value"],"row_count":1}} />'+ )+ )++ await prepareNotebookInsightDataframes(notebook)++ expect(captureException).toHaveBeenCalledWith(new Error('Notebook insight dataframe preparation failed'), {+ action: 'prepare notebook insight dataframe',+ })++ expect(collectNotebookFrameNodes(notebook.values.content)).toEqual([+ expect.objectContaining({ name: 'available_df', hasRun: true }),+ expect.objectContaining({ name: 'sql_df', hasRun: true }),+ ])+ await expect(prepareNotebookInsightDataframes(notebook, ['unavailable_df'])).rejects.toThrow(+ failure === 'missing'+ ? 'The insight query is unavailable. Try again after the insight loads.'+ : 'Could not load insight'+ )+ lookup.mockClear()+ await prepareNotebookInsightDataframes(notebook, ['sql_df'])+ expect(lookup).not.toHaveBeenCalled()+ }+ )+it('retries a failed preparation without creating another cell', async () => {jest.mocked(api.notebooks.sqlV2Run).mockRejectedValueOnce(new Error('Temporary query failure'))mountCreator()diff --git a/products/notebooks/frontend/prepareNotebookInsightDataframes.ts b/products/notebooks/frontend/prepareNotebookInsightDataframes.tsindex cf03e52f7711..606010064b6b 100644--- a/products/notebooks/frontend/prepareNotebookInsightDataframes.ts+++ b/products/notebooks/frontend/prepareNotebookInsightDataframes.ts@@ -1,4 +1,5 @@import type { BuiltLogic } from 'kea'+import posthog from 'posthog-js'import { parseMarkdownNotebook, serializeMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'import { getSerializableProps } from 'lib/components/MarkdownNotebook/utils'@@ -74,9 +75,15 @@ export async function prepareNotebookInsightDataframes(const unmount = logic.mount()try {await logic.asyncActions.syncDataframe()- if (logic.values.error && (!logic.values.unsupported || names)) {+ // Discovery can use the remaining dataframes; explicit dependencies must be available.+ if (logic.values.error && names) {throw new Error(logic.values.error)}+ if (logic.values.error && !logic.values.unsupported) {+ posthog.captureException(new Error('Notebook insight dataframe preparation failed'), {+ action: 'prepare notebook insight dataframe',+ })+ }} finally {unmount()}diff --git a/products/notebooks/mcp/tools.yaml b/products/notebooks/mcp/tools.yamlindex 0c24f25712f2..119ec4eef921 100644--- a/products/notebooks/mcp/tools.yaml+++ b/products/notebooks/mcp/tools.yaml@@ -477,13 +477,14 @@ tools:First insert a Widget component with notebooks-add-cell: cell_type="component", tag_name="Widget",props={"prompt":"Describe the visualization"}, and a short title. If using markdown editing instead, insert<Widget nodeId="a-stable-unique-id" prompt="Describe the visualization" /> into a saved markdown notebook.- Insertion alone does not start generation. Run all notebook SQL and Python dataframes first, then call this- tool with the notebook short_id, the inserted node_id, prompt, and a fresh UUID generation_id. Reuse that- UUID when retrying the same request. Use generation_operation="initial" for a new widget, "regenerate" to- replace it, or "improve" with expected_current_version_id to change the current version. Generation uses AI- credits. Poll notebooks-widget-status until lifecycle_status is ready or failed; notebooks-widget-cancel- stops an active job. Direct the user to the widget in the notebook to review and run it. Generated previews- with dataframe access require the user's approval in the notebook.+ Insertion alone does not start generation. Run the SQL and Python cells the widget should use first;+ unrelated unrun cells are skipped. Then call this tool with the notebook short_id, the inserted node_id,+ prompt, and a fresh UUID generation_id. Reuse that UUID when retrying the same request. Use+ generation_operation="initial" for a new widget, "regenerate" to replace it, or "improve" with+ expected_current_version_id to change the current version. Generation uses AI credits. Poll+ notebooks-widget-status until lifecycle_status is ready or failed; notebooks-widget-cancel stops an active+ job. Direct the user to the widget in the notebook to review and run it. Generated previews with dataframe+ access require the user's approval in the notebook.param_overrides:short_id:description: The notebook's short_id from its URL or notebooks-list, not its UUID id.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 0e12f495c30a..84509372c037 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -8607,7 +8607,7 @@"feature_flag": "notebook-generated-widgets"},"notebooks-widget-generate": {- "description": "Generate or improve an interactive notebook widget from instructions and the notebook's completed SQL and Python dataframes. This tool's availability means generated Widget tags are enabled for the current user. First insert a Widget component with notebooks-add-cell: cell_type=\"component\", tag_name=\"Widget\", props={\"prompt\":\"Describe the visualization\"}, and a short title. If using markdown editing instead, insert <Widget nodeId=\"a-stable-unique-id\" prompt=\"Describe the visualization\" /> into a saved markdown notebook. Insertion alone does not start generation. Run all notebook SQL and Python dataframes first, then call this tool with the notebook short_id, the inserted node_id, prompt, and a fresh UUID generation_id. Reuse that UUID when retrying the same request. Use generation_operation=\"initial\" for a new widget, \"regenerate\" to replace it, or \"improve\" with expected_current_version_id to change the current version. Generation uses AI credits. Poll notebooks-widget-status until lifecycle_status is ready or failed; notebooks-widget-cancel stops an active job. Direct the user to the widget in the notebook to review and run it. Generated previews with dataframe access require the user's approval in the notebook.",+ "description": "Generate or improve an interactive notebook widget from instructions and the notebook's completed SQL and Python dataframes. This tool's availability means generated Widget tags are enabled for the current user. First insert a Widget component with notebooks-add-cell: cell_type=\"component\", tag_name=\"Widget\", props={\"prompt\":\"Describe the visualization\"}, and a short title. If using markdown editing instead, insert <Widget nodeId=\"a-stable-unique-id\" prompt=\"Describe the visualization\" /> into a saved markdown notebook. Insertion alone does not start generation. Run the SQL and Python cells the widget should use first; unrelated unrun cells are skipped. Then call this tool with the notebook short_id, the inserted node_id, prompt, and a fresh UUID generation_id. Reuse that UUID when retrying the same request. Use generation_operation=\"initial\" for a new widget, \"regenerate\" to replace it, or \"improve\" with expected_current_version_id to change the current version. Generation uses AI credits. Poll notebooks-widget-status until lifecycle_status is ready or failed; notebooks-widget-cancel stops an active job. Direct the user to the widget in the notebook to review and run it. Generated previews with dataframe access require the user's approval in the notebook.","category": "Notebooks","feature": "notebooks","summary": "Generate notebook widget",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex d8941bb6da44..c1415d265420 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -9094,7 +9094,7 @@"feature_flag": "notebook-generated-widgets"},"notebooks-widget-generate": {- "description": "Generate or improve an interactive notebook widget from instructions and the notebook's completed SQL and Python dataframes. This tool's availability means generated Widget tags are enabled for the current user. First insert a Widget component with notebooks-add-cell: cell_type=\"component\", tag_name=\"Widget\", props={\"prompt\":\"Describe the visualization\"}, and a short title. If using markdown editing instead, insert <Widget nodeId=\"a-stable-unique-id\" prompt=\"Describe the visualization\" /> into a saved markdown notebook. Insertion alone does not start generation. Run all notebook SQL and Python dataframes first, then call this tool with the notebook short_id, the inserted node_id, prompt, and a fresh UUID generation_id. Reuse that UUID when retrying the same request. Use generation_operation=\"initial\" for a new widget, \"regenerate\" to replace it, or \"improve\" with expected_current_version_id to change the current version. Generation uses AI credits. Poll notebooks-widget-status until lifecycle_status is ready or failed; notebooks-widget-cancel stops an active job. Direct the user to the widget in the notebook to review and run it. Generated previews with dataframe access require the user's approval in the notebook.",+ "description": "Generate or improve an interactive notebook widget from instructions and the notebook's completed SQL and Python dataframes. This tool's availability means generated Widget tags are enabled for the current user. First insert a Widget component with notebooks-add-cell: cell_type=\"component\", tag_name=\"Widget\", props={\"prompt\":\"Describe the visualization\"}, and a short title. If using markdown editing instead, insert <Widget nodeId=\"a-stable-unique-id\" prompt=\"Describe the visualization\" /> into a saved markdown notebook. Insertion alone does not start generation. Run the SQL and Python cells the widget should use first; unrelated unrun cells are skipped. Then call this tool with the notebook short_id, the inserted node_id, prompt, and a fresh UUID generation_id. Reuse that UUID when retrying the same request. Use generation_operation=\"initial\" for a new widget, \"regenerate\" to replace it, or \"improve\" with expected_current_version_id to change the current version. Generation uses AI credits. Poll notebooks-widget-status until lifecycle_status is ready or failed; notebooks-widget-cancel stops an active job. Direct the user to the widget in the notebook to review and run it. Generated previews with dataframe access require the user's approval in the notebook.","category": "Notebooks","feature": "notebooks","summary": "Generate notebook widget",