:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mobile): show formula charts in both report views (#126799)
Chris Volzer21a06d34e7ad
diff --git a/products/mobile/docs/DATA.md b/products/mobile/docs/DATA.mdindex 7785d32621a9..d12ccf035f44 100644--- a/products/mobile/docs/DATA.md+++ b/products/mobile/docs/DATA.md@@ -96,6 +96,7 @@ It also carries `from`, read from the route's `from` param: `inbox` (a row tap),**Full report.** "Read the full report" under the lede opens `/report/{id}/details` when the report has a summary or at least one signal.The screen reads `useReport(id)`, so it shares the report screen's cache and does not poll.+The Charts section follows the summary and shows the same chart titles, captions, and open links as the abbreviated report.The signals can arrive after the first render when a Today page exists, because the report screen does not wait for them then; the Signals section appears when they land.`mobile_report_details_opened` is sent once per open, with `report_id`, `has_summary` and `signal_count`.`mobile_report_details_link_opened` carries `report_id` and `target`: `web` (Open in PostHog), `replay` (a signal's Watch session) or `link` (a link in the summary or a signal).@@ -147,7 +148,9 @@ A metric has a saved snapshot (`value`, `value_at`, up to 14 undated `series` po- **Open link.** `{host}/project/{id}/insights/new#q=<query>` with the embed flags (`full`, `embedded`, `show*`) removed. A link over 8,000 characters is dropped, because nginx refuses a longer request line.`reportChartView(chart, scope)` builds a `ReportChartView`.-The app draws a chart only when it is an `InsightVizNode` with a `TrendsQuery` source, one series, no breakdown, and a display that draws buckets over time (`ActionsLineGraph`, `ActionsLineGraphCumulative`, `ActionsAreaGraph`, the three bar displays, or none).+The app draws a chart only when it is an `InsightVizNode` with a `TrendsQuery` source, one output series, no breakdown, and a display that draws buckets over time (`ActionsLineGraph`, `ActionsLineGraphCumulative`, `ActionsAreaGraph`, the three bar displays, or none).+A single `formulaNodes` entry can combine multiple input series into that output series.+Queries with multiple output formulas keep their open link instead of drawing only the first result.Such a chart gets `data` (its own display kept, the same clean-up as a metric) and a format from `aggregationAxisFormat`.Any other chart (SQL, saved insight, pie, number, table, breakdown) has no `data` and stays in the list with its title and open link:`/sql?open_query=` for a `DataVisualizationNode` with a `HogQLQuery` source, `/insights/{shortId}` for a `SavedInsightNode`.@@ -184,6 +187,10 @@ The query endpoint needs the `query:read` scope. Without it the request answers- While the live query loads, nothing is drawn, so the chart does not draw the snapshot and then redraw.- With no points at all, the observation leaves the chart out. A drawable chart in the Charts section shows a spinner while it loads, then "No data in this window." or an error line.+Each report screen uses `ChartCanvasBudget`, active only while that screen has focus.+The observation and report charts share the limit of six native canvases.+Additional charts and charts on an unfocused screen use sparklines of the same height.+## Actions- **Sheets.** `mobile_report_sheet_opened` carries `sheet` (`handoff`, `resolve`, `dismiss`, `assignee`, `priority`, `decision`, `pull_request_picker`), `from` (`action_bar`, `chip` for the owner and priority chips, `inbox_menu`) and `report_id`. `mobile_report_sheet_dismissed` carries the same properties and is sent only when the sheet closes without its completion: a successful resolve, dismiss, priority or reviewer save, a hand-off attempt, an external agent opened or a prompt copied, a picked pull request, or an answer sent. The completion events below carry `report_id`.diff --git a/products/mobile/src/features/report/ReportScreen.test.tsx b/products/mobile/src/features/report/ReportScreen.test.tsxindex 02e1b29be100..353ee3410da9 100644--- a/products/mobile/src/features/report/ReportScreen.test.tsx+++ b/products/mobile/src/features/report/ReportScreen.test.tsx@@ -6,7 +6,7 @@ import { AppState } from 'react-native'import { setAuthProvider } from '@/api/client'import { useDemoMode } from '@/demo/demoMode'import { reportFixture } from '@/model/adapters/testFixtures'-+import { ReportDetailsScreen } from './details/ReportDetailsScreen'import { ReportScreen } from './ReportScreen'jest.mock('react-native-worklets', () => jest.requireActual('react-native-worklets/src/mock'))@@ -22,7 +22,7 @@ jest.mock('react-native-keyboard-controller', () => jest.requireActual('react-najest.mock('expo-notifications', () => ({}))jest.mock('expo-router', () => ({useFocusEffect: (callback: () => void) => require('react').useEffect(callback, [callback]),- useIsFocused: () => true,+ useIsFocused: () => mockFocused,useRouter: () => ({ push: jest.fn(), setParams: jest.fn(), canGoBack: () => false, replace: jest.fn() }),}))jest.mock('@/auth/useProjectScope', () => {@@ -32,10 +32,44 @@ jest.mock('@/auth/useProjectScope', () => {jest.mock('@/lib/analytics', () => ({ track: jest.fn() }))const REPORT = reportFixture()+let mockFocused = trueconst EXISTING = { uuid: 'existing-user', first_name: 'Existing', last_name: 'Reviewer', email: '[email protected]' }const ADDED = { uuid: 'added-user', first_name: 'Added', last_name: 'Reviewer', email: '[email protected]' }-describe('ReportScreen reviewers', () => {+describe('ReportScreen', () => {+ test.each(['abbreviated', 'full'] as const)('releases canvases when the %s report loses focus', async (kind) => {+ useDemoMode.getState().setEnabled(true)+ const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })+ const wrapper = ({ children }: { children: ReactNode }): ReactElement => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ )+ const reportScreen = (): ReactElement =>+ kind === 'abbreviated' ? (+ <ReportScreen reportId="demo-report-load-time" from="inbox" />+ ) : (+ <ReportDetailsScreen reportId="demo-report-load-time" />+ )+ const view = render(reportScreen(), { wrapper })+ try {+ await waitFor(() => expect(screen.getByTestId('report-chart-load-time-30d-canvas')).toBeTruthy())+ mockFocused = false+ view.rerender(reportScreen())+ expect(screen.queryByTestId('report-chart-load-time-30d-canvas')).toBeNull()+ expect(+ screen.getByTestId('report-chart-load-time-30d-canvas-placeholder', { includeHiddenElements: true })+ ).toBeTruthy()+ expect(screen.queryByTestId('report-observation-chart')).toBeNull()+ mockFocused = true+ view.rerender(reportScreen())+ expect(screen.getByTestId('report-chart-load-time-30d-canvas')).toBeTruthy()+ } finally {+ view.unmount()+ client.clear()+ mockFocused = true+ useDemoMode.getState().setEnabled(false)+ }+ })+test.each(['loaded', 'retry'] as const)('keeps an existing reviewer beyond the first activity page when adding another (%s)',async (scenario) => {diff --git a/products/mobile/src/features/report/ReportScreen.tsx b/products/mobile/src/features/report/ReportScreen.tsxindex 8a3f0176feeb..cc637f8856f8 100644--- a/products/mobile/src/features/report/ReportScreen.tsx+++ b/products/mobile/src/features/report/ReportScreen.tsx@@ -1,5 +1,5 @@import { useQueryClient } from '@tanstack/react-query'-import { useRouter } from 'expo-router'+import { useIsFocused, useRouter } from 'expo-router'import { type ReactElement, useEffect, useState } from 'react'import { View } from 'react-native'import Animated, { useAnimatedScrollHandler, useSharedValue } from 'react-native-reanimated'@@ -16,6 +16,7 @@ import {RESOLVE_REASON_OPTIONS,type ResolveReason,} from '@/model/verdictReasons'+import { ChartCanvasBudget } from '@/ui/chart/budget/ChartCanvasBudget'import { FloatingCard } from '@/ui/FloatingCard'import { WarningIcon } from '@/ui/icons/WarningIcon'import { OverlayHost } from '@/ui/OverlayPortal'@@ -71,9 +72,12 @@ function goBackOrInbox(router: ReturnType<typeof useRouter>): void {export function ReportScreen({ reportId, from }: ReportScreenProps): ReactElement {const demo = useDataMode() === 'demo'+ const focused = useIsFocused()return (<OverlayHost>- {isReportId(reportId, demo) ? <ReportContent reportId={reportId} from={from} /> : <ReportNotFound />}+ <ChartCanvasBudget active={focused}>+ {isReportId(reportId, demo) ? <ReportContent reportId={reportId} from={from} /> : <ReportNotFound />}+ </ChartCanvasBudget></OverlayHost>)}diff --git a/products/mobile/src/features/report/details/ReportDetailsScreen.tsx b/products/mobile/src/features/report/details/ReportDetailsScreen.tsxindex 54562bbc5af0..a5788e05d93f 100644--- a/products/mobile/src/features/report/details/ReportDetailsScreen.tsx+++ b/products/mobile/src/features/report/details/ReportDetailsScreen.tsx@@ -1,4 +1,4 @@-import { useRouter } from 'expo-router'+import { useIsFocused, useRouter } from 'expo-router'import { type ReactElement, useEffect, useRef, useState } from 'react'import { Text, View } from 'react-native'import Animated, { useAnimatedScrollHandler, useSharedValue } from 'react-native-reanimated'@@ -6,6 +6,7 @@ import { useDataMode } from '@/demo/demoMode'import { track } from '@/lib/analytics'import { isReportId } from '@/lib/ids'import type { ReportView } from '@/model/types'+import { ChartCanvasBudget } from '@/ui/chart/budget/ChartCanvasBudget'import { WarningIcon } from '@/ui/icons/WarningIcon'import { LoadingView, StateView } from '@/ui/StateView'import { SCREEN_CONTENT_TOP } from '@/ui/screenLayout'@@ -15,6 +16,7 @@ import { bottomOffset, topOffset, useScreenInsets } from '@/ui/useScreenInsets'import { headlineText } from '../Headline'import { useReport } from '../hooks'+import { ReportCharts } from '../metrics/ReportCharts'import { HEADLINE_GAP, TopChrome } from '../TopChrome'import { useReportReadTracking } from '../useReportReadTracking'import { DetailsFooter } from './DetailsFooter'@@ -33,6 +35,7 @@ export function ReportDetailsScreen({ reportId }: ReportDetailsScreenProps): Reaconst styles = useStyles()const colors = useColors()const router = useRouter()+ const focused = useIsFocused()const demo = useDataMode() === 'demo'const valid = isReportId(reportId, demo)// A deep link can open this screen with nothing under it, so Back then lands on the report itself.@@ -47,21 +50,23 @@ export function ReportDetailsScreen({ reportId }: ReportDetailsScreenProps): Rea}return (<View style={styles.screen} testID="report-details-screen">- {valid ? (- <DetailsContent reportId={reportId} onBack={goBack} />- ) : (- <>- <TopChrome onBack={goBack} withPager={false} />- <StateView- icon={<WarningIcon size={iconSizes.empty} color={colors.tertiary} />}- title="Couldn't find this report"- message="This link doesn't point to a report. Go back and open the report from your inbox."- actionLabel="Go back"- onAction={goBack}- testID="report-details-not-found"- />- </>- )}+ <ChartCanvasBudget active={focused}>+ {valid ? (+ <DetailsContent reportId={reportId} onBack={goBack} />+ ) : (+ <>+ <TopChrome onBack={goBack} withPager={false} />+ <StateView+ icon={<WarningIcon size={iconSizes.empty} color={colors.tertiary} />}+ title="Couldn't find this report"+ message="This link doesn't point to a report. Go back and open the report from your inbox."+ actionLabel="Go back"+ onAction={goBack}+ testID="report-details-not-found"+ />+ </>+ )}+ </ChartCanvasBudget></View>)}@@ -143,6 +148,7 @@ function DetailsBody({ report, refreshing, onBack }: DetailsBodyProps): ReactEle{hasReportDetail(report) ? (<>{report.summary ? <DetailsSummary summary={report.summary} reportId={report.id} /> : null}+ <ReportCharts charts={report.charts} reportId={report.id} accent={report.accent} /><SignalsSection signals={report.signals} reportId={report.id} /></>) : (diff --git a/products/mobile/src/features/report/details/chartRefs.ts b/products/mobile/src/features/report/details/chartRefs.tsindex b2b2df6daf76..79e9aa794c79 100644--- a/products/mobile/src/features/report/details/chartRefs.ts+++ b/products/mobile/src/features/report/details/chartRefs.ts@@ -2,8 +2,8 @@ import type { MarkdownIt } from 'react-native-markdown-display'type Token = ReturnType<MarkdownIt['parse']>[number]-// Report summaries point at their charts with `[label](chart:chart_id)`. The web draws the chart there; the full-// report leaves charts to the report screen, so a reference reads as its label.+// Report summaries point at their charts with `[label](chart:chart_id)`. Both mobile report views draw charts in a+// separate section, so an inline reference reads as its label.const CHART_HREF = /^chart:/ifunction isChartLinkOpen(token: Token): boolean {diff --git a/products/mobile/src/features/report/metrics/ObservationCard.tsx b/products/mobile/src/features/report/metrics/ObservationCard.tsxindex b53062a7ed85..fbfc4b6ac14d 100644--- a/products/mobile/src/features/report/metrics/ObservationCard.tsx+++ b/products/mobile/src/features/report/metrics/ObservationCard.tsx@@ -51,6 +51,7 @@ export function ObservationCard({ metric, reportId, accent }: ObservationCardProlabel={metric.title}formatValue={formatValue}onSelect={onSelect}+ canvasSlot={{ key: `observation:${metric.metricId}`, index: 0 }}testID="report-observation-chart"/></View>diff --git a/products/mobile/src/features/report/metrics/ReportCharts.test.tsx b/products/mobile/src/features/report/metrics/ReportCharts.test.tsxnew file mode 100644index 000000000000..31852ed4b1b0--- /dev/null+++ b/products/mobile/src/features/report/metrics/ReportCharts.test.tsx@@ -0,0 +1,70 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, screen } from '@testing-library/react-native'+import type { ReactElement } from 'react'++import type { MetricData, MetricView, ReportChartView } from '@/model/types'+import { ChartCanvasBudget, MAX_MOUNTED_CANVASES } from '@/ui/chart/budget/ChartCanvasBudget'++import { ObservationCard } from './ObservationCard'+import { ReportCharts } from './ReportCharts'++jest.mock('@/demo/demoMode', () => ({ useDataMode: () => 'demo' }))+jest.mock('@/auth/useProjectScope', () => ({ useProjectScope: () => null }))++const data: MetricData = {+ kind: 'static',+ value: 4,+ series: { interval: 'day', points: [{ at: '2026-10-13', value: 4 }] },+}+const charts: ReportChartView[] = Array.from({ length: 20 }, (_, index) => ({+ chartId: `chart-${index}`,+ title: `Chart ${index}`,+ chart: 'line',+ interval: 'day',+ format: { valueFormat: 'number', unit: null },+ data,+}))+const observation: MetricView = {+ metricId: 'observation',+ role: 'primary',+ title: 'Affected sessions',+ chart: 'bar',+ interval: 'day',+ format: { valueFormat: 'count', unit: null },+ windowLabel: 'Current window',+ filterCount: 0,+ data,+}++describe('ReportCharts', () => {+ test('shares the canvas limit with the observation and releases every canvas when inactive', () => {+ const client = new QueryClient()+ const report = (active: boolean): ReactElement => (+ <QueryClientProvider client={client}>+ <ChartCanvasBudget active={active}>+ <ObservationCard metric={observation} reportId="report-1" accent="alert" />+ <ReportCharts charts={charts} reportId="report-1" accent="alert" />+ </ChartCanvasBudget>+ </QueryClientProvider>+ )+ const canvases = /^report-(chart-.*-canvas|observation-chart)$/+ const placeholders = /^report-(chart-.*-canvas|observation-chart)-placeholder$/+ const view = render(report(true))+ try {+ expect(screen.getAllByTestId(canvases)).toHaveLength(MAX_MOUNTED_CANVASES)+ expect(screen.getByTestId('report-observation-chart')).toBeTruthy()+ expect(screen.getAllByTestId(placeholders, { includeHiddenElements: true })).toHaveLength(+ 21 - MAX_MOUNTED_CANVASES+ )+ expect(screen.getByText('Chart 19')).toBeTruthy()+ view.rerender(report(false))+ expect(screen.queryAllByTestId(canvases)).toHaveLength(0)+ expect(screen.getAllByTestId(placeholders, { includeHiddenElements: true })).toHaveLength(21)+ view.rerender(report(true))+ expect(screen.getAllByTestId(canvases)).toHaveLength(MAX_MOUNTED_CANVASES)+ } finally {+ view.unmount()+ client.clear()+ }+ })+})diff --git a/products/mobile/src/features/report/metrics/ReportCharts.tsx b/products/mobile/src/features/report/metrics/ReportCharts.tsxindex 48ee07aff3ba..bdf81e60899e 100644--- a/products/mobile/src/features/report/metrics/ReportCharts.tsx+++ b/products/mobile/src/features/report/metrics/ReportCharts.tsx@@ -29,8 +29,8 @@ export function ReportCharts({ charts, reportId, accent }: ReportChartsProps): Rreturn (<View style={styles.section} testID="report-charts"><Eyebrow>Charts</Eyebrow>- {charts.map((chart) => (- <ChartCard key={chart.chartId} chart={chart} reportId={reportId} accent={accent} />+ {charts.map((chart, index) => (+ <ChartCard key={chart.chartId} chart={chart} reportId={reportId} accent={accent} index={index + 1} />))}</View>)@@ -40,16 +40,17 @@ interface ChartCardProps {chart: ReportChartViewreportId: stringaccent: Accent+ index: number}-function ChartCard({ chart, reportId, accent }: ChartCardProps): ReactElement {+function ChartCard({ chart, reportId, accent, index }: ChartCardProps): ReactElement {const styles = useStyles()const openUrl = insightUrl(chart.openUrl)return (<View style={styles.card} testID={`report-chart-${chart.chartId}`}><Text style={styles.title}>{chart.title}</Text>{chart.caption ? <Text style={styles.caption}>{chart.caption}</Text> : null}- {chart.data ? <DrawnChart chart={chart} reportId={reportId} accent={accent} /> : null}+ {chart.data ? <DrawnChart chart={chart} reportId={reportId} accent={accent} index={index} /> : null}{openUrl ? (<View style={styles.footer}><OpenInsightLink url={openUrl} reportId={reportId} source="chart" title={chart.title} />@@ -59,7 +60,7 @@ function ChartCard({ chart, reportId, accent }: ChartCardProps): ReactElement {)}-function DrawnChart({ chart, reportId, accent }: ChartCardProps): ReactElement | null {+function DrawnChart({ chart, reportId, accent, index }: ChartCardProps): ReactElement | null {const styles = useStyles()const colors = useColors()const state = useChartPoints(chart.data)@@ -78,6 +79,7 @@ function DrawnChart({ chart, reportId, accent }: ChartCardProps): ReactElement |label={chart.title}formatValue={formatValue}onSelect={onSelect}+ canvasSlot={{ key: `chart:${chart.chartId}`, index }}testID={`report-chart-${chart.chartId}-canvas`}/></View>diff --git a/products/mobile/src/model/adapters/metric.test.ts b/products/mobile/src/model/adapters/metric.test.tsindex 429ddbce4d39..5f33f43fcad5 100644--- a/products/mobile/src/model/adapters/metric.test.ts+++ b/products/mobile/src/model/adapters/metric.test.ts@@ -168,6 +168,34 @@ describe('report metric', () => {test.each<[string, unknown, boolean, string | undefined]>([['a trends line', trends({ trendsFilter: { display: 'ActionsLineGraph' } }), true, NEW_INSIGHT],['a trends graph with no display', trends(), true, NEW_INSIGHT],+ [+ 'one formula combining two input series',+ trends({+ series: [+ { kind: 'EventsNode', event: 'checkout_started' },+ { kind: 'EventsNode', event: 'checkout_retried' },+ ],+ trendsFilter: {+ display: 'ActionsLineGraph',+ formulaNodes: [{ formula: 'B/A' }],+ aggregationAxisFormat: 'percentage_scaled',+ },+ }),+ true,+ NEW_INSIGHT,+ ],+ [+ 'two output formulas from one input series',+ trends({ trendsFilter: { formulaNodes: [{ formula: 'A' }, { formula: 'A*2' }] } }),+ false,+ NEW_INSIGHT,+ ],+ [+ 'two input series without a formula',+ trends({ series: [{ kind: 'EventsNode' }, { kind: 'EventsNode' }] }),+ false,+ NEW_INSIGHT,+ ],['a bold number', trends({ trendsFilter: { display: 'BoldNumber' } }), false, NEW_INSIGHT],['a pie', trends({ trendsFilter: { display: 'ActionsPie' } }), false, NEW_INSIGHT],['a breakdown', trends({ breakdownFilter: { breakdown: '$browser' } }), false, NEW_INSIGHT],diff --git a/products/mobile/src/model/adapters/metric.ts b/products/mobile/src/model/adapters/metric.tsindex 364c731af2a7..01eed6548fd7 100644--- a/products/mobile/src/model/adapters/metric.ts+++ b/products/mobile/src/model/adapters/metric.ts@@ -352,12 +352,14 @@ export function hasBreakdown(source: unknown): boolean {return Boolean(filter?.breakdown) || (Array.isArray(filter?.breakdowns) && filter.breakdowns.length > 0)}-/** The chart kind when the app can draw the chart, else undefined. The app draws one series without a breakdown. */+/** The app draws one output series without a breakdown. A formula can combine several input series. */export function drawableChartKind(insight: TrendsInsight | undefined): MetricChartKind | undefined {- if (!insight || seriesNodes(insight).length !== 1 || hasBreakdown(insight.source)) {+ if (!insight || hasBreakdown(insight.source)) {return undefined}- return timeSeriesChartKind(insight)+ const formulas = asRecord(insight.source.trendsFilter)?.formulaNodes+ const outputCount = Array.isArray(formulas) && formulas.length > 0 ? formulas.length : seriesNodes(insight).length+ return outputCount === 1 ? timeSeriesChartKind(insight) : undefined}/** Keeps the authored display, such as a cumulative line, which the server computes. */