: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(sql-editor): keep ph AI visualization settings in the SQL editor (#68115)
Sam Pennington1fe7a8ec0ba9
diff --git a/ee/hogai/tools/execute_sql/test/test_tool.py b/ee/hogai/tools/execute_sql/test/test_tool.pyindex b3735ad31c28..8024646951d6 100644--- a/ee/hogai/tools/execute_sql/test/test_tool.py+++ b/ee/hogai/tools/execute_sql/test/test_tool.py@@ -120,6 +120,19 @@ class TestExecuteSQLTool(ClickhouseTestMixin, NonAtomicBaseTest):self.assertEqual(right_y_axis_settings.label, "People")self.assertEqual(right_y_axis_settings.showTicks, False)+ tool_call_message = artifact_messages.messages[1]+ assert isinstance(tool_call_message, AssistantToolCallMessage)+ ui_payload = tool_call_message.ui_payload+ assert ui_payload is not None+ payload = ui_payload["execute_sql"]+ self.assertEqual(payload["kind"], "DataVisualizationNode")+ self.assertEqual(payload["display"], "ActionsBar")+ self.assertEqual(payload["chartSettings"]["xAxisLabel"], "Event name")+ self.assertEqual(+ payload["source"]["query"],+ "SELECT event, count() AS events, uniq(distinct_id) AS people FROM events GROUP BY event",+ )+async def test_artifact_id_in_output(self):_create_event(team=self.team, distinct_id="user1", event="test_event")diff --git a/ee/hogai/tools/execute_sql/tool.py b/ee/hogai/tools/execute_sql/tool.pyindex 2a6f5d9ec79c..0da60a1b196c 100644--- a/ee/hogai/tools/execute_sql/tool.py+++ b/ee/hogai/tools/execute_sql/tool.py@@ -163,7 +163,10 @@ class ExecuteSQLTool(HogQLGeneratorMixin, MaxTool):return EXECUTE_SQL_UNRECOVERABLE_ERROR_PROMPT, Nonetool_payload: str | dict[str, object]- if filters is not None:+ if display or chart_settings:+ # Full node so the SQL editor can adopt the visualization settings, not just the SQL+ tool_payload = artifact_query.model_dump(mode="json", exclude_none=True)+ elif filters is not None:tool_payload = source_query.model_dump(mode="json", exclude_none=True)else:tool_payload = artifact_query.source.querydiff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 77d529245b68..b05262f8fa7f 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -1224,7 +1224,7 @@ export const productUrls = {return urls.sqlEditor({ query: query.query })}if ((isDataVisualizationNode(query) || isDataTableNode(query)) && isHogQLQuery(query.source)) {- return urls.sqlEditor({ query: query.source.query })+ return urls.sqlEditor({ query })}return combineUrl('/insights/new', dashboardId ? { dashboard: dashboardId } : {}, {...(type ? { insight: type } : {}),diff --git a/frontend/src/scenes/data-warehouse/editor/maxSqlTool.test.ts b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.test.tsindex 05bb57bb9654..3602b320de1f 100644--- a/frontend/src/scenes/data-warehouse/editor/maxSqlTool.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.test.ts@@ -1,4 +1,5 @@import { DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'+import { ChartDisplayType } from '~/types'import { applyExecuteSqlToolOutput, getExecuteSqlToolContext } from './maxSqlTool'@@ -53,6 +54,25 @@ describe('maxSqlTool', () => {},expectedSuggestedQueryInput: ['SELECT event FROM events WHERE {filters}', 'max_ai'],},+ {+ name: 'applies display and chart settings from DataVisualizationNode tool output',+ toolOutput: {+ kind: NodeKind.DataVisualizationNode,+ source: {+ kind: NodeKind.HogQLQuery,+ query: 'SELECT event, count() FROM events GROUP BY event',+ },+ display: ChartDisplayType.ActionsBar,+ chartSettings: { xAxisLabel: 'Event name' },+ },+ queryInput: 'SELECT count() FROM events',+ expectedSourceQuery: {+ ...sourceQuery,+ display: ChartDisplayType.ActionsBar,+ chartSettings: { xAxisLabel: 'Event name' },+ },+ expectedSuggestedQueryInput: ['SELECT event, count() FROM events GROUP BY event', 'max_ai'],+ },{name: 'clears filters from empty backend filters payload',toolOutput: {diff --git a/frontend/src/scenes/data-warehouse/editor/maxSqlTool.ts b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.tsindex 429d7539deb6..0cdd1cee8955 100644--- a/frontend/src/scenes/data-warehouse/editor/maxSqlTool.ts+++ b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.ts@@ -39,6 +39,8 @@ export function applyExecuteSqlToolOutput({}): void {let nextQueryInput: string | null = nulllet nextFilters: HogQLFilters | null | undefined+ let nextDisplay: DataVisualizationNode['display']+ let nextChartSettings: DataVisualizationNode['chartSettings']if (typeof toolOutput === 'string') {nextQueryInput = toolOutput@@ -56,14 +58,23 @@ export function applyExecuteSqlToolOutput({} else if (sourceOutput && 'filters' in sourceOutput) {nextFilters = (sourceOutput.filters ?? null) as HogQLFilters | null}++ if (typeof toolOutput.display === 'string') {+ nextDisplay = toolOutput.display as DataVisualizationNode['display']+ }+ if (isRecord(toolOutput.chartSettings)) {+ nextChartSettings = toolOutput.chartSettings as DataVisualizationNode['chartSettings']+ }}- if (nextFilters !== undefined) {+ if (nextFilters !== undefined || nextDisplay !== undefined || nextChartSettings !== undefined) {setSourceQuery({...sourceQuery,+ ...(nextDisplay !== undefined ? { display: nextDisplay } : {}),+ ...(nextChartSettings !== undefined ? { chartSettings: nextChartSettings } : {}),source: {...sourceQuery.source,- filters: nextFilters ?? undefined,+ ...(nextFilters !== undefined ? { filters: nextFilters ?? undefined } : {}),},})}diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 1f13d4889eb3..0cf4ded78090 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -770,6 +770,79 @@ describe('sqlEditorLogic', () => {})})+ describe('open_query URL parameter', () => {+ const STACKED_BAR_NODE: DataVisualizationNode = {+ kind: NodeKind.DataVisualizationNode,+ source: {+ kind: NodeKind.HogQLQuery,+ query: 'SELECT toStartOfDay(timestamp) AS day, event, count() FROM events GROUP BY day, event',+ },+ display: ChartDisplayType.ActionsStackedBar,+ chartSettings: { seriesBreakdownColumn: 'event' },+ }++ it('adopts visualization settings without auto-running when opening a serialized DataVisualizationNode', async () => {+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ router.actions.push(urls.insightNew({ query: STACKED_BAR_NODE }))++ // open_query is URL-controlled, so the node is prefilled but never auto-run+ await expectLogic(logic)+ .toDispatchActions(['createTab', 'setSourceQuery'])+ .toNotHaveDispatchedActions(['runQuery'])+ .toMatchValues({+ queryInput: STACKED_BAR_NODE.source.query,+ sourceQuery: partial({+ display: ChartDisplayType.ActionsStackedBar,+ chartSettings: partial({ seriesBreakdownColumn: 'event' }),+ }),+ })+ })++ it('keeps the default visualization and does not auto-run for a plain SQL string', async () => {+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ router.actions.push(urls.sqlEditor({ query: 'SELECT 1' }))++ await expectLogic(logic)+ .toDispatchActions(['createTab', 'setQueryInput'])+ .toNotHaveDispatchedActions(['runQuery'])+ .toMatchValues({+ queryInput: 'SELECT 1',+ sourceQuery: partial({ display: ChartDisplayType.Auto }),+ })+ })++ it('does not crash and falls back to an empty query for a malformed node with no source', async () => {+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ router.actions.push(urls.sqlEditor(), { open_query: { kind: NodeKind.DataVisualizationNode } })++ await expectLogic(logic)+ .toDispatchActions(['createTab'])+ .toNotHaveDispatchedActions(['setSourceQuery', 'runQuery'])+ .toMatchValues({+ queryInput: null,+ sourceQuery: partial({ display: ChartDisplayType.Auto }),+ })+ })+ })+describe('Update view', () => {it('advances the saved baseline after updating so reverting to the original query re-enables Update view', async () => {logic = sqlEditorLogic({diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 6a125014b8a9..61727629085f 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -296,7 +296,9 @@ export function toDataVisualizationNode(return undefined}if (query.kind === NodeKind.DataVisualizationNode) {- return query as DataVisualizationNode+ // A hand-crafted open_query URL can carry a node with no source; only adopt it when the HogQL source is present+ const source = (query as DataVisualizationNode).source+ return source?.kind === NodeKind.HogQLQuery ? (query as DataVisualizationNode) : undefined}// Insights created from the old DataTableNode path store the HogQLQuery under `.source`.// Wrap it so the SQL editor can render and save it through the visualization pipeline.@@ -2506,8 +2508,27 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([tabAdded = truerouter.actions.replace(urls.sqlEditor(), undefined, getTabHash(values))} else if (searchParams.open_query) {- // kea-router decodes numeric/JSON-shaped URL values to non-strings; coerce so queryInput stays a string- actions.createTab(String(searchParams.open_query))+ // kea-router decodes JSON-shaped URL values to objects — a node here carries+ // visualization settings (display, chartSettings) alongside the SQL+ const openQueryNode =+ typeof searchParams.open_query === 'object'+ ? toDataVisualizationNode(searchParams.open_query)+ : undefined+ if (openQueryNode) {+ actions.createTab(openQueryNode.source.query || '')+ actions.setSourceQuery(hasFiltersHashParam ? applyFiltersFromUrl(openQueryNode) : openQueryNode)+ if (!outputTabFromUrl) {+ actions.setActiveTab(OutputTab.Visualization)+ }+ // Prefill only, don't auto-run: open_query is fully URL-controlled, so running here+ // would let a crafted link execute arbitrary HogQL in the user's project on load+ } else {+ // kea-router also decodes numeric/JSON-shaped values; a non-node object is a+ // malformed URL, so fall back to an empty query rather than "[object Object]"+ actions.createTab(+ typeof searchParams.open_query === 'object' ? '' : String(searchParams.open_query)+ )+ }tabAdded = true} else if (hashParams.q &&diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex 388c4eceb5ae..5a16280353ed 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -3,7 +3,12 @@ import { combineUrl } from 'kea-router'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { fileSystemTypes, productUrls } from '~/products'-import { ProductKey, SharingConfigurationSettings } from '~/queries/schema/schema-general'+import {+ DataTableNode,+ DataVisualizationNode,+ ProductKey,+ SharingConfigurationSettings,+} from '~/queries/schema/schema-general'import { ActivityTab, AnnotationType, CommentType, OnboardingStepKey, SDKKey } from '~/types'import type { BillingSectionId } from './billing/types'@@ -67,7 +72,8 @@ export const urls = {connectionId,dashboard,}: {- query?: string+ /** Raw SQL, or a node whose visualization settings (display, chartSettings) should survive the trip */+ query?: string | DataVisualizationNode | DataTableNodeview_id?: stringinsightShortId?: stringdraftId?: string@@ -80,7 +86,7 @@ export const urls = {const params = new URLSearchParams()if (query) {- params.set('open_query', query)+ params.set('open_query', typeof query === 'string' ? query : JSON.stringify(query))} else if (view_id) {params.set('open_view', view_id)} else if (insightShortId) {diff --git a/products/product_analytics/manifest.tsx b/products/product_analytics/manifest.tsxindex c71f06cbf604..f750260280f7 100644--- a/products/product_analytics/manifest.tsx+++ b/products/product_analytics/manifest.tsx@@ -47,9 +47,10 @@ export const manifest: ProductManifest = {return urls.sqlEditor({ query: query.query })}- // Redirect DataNode and DataViz queries with HogQL source to SQL editor+ // Redirect DataNode and DataViz queries with HogQL source to SQL editor,+ // passing the whole node so display/chartSettings/filters survive the tripif ((isDataVisualizationNode(query) || isDataTableNode(query)) && isHogQLQuery(query.source)) {- return urls.sqlEditor({ query: query.source.query })+ return urls.sqlEditor({ query })}return combineUrl('/insights/new', dashboardId ? { dashboard: dashboardId } : {}, {