: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(dashboards): add a universal result context menu (#123411)
Marius Andra51da900e1ed7
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.mdindex 7f91cc7b3f15..eec69718721d 100644--- a/docs/published/handbook/engineering/data-warehouse.md+++ b/docs/published/handbook/engineering/data-warehouse.md@@ -131,7 +131,9 @@ The **Analysis** card ranks **Top N** categories by a selected measure across thEach measure's **Format and display** dialog sets its label, currency, decimal precision, abbreviation, percentage format, and suffix. Percentage formatting expects fractional values (0.25 displays as 25%); percent-of-total and percent-change calculations produce that scale automatically. Formats persist in saved insights and apply to charts, tables, and pivot cells. The **Charts** panel exposes series style and left/right axis selectors for each measure. Bar, line, and area charts support these mixed styles and axes. **Combine line + bar** assigns two measures to separate axes with bar and line styles.-Click a bar, line point, table cell, or pivot cell to explore its source rows. **Filter in new worksheet** preserves the original insight and adds the selected dimensions to a new worksheet. **View underlying rows** loads up to 1,000 matching source rows before aggregation; **Open in SQL editor** carries the same conditions, connection, and effective dashboard filters. When adding a drill-down condition would exceed the filter-group nesting limit, use **View underlying rows** or **Open in SQL editor**. Total cells omit rolled-up dimensions, and **Other** selects the categories outside the current Top N. Comparison-period points open rows from their original dates; their filtered-worksheet action is disabled to avoid combining current dates with prior-period conditions. These actions are unavailable on public shared insights.+In the worksheet editor, click a bar, line point, table cell, or pivot cell to explore its source rows. **Filter in new worksheet** preserves the original insight and adds the selected dimensions to a new worksheet. **View underlying rows** loads up to 1,000 matching source rows before aggregation; **Open in SQL editor** carries the same conditions, connection, and effective dashboard filters. When adding a drill-down condition would exceed the filter-group nesting limit, use **View underlying rows** or **Open in SQL editor**. Total cells omit rolled-up dimensions, and **Other** selects the categories outside the current Top N. Comparison-period points open rows from their original dates; their filtered-worksheet action is disabled to avoid combining current dates with prior-period conditions. These actions are unavailable on public shared insights.++On authenticated dashboards in view mode, clicking a chart result opens a context menu beside the pointer. Chart tooltips stay hidden until the menu closes. BI worksheets offer **View underlying rows**, then **Open in SQL editor**. Product analytics datapoints offer **View people**, **View recordings** when the existing drilldown selects matched recordings, then **Open in SQL editor**. Lifecycle results offer people and SQL only: their actor query identifies bucket members without projecting matched events. The people and SQL actions preserve the selected date, breakdown, and aggregation. SQL and recording links become available after the selected actor rows load. Selecting another result or closing the menu cancels any pending query. Recordings use matched session IDs; when no sessions match, the recordings action stays disabled. Clicking the same result again, pressing Escape, or clicking outside closes the menu. Native links support opening actions in another tab. These actions do not change dashboard filters or create saved insights. Public shares, embeds, exports, and layout editing retain their existing behavior.**Compare previous period** turns date comparison on or off in one click. The adjacent comparison picker still supports custom offsets. Select a bounded date range before enabling comparison.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 05ccc3ec2fc7..4a271262df00 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6860,6 +6860,22 @@ snapshots:hash: v1.k794b7964.26ebc58171eb340426f9fe220739132bca02f59b8489cb5a0b8a6411f99bb34d.oNv5X9sNKiPmhC_sE607b5P0yHAJju-hcC7higWxX9gproducts-business-intelligence-pivot-table--multiple-measures-and-hierarchies--light:hash: v1.k794b7964.a536391f02b293d2bdef0f6bb873b8daf6848e3c6bd2fd1b12f248f5847f2a4e.L_mE9SUEZfVSdz4aGS_wbCmwOg9CYDJr9fC5-sEH0ZU+ products-business-intelligence-result-menu--comparison-period--dark:+ hash: v1.k794b7964.50272d68c5a1d4568fad5027f5f071a87f5d7a3e41f4e2b0ba0c092b328acc12.mvP0bfecTXSDmdsWb-4q60r34LYfl6EW_2JrJgqmAQM+ products-business-intelligence-result-menu--comparison-period--light:+ hash: v1.k794b7964.2f334cb3d8e0b14e9891e9c3914e4543582b300103a0bd4a8d6f9a5ccaae5235.BO5-6A3CwhNrqmkVYGYPkASXTJ2ZCZx9Nq5HjiYSgyQ+ products-business-intelligence-result-menu--current-period--dark:+ hash: v1.k794b7964.ddd1047068aeb74cc2673a652da6db960bb66874844b79d8bd8e7c82163fd6ef.tcHUy676GLUj8peG2MuI_j4GQtFA8NCA7QyMvxH_zSM+ products-business-intelligence-result-menu--current-period--light:+ hash: v1.k794b7964.676f190ca64cc3672cc006db7360ebffd09173681708e665bedb31f622c41ee0.FTRtQXoAgR_gPCQnsH3W0iJXduN0oBlf26nYZezxrDc+ products-business-intelligence-result-menu--long-selection--dark:+ hash: v1.k794b7964.f986ccf0a7f4c0711337f3dad2b68f1d81ff36aad1a7828e8f84dcc13eaf68e2.2poTGOQTZP5mO-32nJ6d_oOUqNTvsdHRosR0breG52s+ products-business-intelligence-result-menu--long-selection--light:+ hash: v1.k794b7964.a62eb1765e29918410ad150513dfd91371b8daf019d6b6b9af2d109023b3ff9d.EVc9nubo1CM8Rd9PFpHOFVu_CeT-xXNA6dJlSt0ThFw+ products-business-intelligence-result-menu--quill--dark:+ hash: v1.k794b7964.f76a844fe2f7045a19d24924c8257af24baa3eb3b702b81a2e9670b967ec0d3f.7_nbU3jP7gbu9cpcylCvjiglHOZgceWGJBz4NA5QYsY+ products-business-intelligence-result-menu--quill--light:+ hash: v1.k794b7964.4d39006321662f5252686829c9c756dc3253f95b167bdf4ca5e25678d86c641a.S3XOsthsePrQwrKNtwIv62cYkmW6A5dTMhcfXbwJ79sproducts-business-intelligence-scatter--detail-and-color--dark:hash: v1.k794b7964.10050e03ee37342a8bf6e58db6149ad8a57aa66d32e5353dd9400dee8d055b30.XTp9ixf5AOcS_sZxzXYYoHvn4OT2xNm0UCHS8cQN1dQproducts-business-intelligence-scatter--detail-and-color--light:@@ -7172,6 +7188,14 @@ snapshots:hash: v1.k794b7964.cd0763f5b062ec767b6efa099e841b62de1f9a3a4dfdb0bf6c24f6c03ab18e91.kJlKCUFvGXQpWFE1iKqZW5d02nl2ciyHueEC_MeT0MMproducts-dashboards-filter-bar--unsaved-changes-popover--light:hash: v1.k794b7964.d76d6e64be7751440cabed822a47f9b113e3c12aa7edc1d4d087171f7a48aa5d.Evf7PgkLMcvli_EU2xrytkIty8G9Djw41eiXgsmY_KQ+ products-dashboards-insight-result-menu--people--dark:+ hash: v1.k794b7964.cc566593cb0936c5d24208ff74b57e8bba9a2ced69c3681866d8eca8f16455ab.FQAb19PNOE3hcLGB3Z5CX3LKENcyHOHyST3drjYWFvQ+ products-dashboards-insight-result-menu--people--light:+ hash: v1.k794b7964.5a7cac6c8a112183e617a69e799ed58d4bd187af3d8ac35750e5cb78f964a392.NoJIbCT117CUKLiczv8lcPRYixOy2z6nF30bHcFVsMs+ products-dashboards-insight-result-menu--quill--dark:+ hash: v1.k794b7964.cc566593cb0936c5d24208ff74b57e8bba9a2ced69c3681866d8eca8f16455ab.FwjyCsf9RAF1BUiLAwMQupAd8h155meJk8NMtc8jSoA+ products-dashboards-insight-result-menu--quill--light:+ hash: v1.k794b7964.5a7cac6c8a112183e617a69e799ed58d4bd187af3d8ac35750e5cb78f964a392.VgE6PFRvRq35suijVUkowWUz07-O-SrU-a9Fe3rsMeAproducts-dashboards-templates-dashboard-template-copy--default--dark:hash: v1.k794b7964.e441fc2d991020695739b9173c39b836a71364c4f3404dcf65f174a109bc919f.xvms_5gbih7s0W9qBwflXMTvNGiKVncitN72D6PQvv4products-dashboards-templates-dashboard-template-copy--default--light:diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsxindex 6f493b188f75..0264fbab7080 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx@@ -32,7 +32,7 @@ import { ErrorBoundary } from '~/layout/ErrorBoundary'import { extractValidationError, extractValidationErrorCode } from '~/queries/nodes/InsightViz/utils'import { Query } from '~/queries/Query/Query'import { DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'-import { queryVizDefinitelyRendersToCanvas } from '~/queries/utils'+import { isBIVisualizationNode, queryVizDefinitelyRendersToCanvas } from '~/queries/utils'import {AccessControlLevel,AccessControlResourceType,@@ -47,6 +47,7 @@ import {} from '~/types'import type { AlertType } from 'products/alerts/frontend/types'+import { DashboardInsightResultMenu } from 'products/dashboards/frontend/components/DashboardInsightResultMenu'import type { TileGroupMoveOptions } from 'products/dashboards/frontend/dashboardTileSections'import { DashboardResizeHandles } from '../handles'@@ -91,6 +92,7 @@ type AlertModalState = {}export interface InsightCardProps extends Resizeable {+ resultMenuEnabled?: boolean/** Insight to display. */insight: InsightModel/** id of the dashboard the card is on (when the card is being displayed on a dashboard) **/@@ -210,6 +212,7 @@ function InsightCardInternal(onOverlayVisibilityChange,filtersOverride,variablesOverride,+ resultMenuEnabled,children,projectId,projectTimezone,@@ -405,6 +408,7 @@ function InsightCardInternal(cachedResults={insight}context={{insightProps: insightLogicProps,+ dashboardResultMenu: resultMenuEnabled,dataVisualizationTableVirtualized:renderVizWhenMounted && placement === DashboardPlacement.Dashboard,// Small tables keep natural column widths because their full row count is cheap to render.@@ -417,11 +421,25 @@ function InsightCardInternal(editMode={false}/>)- }, [BlockingEmptyState, insight, insightLogicProps, variablesOverride, placement, renderVizWhenMounted])+ }, [+ BlockingEmptyState,+ insight,+ insightLogicProps,+ variablesOverride,+ placement,+ renderVizWhenMounted,+ resultMenuEnabled,+ ])const vizContent = shouldRenderViz ? (<div className="InsightCard__viz">- <div className="InsightCard__vizInner">{vizInner}</div>+ <div className="InsightCard__vizInner">+ {resultMenuEnabled && (!isBIVisualizationNode(insight.query) || insight.query.config.querySnapshot) ? (+ <DashboardInsightResultMenu insight={insight}>{vizInner}</DashboardInsightResultMenu>+ ) : (+ vizInner+ )}+ </div></div>) : (<InsightVisualizationSkeleton query={insight.query} />diff --git a/frontend/src/lib/components/ResultMenu/ResultMenu.scss b/frontend/src/lib/components/ResultMenu/ResultMenu.scssnew file mode 100644index 000000000000..697f0a7cdc28--- /dev/null+++ b/frontend/src/lib/components/ResultMenu/ResultMenu.scss@@ -0,0 +1,45 @@+// Both overlays are portaled outside the chart, so scope their visibility through the document.+body:has([data-attr='bi-result-menu']) [data-hog-charts-tooltip] {+ visibility: hidden;+}++.Popover.ResultMenu {+ width: 300px;+ max-width: calc(100vw - 16px);+ transform: none;+ perspective: none;++ > .Popover__box {+ margin: 0;+ opacity: 1;+ transition: none;+ transform: none;+ }+}++.ResultMenu__selection {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: 10px 12px;+ border-bottom: 1px solid var(--color-border-primary);+}++.ResultMenu__items {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: 4px;++ [role='menuitem'] {+ justify-content: flex-start;+ width: 100%;+ min-height: 32px;+ text-align: left;+ }+}++.ResultMenu--quill .ResultMenu__selection {+ padding-inline: 8px;+ margin-bottom: 4px;+}diff --git a/frontend/src/lib/components/ResultMenu/ResultMenu.tsx b/frontend/src/lib/components/ResultMenu/ResultMenu.tsxnew file mode 100644index 000000000000..a271fbd28bf6--- /dev/null+++ b/frontend/src/lib/components/ResultMenu/ResultMenu.tsx@@ -0,0 +1,220 @@+import './ResultMenu.scss'++import { KeyboardEvent, MouseEvent, ReactNode, RefObject, useCallback, useEffect, useRef } from 'react'++import { Popover } from '@posthog/lemon-ui'+import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuItem } from '@posthog/quill'++import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { LemonMenuItem, LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'+import { LinkPrimitive } from 'lib/lemon-ui/Link'+import {+ BREAKDOWN_NULL_STRING_LABEL,+ BREAKDOWN_NULL_DISPLAY,+ BREAKDOWN_OTHER_STRING_LABEL,+ BREAKDOWN_OTHER_DISPLAY,+ formatBreakdownLabel,+} from 'scenes/insights/utils'++export interface ResultMenuAction {+ name: string+ className: string+ disabledReason?: string+ onClick: () => void+ to?: string+ inPlace?: boolean+}++export function ResultMenu({+ selectedResult,+ caption,+ interaction,+ actions,+ close,+ triggerRef,+}: {+ selectedResult: ReactNode+ caption: string+ interaction: { x: number; y: number; timestamp?: number } | null+ actions: ResultMenuAction[]+ close: () => void+ triggerRef?: RefObject<HTMLDivElement>+}): JSX.Element {+ if (typeof selectedResult === 'string') {+ selectedResult = formatBreakdownLabel(+ selectedResult,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ false+ )+ .replaceAll(BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_NULL_DISPLAY)+ .replaceAll(BREAKDOWN_OTHER_STRING_LABEL, BREAKDOWN_OTHER_DISPLAY)+ }+ const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')+ const previousFocus = useRef<HTMLElement | null>(null)+ const focusMenu = useCallback((element: HTMLDivElement | null): void => {+ if (element) {+ previousFocus.current = document.activeElement as HTMLElement | null+ }+ element?.querySelector<HTMLElement>('[role="menuitem"]')?.focus({ preventScroll: true })+ }, [])++ useEffect(() => {+ const onScroll = (event: Event): void => {+ if (!(event.target instanceof Element && event.target.closest('[data-attr="bi-result-menu"]'))) {+ close()+ }+ }+ window.addEventListener('scroll', onScroll, true)+ window.addEventListener('resize', close)+ return () => {+ window.removeEventListener('scroll', onScroll, true)+ window.removeEventListener('resize', close)+ }+ }, [close])++ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {+ if (event.key === 'Escape' || event.key === 'Tab') {+ previousFocus.current?.focus({ preventScroll: true })+ close()+ return+ }+ if (!['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) {+ return+ }+ event.preventDefault()+ const buttons = Array.from(event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"]'))+ const current = buttons.indexOf(document.activeElement as HTMLElement)+ const next =+ event.key === 'Home'+ ? 0+ : event.key === 'End'+ ? buttons.length - 1+ : (current + (event.key === 'ArrowUp' || event.key === 'ArrowLeft' ? -1 : 1) + buttons.length) %+ buttons.length+ buttons[next]?.focus({ preventScroll: true })+ }++ const selection = (+ <div className="ResultMenu__selection" title={typeof selectedResult === 'string' ? selectedResult : undefined}>+ <span className="text-xs text-secondary truncate">{caption}</span>+ <strong className="truncate">{selectedResult}</strong>+ </div>+ )+ const label = typeof selectedResult === 'string' ? `Explore ${selectedResult}` : 'Explore this result'+ const onActionClick = (action: ResultMenuAction, event: MouseEvent): void => {+ if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {+ return+ }+ if (action.inPlace) {+ event.preventDefault()+ }+ action.onClick()+ }++ if (todayRailNav) {+ return (+ <DropdownMenu+ open+ modal={false}+ onOpenChange={(open, details) => {+ if (!open) {+ if (+ details.event.target instanceof Node &&+ triggerRef?.current?.contains(details.event.target)+ ) {+ details.cancel()+ } else {+ close()+ }+ }+ }}+ >+ <DropdownMenuContent+ className="ResultMenu--quill w-[300px]"+ data-attr="bi-result-menu"+ aria-label={label}+ alignOffset={8}+ sideOffset={8}+ anchor={{+ getBoundingClientRect: () =>+ new DOMRect(+ interaction?.x ?? window.innerWidth / 2,+ interaction?.y ?? window.innerHeight / 2,+ 0,+ 0+ ),+ }}+ >+ {selection}+ {actions.map((action) => (+ <DropdownMenuItem+ key={action.name}+ className={action.className}+ disabledReason={action.disabledReason}+ closeOnClick={false}+ onClick={(event) => onActionClick(action, event)}+ {...(action.to && !action.disabledReason+ ? {+ render: (+ <Button+ variant="default"+ size="row"+ left+ render={<LinkPrimitive to={action.to} />}+ />+ ),+ }+ : {})}+ >+ {action.name}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )+ }++ return (+ <Popover+ visible+ additionalRefs={triggerRef ? [triggerRef] : []}+ onClickOutside={close}+ padded={false}+ delayMs={0}+ className="ResultMenu"+ style={{+ position: 'fixed',+ left: Math.max(8, Math.min((interaction?.x ?? window.innerWidth / 2) + 8, window.innerWidth - 308)),+ top: Math.max(8, Math.min((interaction?.y ?? window.innerHeight / 2) + 8, window.innerHeight - 248)),+ }}+ overlay={+ <div data-attr="bi-result-menu">+ {selection}+ <div+ className="ResultMenu__items"+ role="menu"+ aria-label={label}+ onKeyDown={onKeyDown}+ ref={focusMenu}+ >+ <LemonMenuOverlay+ items={actions.map((action): LemonMenuItem => {+ const item = {+ label: action.name,+ className: action.className,+ disabledReason: action.disabledReason,+ onClick: (event: MouseEvent): void => onActionClick(action, event),+ }+ return action.to && !action.disabledReason ? { ...item, to: action.to } : item+ })}+ />+ </div>+ </div>+ }+ />+ )+}diff --git a/frontend/src/lib/components/ResultMenu/personsModalCapture.ts b/frontend/src/lib/components/ResultMenu/personsModalCapture.tsnew file mode 100644index 000000000000..510b150b0ed9--- /dev/null+++ b/frontend/src/lib/components/ResultMenu/personsModalCapture.ts@@ -0,0 +1,35 @@+import type { OpenPersonsModalProps } from 'scenes/trends/persons-modal/PersonsModal'++import type { DataTableNode } from '~/queries/schema/schema-general'++export interface CapturedPersonsModal extends OpenPersonsModalProps {+ open?: () => void+ rowsQuery?: DataTableNode+}++type Capture = (props: CapturedPersonsModal) => void+let clickCapture: Capture | null = null+let releaseTimer: ReturnType<typeof setTimeout> | undefined++// Keep the chart's existing actor-query builder. Only defer modal requests made during this click;+// the timeout spans both React capture and native chart listeners, which run in separate microtasks.+export function capturePersonsModalForClick(capture: Capture): void {+ clickCapture = capture+ clearTimeout(releaseTimer)+ releaseTimer = setTimeout(() => {+ if (clickCapture === capture) {+ clickCapture = null+ }+ }, 0)+}++export function consumePersonsModalClick(props: CapturedPersonsModal): boolean {+ const capture = clickCapture+ if (!capture) {+ return false+ }+ clickCapture = null+ clearTimeout(releaseTimer)+ capture(props)+ return true+}diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PartOfWholeChart.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PartOfWholeChart.tsxindex 7581de7e2416..a65c1874bb14 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PartOfWholeChart.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PartOfWholeChart.tsx@@ -3,6 +3,7 @@ import { ChartDisplayType } from '~/types'import { AxisSeries } from '../../dataVisualizationLogic'import { AxisBreakdownSeries } from '../seriesBreakdownLogic'+import { SqlChartProps } from './SqlChart'import { SqlPieGraph } from './SqlPieGraph'import { SqlProportionBar } from './SqlProportionBar'@@ -14,6 +15,7 @@ export interface PartOfWholeChartProps {chartSettings: ChartSettingspresetChartHeight?: booleanclassName?: string+ onSliceClick?: SqlChartProps['onSliceClick']}export function PartOfWholeChart(props: PartOfWholeChartProps): JSX.Element {diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsxindex e76ceecd4747..31db684e0b36 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsx@@ -1,6 +1,6 @@import type { ReactNode } from 'react'-import type { XAxisConfig, ChartMargins, ValueDomain } from '@posthog/quill-charts'+import type { XAxisConfig, ChartMargins, ValueDomain, RadialSlicePayload } from '@posthog/quill-charts'import { ChartSettings, GoalLine } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'@@ -38,6 +38,7 @@ export type SqlChartProps = {/** Called when the user clicks a data point. Receives the series key, x-axis index, and label.* When provided, the SQL chart shows a "click to inspect" hint in the tooltip. */onPointClick?: (seriesKey: string, dataIndex: number, label: string) => void+ onSliceClick?: (payload: RadialSlicePayload) => voidpointClickHint?: stringdirectPointClick?: booleanlabelFormatter?: (label: string) => stringdiff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsxindex b3b5b639a724..fb8f83877550 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx@@ -29,6 +29,7 @@ export const SqlPieGraph = ({presetChartHeight,className,labelFormatter,+ onSliceClick,}: SqlChartProps): JSX.Element => {const isDonut = visualizationType === ChartDisplayType.ActionsDonutconst { theme, series, legendConfig, total, showTotal, formattingSettings, valueFormatter } =@@ -119,6 +120,7 @@ export const SqlPieGraph = ({centerLabel={centerLabel}dataAttr="sql-pie-chart"onError={handleChartError}+ onSliceClick={onSliceClick}/></div>{legendAtSide && totalDisplay}diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.tsxindex e837329da174..0b1692d9f3ef 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.tsx@@ -19,6 +19,7 @@ export const SqlProportionBar = ({presetChartHeight,className,labelFormatter,+ onSliceClick,}: SqlChartProps): JSX.Element => {const { theme, series, legendConfig, total, showTotal, valueFormatter } = useSqlPartOfWholeChart({ xData, yData, chartSettings, labelFormatter },@@ -48,6 +49,7 @@ export const SqlProportionBar = ({valueFormatter={valueFormatter}dataAttr="sql-proportion-bar"onError={handleChartError}+ onSliceClick={onSliceClick}/>{showTotal && (<div className="pt-4 text-center shrink-0">diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.test.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.test.tsxindex 22c53b5c1284..8902b0d35850 100644--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.test.tsx+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.test.tsx@@ -1,11 +1,19 @@-import { cleanup, render, screen, waitFor, within } from '@testing-library/react'+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'+import type { RadialSlicePayload } from '@posthog/quill-charts'++import { BIField } from '~/queries/schema/schema-business-intelligence'import { VisualizationNode, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'+import { renderDataVisualization } from '~/test/insight-testing'import { ChartDisplayType } from '~/types'+import { buildBIQuery, DEFAULT_BI_CONFIG } from 'products/business_intelligence/frontend/biEditorTypes'++import type { SqlChartProps } from './Components/Charts/SqlChart'+import { buildPieSeries, buildPieSlices } from './Components/Charts/sqlPieGraphAdapter'import { DataTableVisualization } from './DataVisualization'type LemonTableMockProps = {@@ -27,6 +35,18 @@ jest.mock('@posthog/lemon-ui', () => ({},}))+jest.mock('./Components/Charts/PartOfWholeChart', () => ({+ PartOfWholeChart: ({ xData, yData, onSliceClick }: SqlChartProps): JSX.Element => (+ <button+ onClick={() =>+ onSliceClick?.({ series: buildPieSeries(buildPieSlices(xData, yData))[0] } as RadialSlicePayload)+ }+ >+ First slice+ </button>+ ),+}))+describe('DataTableVisualization', () => {const query: VisualizationNode = {kind: NodeKind.DataVisualizationNode,@@ -53,6 +73,68 @@ describe('DataTableVisualization', () => {cleanup()})+ it.each([+ { breakdown: false, alias: false },+ { breakdown: true, alias: false },+ { breakdown: false, alias: true },+ { breakdown: true, alias: true },+ ])('keeps the raw pie selection with breakdown=$breakdown and alias=$alias', async ({ breakdown, alias }) => {+ const field = (name: string): BIField => ({+ id: name,+ name,+ expression: name,+ type: 'string',+ source: { table: 'events' },+ })+ const region = field('region')+ const regionColumn = 'region'+ const config = {+ ...DEFAULT_BI_CONFIG,+ source: region.source,+ chartType: ChartDisplayType.ActionsPie,+ rows: [breakdown ? field('segment') : region],+ columns: breakdown ? [region] : [],+ memberAliases: alias ? [{ field: region, aliases: [{ value: 'west', label: 'West coast' }] }] : [],+ }+ renderDataVisualization({+ context: { dashboardResultMenu: true },+ query: {+ ...buildBIQuery(config)!.node,+ kind: NodeKind.BIVisualizationNode,+ config,+ chartSettings: {+ xAxis: { column: breakdown ? 'segment' : regionColumn },+ yAxis: [{ column: 'count' }],+ ...(breakdown ? { seriesBreakdownColumn: regionColumn } : {}),+ },+ },+ response: breakdown+ ? {+ columns: ['segment', regionColumn, 'count'],+ types: [+ ['segment', 'String'],+ [regionColumn, 'String'],+ ['count', 'Int64'],+ ],+ results: [['first', 'west', 2]],+ }+ : {+ columns: [regionColumn, 'count'],+ types: [+ [regionColumn, 'String'],+ ['count', 'Int64'],+ ],+ results: [['west', 2]],+ },+ })+ fireEvent.click(await screen.findByText('First slice'))+ const menu = await screen.findByRole('menu')+ const link = within(menu).getByText('Open in SQL editor').closest('a')!+ const openedQuery = JSON.parse(new URL(link.href).searchParams.get('open_query')!)+ expect(openedQuery.source.query).toContain("region = 'west'")+ expect(openedQuery.source.query).not.toContain("region = 'West coast'")+ })+it.each([false, true])('opens and closes settings in the correct panel (hosted: %s)', async (hosted) => {function Visualization(): JSX.Element {const [container, setContainer] = useState<HTMLDivElement | null>(null)diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsxindex 4c514768f505..abb3dc1c1f93 100644--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx@@ -38,6 +38,7 @@ import { BIChartYearLabels } from 'products/business_intelligence/frontend/BIChaimport { BIComparisonSummary } from 'products/business_intelligence/frontend/BIComparisonSummary'import { getBIChartRecord } from 'products/business_intelligence/frontend/biDrilldown'import { biDrilldownLogic } from 'products/business_intelligence/frontend/biDrilldownLogic'+import { BIDrilldownMenu } from 'products/business_intelligence/frontend/BIDrilldownMenu'import { BIDrilldownModal } from 'products/business_intelligence/frontend/BIDrilldownModal'import { getBIResultDimensions } from 'products/business_intelligence/frontend/biEditorTypes'import { createBIMemberFormatter } from 'products/business_intelligence/frontend/biMemberAliases'@@ -233,8 +234,19 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSXquery,filtersOverride: props.filtersOverride,variablesOverride: props.variablesOverride,+ dashboardMenu: !props.inSharedMode && props.context?.dashboardResultMenu,}- const { inspect } = useActions(biDrilldownLogic(drilldownProps))+ const drilldownLogic = biDrilldownLogic(drilldownProps)+ const { inspect: inspectResult, setInteraction } = useActions(drilldownLogic)+ const resultMenuTriggerRef = useRef<HTMLDivElement>(null)+ const inspectedPoint = useRef(false)+ const inspect = useCallback(+ (record: Record<string, unknown>): void => {+ inspectedPoint.current = true+ inspectResult(record)+ },+ [inspectResult]+ )const isQuerySnapshot = query.kind === NodeKind.BIVisualizationNode && !!query.config.querySnapshotconst canDrill = query.kind === NodeKind.BIVisualizationNode && !isQuerySnapshot && !props.inSharedMode@@ -351,17 +363,19 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX): undefinedconst aliasLabels = new Map<string, string>()+ const records = new Map<string, Record<string, unknown>>()let pieXData = pieData.xDatalet pieYData = pieData.yDataconst memberFormatter =query.kind === NodeKind.BIVisualizationNode && pieDimension? createBIMemberFormatter(query.config, pieDimension.field): undefined- if (memberFormatter) {+ if (query.kind === NodeKind.BIVisualizationNode) {if (pieData.yData.every((series) => 'breakdownValue' in series)) {pieYData = pieData.yData.map((series) => {const key = JSON.stringify([series.breakdownValue, series.name])aliasLabels.set(key, series.settings?.display?.label ?? series.name)+ records.set(key, getBIChartRecord(query, '', undefined, series.breakdownValue))return { ...series, name: key }})} else if (pieXData && pieData.yData.length === 1) {@@ -369,7 +383,15 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX...pieXData,data: pieXData.data.map((value) => {const key = JSON.stringify(value ?? null)- aliasLabels.set(key, memberFormatter(value))+ aliasLabels.set(+ key,+ memberFormatter+ ? memberFormatter(value)+ : value == null || value === ''+ ? '[No value]'+ : String(value)+ )+ records.set(key, { [pieData.xData!.column.name]: value })return key}),}@@ -380,6 +402,7 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSXxData: pieXData,yData: pieYData,labelFormatter: aliasLabels.size ? (label: string): string => aliasLabels.get(label) ?? label : undefined,+ records,}}, [effectiveVisualizationType, seriesBreakdownData, xData, yData, query, chartSettings.seriesBreakdownColumn])@@ -528,6 +551,16 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX<PartOfWholeChartclassName="p-3"{...pieDisplayData}+ onSliceClick={+ canDrill+ ? ({ series }) => {+ const record = pieDisplayData.records.get(series.key)+ if (record) {+ inspect(record)+ }+ }+ : undefined+ }visualizationType={effectiveVisualizationType}chartSettings={chartSettings}presetChartHeight={presetChartHeight}@@ -544,6 +577,7 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSXrows={'results' in response && Array.isArray(response.results) ? response.results : []}chartKey={dataVisualizationProps.key}onKeepOnly={props.editMode && !props.inSharedMode ? props.context?.onKeepBISelection : undefined}+ onInspect={canDrill ? inspect : undefined}className="p-3"xData={xData}yData={yData}@@ -606,13 +640,18 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX) : null}{component}{canDrill ? (- <BIDrilldownModal- logicProps={drilldownProps}- navigationDisabledReason={props.context?.biHierarchyDrillDisabledReason}- onNavigate={- props.editMode && !props.inSharedMode ? props.context?.onDrillBIHierarchy : undefined- }- />+ <>+ {drilldownProps.dashboardMenu && (+ <BIDrilldownMenu logicProps={drilldownProps} triggerRef={resultMenuTriggerRef} />+ )}+ <BIDrilldownModal+ logicProps={drilldownProps}+ navigationDisabledReason={props.context?.biHierarchyDrillDisabledReason}+ onNavigate={+ props.editMode && !props.inSharedMode ? props.context?.onDrillBIHierarchy : undefined+ }+ />+ </>) : null}</>)@@ -621,10 +660,41 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSXif (props.embedded) {return (<div+ ref={resultMenuTriggerRef}className={clsx('DataVisualization InsightCard__viz',effectiveVisualizationType === ChartDisplayType.Metric && 'InsightCard__viz--Metric')}+ onClick={+ canDrill && drilldownProps.dashboardMenu+ ? (event) => {+ if (+ event.currentTarget.contains(event.target as Node) &&+ !!drilldownLogic.values.interaction &&+ !inspectedPoint.current &&+ !(event.target as Element).closest('a, button, input, select, [role="button"]')+ ) {+ inspect({})+ }+ }+ : undefined+ }+ onClickCapture={+ canDrill && drilldownProps.dashboardMenu+ ? (event) => {+ if (event.currentTarget.contains(event.target as Node)) {+ inspectedPoint.current = false+ const rect = (event.target as Element).getBoundingClientRect()+ setInteraction({+ x: event.detail ? event.clientX : rect.x + rect.width / 2,+ y: event.detail ? event.clientY : rect.y + rect.height / 2,+ clickCount: event.detail,+ timestamp: event.timeStamp,+ })+ }+ }+ : undefined+ }>{component}</div>diff --git a/frontend/src/queries/types.ts b/frontend/src/queries/types.tsindex 5459a44d8c26..d17a1547b09e 100644--- a/frontend/src/queries/types.ts+++ b/frontend/src/queries/types.ts@@ -19,6 +19,8 @@ import { BIVisualizationNode } from './schema/schema-business-intelligence'/** Pass custom metadata to queries. Used for e.g. custom columns in the DataTable. */export interface QueryContext<Q extends QuerySchema = QuerySchema> {+ dashboardResultMenu?: boolean+/** Column templates for the DataTable */columns?: Record<string, QueryContextColumn>tableLayout?: 'auto' | 'fixed'diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsxindex 176ccd79a9d0..0c6c6d207d71 100644--- a/frontend/src/scenes/dashboard/DashboardItems.tsx+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx@@ -635,6 +635,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPkey={tile.id}tile={tile}insight={insight}+ resultMenuEnabled={placement === DashboardPlacement.Dashboard && !isSharedView() && !layoutEditMode}loadingQueued={loadingQueued}loading={loading}// The dashboard load queue owns this tile, so the card must not start its own query.diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex e5c50a5e296f..dcd3b71d1f81 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -1635,6 +1635,28 @@ describe('sqlEditorLogic', () => {})describe('open_query URL parameter', () => {+ it.each([NodeKind.InsightActorsQuery, NodeKind.FunnelsActorsQuery])(+ 'does not execute a URL-supplied %s',+ async (kind) => {+ const performQuery = jest.spyOn(queryRunner, 'performQuery')+ try {+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })+ logic.mount()+ router.actions.push(urls.sqlEditor(), {+ open_query: {+ kind: NodeKind.DataTableNode,+ source: { kind: NodeKind.ActorsQuery, source: { kind }, select: ['sleep(10)'] },+ },+ })+ await expectLogic(logic).toDispatchActions(['createTab']).toNotHaveDispatchedActions(['runQuery'])+ expect(performQuery.mock.calls.some(([query]) => query.kind === NodeKind.ActorsQuery)).toBe(false)+ expect(logic.values.insightLoading).toBe(false)+ } finally {+ performQuery.mockRestore()+ }+ }+ )+const STACKED_BAR_NODE: DataVisualizationNode = {kind: NodeKind.DataVisualizationNode,source: {diff --git a/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx b/frontend/src/scenes/trends/persons-modal/PersonsModal.tsxindex 2057ac0a2ca2..09430fc045a7 100644--- a/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx+++ b/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx@@ -22,6 +22,7 @@ import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'import { PropertiesTable } from 'lib/components/PropertiesTable'import { PropertiesTimeline } from 'lib/components/PropertiesTimeline'+import { consumePersonsModalClick } from 'lib/components/ResultMenu/personsModalCapture'import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'import ViewRecordingsPlaylistButton from 'lib/components/ViewRecordingButton/ViewRecordingsPlaylistButton'import { IconPlayCircle } from 'lib/lemon-ui/icons'@@ -666,6 +667,10 @@ export const openPersonsModal = (props: OpenPersonsModalProps): void => {return}+ if (consumePersonsModalClick(props)) {+ return+ }+const div = document.createElement('div')const root = createRoot(div)function destroy(): void {diff --git a/frontend/src/scenes/trends/persons-modal/getPersonsRecordingFilters.ts b/frontend/src/scenes/trends/persons-modal/getPersonsRecordingFilters.tsnew file mode 100644index 000000000000..ab3682981f13--- /dev/null+++ b/frontend/src/scenes/trends/persons-modal/getPersonsRecordingFilters.ts@@ -0,0 +1,193 @@+import { ActorsQuery, NodeKind } from '~/queries/schema/schema-general'+import {+ FilterLogicalOperator,+ RecordingUniversalFilters,+ UniversalFilterValue,+ PropertyFilterType,+ PropertyOperator,+} from '~/types'++// Scope session recordings to the funnel's selected breakdown value. Load-bearing:+// matched_recordings from the backend contains ALL of each actor's session IDs, so we+// need this filter to actually narrow the list. Returns null for breakdown types that+// can't be a single property filter (hogql / data_warehouse / multi-key / multi-value).++function buildFunnelBreakdownFilter(source: ActorsQuery['source'] | null): UniversalFilterValue | null {+ if (!source || source.kind !== NodeKind.FunnelsActorsQuery || source.funnelStepBreakdown == null) {+ return null+ }+ const breakdownFilter = source.source.breakdownFilter+ const breakdown = breakdownFilter?.breakdown+ const breakdownType = breakdownFilter?.breakdown_type ?? 'event'++ // Backend sends single values as one-element arrays (e.g. ["NL"]). Unwrap them; bail+ // for genuine multi-value arrays — a click represents one selected value.+ const rawBreakdownValue = source.funnelStepBreakdown+ let breakdownValue: string | number+ if (Array.isArray(rawBreakdownValue)) {+ if (rawBreakdownValue.length !== 1) {+ return null+ }+ breakdownValue = rawBreakdownValue[0]+ } else {+ breakdownValue = rawBreakdownValue+ }++ // Cohort → cohort membership filter. Skip the "All users" pseudo-cohort (0 / 'all').+ if (breakdownType === 'cohort') {+ if (breakdownValue === 0 || breakdownValue === 'all') {+ return null+ }+ const cohortId = typeof breakdownValue === 'number' ? breakdownValue : Number(breakdownValue)+ if (!Number.isFinite(cohortId)) {+ return null+ }+ return {+ type: PropertyFilterType.Cohort,+ key: 'id',+ value: cohortId,+ operator: PropertyOperator.In,+ }+ }++ // Non-cohort types need a single property key.+ if (!breakdown || Array.isArray(breakdown)) {+ return null+ }++ const key = String(breakdown)+ const base = { key, value: breakdownValue, operator: PropertyOperator.Exact }++ switch (breakdownType) {+ case 'event':+ return { ...base, type: PropertyFilterType.Event }+ case 'event_metadata':+ return { ...base, type: PropertyFilterType.EventMetadata }+ case 'person':+ return { ...base, type: PropertyFilterType.Person }+ case 'session':+ return { ...base, type: PropertyFilterType.Session }+ case 'group':+ if (breakdownFilter?.breakdown_group_type_index == null) {+ return null+ }+ return {+ ...base,+ type: PropertyFilterType.Group,+ group_type_index: breakdownFilter.breakdown_group_type_index,+ }+ // hogql / data_warehouse / revenue_analytics don't map to a single property filter.+ default:+ return null+ }+}++export const getPersonsRecordingFilters = (+ actorsQuery: ActorsQuery | null,+ sessionIds: string[]+): Partial<RecordingUniversalFilters> => {+ if (!actorsQuery || !actorsQuery.source) {+ return {}+ }++ const source = actorsQuery.source++ // Scope recordings to the selected funnel breakdown value (e.g. country = "NL").+ const funnelBreakdownFilter = buildFunnelBreakdownFilter(source)++ // The actual insight query (with series, properties, etc.) is nested at source.source+ let insightQuery = source+ if ('source' in source && source.source) {+ insightQuery = source.source as any+ }++ let date_from: string | undefined+ let date_to: string | undefined++ if ('dateRange' in insightQuery && insightQuery.dateRange) {+ const dateRange = insightQuery.dateRange as any+ date_from = dateRange.date_from || undefined+ date_to = dateRange.date_to || undefined+ }++ // If we have session IDs from matched_recordings, use them directly for efficient lookup+ if (sessionIds.length > 0) {+ return {+ session_ids: sessionIds,+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: funnelBreakdownFilter ? [funnelBreakdownFilter] : [],+ },+ ],+ },+ duration: [],+ date_from,+ date_to,+ }+ }++ // For non-funnel queries or funnels without session IDs, use filter-based approach+ const filters: UniversalFilterValue[] = []++ // Extract events from the insight query series+ if ('series' in insightQuery && Array.isArray(insightQuery.series)) {+ // drop-off actors (negative funnelStep) only completed the steps before the+ // drop-off, so only those can be required as event filters+ let seriesToFilterOn: any[] = insightQuery.series+ if (source.kind === NodeKind.FunnelsActorsQuery && typeof source.funnelStep === 'number') {+ const completedStepCount = source.funnelStep > 0 ? source.funnelStep : Math.abs(source.funnelStep) - 1+ seriesToFilterOn = insightQuery.series.slice(0, completedStepCount)+ }+ seriesToFilterOn.forEach((series) => {+ let entityFilter: any = null+ if ('event' in series && series.event) {+ entityFilter = {+ id: series.event,+ name: series.event,+ type: 'events',+ }+ } else if (series.kind === NodeKind.ActionsNode && series.id != null) {+ // action steps have an action id, not an event name+ entityFilter = {+ id: series.id,+ name: series.name,+ type: 'actions',+ }+ }+ if (entityFilter) {+ if ('properties' in series && Array.isArray(series.properties) && series.properties.length > 0) {+ entityFilter.properties = series.properties+ }+ filters.push(entityFilter)+ }+ })+ }++ // Add breakdown filter for funnels+ if (funnelBreakdownFilter) {+ filters.push(funnelBreakdownFilter)+ }++ // Add global properties from the insight query+ if ('properties' in insightQuery && Array.isArray(insightQuery.properties) && insightQuery.properties.length > 0) {+ filters.push(...insightQuery.properties)+ }++ // Build the result for non-funnel or fallback cases+ return {+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: filters,+ },+ ],+ },+ date_from,+ date_to,+ }+}diff --git a/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts b/frontend/src/scenes/trends/persons-modal/personsModalLogic.tsindex b4ce895a825d..46894a9d4eda 100644--- a/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts+++ b/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts@@ -44,96 +44,19 @@ import {ActivityTab,ActorType,CommonActorType,- FilterLogicalOperator,GroupActorType,PersonActorType,SessionActorType,- PropertyFilterType,- PropertyOperator,RecordingUniversalFilters,- UniversalFilterValue,} from '~/types'import type { Noun } from '../../../models/groupsModel'import type { InsightQueryNode } from '../../../queries/schema/schema-general'import type { GroupType, GroupTypeIndex } from '../../../types'+import { getPersonsRecordingFilters } from './getPersonsRecordingFilters'const RESULTS_PER_PAGE = 100-// Scope session recordings to the funnel's selected breakdown value. Load-bearing:-// matched_recordings from the backend contains ALL of each actor's session IDs, so we-// need this filter to actually narrow the list. Returns null for breakdown types that-// can't be a single property filter (hogql / data_warehouse / multi-key / multi-value).-function buildFunnelBreakdownFilter(source: ActorsQuery['source'] | null): UniversalFilterValue | null {- if (!source || source.kind !== NodeKind.FunnelsActorsQuery || source.funnelStepBreakdown == null) {- return null- }- const breakdownFilter = source.source.breakdownFilter- const breakdown = breakdownFilter?.breakdown- const breakdownType = breakdownFilter?.breakdown_type ?? 'event'-- // Backend sends single values as one-element arrays (e.g. ["NL"]). Unwrap them; bail- // for genuine multi-value arrays — a click represents one selected value.- const rawBreakdownValue = source.funnelStepBreakdown- let breakdownValue: string | number- if (Array.isArray(rawBreakdownValue)) {- if (rawBreakdownValue.length !== 1) {- return null- }- breakdownValue = rawBreakdownValue[0]- } else {- breakdownValue = rawBreakdownValue- }-- // Cohort → cohort membership filter. Skip the "All users" pseudo-cohort (0 / 'all').- if (breakdownType === 'cohort') {- if (breakdownValue === 0 || breakdownValue === 'all') {- return null- }- const cohortId = typeof breakdownValue === 'number' ? breakdownValue : Number(breakdownValue)- if (!Number.isFinite(cohortId)) {- return null- }- return {- type: PropertyFilterType.Cohort,- key: 'id',- value: cohortId,- operator: PropertyOperator.In,- }- }-- // Non-cohort types need a single property key.- if (!breakdown || Array.isArray(breakdown)) {- return null- }-- const key = String(breakdown)- const base = { key, value: breakdownValue, operator: PropertyOperator.Exact }-- switch (breakdownType) {- case 'event':- return { ...base, type: PropertyFilterType.Event }- case 'event_metadata':- return { ...base, type: PropertyFilterType.EventMetadata }- case 'person':- return { ...base, type: PropertyFilterType.Person }- case 'session':- return { ...base, type: PropertyFilterType.Session }- case 'group':- if (breakdownFilter?.breakdown_group_type_index == null) {- return null- }- return {- ...base,- type: PropertyFilterType.Group,- group_type_index: breakdownFilter.breakdown_group_type_index,- }- // hogql / data_warehouse / revenue_analytics don't map to a single property filter.- default:- return null- }-}-export interface PersonModalLogicProps {query?: InsightActorsQuery | FunnelsActorsQuery | ExperimentActorsQuery | PathsV2ActorsQuery | nullurl?: string | null@@ -711,121 +634,8 @@ export const personsModalLogic = kea<personsModalLogicType>([],recordingFilters: [(s) => [s.actorsQuery, s.sessionIdsFromLoadedActors],- (actorsQuery: ActorsQuery | null, sessionIds: string[]): Partial<RecordingUniversalFilters> => {- if (!actorsQuery || !actorsQuery.source) {- return {}- }-- const source = actorsQuery.source-- // Scope recordings to the selected funnel breakdown value (e.g. country = "NL").- const funnelBreakdownFilter = buildFunnelBreakdownFilter(source)-- // The actual insight query (with series, properties, etc.) is nested at source.source- let insightQuery = source- if ('source' in source && source.source) {- insightQuery = source.source as any- }-- let date_from: string | undefined- let date_to: string | undefined-- if ('dateRange' in insightQuery && insightQuery.dateRange) {- const dateRange = insightQuery.dateRange as any- date_from = dateRange.date_from || undefined- date_to = dateRange.date_to || undefined- }-- // If we have session IDs from matched_recordings, use them directly for efficient lookup- if (sessionIds.length > 0) {- return {- session_ids: sessionIds,- filter_group: {- type: FilterLogicalOperator.And,- values: [- {- type: FilterLogicalOperator.And,- values: funnelBreakdownFilter ? [funnelBreakdownFilter] : [],- },- ],- },- duration: [],- date_from,- date_to,- }- }-- // For non-funnel queries or funnels without session IDs, use filter-based approach- const filters: UniversalFilterValue[] = []-- // Extract events from the insight query series- if ('series' in insightQuery && Array.isArray(insightQuery.series)) {- // drop-off actors (negative funnelStep) only completed the steps before the- // drop-off, so only those can be required as event filters- let seriesToFilterOn: any[] = insightQuery.series- if (source.kind === NodeKind.FunnelsActorsQuery && typeof source.funnelStep === 'number') {- const completedStepCount =- source.funnelStep > 0 ? source.funnelStep : Math.abs(source.funnelStep) - 1- seriesToFilterOn = insightQuery.series.slice(0, completedStepCount)- }- seriesToFilterOn.forEach((series) => {- let entityFilter: any = null- if ('event' in series && series.event) {- entityFilter = {- id: series.event,- name: series.event,- type: 'events',- }- } else if (series.kind === NodeKind.ActionsNode && series.id != null) {- // action steps have an action id, not an event name- entityFilter = {- id: series.id,- name: series.name,- type: 'actions',- }- }- if (entityFilter) {- if (- 'properties' in series &&- Array.isArray(series.properties) &&- series.properties.length > 0- ) {- entityFilter.properties = series.properties- }- filters.push(entityFilter)- }- })- }-- // Add breakdown filter for funnels- if (funnelBreakdownFilter) {- filters.push(funnelBreakdownFilter)- }-- // Add global properties from the insight query- if (- 'properties' in insightQuery &&- Array.isArray(insightQuery.properties) &&- insightQuery.properties.length > 0- ) {- filters.push(...insightQuery.properties)- }-- // Build the result for non-funnel or fallback cases- return {- filter_group: {- type: FilterLogicalOperator.And,- values: [- {- type: FilterLogicalOperator.And,- values: filters,- },- ],- },- date_from,- date_to,- }- },+ (actorsQuery: ActorsQuery | null, sessionIds: string[]): Partial<RecordingUniversalFilters> =>+ getPersonsRecordingFilters(actorsQuery, sessionIds),],}),diff --git a/products/business_intelligence/frontend/BIDrilldownMenu.stories.tsx b/products/business_intelligence/frontend/BIDrilldownMenu.stories.tsxnew file mode 100644index 000000000000..d6420139184a--- /dev/null+++ b/products/business_intelligence/frontend/BIDrilldownMenu.stories.tsx@@ -0,0 +1,64 @@+import { Meta, StoryObj } from '@storybook/react'++import { ResultMenu as ResultMenuComponent } from 'lib/components/ResultMenu/ResultMenu'+import { FEATURE_FLAGS } from 'lib/constants'+import { urls } from 'scenes/urls'++import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'+import { NodeKind } from '~/queries/schema/schema-general'++import { getBIDrillQueries, getBIDrillSelection } from './biDrilldown'+import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'++const meta: Meta = {+ title: 'Products/Business intelligence/Result menu',+ parameters: { layout: 'fullscreen', testOptions: { waitForSelector: '[data-attr="bi-result-menu"]' } },+}+export default meta++function ResultMenu({ previous = false, longLabel = false }: { previous?: boolean; longLabel?: boolean }): JSX.Element {+ const config = {+ ...DEFAULT_BI_CONFIG,+ source: { table: 'orders' },+ rows: [+ {+ id: 'status',+ name: 'Status',+ expression: 'status',+ type: 'string' as const,+ source: { table: 'orders' },+ },+ ],+ }+ const query: BIVisualizationNode = { ...buildBIQuery(config)!.node, kind: NodeKind.BIVisualizationNode, config }+ const selection = getBIDrillSelection(config, {+ status: longLabel ? 'Awaiting confirmation from the payment provider' : 'paid',+ ...(previous ? { bi_comparison: 'Previous period' } : {}),+ })+ const queryUrl = urls.sqlEditor({ query: getBIDrillQueries(query, selection)!.rows })+ return (+ <div style={{ width: 520, height: 460 }}>+ <ResultMenuComponent+ selectedResult={selection.labels.map(({ name, value }) => `${name}: ${value}`).join(' · ')}+ caption={previous ? 'Comparison period' : 'Current period'}+ interaction={{ x: 260, y: 240 }}+ // Keep the visual preview open while the snapshot runner resizes the viewport.+ close={() => {}}+ actions={['View underlying rows', 'Open in SQL editor'].map((name) => ({+ name,+ className: '',+ to: queryUrl,+ onClick: () => {},+ }))}+ />+ </div>+ )+}++export const CurrentPeriod: StoryObj = { render: () => <ResultMenu /> }+export const LongSelection: StoryObj = { render: () => <ResultMenu longLabel /> }+export const ComparisonPeriod: StoryObj = { render: () => <ResultMenu previous /> }+export const Quill: StoryObj = {+ parameters: { featureFlags: [FEATURE_FLAGS.TODAY_RAIL_NAV] },+ render: () => <ResultMenu />,+}diff --git a/products/business_intelligence/frontend/BIDrilldownMenu.test.tsx b/products/business_intelligence/frontend/BIDrilldownMenu.test.tsxnew file mode 100644index 000000000000..2fcc079afb07--- /dev/null+++ b/products/business_intelligence/frontend/BIDrilldownMenu.test.tsx@@ -0,0 +1,81 @@+import '@testing-library/jest-dom'++import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'++import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'+import { NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { biDrilldownLogic } from './biDrilldownLogic'+import { BIDrilldownMenu } from './BIDrilldownMenu'+import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'++describe('native result-menu links', () => {+ beforeEach(() => initKeaTests())+ afterEach(cleanup)++ it.each([false, true])(+ 'renders real destinations without intercepting modified clicks (quill=%s)',+ async (quill) => {+ featureFlagLogic.actions.setFeatureFlags([], { 'today-rail-nav': quill })+ const config = {+ ...DEFAULT_BI_CONFIG,+ source: { table: 'orders' },+ rows: [+ {+ id: 'status',+ name: 'Status',+ expression: 'status',+ type: 'string' as const,+ source: { table: 'orders' },+ },+ ],+ }+ const query: BIVisualizationNode = {+ ...buildBIQuery(config)!.node,+ kind: NodeKind.BIVisualizationNode,+ config,+ }+ const props = {+ key: 'native-links',+ query,+ dashboardMenu: true,+ }+ const logic = biDrilldownLogic(props)+ const unmount = logic.mount()+ try {+ logic.actions.inspect({ status: 'paid' })+ render(<BIDrilldownMenu logicProps={props} />)+ await screen.findByText('View underlying rows')+ const names = ['View underlying rows', 'Open in SQL editor']+ for (const name of names) {+ const link = screen.getByText(name).closest('a')!+ expect(link).not.toBeNull()+ expect(link.getAttribute('href')).toMatch(/\/project\/\d+\/(dashboard|bi|sql)/)+ for (const modifier of [{ metaKey: true }, { ctrlKey: true }]) {+ const click = new MouseEvent('click', { bubbles: true, cancelable: true, ...modifier })+ act(() => {+ link.dispatchEvent(click)+ })+ expect(click.defaultPrevented).toBe(false)+ expect(logic.values.record).toEqual({ status: 'paid' })+ }+ }+ expect(screen.getAllByRole('menuitem').map((item) => item.textContent)).toEqual(names)+ expect(screen.queryByText('Filter dashboard by this result')).not.toBeInTheDocument()+ expect(screen.queryByText('Filter in new worksheet')).not.toBeInTheDocument()+ fireEvent.click(screen.getByText('View underlying rows'))+ expect(logic.values.showRows).toBe(true)+ act(() => logic.actions.inspect({ count: 8 }))+ expect(screen.queryByText('Filter dashboard by this result')).not.toBeInTheDocument()+ expect(screen.getAllByRole('menuitem')).toHaveLength(2)+ fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' })+ expect(logic.values.record).toBeNull()+ } finally {+ unmount()+ }+ }+ )+})diff --git a/products/business_intelligence/frontend/BIDrilldownMenu.tsx b/products/business_intelligence/frontend/BIDrilldownMenu.tsxnew file mode 100644index 000000000000..09a4eca014f1--- /dev/null+++ b/products/business_intelligence/frontend/BIDrilldownMenu.tsx@@ -0,0 +1,51 @@+import { useActions, useValues } from 'kea'+import { RefObject } from 'react'++import { ResultMenu, ResultMenuAction } from 'lib/components/ResultMenu/ResultMenu'+import { urls } from 'scenes/urls'++import { BIDrilldownProps, biDrilldownLogic } from './biDrilldownLogic'++export function BIDrilldownMenu({+ logicProps,+ triggerRef,+}: {+ logicProps: BIDrilldownProps+ triggerRef?: RefObject<HTMLDivElement>+}): JSX.Element | null {+ const { selection, queries, interaction, showRows } = useValues(biDrilldownLogic(logicProps))+ const { close, viewRows, openSqlEditor } = useActions(biDrilldownLogic(logicProps))+ if (!selection || showRows) {+ return null+ }+ const selectedResult =+ selection.labels.map(({ name, value }) => `${name}: ${value}`).join(' · ') || 'All matching rows'+ const actions: ResultMenuAction[] = [+ {+ name: 'View underlying rows',+ className: 'ResultMenu__rows',+ disabledReason: !queries ? 'Check the worksheet’s data source and fields before trying again.' : undefined,+ onClick: viewRows,+ to: queries ? urls.sqlEditor({ query: queries.rows }) : undefined,+ inPlace: true,+ },+ {+ name: 'Open in SQL editor',+ className: 'ResultMenu__sql',+ disabledReason: !queries ? 'Check the worksheet’s data source and fields before trying again.' : undefined,+ onClick: openSqlEditor,+ to: queries ? urls.sqlEditor({ query: queries.rows }) : undefined,+ },+ ]++ return (+ <ResultMenu+ triggerRef={triggerRef}+ selectedResult={selectedResult}+ caption={selection.previous ? 'Comparison period' : 'Current period'}+ interaction={interaction}+ actions={actions}+ close={close}+ />+ )+}diff --git a/products/business_intelligence/frontend/BIDrilldownModal.tsx b/products/business_intelligence/frontend/BIDrilldownModal.tsxindex e38da9b3ad8a..d14b200f8a7f 100644--- a/products/business_intelligence/frontend/BIDrilldownModal.tsx+++ b/products/business_intelligence/frontend/BIDrilldownModal.tsx@@ -23,7 +23,12 @@ export function BIDrilldownModal({const { selection, queries, showRows, hierarchyDrills } = useValues(biDrilldownLogic(props))const { close, viewRows } = useActions(biDrilldownLogic(props))return (- <LemonModal title="Explore this result" isOpen={!!selection} onClose={close} width={showRows ? '90vw' : 520}>+ <LemonModal+ title="Explore this result"+ isOpen={!!selection && (!props.dashboardMenu || showRows)}+ onClose={close}+ width={showRows ? '90vw' : 520}+ >{queries ? (<div className="flex flex-col gap-3"><p className="m-0">@@ -40,47 +45,50 @@ export function BIDrilldownModal({</ul>) : null}<div className="flex flex-wrap gap-2">- {hierarchyDrills.map(({ hierarchy, next, worksheet }) => (+ {!props.dashboardMenu &&+ hierarchyDrills.map(({ hierarchy, next, worksheet }) => (+ <LemonButton+ key={hierarchy.id}+ type="primary"+ disabledReason={navigationDisabledReason}+ to={+ onNavigate+ ? undefined+ : `${urls.businessIntelligenceNew()}#q=${encodeURIComponent(JSON.stringify(worksheet))}`+ }+ onClick={() => {+ onNavigate?.(worksheet)+ close()+ }}+ tooltip={`${hierarchy.name}: ${onNavigate ? 'filters this worksheet to the selection' : 'opens a new worksheet filtered to this selection'}`}+ >+ Drill to {next.name}+ {onNavigate ? '' : ' in new worksheet'}+ </LemonButton>+ ))}+ {!props.dashboardMenu && (<LemonButton- key={hierarchy.id}type="primary"- disabledReason={navigationDisabledReason}- to={- onNavigate- ? undefined- : `${urls.businessIntelligenceNew()}#q=${encodeURIComponent(JSON.stringify(worksheet))}`- }onClick={() => {- onNavigate?.(worksheet)+ if (props.query.kind === NodeKind.BIVisualizationNode) {+ captureBIWorksheetAction('drilldown_worksheet_opened', props.query.config)+ }close()}}- tooltip={`${hierarchy.name}: ${onNavigate ? 'filters this worksheet to the selection' : 'opens a new worksheet filtered to this selection'}`}+ to={+ queries.worksheet+ ? `${urls.businessIntelligenceNew()}#q=${encodeURIComponent(JSON.stringify(queries.worksheet))}`+ : undefined+ }+ disabledReason={+ !queries.worksheet+ ? 'Maximum filter group depth reached. View the underlying rows instead.'+ : undefined+ }>- Drill to {next.name}- {onNavigate ? '' : ' in new worksheet'}+ Filter in new worksheet</LemonButton>- ))}- <LemonButton- type="primary"- onClick={() => {- if (props.query.kind === NodeKind.BIVisualizationNode) {- captureBIWorksheetAction('drilldown_worksheet_opened', props.query.config)- }- close()- }}- to={- queries.worksheet- ? `${urls.businessIntelligenceNew()}#q=${encodeURIComponent(JSON.stringify(queries.worksheet))}`- : undefined- }- disabledReason={- !queries.worksheet- ? 'Maximum filter group depth reached. View the underlying rows instead.'- : undefined- }- >- Filter in new worksheet- </LemonButton>+ )}<LemonButtontype="secondary"onClick={viewRows}diff --git a/products/business_intelligence/frontend/BIScatterGraph.tsx b/products/business_intelligence/frontend/BIScatterGraph.tsxindex dad4cff3bc67..32064e26e3a0 100644--- a/products/business_intelligence/frontend/BIScatterGraph.tsx+++ b/products/business_intelligence/frontend/BIScatterGraph.tsx@@ -18,6 +18,7 @@ export interface BIScatterGraphProps extends SqlScatterGraphProps {rows: unknown[][]chartKey: stringonKeepOnly?: (records: Record<string, unknown>[]) => void+ onInspect?: (record: Record<string, unknown>) => void}export function BIScatterGraph({@@ -26,6 +27,7 @@ export function BIScatterGraph({rows,chartKey,onKeepOnly,+ onInspect,...chartProps}: BIScatterGraphProps): JSX.Element {const logic = biScatterLogic({@@ -199,7 +201,17 @@ export function BIScatterGraph({toggle(point.meta.rowKey)}}- : undefined+ : onInspect+ ? (point) => {+ if (point.meta?.rowIndex !== undefined) {+ onInspect(+ Object.fromEntries(+ columns.map((column, index) => [column, rows[point.meta!.rowIndex!][index]])+ )+ )+ }+ }+ : undefined}onAreaSelect={onKeepOnlydiff --git a/products/business_intelligence/frontend/biDrilldownLogic.ts b/products/business_intelligence/frontend/biDrilldownLogic.tsindex f81db042ba7e..ab1781fe25be 100644--- a/products/business_intelligence/frontend/biDrilldownLogic.ts+++ b/products/business_intelligence/frontend/biDrilldownLogic.ts@@ -1,5 +1,7 @@import { MakeLogicType, actions, kea, key, path, props, reducers, selectors, listeners } from 'kea'+import { objectsEqual } from 'lib/utils/objects'+import { VisualizationNode, NodeKind, DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'import { BIDrillSelection, getBIDrillQueries, getBIDrillSelection, getBIEffectiveQuery } from './biDrilldown'@@ -11,11 +13,20 @@ export interface BIDrilldownProps {query: VisualizationNodefiltersOverride?: DashboardFilter | nullvariablesOverride?: Record<string, HogQLVariable> | null+ dashboardMenu?: boolean+}++export interface BIDrillInteraction {+ x: number+ y: number+ clickCount: number+ timestamp?: number}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface biDrilldownLogicValues {hierarchyDrills: BIHierarchyDrill[]+ interaction: BIDrillInteraction | nullqueries: ReturnType<typeof getBIDrillQueries>query: VisualizationNoderecord: Record<string, unknown> | null@@ -31,6 +42,12 @@ export interface biDrilldownLogicActions {inspect: (record: Record<string, unknown>) => {record: Record<string, unknown>}+ openSqlEditor: () => {+ value: true+ }+ setInteraction: (interaction: BIDrillInteraction) => {+ interaction: BIDrillInteraction+ }viewRows: () => {value: true}@@ -58,17 +75,28 @@ export const biDrilldownLogic = kea<biDrilldownLogicType>([props({} as BIDrilldownProps),key((props) => props.key),path((key) => ['products', 'business_intelligence', 'biDrilldownLogic', key]),- actions({ inspect: (record: Record<string, unknown>) => ({ record }), close: true, viewRows: true }),- reducers({+ actions({+ inspect: (record: Record<string, unknown>) => ({ record }),+ setInteraction: (interaction: BIDrillInteraction) => ({ interaction }),+ openSqlEditor: true,+ close: true,+ viewRows: true,+ }),+ reducers(({ props }) => ({+ interaction: [+ null as BIDrillInteraction | null,+ { setInteraction: (_, { interaction }) => interaction, close: () => null },+ ],record: [null as Record<string, unknown> | null,{- inspect: (_, { record }) => record,+ inspect: (previous, { record }) =>+ props.dashboardMenu ? (objectsEqual(previous, record) ? null : record) : record,close: () => null,},],showRows: [false, { inspect: () => false, viewRows: () => true, close: () => false }],- }),+ })),selectors({hierarchyDrills: [(s) => [s.selection, s.query],@@ -96,14 +124,26 @@ export const biDrilldownLogic = kea<biDrilldownLogicType>([selection ? getBIDrillQueries(query, selection) : null,],}),- listeners(({ values }) => ({+ listeners(({ values, actions }) => ({inspect: () => {+ if (!values.record) {+ actions.close()+ return+ }if (values.query.kind === NodeKind.BIVisualizationNode && values.selection) {captureBIWorksheetAction('drilldown_opened', values.query.config, {previous_period: values.selection.previous,})}},+ openSqlEditor: () => {+ if (values.queries) {+ if (values.query.kind === NodeKind.BIVisualizationNode) {+ captureBIWorksheetAction('drilldown_sql_opened', values.query.config)+ }+ actions.close()+ }+ },viewRows: () => {if (values.query.kind === NodeKind.BIVisualizationNode) {captureBIWorksheetAction('underlying_rows_viewed', values.query.config, {diff --git a/products/dashboards/frontend/components/DashboardInsightResultMenu.stories.tsx b/products/dashboards/frontend/components/DashboardInsightResultMenu.stories.tsxnew file mode 100644index 000000000000..ca9805314bec--- /dev/null+++ b/products/dashboards/frontend/components/DashboardInsightResultMenu.stories.tsx@@ -0,0 +1,85 @@+import type { Meta, StoryObj } from '@storybook/react'++import { BarChart, type PointClickData } from '@posthog/quill-charts'++import { useChartTheme } from 'lib/charts/hooks'+import { FEATURE_FLAGS } from 'lib/constants'+import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'++import { mswDecorator } from '~/mocks/browser'+import { NodeKind } from '~/queries/schema/schema-general'+import { InsightModel, InsightShortId } from '~/types'++import { DashboardInsightResultMenu } from './DashboardInsightResultMenu'++const insight = {+ id: 1,+ short_id: 'menu-demo' as InsightShortId,+ name: 'Visitors by browser',+ query: {+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],+ dateRange: { date_from: '2026-01-01', date_to: '2026-01-07' },+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },+ },+ },+} as unknown as InsightModel++function Example(): JSX.Element {+ const theme = useChartTheme()+ const inspect = (point: PointClickData): void => {+ openPersonsModal({+ title: point.label,+ query: {+ kind: NodeKind.InsightActorsQuery,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],+ dateRange: { date_from: '2026-01-01', date_to: '2026-01-07' },+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },+ },+ breakdown: point.label,+ includeRecordings: true,+ },+ additionalSelect: { matched_recordings: 'matched_recordings' },+ })+ }+ return (+ <div className="w-full max-w-2xl h-80 border rounded p-4">+ <h3>Visitors by browser</h3>+ <div className="h-60">+ <DashboardInsightResultMenu insight={insight}>+ <BarChart+ labels={['Chrome', 'Safari', 'Firefox']}+ series={[{ key: 'visitors', label: 'Visitors', data: [120, 80, 40] }]}+ theme={theme}+ config={{ tooltip: { resolveClickToNearestSeries: true } }}+ onPointClick={inspect}+ />+ </DashboardInsightResultMenu>+ </div>+ </div>+ )+}++const meta: Meta = {+ title: 'Products/Dashboards/Insight result menu',+ parameters: { mockDate: '2026-01-08', layout: 'padded' },+ decorators: [+ mswDecorator({+ post: {+ '/api/environments/:team_id/query/ActorsQuery/': {+ hogql: "SELECT id FROM persons WHERE properties.$browser = 'Chrome'",+ results: [[{ id: 'example-person' }, [{ session_id: 'example-session' }]]],+ },+ },+ }),+ ],+ render: () => <Example />,+}+export default meta++export const People: StoryObj = {}+export const Quill: StoryObj = { parameters: { featureFlags: [FEATURE_FLAGS.TODAY_RAIL_NAV] } }diff --git a/products/dashboards/frontend/components/DashboardInsightResultMenu.test.tsx b/products/dashboards/frontend/components/DashboardInsightResultMenu.test.tsxnew file mode 100644index 000000000000..a02a444e0331--- /dev/null+++ b/products/dashboards/frontend/components/DashboardInsightResultMenu.test.tsx@@ -0,0 +1,324 @@+import '@testing-library/jest-dom'++import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'++import api from 'lib/api'+import { consumePersonsModalClick } from 'lib/components/ResultMenu/personsModalCapture'+import { openPersonsModal, OpenPersonsModalProps } from 'scenes/trends/persons-modal/PersonsModal'++import * as queryRunner from '~/queries/query'+import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'+import { NodeKind, ActorsQueryResponse, HogQLQuery } from '~/queries/schema/schema-general'+import { insightOnDashboard } from '~/scenes/dashboard/dashboardLogic.testHelpers'+import { initKeaTests } from '~/test/init'+import { BaseMathType, ChartDisplayType, GroupMathType } from '~/types'++import { DashboardInsightResultMenu } from './DashboardInsightResultMenu'++const openedModal = jest.fn()+jest.mock('scenes/trends/persons-modal/PersonsModal', () => ({+ openPersonsModal: (props: OpenPersonsModalProps): void => {+ if (!consumePersonsModalClick(props)) {+ openedModal(props)+ }+ },+}))++afterEach(() => {+ cleanup()+ jest.restoreAllMocks()+})+beforeEach(() => {+ initKeaTests()+ openedModal.mockClear()+ jest.spyOn(api, 'cancelQuery').mockResolvedValue()+ jest.spyOn(queryRunner, 'performQuery').mockResolvedValue({+ hogql: "SELECT id FROM persons WHERE properties.country = 'US'",+ results: [[{ id: 'person-selected' }, [{ session_id: 'session-selected' }]]],+ })+})++describe('dashboard result menu', () => {+ it('loads lifecycle people and SQL without requesting unsupported recordings', async () => {+ const request: OpenPersonsModalProps = {+ title: 'Resurrecting users',+ query: {+ kind: NodeKind.InsightActorsQuery,+ source: {+ kind: NodeKind.LifecycleQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],+ },+ day: '2026-01-02',+ status: 'resurrecting',+ includeRecordings: true,+ },+ additionalSelect: {},+ }+ render(+ <DashboardInsightResultMenu insight={insightOnDashboard(1, [1])}>+ <button onClick={() => openPersonsModal(request)}>Lifecycle point</button>+ </DashboardInsightResultMenu>+ )+ fireEvent.click(screen.getByText('Lifecycle point'))+ await waitFor(() => expect(screen.getByText('Open in SQL editor').closest('a')).not.toBeNull())+ expect(screen.queryByText('View recordings')).not.toBeInTheDocument()+ expect(queryRunner.performQuery).toHaveBeenCalledWith(+ expect.objectContaining({ source: request.query, select: ['actor'] }),+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ undefined,+ expect.any(String)+ )+ fireEvent.click(screen.getByText('View people'))+ expect(openedModal).toHaveBeenCalledWith(request)+ })++ it('opens BI query snapshots in the SQL editor with their source intact', () => {+ const source: HogQLQuery = {+ kind: NodeKind.HogQLQuery,+ query: 'SELECT count() FROM orders',+ connectionId: 'demo-connection',+ }+ const query: BIVisualizationNode = {+ kind: NodeKind.BIVisualizationNode,+ source,+ config: {+ source: null,+ querySnapshot: source,+ chartType: ChartDisplayType.ActionsBar,+ rows: [],+ columns: [],+ values: [],+ filters: [],+ limit: 1000,+ },+ }+ render(+ <DashboardInsightResultMenu insight={{ ...insightOnDashboard(1, [1]), query }}>+ <div>Snapshot chart</div>+ </DashboardInsightResultMenu>+ )+ fireEvent.click(screen.getByText('Snapshot chart'))+ for (const label of ['View underlying rows', 'Open in SQL editor']) {+ const link = screen.getByText(label).closest('a')!+ expect(JSON.parse(new URL(link.href).searchParams.get('open_query')!)).toEqual({+ kind: NodeKind.DataVisualizationNode,+ source,+ display: ChartDisplayType.ActionsTable,+ })+ }+ expect(queryRunner.performQuery).not.toHaveBeenCalled()+ })++ it.each([undefined, 0] as const)(+ 'defers the original datapoint drilldown with all user/group filters intact (group=%s)',+ async (groupIndex) => {+ const request: OpenPersonsModalProps = {+ title: 'Selected country',+ query: {+ kind: NodeKind.InsightActorsQuery,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ math: groupIndex === undefined ? BaseMathType.UniqueUsers : GroupMathType.UniqueGroup,+ ...(groupIndex !== undefined ? { math_group_type_index: groupIndex } : {}),+ },+ ],+ dateRange: { date_from: '-7d' },+ breakdownFilter: { breakdown: '$geoip_country_code', breakdown_type: 'person' },+ },+ series: 0,+ day: '2026-01-02',+ breakdown: ['US'],+ },+ additionalSelect: { matched_recordings: 'matched_recordings' },+ orderBy: ['actor_id DESC'],+ }+ render(+ <DashboardInsightResultMenu insight={insightOnDashboard(1, [1])}>+ <button onClick={() => openPersonsModal(request)}>Chart point</button>+ </DashboardInsightResultMenu>+ )+ fireEvent.click(screen.getByText('Chart point'))+ expect(openedModal).not.toHaveBeenCalled()+ expect(screen.getByText('Selected country')).toBeInTheDocument()+ expect(screen.queryByText('Explore in new insight')).not.toBeInTheDocument()+ expect(screen.queryByText('Filter dashboard by this result')).not.toBeInTheDocument()+ expect(screen.getAllByRole('menuitem').map((item) => item.textContent)).toEqual([+ 'View people',+ 'View recordings',+ 'Open in SQL editor',+ ])+ fireEvent.click(screen.getByText('Chart point'))+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()+ fireEvent.click(screen.getByText('Chart point'))+ const rows = screen.getByText('View people')+ const href = rows.closest('a')!.getAttribute('href')!+ expect(decodeURIComponent(href)).toContain('"kind":"ActorsQuery"')+ expect(decodeURIComponent(href)).toContain('"day":"2026-01-02"')+ expect(decodeURIComponent(href)).toContain('"breakdown":["US"]')+ await waitFor(() => expect(screen.getByText('Open in SQL editor').closest('a')).not.toBeNull())+ const sqlHref = screen.getByText('Open in SQL editor').closest('a')!.getAttribute('href')!+ expect(new URL(sqlHref, 'https://example.com').searchParams.get('open_query')).toBe(+ "SELECT id FROM persons WHERE properties.country = 'US'"+ )+ const replayHref = screen.getByText('View recordings').closest('a')!.getAttribute('href')!+ expect(decodeURIComponent(replayHref)).toContain('"session_ids":["session-selected"]')+ expect(queryRunner.performQuery).toHaveBeenCalledWith(+ expect.objectContaining({+ kind: NodeKind.ActorsQuery,+ source: request.query,+ select: ['actor', 'matched_recordings'],+ orderBy: request.orderBy,+ }),+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ undefined,+ expect.any(String)+ )+ fireEvent.click(rows)+ expect(openedModal).toHaveBeenCalledTimes(1)+ expect(openedModal).toHaveBeenCalledWith(request)+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()+ }+ )+ it('resolves funnel rows without exposing unrelated recordings when no sessions match', async () => {+ jest.mocked(queryRunner.performQuery).mockResolvedValue({ hogql: 'SELECT id FROM persons', results: [] })+ const request: OpenPersonsModalProps = {+ title: 'Funnel step',+ query: {+ kind: NodeKind.FunnelsActorsQuery,+ source: { kind: NodeKind.FunnelsQuery, series: [{ kind: NodeKind.EventsNode, event: '$pageview' }] },+ funnelStep: 1,+ funnelStepBreakdown: ['US'],+ },+ additionalSelect: { matched_recordings: 'matched_recordings' },+ }+ render(+ <DashboardInsightResultMenu insight={insightOnDashboard(1, [1])}>+ <button onClick={() => openPersonsModal(request)}>Funnel point</button>+ </DashboardInsightResultMenu>+ )+ fireEvent.click(screen.getByText('Funnel point'))+ await waitFor(() => expect(screen.getByText('Open in SQL editor').closest('a')).not.toBeNull())+ expect(queryRunner.performQuery).toHaveBeenCalledWith(+ expect.objectContaining({ source: request.query }),+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ undefined,+ expect.any(String)+ )+ expect(screen.getByText('View recordings').closest('a')).toBeNull()+ })++ it('discards an older result after selecting another point and lets failed requests retry', async () => {+ let resolveFirst!: (response: ActorsQueryResponse) => void+ jest.mocked(queryRunner.performQuery)+ .mockImplementationOnce(+ () =>+ new Promise<ActorsQueryResponse>((resolve) => {+ resolveFirst = resolve+ })+ )+ .mockRejectedValueOnce(new Error('Query failed'))+ .mockResolvedValueOnce({ hogql: 'SELECT 2', results: [] })+ const point = (day: string): OpenPersonsModalProps => ({+ title: day,+ query: {+ kind: NodeKind.InsightActorsQuery,+ source: { kind: NodeKind.TrendsQuery, series: [{ kind: NodeKind.EventsNode, event: '$pageview' }] },+ day,+ },+ })+ render(+ <DashboardInsightResultMenu insight={insightOnDashboard(1, [1])}>+ <button onClick={() => openPersonsModal(point('2026-01-01'))}>First point</button>+ <button onClick={() => openPersonsModal(point('2026-01-02'))}>Second point</button>+ </DashboardInsightResultMenu>+ )+ fireEvent.click(screen.getByText('First point'))+ await waitFor(() => expect(queryRunner.performQuery).toHaveBeenCalledTimes(1))+ fireEvent.click(screen.getByText('Second point'))+ await waitFor(() => expect(queryRunner.performQuery).toHaveBeenCalledTimes(2))+ const firstCall = jest.mocked(queryRunner.performQuery).mock.calls[0]+ const secondCall = jest.mocked(queryRunner.performQuery).mock.calls[1]+ expect(firstCall[1]?.signal?.aborted).toBe(true)+ expect(api.cancelQuery).toHaveBeenCalledWith(firstCall[3])+ expect(secondCall[3]).not.toBe(firstCall[3])+ expect(secondCall[1]?.signal?.aborted).toBe(false)+ await act(async () => resolveFirst({ hogql: 'SELECT 1', results: [] } as unknown as ActorsQueryResponse))+ expect(screen.getByText('Open in SQL editor').closest('a')).toBeNull()+ fireEvent.click(screen.getByText('Second point'))+ fireEvent.click(screen.getByText('Second point'))+ await waitFor(() => expect(screen.getByText('Open in SQL editor').closest('a')).not.toBeNull())+ const link = screen.getByText('Open in SQL editor').closest('a')!+ expect(new URL(link.href).searchParams.get('open_query')).toBe('SELECT 2')+ })++ it.each(['dismiss', 'unmount', 'complete'] as const)('cancels only pending queries on %s', async (finish) => {+ let resolveQuery!: (response: ActorsQueryResponse) => void+ jest.mocked(queryRunner.performQuery).mockImplementationOnce(+ (_, options) =>+ new Promise<ActorsQueryResponse>((resolve, reject) => {+ resolveQuery = resolve+ options?.signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')))+ })+ )+ const { unmount } = render(+ <DashboardInsightResultMenu insight={insightOnDashboard(1, [1])}>+ <button+ onClick={() =>+ openPersonsModal({+ title: 'Selected people',+ query: {+ kind: NodeKind.InsightActorsQuery,+ source: { kind: NodeKind.TrendsQuery, series: [] },+ },+ })+ }+ >+ Chart point+ </button>+ </DashboardInsightResultMenu>+ )+ fireEvent.click(screen.getByText('Chart point'))+ await waitFor(() => expect(queryRunner.performQuery).toHaveBeenCalledTimes(1))+ const call = jest.mocked(queryRunner.performQuery).mock.calls[0]+ if (finish === 'complete') {+ await act(async () => resolveQuery({ hogql: 'SELECT 1', results: [] } as unknown as ActorsQueryResponse))+ await waitFor(() => expect(screen.getByText('Open in SQL editor').closest('a')).not.toBeNull())+ }+ if (finish === 'dismiss') {+ fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' })+ } else {+ unmount()+ }+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument())+ expect(call[1]?.signal?.aborted).toBe(finish !== 'complete')+ if (finish === 'complete') {+ expect(api.cancelQuery).not.toHaveBeenCalled()+ } else {+ expect(api.cancelQuery).toHaveBeenCalledTimes(1)+ expect(api.cancelQuery).toHaveBeenCalledWith(call[3])+ }+ })++ it('does not offer recordings for a drilldown without recording support', () => {+ const request: OpenPersonsModalProps = {+ title: 'Selected people',+ query: {+ kind: NodeKind.InsightActorsQuery,+ source: { kind: NodeKind.StickinessQuery, series: [{ kind: NodeKind.EventsNode, event: '$pageview' }] },+ },+ }+ render(+ <DashboardInsightResultMenu insight={insightOnDashboard(1, [1])}>+ <button onClick={() => openPersonsModal(request)}>Chart point</button>+ </DashboardInsightResultMenu>+ )+ fireEvent.click(screen.getByText('Chart point'))+ expect(screen.queryByText('View recordings')).not.toBeInTheDocument()+ fireEvent.scroll(window)+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()+ })+})diff --git a/products/dashboards/frontend/components/DashboardInsightResultMenu.tsx b/products/dashboards/frontend/components/DashboardInsightResultMenu.tsxnew file mode 100644index 000000000000..cc48235e0fa1--- /dev/null+++ b/products/dashboards/frontend/components/DashboardInsightResultMenu.tsx@@ -0,0 +1,224 @@+import { useValues } from 'kea'+import { ReactNode, useId, useRef, useState } from 'react'++import { capturePersonsModalForClick, CapturedPersonsModal } from 'lib/components/ResultMenu/personsModalCapture'+import { ResultMenu } from 'lib/components/ResultMenu/ResultMenu'+import { objectsEqual } from 'lib/utils/objects'+import { getPersonsRecordingFilters } from 'scenes/trends/persons-modal/getPersonsRecordingFilters'+import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'+import { urls } from 'scenes/urls'++import { DataTableNode, DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'+import {+ isActorsQuery,+ isBIVisualizationNode,+ isDataTableNode,+ isDataVisualizationNode,+ isHogQLQuery,+} from '~/queries/utils'+import { ChartDisplayType, InsightModel, ReplayTabs } from '~/types'++import { dashboardInsightResultMenuLogic } from './dashboardInsightResultMenuLogic'++export function DashboardInsightResultMenu({+ insight,+ children,+}: {+ insight: InsightModel+ children: ReactNode+}): JSX.Element {+ const [position, setPosition] = useState<{ x: number; y: number; timestamp: number } | null>(null)+ const [actors, setActors] = useState<CapturedPersonsModal | null>(null)+ const triggerRef = useRef<HTMLDivElement>(null)+ const captured = useRef(false)+ const close = (): void => {+ setPosition(null)+ setActors(null)+ }+ const query = insight.query+ const sqlQuery: DataVisualizationNode | DataTableNode | undefined =+ query && isBIVisualizationNode(query)+ ? {+ kind: NodeKind.DataVisualizationNode,+ source: query.source,+ display: ChartDisplayType.ActionsTable,+ }+ : query &&+ ((isDataVisualizationNode(query) && query.kind === NodeKind.DataVisualizationNode) ||+ (isDataTableNode(query) && isHogQLQuery(query.source)))+ ? query+ : undefined+ const recordingQuery = actors?.query+ const canViewRecordings = !!recordingQuery && !!actors?.additionalSelect?.matched_recordings+ const rowsQuery: DataTableNode | undefined =+ actors?.rowsQuery ??+ (actors?.query+ ? {+ kind: NodeKind.DataTableNode,+ source: {+ kind: NodeKind.ActorsQuery,+ source: actors.query,+ select: [+ ...new Set([+ 'actor',+ ...Object.values(actors.additionalSelect || {}),+ ...(canViewRecordings ? ['matched_recordings'] : []),+ ]),+ ],+ orderBy: actors.orderBy,+ },+ full: true,+ }+ : undefined)+ const rowsUrl = rowsQuery+ ? urls.insightNew({ query: rowsQuery })+ : sqlQuery+ ? urls.sqlEditor({+ query: isDataTableNode(sqlQuery) ? sqlQuery : { ...sqlQuery, display: ChartDisplayType.ActionsTable },+ })+ : undefined+ const { selectedResult: resolvedResult, resultLoading } = useValues(+ dashboardInsightResultMenuLogic({+ key: useId(),+ query: position && rowsQuery && isActorsQuery(rowsQuery.source) ? rowsQuery.source : null,+ })+ )+ const sqlUrl = resolvedResult?.sql+ ? urls.sqlEditor({ query: resolvedResult.sql })+ : sqlQuery+ ? urls.sqlEditor({ query: sqlQuery })+ : undefined+ const resultUnavailableReason = resultLoading+ ? 'Loading the selected result…'+ : 'Could not load the selected result. Select the data point again to retry.'+ const selectedResult = actors?.title+ ? typeof actors.title === 'function'+ ? actors.title('Results')+ : actors.title+ : insight.name || 'Untitled insight'+ return (+ <div+ ref={triggerRef}+ className="flex flex-1 flex-col min-h-0 h-full"+ onClickCapture={(event) => {+ if (+ !event.currentTarget.contains(event.target as Node) ||+ (event.target as Element).closest('a, input, select') ||+ event.metaKey ||+ event.ctrlKey ||+ event.altKey ||+ event.shiftKey+ ) {+ return+ }+ captured.current = false+ const rect = (event.target as Element).getBoundingClientRect()+ const point = {+ x: event.detail ? event.clientX : rect.x + rect.width / 2,+ y: event.detail ? event.clientY : rect.y + rect.height / 2,+ timestamp: event.timeStamp,+ }+ capturePersonsModalForClick((request) => {+ captured.current = true+ if (+ position &&+ actors &&+ objectsEqual(actors.query, request.query) &&+ objectsEqual(actors.rowsQuery, request.rowsQuery) &&+ actors.url === request.url &&+ actors.urlsIndex === request.urlsIndex &&+ objectsEqual(actors.urls, request.urls)+ ) {+ close()+ return+ }+ setActors(request)+ setPosition(point)+ })+ }}+ onClick={(event) => {+ if (+ !event.currentTarget.contains(event.target as Node) ||+ captured.current ||+ (event.target as Element).closest('a, button, input, select, [role="button"]') ||+ event.metaKey ||+ event.ctrlKey ||+ event.altKey ||+ event.shiftKey+ ) {+ return+ }+ if (position) {+ close()+ return+ }+ setActors(null)+ setPosition({ x: event.clientX, y: event.clientY, timestamp: event.timeStamp })+ }}+ >+ {children}+ {position && (+ <ResultMenu+ triggerRef={triggerRef}+ selectedResult={selectedResult}+ caption={actors ? insight.name || 'Insight result' : 'Dashboard insight'}+ interaction={position}+ close={close}+ actions={[+ {+ name: sqlQuery ? 'View underlying rows' : 'View people',+ className: 'ResultMenu__rows',+ to: rowsUrl,+ inPlace: !!actors,+ disabledReason:+ !actors && !sqlQuery+ ? 'Select a data point to view the users or groups behind it.'+ : undefined,+ onClick: () => {+ const request = actors+ close()+ if (request) {+ request.open ? request.open() : openPersonsModal(request)+ }+ },+ },+ ...(canViewRecordings && recordingQuery+ ? [+ {+ name: 'View recordings',+ className: 'ResultMenu__recordings',+ to: resolvedResult?.sessionIds.length+ ? urls.replay(+ ReplayTabs.Home,+ getPersonsRecordingFilters(+ { kind: NodeKind.ActorsQuery, source: recordingQuery },+ resolvedResult.sessionIds+ )+ )+ : undefined,+ disabledReason: resolvedResult?.sessionIds.length+ ? undefined+ : resolvedResult+ ? 'No recordings found for this result.'+ : resultUnavailableReason,+ onClick: close,+ },+ ]+ : []),+ {+ name: 'Open in SQL editor',+ className: 'ResultMenu__sql',+ to: sqlUrl,+ disabledReason: sqlUrl+ ? undefined+ : actors+ ? resultUnavailableReason+ : 'Select a data point to edit its underlying query.',+ onClick: close,+ },+ ]}+ />+ )}+ </div>+ )+}diff --git a/products/dashboards/frontend/components/dashboardInsightResultMenuLogic.ts b/products/dashboards/frontend/components/dashboardInsightResultMenuLogic.tsnew file mode 100644index 000000000000..94301a14d3f4--- /dev/null+++ b/products/dashboards/frontend/components/dashboardInsightResultMenuLogic.ts@@ -0,0 +1,128 @@+import { MakeLogicType, afterMount, kea, key, path, props, propsChanged, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { v4 as uuid } from 'uuid'++import api from 'lib/api'+import { objectsEqual } from 'lib/utils/objects'++import { performQuery } from '~/queries/query'+import { ActorsQuery } from '~/queries/schema/schema-general'++export interface DashboardInsightResultMenuProps {+ key: string+ query: ActorsQuery | null+}++interface ActorResult {+ query: ActorsQuery+ sql: string | undefined+ sessionIds: string[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dashboardInsightResultMenuLogicValues {+ result: ActorResult | null+ resultLoading: boolean+ selectedResult: ActorResult | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dashboardInsightResultMenuLogicActions {+ loadResult: (_: void) => void+ loadResultFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadResultSuccess: (+ result: ActorResult | null,+ payload?: void+ ) => {+ result: ActorResult | null+ payload?: void+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dashboardInsightResultMenuLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ selectedResult: (result: ActorResult | null, arg: any) => ActorResult | null+ }+}++export type dashboardInsightResultMenuLogicType = MakeLogicType<+ dashboardInsightResultMenuLogicValues,+ dashboardInsightResultMenuLogicActions,+ DashboardInsightResultMenuProps,+ dashboardInsightResultMenuLogicMeta+>++export const dashboardInsightResultMenuLogic = kea<dashboardInsightResultMenuLogicType>([+ props({} as DashboardInsightResultMenuProps),+ key((props): string => props.key),+ path((key) => ['products', 'dashboards', 'components', 'dashboardInsightResultMenuLogic', key]),+ loaders(({ props, cache }) => ({+ result: [+ null as ActorResult | null,+ {+ loadResult: async (_: void, breakpoint): Promise<ActorResult | null> => {+ cache.disposables.dispose('actorQuery')+ const query = props.query+ if (!query) {+ return null+ }+ const controller = new AbortController()+ const queryId = uuid()+ let settled = false+ cache.disposables.add(+ () => () => {+ if (!settled) {+ controller.abort()+ void api.cancelQuery(queryId).catch((error) => {+ console.warn('Failed cancelling dashboard actor query', error)+ })+ }+ },+ 'actorQuery',+ { pauseOnPageHidden: false }+ )+ const response = await performQuery(query, { signal: controller.signal }, undefined, queryId)+ .catch((error) => {+ breakpoint()+ throw error+ })+ .finally(() => {+ settled = true+ })+ breakpoint()+ const recordingsIndex = query.select?.indexOf('matched_recordings') ?? -1+ const recordings: { session_id?: string }[] =+ recordingsIndex < 0 ? [] : response.results.flatMap((row) => row[recordingsIndex] ?? [])+ return {+ query,+ sql: response.hogql,+ sessionIds: [+ ...new Set(recordings.flatMap(({ session_id }) => (session_id ? [session_id] : []))),+ ],+ }+ },+ },+ ],+ })),+ selectors({+ selectedResult: [+ (s) => [s.result, (_, props) => props.query],+ (result: ActorResult | null, query: ActorsQuery | null): ActorResult | null =>+ result && objectsEqual(result.query, query) ? result : null,+ ],+ }),+ afterMount(({ actions }) => actions.loadResult()),+ propsChanged(({ actions, props }, previousProps) => {+ if (!objectsEqual(props.query, previousProps.query)) {+ actions.loadResult()+ }+ }),+])diff --git a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsxindex 62ef56e42f35..a77e8f4a8e54 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx+++ b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx@@ -148,12 +148,13 @@ export function FunnelLineChart({showTrendLines: funnelsFilter?.showTrendLines ?? false,valueLabels: showValuesOnSeries ? { formatter: (value) => `${value}%` } : false,showCrosshair: true,- tooltip: INSIGHT_TOOLTIP_CONFIG,+ tooltip: { ...INSIGHT_TOOLTIP_CONFIG, resolveClickToNearestSeries: context?.dashboardResultMenu },}),curve: chartStyleCurve(funnelsFilter?.chartStyle),legend: legendConfig,}),[+ context?.dashboardResultMenu,steps,interval,timezone,diff --git a/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsx b/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsxindex ea18d7829a13..a3825f19460d 100644--- a/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsx+++ b/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsx@@ -27,6 +27,7 @@ import {} from '../shared/retentionChartTransforms'interface RetentionBarChartProps {+ resultMenuEnabled?: booleaninSharedMode?: boolean}const EMPTY_GOAL_LINES: GoalLine[] = []@@ -51,7 +52,10 @@ function resolveGroupTypeLabel(return aggregationLabel(labelGroupType).plural}-export function RetentionBarChart({ inSharedMode = false }: RetentionBarChartProps): JSX.Element | null {+export function RetentionBarChart({+ inSharedMode = false,+ resultMenuEnabled = false,+}: RetentionBarChartProps): JSX.Element | null {const { insightProps } = useValues(insightLogic)const theme = useChartTheme()@@ -158,12 +162,15 @@ export function RetentionBarChart({ inSharedMode = false }: RetentionBarChartProisPercentage,goalLines,series,- tooltip: INSIGHT_TOOLTIP_CONFIG,+ tooltip: {+ ...INSIGHT_TOOLTIP_CONFIG,+ resolveClickToNearestSeries: resultMenuEnabled && !inSharedMode,+ },isIntervalView,period,timezone,}),- [isPercentage, goalLines, series, isIntervalView, period, timezone]+ [resultMenuEnabled, inSharedMode, isPercentage, goalLines, series, isIntervalView, period, timezone])if (filteredTrendSeries.length === 0 && hasValidBreakdown) {diff --git a/products/product_analytics/frontend/insights/retention/RetentionContainer.tsx b/products/product_analytics/frontend/insights/retention/RetentionContainer.tsxindex fdfe85fcaad2..2fd788d23dec 100644--- a/products/product_analytics/frontend/insights/retention/RetentionContainer.tsx+++ b/products/product_analytics/frontend/insights/retention/RetentionContainer.tsx@@ -19,6 +19,7 @@ export function RetentionContainer({embedded,inSharedMode,vizSpecificOptions,+ context,}: {inCardView?: booleanembedded?: boolean@@ -42,7 +43,7 @@ export function RetentionContainer({{!inCardView && !inSharedMode && <RetentionEmptyResultsBanner />}{showLineGraph && (<div className="RetentionContainer__graph">- <RetentionGraph inSharedMode={inSharedMode} />+ <RetentionGraph inSharedMode={inSharedMode} resultMenuEnabled={context?.dashboardResultMenu} /></div>)}{showLineGraph && showTable ? <LemonDivider /> : null}diff --git a/products/product_analytics/frontend/insights/retention/RetentionGraph.tsx b/products/product_analytics/frontend/insights/retention/RetentionGraph.tsxindex d83ff40ddaca..3f439df66490 100644--- a/products/product_analytics/frontend/insights/retention/RetentionGraph.tsx+++ b/products/product_analytics/frontend/insights/retention/RetentionGraph.tsx@@ -9,16 +9,20 @@ import { retentionGraphLogic } from './retentionGraphLogic'import { RetentionLineChart } from './RetentionLineChart/RetentionLineChart'interface RetentionGraphProps {+ resultMenuEnabled?: booleaninSharedMode?: boolean}-export function RetentionGraph({ inSharedMode = false }: RetentionGraphProps): JSX.Element | null {+export function RetentionGraph({+ inSharedMode = false,+ resultMenuEnabled = false,+}: RetentionGraphProps): JSX.Element | null {const { insightProps } = useValues(insightLogic)const { retentionFilter } = useValues(retentionGraphLogic(insightProps))const isBarDisplay = retentionFilter?.display === ChartDisplayType.ActionsBarif (isBarDisplay) {- return <RetentionBarChart inSharedMode={inSharedMode} />+ return <RetentionBarChart inSharedMode={inSharedMode} resultMenuEnabled={resultMenuEnabled} />}- return <RetentionLineChart inSharedMode={inSharedMode} />+ return <RetentionLineChart inSharedMode={inSharedMode} resultMenuEnabled={resultMenuEnabled} />}diff --git a/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx b/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsxindex d46fdc3b6c7a..d682c2e40ff4 100644--- a/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx+++ b/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx@@ -33,6 +33,7 @@ import {} from '../shared/retentionChartTransforms'interface RetentionLineChartProps {+ resultMenuEnabled?: booleaninSharedMode?: boolean}const EMPTY_GOAL_LINES: GoalLine[] = []@@ -57,7 +58,10 @@ function resolveGroupTypeLabel(return aggregationLabel(labelGroupType).plural}-export function RetentionLineChart({ inSharedMode = false }: RetentionLineChartProps): JSX.Element | null {+export function RetentionLineChart({+ inSharedMode = false,+ resultMenuEnabled = false,+}: RetentionLineChartProps): JSX.Element | null {const { insightProps } = useValues(insightLogic)const { insightDataLoading } = useValues(insightVizDataLogic(insightProps))const theme = useChartTheme()@@ -194,14 +198,28 @@ export function RetentionLineChart({ inSharedMode = false }: RetentionLineChartPgoalLines,showTrendLines,series,- tooltip: INSIGHT_TOOLTIP_CONFIG,+ tooltip: {+ ...INSIGHT_TOOLTIP_CONFIG,+ resolveClickToNearestSeries: resultMenuEnabled && !inSharedMode,+ },isIntervalView,period,timezone,}),curve: chartStyleCurve(retentionFilter?.chartStyle),}),- [isPercentage, goalLines, showTrendLines, series, isIntervalView, period, timezone, retentionFilter?.chartStyle]+ [+ resultMenuEnabled,+ inSharedMode,+ isPercentage,+ goalLines,+ showTrendLines,+ series,+ isIntervalView,+ period,+ timezone,+ retentionFilter?.chartStyle,+ ])if (filteredTrendSeries.length === 0 && hasValidBreakdown) {diff --git a/products/product_analytics/frontend/insights/retention/retentionModalLogic.test.ts b/products/product_analytics/frontend/insights/retention/retentionModalLogic.test.tsindex 8705a2f5539c..66dde7a33b39 100644--- a/products/product_analytics/frontend/insights/retention/retentionModalLogic.test.ts+++ b/products/product_analytics/frontend/insights/retention/retentionModalLogic.test.ts@@ -1,5 +1,6 @@import { expectLogic } from 'kea-test-utils'+import { capturePersonsModalForClick } from 'lib/components/ResultMenu/personsModalCapture'import { teamLogic } from 'scenes/teamLogic'import { useMocks } from '~/mocks/jest'@@ -159,6 +160,23 @@ describe('retentionModalLogic', () => {}})+ it('defers a dashboard cohort drilldown until View underlying rows and retains its selected column', async () => {+ await loadResults(twoBreakdownGroups)+ const capture = jest.fn()+ capturePersonsModalForClick(capture)+ await expectLogic(logic, () => logic.actions.openModal(1, 'Firefox', 2)).toNotHaveDispatchedActions([+ 'loadPeople',+ ])+ expect(logic.values.selectedInterval).toBeNull()+ expect(capture).toHaveBeenCalledTimes(1)+ const request = capture.mock.calls[0][0]+ expect(request.rowsQuery.source.source).toMatchObject({ interval: 1, breakdown: ['Firefox'] })+ await expectLogic(logic, () => request.open()).toDispatchActions(['loadPeople'])+ expect(logic.values.selectedInterval).toBe(1)+ expect(logic.values.selectedBreakdownValue).toBe('Firefox')+ expect(logic.values.selectedColumnIndex).toBe(2)+ })+it('closes the modal when the reloaded results no longer contain the selected row', async () => {await loadResults(fourCohorts)await expectLogic(logic, () => {diff --git a/products/product_analytics/frontend/insights/retention/retentionModalLogic.ts b/products/product_analytics/frontend/insights/retention/retentionModalLogic.tsindex e1c4cd022ef0..c317d879db0e 100644--- a/products/product_analytics/frontend/insights/retention/retentionModalLogic.ts+++ b/products/product_analytics/frontend/insights/retention/retentionModalLogic.ts@@ -3,6 +3,7 @@ import { subscriptions } from 'kea-subscriptions'import api from 'lib/api'import type { DataColorTheme } from 'lib/colors'+import { consumePersonsModalClick } from 'lib/components/ResultMenu/personsModalCapture'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { cohortSavedToast } from 'scenes/cohorts/cohortSavedToast'@@ -39,6 +40,7 @@ import { retentionToActorsQuery } from './queries'import { retentionLogic } from './retentionLogic'import { retentionPeopleLogic } from './retentionPeopleLogic'import { ProcessedRetentionPayload } from './types'+import { formatRetentionCohortLabel } from './utils'const DEFAULT_RETENTION_LOGIC_KEY = 'default_retention_key'@@ -351,12 +353,27 @@ export const retentionModalLogic = kea<retentionModalLogicType>([},})),listeners(({ actions, values }) => ({- openModal: ({ rowIndex, breakdownValue }: { rowIndex: number; breakdownValue?: string | number | null }) => {+ openModal: ({ rowIndex, breakdownValue, columnIndex }) => {// Backstop for render surfaces that don't check canOpenPersonModal before dispatching:// custom aggregation targets can't resolve actors, so don't fire the query.if (!values.canOpenPersonModal) {return}+ const row = values.selectedRow+ if (+ row &&+ values.actorsQuery &&+ consumePersonsModalClick({+ title: row.date+ ? `${formatRetentionCohortLabel(row, values.retentionFilter?.period)} Cohort`+ : row.label,+ rowsQuery: { kind: NodeKind.DataTableNode, source: values.actorsQuery, full: true },+ open: () => actions.openModal(rowIndex, breakdownValue, columnIndex),+ })+ ) {+ actions.closeModal()+ return+ }actions.loadPeople(rowIndex, breakdownValue)},saveAsCohort: async ({ cohortName }) => {diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsxindex 10331566c24e..85ab3e1c347a 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx+++ b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx@@ -132,12 +132,12 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.ElyAxisScaleType,isGrouped,valueLabels: showValuesOnSeries ? { formatter: stickinessPercentFormatter } : false,- tooltip: tooltipConfig,+ tooltip: { ...tooltipConfig, resolveClickToNearestSeries: context?.dashboardResultMenu },}),// Interactive legend is a component concern, kept out of the pure transform.legend: legendConfig,}),- [yAxisScaleType, isGrouped, showValuesOnSeries, legendConfig, tooltipConfig]+ [context?.dashboardResultMenu, yAxisScaleType, isGrouped, showValuesOnSeries, legendConfig, tooltipConfig])// Close over the primitives so the click memos don't invalidate when unrelateddiff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsxindex 621810bb4981..34a6575e5f32 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx@@ -132,13 +132,20 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.yAxisScaleType,valueLabels: showValuesOnSeries ? { formatter: stickinessPercentFormatter } : false,showCrosshair: true,- tooltip: tooltipConfig,+ tooltip: { ...tooltipConfig, resolveClickToNearestSeries: context?.dashboardResultMenu },}),curve: chartStyleCurve(stickinessFilter?.chartStyle),// Interactive legend is a component concern, kept out of the pure transform.legend: legendConfig,}),- [yAxisScaleType, showValuesOnSeries, legendConfig, tooltipConfig, stickinessFilter?.chartStyle]+ [+ context?.dashboardResultMenu,+ yAxisScaleType,+ showValuesOnSeries,+ legendConfig,+ tooltipConfig,+ stickinessFilter?.chartStyle,+ ])const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModaldiff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsxindex 9c4ef42de7ac..8835971e974f 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx@@ -121,8 +121,8 @@ describe('TrendsBarChart (ActionsBar)', () => {)})- it('opens the persons modal on click for a single series', async () => {- renderInsight({ query: trendsBar() })+ it.each([false, true])('opens the persons modal directly on a dashboard (compare=%s)', async (compare) => {+ renderInsight({ query: trendsBar({ compareFilter: { compare } }), context: { dashboardResultMenu: true } })await screen.findByLabelText(/chart with/i, undefined, { timeout: 5000 })await chart.clickAtIndex(2)diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsxindex 303cfc32505a..fdcb54ffdfe4 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx@@ -265,7 +265,7 @@ export function TrendsBarChart({yAxisLabel: trendsFilter?.yAxisLabel,goalLines,valueLabels: showValuesOnSeries ? { formatter: valueLabelFormatter } : false,- tooltip: INSIGHT_TOOLTIP_CONFIG,+ tooltip: { ...INSIGHT_TOOLTIP_CONFIG, resolveClickToNearestSeries: context?.dashboardResultMenu },}),// Interactive legend (toggle callbacks, context menu) is a component concern, kept out// of the pure transform so the builder stays free of React state.@@ -281,6 +281,7 @@ export function TrendsBarChart({timezone,currentPeriodResult?.days,hideAxes,+ context?.dashboardResultMenu,trendsFilter?.xAxisLabel,trendsFilter?.yAxisLabel,goalLines,@@ -311,7 +312,7 @@ export function TrendsBarChart({}return {showGrid: true,- tooltip: AGGREGATED_TOOLTIP_CONFIG,+ tooltip: { ...AGGREGATED_TOOLTIP_CONFIG, resolveClickToNearestSeries: context?.dashboardResultMenu },yScaleType: yAxisScaleType === 'log10' ? 'log' : 'linear',axisOrientation: 'horizontal',barLayout: 'stacked',@@ -332,6 +333,7 @@ export function TrendsBarChart({bars: { fitToHeight: embedded, divergingStack: true },}}, [+ context?.dashboardResultMenu,hideAxes,yAxisScaleType,aggregatedYTickFormatter,diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsxindex 38b451625339..52324bb09cf6 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx@@ -140,10 +140,11 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLitimezone,allDays: currentPeriodResult?.days ?? [],valueLabels: showValuesOnSeries || showPercentagesOnSeries ? { formatter: valueLabelFormatter } : false,- tooltip: LIFECYCLE_TOOLTIP_CONFIG,+ tooltip: { ...LIFECYCLE_TOOLTIP_CONFIG, resolveClickToNearestSeries: context?.dashboardResultMenu },legend: legendConfig,}),[+ context?.dashboardResultMenu,indexedResults,buildMeta,currentPeriodResult?.labels,diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsxindex 7286cb372a19..c6256086a8af 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx@@ -349,10 +349,11 @@ export function TrendsLineChart({valueLabels: showValuesOnSeries && valueLabelFormatter ? { formatter: valueLabelFormatter } : false,curve: chartStyleCurve(trendsFilter?.chartStyle),showCrosshair: true,- tooltip: INSIGHT_TOOLTIP_CONFIG,+ tooltip: { ...INSIGHT_TOOLTIP_CONFIG, resolveClickToNearestSeries: context?.dashboardResultMenu },legend: legendConfig,}),[+ context?.dashboardResultMenu,indexedResults,trendsFilter,baseCurrency,