: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
feat(hogql): render named icons in query results (#118105)
Paul D'Ambra88b88608444e
diff --git a/frontend/__snapshots__/queries-datatable-expliciticon--query-result--dark.png b/frontend/__snapshots__/queries-datatable-expliciticon--query-result--dark.pngnew file mode 100644index 000000000000..712b7b416504Binary files /dev/null and b/frontend/__snapshots__/queries-datatable-expliciticon--query-result--dark.png differdiff --git a/frontend/__snapshots__/queries-datatable-expliciticon--query-result--light.png b/frontend/__snapshots__/queries-datatable-expliciticon--query-result--light.pngnew file mode 100644index 000000000000..99d40d2b37e8Binary files /dev/null and b/frontend/__snapshots__/queries-datatable-expliciticon--query-result--light.png differdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 616afb37858b..375fce70e745 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8334,6 +8334,18 @@ snapshots:hash: v1.k794b7964.ded75abe4e8eb09bccf9b970188d13b022bf0c43636e887273791b72a4636ee2.R28mwGSEfFH1ZxrFl4cRA-zpg5RprlDTRSu96cg-v20products-workflows-template-card--picker--light:hash: v1.k794b7964.59e165d7ede2cc4e3138b95c64a7329134a16e722ff2fe224f8bf700e81d544c.SRWbL89CbOMgwObgHB8qGt_63Lh4SB0-2of7YS3PlQw+ queries-datatable-expliciticon--customer-images--narrow--dark:+ hash: v1.k794b7964.41a7805bb6fc2e8f2e3798e91b604104570b3b6416742fd1bb63da8f828e3b62.ImiJjFjF3t9w1AwEEia8WL3DfZPHacEJhvrLFQiHqW4+ queries-datatable-expliciticon--customer-images--narrow--light:+ hash: v1.k794b7964.eac1e33c6cd586e55422c5f38ed8aa8ce5373bae559e7eb84f08556cb97fab76.nvDSd91SUsazbCuyRc7Ro4Kmq1Id9LTr7IhF18UI5Q4+ queries-datatable-expliciticon--customer-images--wide--dark:+ hash: v1.k794b7964.41a7805bb6fc2e8f2e3798e91b604104570b3b6416742fd1bb63da8f828e3b62.v7Rc9dDICqUiCrmf98uvK8Y7nGwyX5XjVB8eq6L5Keg+ queries-datatable-expliciticon--customer-images--wide--light:+ hash: v1.k794b7964.eac1e33c6cd586e55422c5f38ed8aa8ce5373bae559e7eb84f08556cb97fab76.UqzUQGKvzjtyo0aDmeVf8bhhDNUZzeaEoiFaO6Snw-A+ queries-datatable-expliciticon--query-result--dark:+ hash: v1.k794b7964.cc3f4b4df15bd7680a9b679ca3a94ee2f2b5b8280b54804b2d660a1d51f53dca.0OslRLTIOrEEAmg3MSk_Xp4XRYkH8Y73Svwhz78Wje4+ queries-datatable-expliciticon--query-result--light:+ hash: v1.k794b7964.df833adef5b5670cedd05e7cc282cdb04e65401492d9fc030a6437201561ec82.f8E44DPoHhYMUvejnRmIcNnheMKdiSRMa_5GdLCupY8queries-webvitals--web-vitals--dark:hash: v1.k794b7964.2ae778a0c5fdba3c69dfcbd3e9589c3c3d9cc2f0fef2eefd304c565be7e9a7c9.hH71byl33sIAdRCgaPk1lDOev0qooW1xhv0AL_yrIvgqueries-webvitals--web-vitals--light:@@ -10250,6 +10262,10 @@ snapshots:hash: v1.k794b7964.29a6892f69408e75d2bcdae29d497728fde99162145970d71f8eb360c496e3f0.o9tf11AX8PLroocZlorxrzHmh47URcAZrYIxqcH7kKoscenes-app-data-warehouse-sql-editor--bi-table-analysis--light:hash: v1.k794b7964.dbf2cf1ce2e9f86054f7dddb2cbe184dafef8fee54792354aba104f1b8edecba.qbtA2DIHLtYHtxUnH9FjPmnfkr6nie7aEyVjAfCSC3c+ scenes-app-data-warehouse-sql-editor--customer-images--dark:+ hash: v1.k794b7964.10b9dd73c78556d1b3990ff4ba8d0872e17f375ed655c487b3ca9ca8af21c665.K_W25GnvkQUo791SarbtGIBFaySZ0v_Ebd4cv6sJhsQ+ scenes-app-data-warehouse-sql-editor--customer-images--light:+ hash: v1.k794b7964.ce993f3850f54ddccef58a05eceb9e2c97aa9a55a10c79ccec026ab34b41ef2c.wKHSElvN1JjL3MGp2vC9ReSCbeinqDlJse66vWOjUDMscenes-app-data-warehouse-sql-editor--edited-insight--dark:hash: v1.k794b7964.4e81f33deba8184b2e4d8c90c20967f98d4cfac08a1903c8b1805604ad94983f.ZI5eb066W3jZYoEroMzzCE08QMOQvQmyTaxzxOZey88scenes-app-data-warehouse-sql-editor--edited-insight--light:diff --git a/frontend/src/queries/nodes/DataTable/ExplicitIcon.stories.tsx b/frontend/src/queries/nodes/DataTable/ExplicitIcon.stories.tsxnew file mode 100644index 000000000000..781fb20c286a--- /dev/null+++ b/frontend/src/queries/nodes/DataTable/ExplicitIcon.stories.tsx@@ -0,0 +1,57 @@+import type { Meta, StoryObj } from '@storybook/react'++import { DataTable } from '~/queries/nodes/DataTable/DataTable'+import { IMAGE_QUERY, IMAGE_RESULTS } from '~/queries/nodes/HogQLX/image.fixtures'+import { DataTableNode, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'++const query: DataTableNode = {+ kind: NodeKind.DataTableNode,+ source: {+ kind: NodeKind.HogQLQuery,+ query: "SELECT withIcon('Claude Code', 'Claude') AS client, 12 AS calls UNION ALL SELECT withIcon('OpenAI Codex', 'OpenAI'), 7",+ },+}++const cachedResults: HogQLQueryResponse = {+ columns: ['client', 'calls'],+ types: ['Tuple', 'UInt64'],+ results: [+ [['__hx_tag', 'BrandMarkLabel', 'label', 'Claude Code', 'mark', 'Claude'], 12],+ [['__hx_tag', 'BrandMarkLabel', 'label', 'OpenAI Codex', 'mark', 'OpenAI'], 7],+ ],+}++const meta: Meta<typeof DataTable> = {+ title: 'Queries/DataTable/ExplicitIcon',+ component: DataTable,+ parameters: {+ testOptions: { waitForSelector: '[data-attr="hogqlx-brand-mark-label"]' },+ },+}++export default meta++export const QueryResult: StoryObj<typeof DataTable> = {+ render: () => (+ <div className="p-4">+ <DataTable query={query} setQuery={() => {}} cachedResults={cachedResults} readOnly />+ </div>+ ),+}++export const CustomerImages: StoryObj<typeof DataTable> = {+ tags: ['hogqlx-images'],+ parameters: {+ testOptions: { waitForSelector: 'img[alt="Custom SVG"]', viewportWidths: ['narrow', 'wide'] },+ },+ render: () => (+ <div className="p-4">+ <DataTable+ query={{ kind: NodeKind.DataTableNode, source: { kind: NodeKind.HogQLQuery, query: IMAGE_QUERY } }}+ setQuery={() => {}}+ cachedResults={IMAGE_RESULTS}+ readOnly+ />+ </div>+ ),+}diff --git a/frontend/src/queries/nodes/HogQLX/image.fixtures.ts b/frontend/src/queries/nodes/HogQLX/image.fixtures.tsnew file mode 100644index 000000000000..bde18e77a2a4--- /dev/null+++ b/frontend/src/queries/nodes/HogQLX/image.fixtures.ts@@ -0,0 +1,43 @@+import type { HogQLQueryResponse } from '~/queries/schema/schema-general'++const svgSource = `data:image/svg+xml,${encodeURIComponent(+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="#e87722"/><path d="M7 12h10M12 7v10" stroke="white" stroke-width="2"/></svg>'+)}`+const pngSource =+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAJUlEQVR4nGNgGAWDDig0LPhPCR61YNSCUQtGLRi1YHhYMAroDgC3sz8f5SN7GwAAAABJRU5ErkJggg=='++export const IMAGE_QUERY = `SELECT+ <img src='${svgSource}' alt='Custom SVG' width={128} height={128} /> AS image,+ 'SVG logo' AS name,+ 12 AS calls,+ withIcon(toBool(1), 'Claude') AS status+UNION ALL SELECT+ <img src='${pngSource}' alt='Custom PNG' width={24} height={24} />,+ 'PNG logo',+ 7,+ withIcon(toBool(0), 'Claude')`++export const IMAGE_RESULTS: HogQLQueryResponse = {+ columns: ['image', 'name', 'calls', 'status'],+ types: [+ ['image', 'Tuple(String, String, String, String, String, String, String, UInt8, String, UInt8)'],+ ['name', 'String'],+ ['calls', 'UInt8'],+ ['status', 'Tuple(String, String, String, Nullable(Bool), String, String)'],+ ],+ results: [+ [+ ['__hx_tag', 'img', 'src', svgSource, 'alt', 'Custom SVG', 'width', 128, 'height', 128],+ 'SVG logo',+ 12,+ ['__hx_tag', 'BrandMarkLabel', 'label', true, 'mark', 'Claude'],+ ],+ [+ ['__hx_tag', 'img', 'src', pngSource, 'alt', 'Custom PNG', 'width', 24, 'height', 24],+ 'PNG logo',+ 7,+ ['__hx_tag', 'BrandMarkLabel', 'label', false, 'mark', 'Claude'],+ ],+ ],+ hasMore: false,+}diff --git a/frontend/src/queries/nodes/HogQLX/image.ts b/frontend/src/queries/nodes/HogQLX/image.tsnew file mode 100644index 000000000000..f72808eb44a6--- /dev/null+++ b/frontend/src/queries/nodes/HogQLX/image.ts@@ -0,0 +1,25 @@+import { isUUIDLike } from 'lib/utils/guards'+import { clamp } from 'lib/utils/numbers'++const MAX_IMAGE_SOURCE_LENGTH = 64 * 1024+const MAX_IMAGE_DIMENSION = 24+const DATA_IMAGE_SOURCE = /^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)(;(charset=utf-8|utf8))?(;base64)?,/i+// Other same-origin paths can redirect off-site, so only the uploaded media route, which serves bytes, is allowed.+const UPLOADED_MEDIA_PREFIX = '/uploaded_media/'++export function imageSource(value: unknown): string | null {+ if (typeof value !== 'string' || value.length > MAX_IMAGE_SOURCE_LENGTH) {+ return null+ }+ if (DATA_IMAGE_SOURCE.test(value)) {+ return value+ }+ return value.startsWith(UPLOADED_MEDIA_PREFIX) && isUUIDLike(value.slice(UPLOADED_MEDIA_PREFIX.length))+ ? value+ : null+}++export function imageDimension(value: unknown): number {+ const size = typeof value === 'number' || typeof value === 'string' ? Number(value) : NaN+ return Number.isFinite(size) && size > 0 ? clamp(size, 0, MAX_IMAGE_DIMENSION) : MAX_IMAGE_DIMENSION+}diff --git a/frontend/src/queries/nodes/HogQLX/render.test.tsx b/frontend/src/queries/nodes/HogQLX/render.test.tsxindex 200ede0fa9cb..c2bc5617f1f2 100644--- a/frontend/src/queries/nodes/HogQLX/render.test.tsx+++ b/frontend/src/queries/nodes/HogQLX/render.test.tsx@@ -1,3 +1,7 @@+import '@testing-library/jest-dom'++import { render } from '@testing-library/react'+import { parseHogQLX, renderHogQLX } from '~/queries/nodes/HogQLX/render'describe('HogQLX', () => {@@ -61,6 +65,101 @@ describe('HogQLX', () => {})describe('render', () => {+ it.each([+ '/uploaded_media/0190f5a2-3b4c-7d8e-9f01-23456789abcd',+ 'data:image/png;base64,aGVsbG8=',+ 'data:image/svg+xml,%3Csvg%20xmlns="http://www.w3.org/2000/svg"/%3E',+ 'data:image/svg+xml;charset=utf-8,%3Csvg/%3E',+ 'data:image/svg+xml;utf8,%3Csvg/%3E',+ 'data:image/svg+xml;base64,PHN2Zy8+',+ ])('renders an image from %s', (src) => {+ const { container } = render(+ renderHogQLX(['__hx_tag', 'img', 'src', src, 'alt', 'Customer logo', 'width', 24, 'height', 16])+ )+ const image = container.querySelector('img')+ expect(image).toHaveAttribute('src', src)+ expect(image).toHaveAttribute('alt', 'Customer logo')+ expect(image).toHaveStyle({ width: '24px', height: '16px' })+ })++ it.each([+ null,+ { toString: 'bad' },+ 'javascript:alert(1)',+ 'https://example.com/logo.svg',+ '/uploaded/logo.png',+ '/oauth/authorize?redirect_uri=https%3A%2F%2Fexample.com',+ '/uploaded_media/0190f5a2-3b4c-7d8e-9f01-23456789abcd' + '?next=https://example.com',+ '/uploaded_media/../oauth/authorize',+ 'http://example.com/logo.png',+ '//example.com/logo.png',+ '/\\example.com/logo.png',+ 'data:text/html,<svg onload="alert(1)"/>',+ 'data:image/svg+xml,' + 'a'.repeat(64 * 1024),+ ])('does not load an invalid image source (%#)', (src) => {+ const { container } = render(renderHogQLX({ __hx_tag: 'img', src, alt: 'Customer logo' }))+ expect(container.querySelector('img')).toBeNull()+ expect(container.textContent).toBe('Customer logo')+ })++ it.each([+ [undefined, 24],+ ['24', 24],+ [128, 24],+ [16, 16],+ [10000, 24],+ [-1, 24],+ [0, 24],+ ['100%', 24],+ [{ toString: 'bad' }, 24],+ ])('bounds image dimensions (%#)', (size, expected) => {+ const { container } = render(+ renderHogQLX({ __hx_tag: 'img', src: 'data:image/png;base64,aGVsbG8=', width: size, height: size })+ )+ expect(container.querySelector('img')).toHaveStyle({ width: `${expected}px`, height: `${expected}px` })+ })++ it('only forwards allowed image attributes', () => {+ const { container } = render(+ renderHogQLX({+ __hx_tag: 'img',+ src: 'data:image/png;base64,aGVsbG8=',+ alt: { toString: 'bad' },+ onload: 'alert(1)',+ srcSet: 'https://example.com/other.svg 2x',+ style: { width: 10000 },+ children: '<svg onload="alert(1)"/>',+ })+ )+ const image = container.querySelector('img')+ expect(image).toHaveAttribute('alt', '')+ expect(image).not.toHaveAttribute('onload')+ expect(image).not.toHaveAttribute('srcset')+ expect(image).toHaveStyle({ width: '24px' })+ expect(container.querySelector('svg')).toBeNull()+ })++ it.each(['Claude', 'Unknown mark', 'constructor', 'toString', '__proto__'])(+ 'renders a query label with %s mark',+ (mark) => {+ const { container } = render(+ renderHogQLX(['__hx_tag', 'BrandMarkLabel', 'label', 'Claude Code', 'mark', mark])+ )++ expect(container.textContent).toContain('Claude Code')+ expect(container.querySelector('svg')).not.toBeNull()+ }+ )++ it.each([+ ['label', { toString: 'bad' }, 'Claude'],+ ['mark', 'Claude Code', { toString: 'bad' }],+ ])('does not throw for an object %s', (_, label, mark) => {+ const { container } = render(renderHogQLX({ __hx_tag: 'BrandMarkLabel', label, mark }))+ expect(container.textContent).toBe(typeof label === 'string' ? label : '')+ expect(container.querySelector('svg') !== null).toBe(typeof label === 'string')+ })+it('should render Sparkline', () => {const value = {__hx_tag: 'Sparkline',diff --git a/frontend/src/queries/nodes/HogQLX/render.tsx b/frontend/src/queries/nodes/HogQLX/render.tsxindex 7ae986054cc2..e063f077dfc7 100644--- a/frontend/src/queries/nodes/HogQLX/render.tsx+++ b/frontend/src/queries/nodes/HogQLX/render.tsx@@ -10,6 +10,10 @@ import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecimport { LightErrorBoundary } from '~/layout/ErrorBoundary/ErrorBoundary'+import { BrandMarkLabel } from 'products/mcp_analytics/frontend/components/BrandMarkLabel'++import { imageDimension, imageSource } from './image'+// NB!!! Sync this list with posthog/hogql/hogqlx.py// These tags only get the `key` and `children` attributes.const HOGQLX_TAGS_NO_ATTRIBUTES = [@@ -58,6 +62,16 @@ export function parseHogQLX(value: any): any {return value.map((v) => parseHogQLX(v))}+function primitiveString(value: unknown): string | null {+ if (value == null) {+ return ''+ }+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {+ return String(value)+ }+ return null+}+export function renderHogQLX(value: any): JSX.Element {const object = parseHogQLX(value)@@ -124,6 +138,32 @@ export function renderHogQLX(value: any): JSX.Element {/></LightErrorBoundary>)+ } else if (tag === 'BrandMarkLabel') {+ const label = primitiveString(rest.label)+ if (label === null) {+ return <></>+ }+ return (+ <LightErrorBoundary>+ <BrandMarkLabel label={label} mark={primitiveString(rest.mark) ?? ''} />+ </LightErrorBoundary>+ )+ } else if (tag === 'img') {+ const src = imageSource(rest.src)+ const alt = typeof rest.alt === 'string' ? rest.alt : ''+ if (!src) {+ return <>{alt}</>+ }+ return (+ <img+ src={src}+ alt={alt}+ style={{ width: imageDimension(rest.width), height: imageDimension(rest.height) }}+ className="inline-block max-w-full object-contain align-middle"+ loading="lazy"+ decoding="async"+ />+ )} else if (tag === 'a') {const { href, children, source, target } = restconst value = children ?? sourcediff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsxindex b5a3429c268f..185a0ca5e34c 100644--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx@@ -761,7 +761,7 @@ export function OutputPane({ tabId, showToolbar = true, biMode = false, onShareT}// Hack to get bools to render in the data grid- if (type && type.indexOf('Bool') !== -1) {+ if (cleanClickhouseType(type) === 'Bool') {return {...baseColumn,renderCell: (props: any) => {diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsxindex a4e83b92b9dd..cbe6eb2023ca 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx@@ -14,6 +14,7 @@ import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'import type { MockResolverInfo } from '~/mocks/utils'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { IMAGE_QUERY, IMAGE_RESULTS } from '~/queries/nodes/HogQLX/image.fixtures'import { BIConfig, BIField } from '~/queries/schema/schema-business-intelligence'import {DatabaseSchemaMaterializedViewTable,@@ -207,6 +208,40 @@ export default metatype Story = StoryObj<{}>export const TopToolsPerServer: Story = {}+export const CustomerImages: Story = {+ tags: ['hogqlx-images'],+ parameters: {+ pageUrl: urls.sqlEditor({ query: IMAGE_QUERY }),+ testOptions: { waitForSelector: 'img[alt="Custom SVG"]', viewport: { width: 1600, height: 900 } },+ msw: {+ mocks: {+ post: {+ '/api/environments/:team_id/query/HogQLQuery/': IMAGE_RESULTS,+ },+ },+ },+ },+ play: async ({ canvasElement }) => {+ const editor = sqlEditorLogic({ tabId: 'default' })+ await waitFor(() => {+ expect(editor.values.queryInput).toBe(IMAGE_QUERY)+ expect(dataNodeLogic.findMounted({ key: editor.values.dataLogicKey })).toBeDefined()+ })+ const runButton = canvasElement.querySelector('[data-attr="sql-editor-run-button"]')+ expect(runButton).not.toBeNull()+ await userEvent.click(runButton!)+ await waitFor(() => {+ const image = canvasElement.querySelector('img[alt="Custom SVG"]')+ expect(image).not.toBeNull()+ expect(image!.getBoundingClientRect().height).toBeLessThanOrEqual(24)+ const labels = canvasElement.querySelectorAll('[data-attr="hogqlx-brand-mark-label"]')+ expect(Array.from(labels, (label) => label.textContent)).toEqual(['true', 'false'])+ })+ const dataLogic = dataNodeLogic.findMounted({ key: editor.values.dataLogicKey })!+ dataLogic.actions.setElapsedTime(180)+ },+}+export const HostedTrino: Story = {parameters: {featureFlags: [FEATURE_FLAGS.MANAGED_TRINO_QUERY],diff --git a/posthog/hogql/functions/__init__.py b/posthog/hogql/functions/__init__.pyindex 9bae132b0cce..369e1b1a8771 100644--- a/posthog/hogql/functions/__init__.py+++ b/posthog/hogql/functions/__init__.py@@ -6,6 +6,7 @@ from .mapping import find_hogql_aggregation, find_hogql_function, find_hogql_posfrom .recording_button import recording_buttonfrom .sparkline import sparklinefrom .survey import get_survey_response, unique_survey_submissions_filter+from .with_icon import with_icon__all__ = ["find_hogql_function",@@ -18,6 +19,7 @@ __all__ = ["cohort","sparkline","recording_button",+ "with_icon","explain_csp_report","get_survey_response","unique_survey_submissions_filter",diff --git a/posthog/hogql/functions/posthog.py b/posthog/hogql/functions/posthog.pyindex cb3d47dddc5e..b649c360ad50 100644--- a/posthog/hogql/functions/posthog.py+++ b/posthog/hogql/functions/posthog.py@@ -6,6 +6,7 @@ HOGQL_POSTHOG_FUNCTIONS: dict[str, HogQLFunctionMeta] = {"matchesAction": HogQLFunctionMeta("matchesAction", 1, 1),"sparkline": HogQLFunctionMeta("sparkline", 1, 1),"recordingButton": HogQLFunctionMeta("recordingButton", 1, 2),+ "withIcon": HogQLFunctionMeta("withIcon", 2, 2),"explainCSPReport": HogQLFunctionMeta("explainCSPReport", 1, 1),# Allow case-insensitive matching since people might not know "SemVer" is the right capitalization.# The regex strictly validates X.Y.Z with no leading zeros (matching the Rust `semver` cratediff --git a/posthog/hogql/functions/test/test_with_icon.py b/posthog/hogql/functions/test/test_with_icon.pynew file mode 100644index 000000000000..4a50b80684ef--- /dev/null+++ b/posthog/hogql/functions/test/test_with_icon.py@@ -0,0 +1,42 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.hogql.query import execute_hogql_query+++class TestWithIcon(BaseTest):+ @parameterized.expand(+ [+ (+ "named_icon",+ "SELECT withIcon('Claude Code', 'Claude')",+ ("__hx_tag", "BrandMarkLabel", "label", "Claude Code", "mark", "Claude"),+ ),+ (+ "image_url",+ "SELECT <img src='https://example.com/logo.png' alt='Customer logo' width={24} height={16} />",+ (+ "__hx_tag",+ "img",+ "src",+ "https://example.com/logo.png",+ "alt",+ "Customer logo",+ "width",+ 24,+ "height",+ 16,+ ),+ ),+ (+ "svg_data",+ "SELECT <img src='data:image/svg+xml,%3Csvg/%3E' />",+ ("__hx_tag", "img", "src", "data:image/svg+xml,%3Csvg/%3E"),+ ),+ ]+ )+ def test_explicit_image_in_query_result(self, _name: str, query: str, expected: tuple[str | int, ...]) -> None:+ response = execute_hogql_query(query, self.team)++ self.assertEqual(response.results[0][0], expected)diff --git a/posthog/hogql/functions/with_icon.py b/posthog/hogql/functions/with_icon.pynew file mode 100644index 000000000000..c89bbea3413b--- /dev/null+++ b/posthog/hogql/functions/with_icon.py@@ -0,0 +1,14 @@+from posthog.hogql import ast+++def with_icon(node: ast.Expr, args: list[ast.Expr]) -> ast.Expr:+ return ast.Tuple(+ exprs=[+ ast.Constant(value="__hx_tag"),+ ast.Constant(value="BrandMarkLabel"),+ ast.Constant(value="label"),+ args[0],+ ast.Constant(value="mark"),+ args[1],+ ]+ )diff --git a/posthog/hogql/hogqlx.py b/posthog/hogql/hogqlx.pyindex f1851a2df180..2f4c2936b589 100644--- a/posthog/hogql/hogqlx.py+++ b/posthog/hogql/hogqlx.py@@ -4,9 +4,10 @@ from posthog.hogql import ast## ::NB:: Sync this list with frontend/src/queries/nodes/HogQLX/render.tsx## Sanitization is done on the client side, as we can never be sure what tuple('__hx_tag', 'tag_name') comes our way.-HOGQLX_COMPONENTS = ["Sparkline", "RecordingButton", "ExplainCSPReport"]+HOGQLX_COMPONENTS = ["Sparkline", "RecordingButton", "ExplainCSPReport", "BrandMarkLabel"]HOGQLX_TAGS_SPECIAL = ["a",+ "img","blink","marquee","redacted",diff --git a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambrindex f31e07a6a327..3f45da5fafc7 100644--- a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr+++ b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr@@ -326,6 +326,7 @@'recordingButton','sparkline','uniqueSurveySubmissionsFilter',+ 'withIcon',]),'scalar': list(['IPv4ToIPv6',diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex f217e5695dd2..234084074c68 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -51,6 +51,7 @@ from posthog.hogql.functions.traffic_type import (has_user_agent_rule,is_bot,)+from posthog.hogql.functions.with_icon import with_iconfrom posthog.hogql.hogqlx import HOGQLX_COMPONENTS, HOGQLX_TAGS, convert_to_hxfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.resolver_utils import (@@ -2053,6 +2054,8 @@ class Resolver(CloningVisitor):return self.visit(sparkline(node=node, args=node.args))if node.name == "recordingButton":return self.visit(recording_button(node=node, args=node.args))+ if node.name == "withIcon":+ return self.visit(with_icon(node=node, args=node.args))if node.name == "explainCSPReport":return self.visit(explain_csp_report(node=node, args=node.args))if node.name == "matchesAction":diff --git a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambrindex 89e95a50d29f..8425549670d0 100644--- a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr+++ b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr@@ -74,7 +74,7 @@And lastly these are some HogQL specific functions:```- ['matchesAction', 'sparkline', 'recordingButton', 'explainCSPReport', 'sortablesemver', 'embedText', 'jev', 'decide', 'lookupDomainType', 'lookupPaidSourceType', 'lookupPaidMediumType', 'lookupOrganicSourceType', 'lookupOrganicMediumType', 'convertCurrency', 'getSurveyResponse', 'uniqueSurveySubmissionsFilter', 'getTrafficType', 'getTrafficCategory', 'isLikelyBot', 'getBotType', 'getBotName', 'getBotOperator']+ ['matchesAction', 'sparkline', 'recordingButton', 'withIcon', 'explainCSPReport', 'sortablesemver', 'embedText', 'jev', 'decide', 'lookupDomainType', 'lookupPaidSourceType', 'lookupPaidMediumType', 'lookupOrganicSourceType', 'lookupOrganicMediumType', 'convertCurrency', 'getSurveyResponse', 'uniqueSurveySubmissionsFilter', 'getTrafficType', 'getTrafficCategory', 'isLikelyBot', 'getBotType', 'getBotName', 'getBotOperator']```You fix HogQL errors that may come from either HogQL resolver errors or clickhouse execution errors. You don't help with other knowledge.diff --git a/products/mcp_analytics/frontend/components/BrandMark.tsx b/products/mcp_analytics/frontend/components/BrandMark.tsxindex 83433801fe40..8b982a5016af 100644--- a/products/mcp_analytics/frontend/components/BrandMark.tsx+++ b/products/mcp_analytics/frontend/components/BrandMark.tsx@@ -25,7 +25,15 @@ const ICON_MARKS: Record<}function isIconMark(name: BrandMarkName): name is IconMarkName {- return name in ICON_MARKS+ return Object.prototype.hasOwnProperty.call(ICON_MARKS, name)+}++// Mark names from untrusted input, such as HogQL's withIcon(), must pass through here before reaching BrandMark.+export function toBrandMarkName(name: string): BrandMarkName {+ return Object.prototype.hasOwnProperty.call(ICON_MARKS, name) ||+ Object.prototype.hasOwnProperty.call(BRAND_MARKS, name)+ ? (name as BrandMarkName)+ : 'Other harnesses'}// Pass a label only when the mark stands alone. Next to a visible name, an unlabelled mark stays hiddendiff --git a/products/mcp_analytics/frontend/components/BrandMarkLabel.tsx b/products/mcp_analytics/frontend/components/BrandMarkLabel.tsxnew file mode 100644index 000000000000..755c23f59e99--- /dev/null+++ b/products/mcp_analytics/frontend/components/BrandMarkLabel.tsx@@ -0,0 +1,10 @@+import { BrandMark, toBrandMarkName } from './BrandMark'++export function BrandMarkLabel({ label, mark }: { label: string; mark: string }): JSX.Element {+ return (+ <span className="inline-flex items-center gap-1.5" data-attr="hogqlx-brand-mark-label">+ <BrandMark name={toBrandMarkName(mark)} />+ <span>{label}</span>+ </span>+ )+}diff --git a/services/hogql-language-service/internal/completion/functions.go b/services/hogql-language-service/internal/completion/functions.goindex 1ee709237db1..cfb8490844d9 100644--- a/services/hogql-language-service/internal/completion/functions.go+++ b/services/hogql-language-service/internal/completion/functions.go@@ -63,5 +63,5 @@ toStartOfISOYear toStartOfInterval toStartOfMinute toStartOfMonth toStartOfQuarttoYYYYMMDD toYYYYMMDDhhmmss toYear toYearWeek to_char to_date to_timestamp today tokens topK topLevelDomain transform translate translateUTF8 trim trimLeft trimRight trunc tryBase58Decode tryBase64Decodetumble tumbleEnd tumbleStart tuple tupleDivide tupleDivideByNumber tupleElement tupleHammingDistance tupleMinus tupleMultiply tupleMultiplyByNumber tupleNegate tuplePlus tupleToNameValuePairs unhex uniq uniqCombined uniqCombined64 uniqExact uniqExactIfuniqExactMerge uniqExactState uniqHLL12 uniqHLL12If uniqIf uniqMap uniqMapMerge uniqMapMergeIf uniqMerge uniqMergeIf uniqState uniqStateIf uniqTheta uniqThetaIf uniqUpToMerge uniqueSurveySubmissionsFilter untuple upper upperUTF8 varPop-varPopIf varSamp varSampIf width_bucket windowFunnel xor yesterday+varPopIf varSamp varSampIf width_bucket windowFunnel withIcon xor yesterday`)