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.

fix(llma): preserve sql editor filters in max (#57619)

Marius Andra44da279822c6
diff --git a/ee/hogai/chat_agent/sql/mixins.py b/ee/hogai/chat_agent/sql/mixins.py
index 3fe127365bb6..f533f8742d7d 100644
--- a/ee/hogai/chat_agent/sql/mixins.py
+++ b/ee/hogai/chat_agent/sql/mixins.py
@@ -119,14 +119,13 @@ class HogQLOutputParserMixin(HogQLDatabaseMixin):
)
def _build_axis_formatting(self, result: RawSQLSchemaGeneratorOutput) -> ChartSettingsFormatting | None:
- if not any(
- [
- result.y_axis_format,
- result.y_axis_decimal_places is not None,
- result.y_axis_prefix,
- result.y_axis_suffix,
- ]
- ):
+ has_formatting = (
+ result.y_axis_format not in (None, Style.NONE)
+ or result.y_axis_decimal_places is not None
+ or bool(result.y_axis_prefix)
+ or bool(result.y_axis_suffix)
+ )
+ if not has_formatting:
return None
return ChartSettingsFormatting(
style=result.y_axis_format,
diff --git a/ee/hogai/chat_agent/sql/test/test_sql_mixins.py b/ee/hogai/chat_agent/sql/test/test_sql_mixins.py
index c10b7c98f91f..8ff0ae25d69f 100644
--- a/ee/hogai/chat_agent/sql/test/test_sql_mixins.py
+++ b/ee/hogai/chat_agent/sql/test/test_sql_mixins.py
@@ -79,6 +79,49 @@ class TestSQLMixins(NonAtomicBaseTest):
self.assertEqual(result.query.chartSettings.yAxis[0].column, "events")
self.assertEqual(result.query.chartSettings.yAxis[0].settings.formatting.style, "short")
+ def test_parse_output_with_none_axis_format_omits_empty_formatting(self):
+ mixin = self._node
+
+ result = mixin._parse_output(
+ {
+ "query": "SELECT toStartOfDay(timestamp) AS day, count() AS events FROM events GROUP BY day",
+ "display": "ActionsLineGraph",
+ "x_axis": "day",
+ "y_axis": ["events"],
+ "series_breakdown_column": None,
+ "y_axis_format": "none",
+ "y_axis_decimal_places": None,
+ "y_axis_prefix": None,
+ "y_axis_suffix": None,
+ "show_legend": False,
+ }
+ )
+
+ self.assertIsNone(result.query.chartSettings.yAxis[0].settings)
+
+ def test_parse_output_with_none_axis_format_preserves_other_formatting(self):
+ mixin = self._node
+
+ result = mixin._parse_output(
+ {
+ "query": "SELECT toStartOfDay(timestamp) AS day, count() AS latency FROM events GROUP BY day",
+ "display": "ActionsLineGraph",
+ "x_axis": "day",
+ "y_axis": ["latency"],
+ "series_breakdown_column": None,
+ "y_axis_format": "none",
+ "y_axis_decimal_places": 2,
+ "y_axis_prefix": None,
+ "y_axis_suffix": "ms",
+ "show_legend": False,
+ }
+ )
+
+ formatting = result.query.chartSettings.yAxis[0].settings.formatting
+ self.assertEqual(formatting.style, "none")
+ self.assertEqual(formatting.decimalPlaces, 2)
+ self.assertEqual(formatting.suffix, "ms")
+
def test_parse_output_with_empty_query(self):
"""Test parsing with empty query string."""
mixin = self._node
diff --git a/ee/hogai/context/notebook/prompts.py b/ee/hogai/context/notebook/prompts.py
index a1c9070a8656..00103a0d3097 100644
--- a/ee/hogai/context/notebook/prompts.py
+++ b/ee/hogai/context/notebook/prompts.py
@@ -13,4 +13,10 @@ ROOT_NOTEBOOKS_CONTEXT_PROMPT = """
The user has provided the following notebooks:
{{{notebooks}}}
+
+Notebook SQL editor nodes are represented as query definitions with `kind = "DataVisualizationNode"` and
+`source.kind = "HogQLQuery"`. In those nodes, `source.query` is the SQL text and `source.filters` stores date,
+test-account, and property filters that are applied through `{filters}` placeholders in the SQL. When changing the
+time range or global property filters for a notebook SQL node, preserve `{filters}` in `source.query` and update
+`source.filters` instead of replacing the placeholder with explicit SQL conditions.
""".strip()
diff --git a/ee/hogai/tools/execute_sql/prompts.py b/ee/hogai/tools/execute_sql/prompts.py
index f888c643e780..d8edddc27928 100644
--- a/ee/hogai/tools/execute_sql/prompts.py
+++ b/ee/hogai/tools/execute_sql/prompts.py
@@ -64,6 +64,15 @@ WHERE e.event IN (SELECT event FROM events WHERE ...)
# Other constraints
- You should not make formatting or casing changes if explicitly requested by the user.
- You should not use double curly braces (`{{{{` or `}}}}`) for templating. The only templating syntax allowed is single curly braces with variables in the "variables" namespace (for example: `{{{{variables.org}}}}`).<%={{{{ }}}}=%>
+- SQL editor nodes can use `{filters}` placeholders. These placeholders are backed by `HogQLQuery.filters`, not by SQL text:
+ - If the current query contains `{filters}` and the user asks to change the date range or property filters, keep the placeholder in the SQL and pass updated `filters` to this tool.
+ - When keeping `{filters}` in the SQL, pass the complete desired `filters` object to this tool. Copy `current_query_node.source.filters` unchanged unless the user asked to change or remove filters.
+ - To remove all editor filters while preserving `{filters}`, pass an empty `filters` object (`{}`).
+ - Do not replace `{filters}` with explicit `timestamp` clauses when the user's request can be represented in `filters.dateRange`.
+ - Supported filter placeholders are `{filters}`, `{filters.dateRange.from}`, and `{filters.dateRange.to}`.
+ - `{filters}` can be used only in SELECT queries that select from PostHog event-like tables: `events`, `ai_events`, `sessions`, `logs`, log attributes, traces, or `groups`. It is not valid for arbitrary data warehouse/source tables.
+ - Date filters map to `timestamp` for events/logs/traces, `$start_timestamp` for sessions, and `created_at` for groups.
+ - `filters` can include `dateRange` (`date_from`, `date_to`), `filterTestAccounts`, and `properties`. Property filters apply to event scope on event/log/trace queries, group scope on `groups`, and session scope on `sessions` unless the query also includes `events`.
- If a filter is optional, ALWAYS implement via the variables namespace with guards:
- ALWAYS use the "variables." prefix (e.g., variables.org, variables.browser) - never use bare variable names
- Use coalesce() or IS NULL checks to handle optional values
@@ -143,4 +152,13 @@ The current HogQL query (which CAN be empty) is:
<current_query>
{current_query}
</current_query>
+
+The current SQL editor query node, if available, is:
+<current_query_node>
+{current_query_node}
+</current_query_node>
+
+When `current_query_node.source.filters` exists, those filters are applied through `{filters}` placeholders in `current_query_node.source.query`.
+For notebook SQL editor nodes, the query is usually a `DataVisualizationNode` with `source.kind = "HogQLQuery"`.
+If the user asks to change "last 90 days", "test accounts", or property filters and the query contains `{filters}`, update the tool's `filters` argument instead of editing the SQL text.
""".strip()
diff --git a/ee/hogai/tools/execute_sql/test/test_tool.py b/ee/hogai/tools/execute_sql/test/test_tool.py
index 70be71fd54ef..0e965a1da9d1 100644
--- a/ee/hogai/tools/execute_sql/test/test_tool.py
+++ b/ee/hogai/tools/execute_sql/test/test_tool.py
@@ -9,6 +9,8 @@ from posthog.schema import (
AssistantToolCallMessage,
ChartDisplayType,
DataVisualizationNode,
+ DateRange,
+ HogQLFilters,
VisualizationArtifactContent,
)
@@ -141,6 +143,62 @@ class TestExecuteSQLTool(ClickhouseTestMixin, NonAtomicBaseTest):
tool_call_content = artifact_messages.messages[1].content
self.assertIn(artifact_id, tool_call_content)
+ async def test_sql_execution_preserves_filters_in_hogql_query(self) -> None:
+ _create_event(team=self.team, distinct_id="user1", event="test_event")
+ tool = await self._create_tool()
+
+ filters = HogQLFilters(dateRange=DateRange(date_from="-90d"))
+ result_text, artifact_messages = await tool._arun_impl(
+ "SELECT count() FROM events WHERE {filters}",
+ "Recent events",
+ "Events matching the editor filters",
+ filters=filters,
+ )
+
+ self.assertEqual(result_text, "")
+ self.assertIsNotNone(artifact_messages)
+
+ artifact_id = artifact_messages.messages[0].artifact_id
+ self.assertIsNotNone(artifact_id)
+ artifact = await AgentArtifact.objects.aget(short_id=artifact_id, team=self.team)
+ content = VisualizationArtifactContent.model_validate(artifact.data)
+
+ self.assertIsInstance(content.query, DataVisualizationNode)
+ assert isinstance(content.query, DataVisualizationNode)
+ self.assertEqual(content.query.source.filters, filters)
+
+ tool_call_message = artifact_messages.messages[1]
+ self.assertIsInstance(tool_call_message, AssistantToolCallMessage)
+ 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["query"], "SELECT count() FROM events WHERE {filters}")
+ self.assertEqual(payload["filters"]["dateRange"]["date_from"], "-90d")
+
+ async def test_sql_execution_returns_empty_filters_payload(self) -> None:
+ _create_event(team=self.team, distinct_id="user1", event="test_event")
+ tool = await self._create_tool()
+
+ result_text, artifact_messages = await tool._arun_impl(
+ "SELECT count() FROM events WHERE {filters}",
+ "Recent events",
+ "Events matching the editor filters",
+ filters=HogQLFilters(),
+ )
+
+ self.assertEqual(result_text, "")
+ self.assertIsNotNone(artifact_messages)
+
+ tool_call_message = artifact_messages.messages[1]
+ self.assertIsInstance(tool_call_message, AssistantToolCallMessage)
+ 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["query"], "SELECT count() FROM events WHERE {filters}")
+ self.assertEqual(payload["filters"], {})
+
@patch("posthoganalytics.feature_enabled", new=Mock(return_value=True))
async def test_select_from_system_insights(self):
await sync_to_async(Insight.objects.create)(
diff --git a/ee/hogai/tools/execute_sql/tool.py b/ee/hogai/tools/execute_sql/tool.py
index 87fc8daeb4b5..3a35a019e648 100644
--- a/ee/hogai/tools/execute_sql/tool.py
+++ b/ee/hogai/tools/execute_sql/tool.py
@@ -13,6 +13,7 @@ from posthog.schema import (
ChartDisplayType,
ChartSettings,
DataVisualizationNode,
+ HogQLFilters,
VisualizationArtifactContent,
)
@@ -43,6 +44,15 @@ from .prompts import (
class ExecuteSQLToolArgs(BaseModel):
query: str = Field(description="The final SQL query to be executed.")
+ filters: HogQLFilters | None = Field(
+ default=None,
+ description=(
+ "Optional filters applied through `{filters}` placeholders in the query. "
+ "Use this when editing a SQL editor query that already uses `{filters}` and the user asks to change "
+ "dateRange, property filters, or test-account filtering. Set this to an empty object to clear existing "
+ "SQL editor filters while preserving the `{filters}` placeholder."
+ ),
+ )
viz_title: str = Field(
description="Short, concise name of the SQL query (2-5 words) that will be displayed as a header in the visualization."
)
@@ -88,6 +98,7 @@ class ExecuteSQLTool(HogQLGeneratorMixin, MaxTool):
query: str,
viz_title: str,
viz_description: str,
+ filters: HogQLFilters | None = None,
display: AssistantDataVisualizationDisplayType | None = None,
chart_settings: AssistantDataVisualizationChartSettings | dict[str, object] | None = None,
) -> tuple[str, ToolMessagesArtifact | None]:
@@ -99,7 +110,12 @@ class ExecuteSQLTool(HogQLGeneratorMixin, MaxTool):
except PydanticOutputParserException as e:
return format_prompt_string(EXECUTE_SQL_RECOVERABLE_ERROR_PROMPT, error=str(e)), None
- artifact_query = parsed_query.query
+ source_query = (
+ parsed_query.query.source.model_copy(update={"filters": filters})
+ if filters is not None
+ else parsed_query.query.source
+ )
+ artifact_query = parsed_query.query.model_copy(update={"source": source_query})
if display or chart_settings:
if isinstance(chart_settings, AssistantDataVisualizationChartSettings):
chart_settings_data = chart_settings.model_dump(mode="json", exclude_none=True)
@@ -111,7 +127,7 @@ class ExecuteSQLTool(HogQLGeneratorMixin, MaxTool):
chart_settings_data = None
artifact_query = DataVisualizationNode(
- source=parsed_query.query.source,
+ source=source_query,
display=ChartDisplayType(display) if display else None,
chartSettings=ChartSettings.model_validate(chart_settings_data) if chart_settings_data else None,
)
@@ -129,7 +145,7 @@ class ExecuteSQLTool(HogQLGeneratorMixin, MaxTool):
insight_context = InsightContext(
team=self._team,
- query=parsed_query.query,
+ query=artifact_query,
name=viz_title,
description=viz_description,
insight_id=artifact_message.artifact_id,
@@ -143,6 +159,12 @@ class ExecuteSQLTool(HogQLGeneratorMixin, MaxTool):
except Exception:
return EXECUTE_SQL_UNRECOVERABLE_ERROR_PROMPT, None
+ tool_payload: str | dict[str, object]
+ if filters is not None:
+ tool_payload = source_query.model_dump(mode="json", exclude_none=True)
+ else:
+ tool_payload = artifact_query.source.query
+
return "", ToolMessagesArtifact(
messages=[
artifact_message,
@@ -150,7 +172,7 @@ class ExecuteSQLTool(HogQLGeneratorMixin, MaxTool):
content=result,
id=str(uuid4()),
tool_call_id=self.tool_call_id,
- ui_payload={self.get_name(): parsed_query.query.source.query},
+ ui_payload={self.get_name(): tool_payload},
),
]
)
diff --git a/ee/hogai/tools/read_data/prompts.py b/ee/hogai/tools/read_data/prompts.py
index 44bc22e6d3dd..66a7172e3e65 100644
--- a/ee/hogai/tools/read_data/prompts.py
+++ b/ee/hogai/tools/read_data/prompts.py
@@ -73,6 +73,7 @@ Retrieves a saved notebook by its short ID. Returns the notebook content as simp
## Output format:
The notebook content is returned as simplified markdown. Insight visualizations are represented as `<insight>` tags with their query definition. Session replays are represented as `<session_replay>` tags with the session ID.
+Notebook SQL editor nodes are represented as `DataVisualizationNode` query definitions with a `HogQLQuery` source. For these nodes, `source.query` is the SQL text and `source.filters` is applied through `{filters}` placeholders.
# Feature flag
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
index d15b3b817998..a5348a128d72 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
@@ -28,6 +28,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { FixErrorButton } from './components/FixErrorButton'
import { ConnectionSelector } from './ConnectionSelector'
import { editorSizingLogic } from './editorSizingLogic'
+import { applyExecuteSqlToolOutput, getExecuteSqlToolContext } from './maxSqlTool'
import { OutputPane } from './OutputPane'
import { QueryFiltersMenu } from './QueryFiltersMenu'
import { QueryPane } from './QueryPane'
@@ -87,6 +88,7 @@ export function QueryWindow({
setMetadataLoading,
setSendRawQuery,
openMaterializationModal,
+ setSourceQuery,
} = useActions(logic)
const { setSuggestedQueryInput, reportAIQueryPromptOpen } = useActions(logic)
@@ -211,15 +213,19 @@ export function QueryWindow({
buttonClassName="size-[26px]"
maxToolProps={{
identifier: 'execute_sql',
- context: {
- current_query: queryInput,
- },
+ context: getExecuteSqlToolContext(queryInput, sourceQuery),
contextDescription: {
text: 'Current query',
icon: iconForType('sql_editor'),
},
- callback: (toolOutput: string) => {
- setSuggestedQueryInput(toolOutput, 'max_ai')
+ callback: (toolOutput: unknown) => {
+ applyExecuteSqlToolOutput({
+ toolOutput,
+ queryInput,
+ sourceQuery,
+ setSourceQuery,
+ setSuggestedQueryInput,
+ })
},
suggestions: [],
onMaxOpen: () => {
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index c9a6fa05932a..a4310768b0e2 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -36,6 +36,7 @@ import { ViewLinkModal } from '../ViewLinkModal'
import { connectionSelectorLogic } from './connectionSelectorLogic'
import { editorSceneLogic } from './editorSceneLogic'
import { editorSizingLogic } from './editorSizingLogic'
+import { applyExecuteSqlToolOutput, getExecuteSqlToolContext } from './maxSqlTool'
import { QueryInfo } from './output-pane-tabs/QueryInfo'
import { OutputPane } from './OutputPane'
import { outputPaneLogic } from './outputPaneLogic'
@@ -310,6 +311,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
saveAsInsight,
saveAsView,
saveAsEndpoint,
+ setSourceQuery,
setSuggestedQueryInput,
reportAIQueryPromptOpen,
} = useActions(sqlEditorLogic)
@@ -408,15 +410,19 @@ function SQLEditorSceneTitle(): JSX.Element | null {
{...titleSectionProps}
maxToolProps={{
identifier: 'execute_sql',
- context: {
- current_query: queryInput,
- },
+ context: getExecuteSqlToolContext(queryInput, sourceQuery),
contextDescription: {
text: 'Current query',
icon: iconForType('sql_editor'),
},
- callback: (toolOutput: string) => {
- setSuggestedQueryInput(toolOutput, 'max_ai')
+ callback: (toolOutput: unknown) => {
+ applyExecuteSqlToolOutput({
+ toolOutput,
+ queryInput,
+ sourceQuery,
+ setSourceQuery,
+ setSuggestedQueryInput,
+ })
},
suggestions: [],
onMaxOpen: () => {
diff --git a/frontend/src/scenes/data-warehouse/editor/maxSqlTool.test.ts b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.test.ts
new file mode 100644
index 000000000000..05bb57bb9654
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.test.ts
@@ -0,0 +1,97 @@
+import { DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'
+
+import { applyExecuteSqlToolOutput, getExecuteSqlToolContext } from './maxSqlTool'
+
+describe('maxSqlTool', () => {
+ const sourceQuery: DataVisualizationNode = {
+ kind: NodeKind.DataVisualizationNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: 'SELECT count() FROM events WHERE {filters}',
+ filters: { dateRange: { date_from: '-30d' } },
+ response: { results: [] },
+ },
+ response: undefined,
+ }
+
+ it('passes a query node without response payloads as context', () => {
+ const context = getExecuteSqlToolContext('SELECT 1', sourceQuery)
+
+ expect(context.current_query).toEqual('SELECT 1')
+ expect(context.current_query_node).toEqual({
+ kind: NodeKind.DataVisualizationNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: 'SELECT count() FROM events WHERE {filters}',
+ filters: { dateRange: { date_from: '-30d' } },
+ },
+ })
+ })
+
+ it.each([
+ {
+ name: 'handles legacy string tool output',
+ toolOutput: 'SELECT event FROM events',
+ queryInput: 'SELECT count() FROM events',
+ expectedSourceQuery: null,
+ expectedSuggestedQueryInput: ['SELECT event FROM events', 'max_ai'],
+ },
+ {
+ name: 'applies filters from HogQL query tool output',
+ toolOutput: {
+ kind: NodeKind.HogQLQuery,
+ query: 'SELECT event FROM events WHERE {filters}',
+ filters: { dateRange: { date_from: '-90d' } },
+ },
+ queryInput: 'SELECT count() FROM events WHERE {filters}',
+ expectedSourceQuery: {
+ ...sourceQuery,
+ source: {
+ ...sourceQuery.source,
+ filters: { dateRange: { date_from: '-90d' } },
+ },
+ },
+ expectedSuggestedQueryInput: ['SELECT event FROM events WHERE {filters}', 'max_ai'],
+ },
+ {
+ name: 'clears filters from empty backend filters payload',
+ toolOutput: {
+ kind: NodeKind.HogQLQuery,
+ query: 'SELECT count() FROM events WHERE {filters}',
+ filters: {},
+ },
+ queryInput: 'SELECT count() FROM events WHERE {filters}',
+ expectedSourceQuery: {
+ ...sourceQuery,
+ source: {
+ ...sourceQuery.source,
+ filters: {},
+ },
+ },
+ expectedSuggestedQueryInput: null,
+ },
+ ])('$name', ({ toolOutput, queryInput, expectedSourceQuery, expectedSuggestedQueryInput }) => {
+ const setSourceQuery = jest.fn()
+ const setSuggestedQueryInput = jest.fn()
+
+ applyExecuteSqlToolOutput({
+ toolOutput,
+ queryInput,
+ sourceQuery,
+ setSourceQuery,
+ setSuggestedQueryInput,
+ })
+
+ if (expectedSourceQuery) {
+ expect(setSourceQuery).toHaveBeenCalledWith(expectedSourceQuery)
+ } else {
+ expect(setSourceQuery).not.toHaveBeenCalled()
+ }
+
+ if (expectedSuggestedQueryInput) {
+ expect(setSuggestedQueryInput).toHaveBeenCalledWith(...expectedSuggestedQueryInput)
+ } else {
+ expect(setSuggestedQueryInput).not.toHaveBeenCalled()
+ }
+ })
+})
diff --git a/frontend/src/scenes/data-warehouse/editor/maxSqlTool.ts b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.ts
new file mode 100644
index 000000000000..429d7539deb6
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.ts
@@ -0,0 +1,74 @@
+import type { DataVisualizationNode, HogQLFilters } from '~/queries/schema/schema-general'
+
+type SetSourceQuery = (sourceQuery: DataVisualizationNode) => void
+type SetSuggestedQueryInput = (suggestedQueryInput: string, source?: 'max_ai') => void
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function getCurrentQueryNodeContext(sourceQuery: DataVisualizationNode): DataVisualizationNode {
+ const currentQueryNode = { ...sourceQuery, source: { ...sourceQuery.source } }
+ delete currentQueryNode.response
+ delete currentQueryNode.source.response
+ return currentQueryNode
+}
+
+export function getExecuteSqlToolContext(
+ queryInput: string | null,
+ sourceQuery: DataVisualizationNode
+): Record<string, unknown> {
+ return {
+ current_query: queryInput,
+ current_query_node: getCurrentQueryNodeContext(sourceQuery),
+ }
+}
+
+export function applyExecuteSqlToolOutput({
+ toolOutput,
+ queryInput,
+ sourceQuery,
+ setSourceQuery,
+ setSuggestedQueryInput,
+}: {
+ toolOutput: unknown
+ queryInput: string | null
+ sourceQuery: DataVisualizationNode
+ setSourceQuery: SetSourceQuery
+ setSuggestedQueryInput: SetSuggestedQueryInput
+}): void {
+ let nextQueryInput: string | null = null
+ let nextFilters: HogQLFilters | null | undefined
+
+ if (typeof toolOutput === 'string') {
+ nextQueryInput = toolOutput
+ } else if (isRecord(toolOutput)) {
+ const sourceOutput = isRecord(toolOutput.source) ? toolOutput.source : null
+
+ if (typeof toolOutput.query === 'string') {
+ nextQueryInput = toolOutput.query
+ } else if (sourceOutput && typeof sourceOutput.query === 'string') {
+ nextQueryInput = sourceOutput.query
+ }
+
+ if ('filters' in toolOutput) {
+ nextFilters = (toolOutput.filters ?? null) as HogQLFilters | null
+ } else if (sourceOutput && 'filters' in sourceOutput) {
+ nextFilters = (sourceOutput.filters ?? null) as HogQLFilters | null
+ }
+ }
+
+ if (nextFilters !== undefined) {
+ setSourceQuery({
+ ...sourceQuery,
+ source: {
+ ...sourceQuery.source,
+ filters: nextFilters ?? undefined,
+ },
+ })
+ }
+
+ if (nextQueryInput !== null && nextQueryInput !== queryInput) {
+ setSuggestedQueryInput(nextQueryInput, 'max_ai')
+ }
+}
diff --git a/packages/quill/packages/primitives/src/autocomplete.stories.tsx b/packages/quill/packages/primitives/src/autocomplete.stories.tsx
index 602b7ca52d8b..57402edaa8bc 100644
--- a/packages/quill/packages/primitives/src/autocomplete.stories.tsx
+++ b/packages/quill/packages/primitives/src/autocomplete.stories.tsx
@@ -261,7 +261,7 @@ export const CommandPalette: Story = {
<span className="font-mono ml-auto text-xs text-muted-foreground/80">
2 days ago
</span>
-
+
</AutocompleteItem>
)}
</AutocompleteCollection>
@@ -351,7 +351,7 @@ export const CommandPaletteCustomEmpty: Story = {
<span className="font-mono ml-auto text-xs text-muted-foreground/80">
2 days ago
</span>
-
+
</AutocompleteItem>
)}
</AutocompleteCollection>