: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(alerts): render the alert simulation chart with quill charts (#86564)
Sam Penningtonfd2d6496dca9
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1b0cb88aaef1..c41aa5f6bfce 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4745,25 +4745,25 @@ snapshots:posthog-3000-keyboard-shortcut--within-tooltip--light:hash: v1.k794b7964.aa2d9701c9134d5c374b6517f2fa542eb24c7e15ebf0d65f64efbc0ec2a99efa.BL1mMRm5CNDAmAMk-2pf-lp8EI6t65oBqoy990BdgyQproducts-alerts-alert-history-chart--anomaly-probability-cutoff--dark:- hash: v1.k794b7964.24b4adbdb188cde0541f0f66f73af27bdd04408c31291bf68316bb3817759643.GuBTwp4mmQHHVO07xyvgxbSCEuKylDxNzue0viIzLts+ hash: v1.k794b7964.d8bfbcdf6258aaa31643fb641a3c4c5679ec385116869f16e892a23b657ff910.rSI-RaJqddtdxzgnTMB65ntFwfOTQ1FTvx5ISZT2VHYproducts-alerts-alert-history-chart--anomaly-probability-cutoff--light:- hash: v1.k794b7964.500239b49ffc44daa00a24697ef4946abf9758e01dedee6dbb1d1af3906f257c.nl3i95cuHsjkdCBCnS4xRr8tQF_B2SfUyS4F_g_55LI+ hash: v1.k794b7964.bf88e81ad8b34d4f9ece6568275319edd07ca1778e6767ada0cfbc8b11d409a5.wTXTtVDIcUl5_F3uuL3TkIgzQ4FfUi-42IXNLtWrgO4products-alerts-alert-history-chart--default--dark:- hash: v1.k794b7964.efa18d82f9a40253504c02eb062d651733a4b9cd5bef60cb826a2d2d4e5aca15.ygobekdfgBV5hQ5lhMqSVntK2thZLJ62elkYyIsup2A+ hash: v1.k794b7964.5f80261867dfc65f19ccef144fac19669df2765ae6d3059e3a8a713d18d02f2e.VltOzLJjhvhc6neuKq7VMBLqe9Z32JDVDdJeiJr5hncproducts-alerts-alert-history-chart--default--light:- hash: v1.k794b7964.a7d3030c73c7d63ac5ebdb9f35f985b226f08b02b51bbca23b57a4cf7bc923ab.wxt6Ij2d2K3YHE_xMHn31yw55jtjg3NumtkOFqIt-pg+ hash: v1.k794b7964.3f9a52b3393d2509d9f34bc63feb257b1356478f17eb48d0866e23f5e60f6800.c8hZrHeK0bGi_ToWWPYQ3pKIFqBt9qpBMs2blvwMPEgproducts-alerts-alert-history-chart--percentage-thresholds--dark:- hash: v1.k794b7964.2046df03cbbcf8dfe13000c0b206825d4eeb0a245d77018eca9e667cac408220.aQCr7KvmqJfS_vvMr0sCmxpChikqme1d-XafYaz5lnk+ hash: v1.k794b7964.47dfba3bed051ef991292a0975006f037917951e85532058204729b8ed96cfb6.8lvTV6Y5wRcXQvEkfE6Qw1SeeUoHHBJDpMJcvhoFa0Qproducts-alerts-alert-history-chart--percentage-thresholds--light:- hash: v1.k794b7964.4bbbbc9b49cda8e42351cc594ad03efa6ee5814ca544fff3744faa9d1a4e3ae1.Yj-kqEp4dDdxh1kcOikNz-_-fGpqJPDT1c_rIf7UCyM+ hash: v1.k794b7964.b783816797aa9d4dca9f2d98d5da87d33ed859efb98225c1497ea6915f8e1e69._oGhSZarZKQpZpBxyLY6LE4tEfU00k6ID_jdRwIz3e8products-alerts-alert-history-chart--threshold-changed--dark:- hash: v1.k794b7964.be71ec307fbbba2ac6bd1526a4715e2b0694569a22e238e89b2010c67ec8a572.X1TzLmh_AD3_Z7FDKT6xCtBUaIiCf9pA399uMF_FLHk+ hash: v1.k794b7964.7bf1274551a74797d5833aaef99e0a8e3b94601da2c9f0d404dc4242a11f13ee.lXzcaeoPoWGMrObwVAEvoMvMmF5GMk6QEOobb5_TFdMproducts-alerts-alert-history-chart--threshold-changed--light:- hash: v1.k794b7964.d8da461055012775ff1c2b8fc9d1f5a9c89b29ff26fc55f5d46a3d8cd16dd528.QcTzP3OJNKPkc5oFv-o12pqIzZhAsGe3dx535bJZRpM+ hash: v1.k794b7964.2f3272da0133084fc9f0642a0c9fc6ef2d17966cb90f15a061af194de6aeb65a.cPsoLgzTHziozJsBVANa09XANxKRiJ9Ow6AmjKBTDuoproducts-alerts-alert-history-chart--truncated-history--dark:- hash: v1.k794b7964.a6c3e16a4c2d3afbda4f0c6ee8654059c1ce1af118e06ff9684245d7d4e90d56.9SeAY0VADP000GUzOLjde2l3zk2b9byQ_OcXjfqIlJw+ hash: v1.k794b7964.90455fb16477e13cef13f6cb74b8abc051d4994e8367ef4b3f48eae05e3d60ac.xh6PbdClVykw-EidRF0HQ0qokwczbQ9Wp5O3otHOEboproducts-alerts-alert-history-chart--truncated-history--light:- hash: v1.k794b7964.fb04c5eb2dee3e54286be4a599a42b81f81f696254510bc5dc107ce44a182231.fmS-_SPCu4bmN_8mtGiy_Oux8l-ylT8S8UvLt2OtwZo+ hash: v1.k794b7964.a6451435f2289854bb80da841df8a6f9d7cbd9dcd5226a1f084df4a58e43ea15.NPQCI2X1Msq2OjxA2G-uDiMooR2KkSLUOa44T0ipv4cproducts-alerts-alert-modal--create-wizard--dark:hash: v1.k794b7964.e3efb1235db76f2fe8b3ccff465df9b84263211b8648d57a725cfcf3a92c08c9.mTtZUY5-gkDVf9yjhBIR_Cx1_5arKEIEJh-2g-cLQBQproducts-alerts-alert-modal--create-wizard--light:@@ -4840,6 +4840,14 @@ snapshots:hash: v1.k794b7964.5882b745c748c44c9f3b1026e1c35953d8e2034b5f31588d2030a8502bd5afdd.k0NFXRurTVmlsO_6I1VF93n7KlCAP3ye3kztNwuaV0kproducts-alerts-shared-components--quiet-hours--light:hash: v1.k794b7964.fcd387116bcdd0296037b1d39ca7292a9f907f38e1de5dd3cdf7208f2b030090.qfzWLrCzf5SGKavDpoj3Kp6bw_h6tyghF8SEt3aunp4+ products-alerts-simulation-summary--single-score--dark:+ hash: v1.k794b7964.323f30cad099e956b726de1a0c13cad9fe154bbb8875a97271cc64b5901156c4.PrWg937npd7kPy2CWA_6vOHXEPfBGpeSFMNjva_cNvA+ products-alerts-simulation-summary--single-score--light:+ hash: v1.k794b7964.494b6d4b3474130b75a5cfe5aa5f40e03a9a01730e4edef0827e20876d1f306c.5oF3OfqASerOC-oLHc0U3oT6eBeUo_nk_G0oXvNEnsc+ products-alerts-simulation-summary--sub-detector-scores--dark:+ hash: v1.k794b7964.9b9173dedd94291c385ee5715e514f79dfb1cf18b8add4e9ff40b316b5b693cf._BBMLMlcVv4VsMnT1HPd_PtgeKB_DMccaaBLhxDuiTI+ products-alerts-simulation-summary--sub-detector-scores--light:+ hash: v1.k794b7964.9feb4230d4009e6003dc794c073a3bb90ddd01ebfc2b97ee5cc0f33db48c5947.EcS4qy17BLNw7s4VhlznrFQIt25dU9KvIbfXez_ezDQproducts-dashboards--dashboard-states--dark:hash: v1.k794b7964.cc591635f83447f7bcfb802062302b8b1bbcd51826110b12fa0f68d4830dcfd3.CIgt_KxCyQRgbn7DPF4MDXc5JBlSxbaCPS0Snyx3cRsproducts-dashboards--dashboard-states--light:diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 89ecfffa175c..7ee211de8e54 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -102,8 +102,8 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration_ms | duration_ns`, plus `prefix`/`suffix`. Numeric and percentage ticks default to two decimals but gain a decimal per leading zero below 0.1, so a small-valued axis (say latency in seconds over 0–0.012) doesn't render every tick as `0.01`; `decimalPlaces` pins the precision instead. The duration formats keep three significant digits below a minute for the same reason, then switch to the `1m 30s` unit breakdown.- Fixed x-axis tick rotation: set `xAxis.tickLabelRotation` on a time-series chart (`-45` tilts labels left). Values are clamped to `-90..90`; omit it to keep horizontal labels and existing collision behavior.- y-axis baseline: defaults to clamping a non-negative axis down to 0 (matching the classic insight axis). To float the axis to its data range instead — zooming in on the variation — set `yAxis.startAtZero: false` on `TimeSeriesLineChart`, or `config.floatBaseline: true` on the lower-level `LineChart`. Ignored on a log scale (no zero baseline) and applied to the primary axis only. Bar charts always draw from a zero baseline, so the flag is a no-op there.-- y-axis min/max: `yAxis.min` / `yAxis.max` pin either end of the primary value axis on `TimeSeriesLineChart` (`config.valueDomain: { min, max }` on the lower-level `LineChart` — the same option that carries `include`, since a capped axis still has to stretch to reach an off-scale goal line; `mergeValueDomains` combines them field by field). How many ends are set decides the behavior: **both** pins the axis (skips `nice()`, discards `include`, overrides percent layout), **one** clamps that end and leaves the other automatic. A single clamp composes with auto-scaling — it runs after `include` folding, the zero-baseline clamp and `nice()`, so only the extreme label is the raw bound while interior ticks stay round — and is ignored under a percent layout, where the domain is already 0..1. On a log scale a non-positive bound is dropped. A non-finite bound counts as unset, so `{ min: 0, max: Math.max(...[]) }` floors at zero rather than collapsing. An inverted `min >= max` pair falls back to the automatic domain rather than swapping. Overlays positioned off the value scale hide themselves outside the bounded window rather than painting over the chrome: a goal line drops out, and so does the value label of a clipped point (a point sitting exactly on the bound keeps its label). Bar and combo charts deliberately ignore `min`/`max`, even though they take the same `yAxis` config: a bar encodes magnitude as length from zero, so a bounded baseline misreads it — 10 vs 11 would draw as 1 vs 2. Pin `valueDomain` there instead, which rescales the bars rather than truncating them.-- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. Duration formatters accept seconds (`duration`), milliseconds (`duration_ms`), or nanoseconds (`duration_ns`). `hide` and `startAtZero` are honored per entry (bar-series axes keep their zero baseline). A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. More than two axes work too (trends `showMultipleYAxes`): they stack outward per side and alternate sides. Each entry's `label` renders that axis's title at its own gutter — every axis is titled the same way (a single-object `yAxis`/scalar `yAxisLabel` is just the one left axis), driven by the shared `computeYAxisGutters` layout that `AxisLabels` (ticks) and `AxisTitles` (titles) both read so the two can't drift. `TimeSeriesBarChart`/`TimeSeriesComboChart` take the same `yAxis` array; a sole axis pinned `right` renders on the right on every chart type.+- y-axis min/max: `yAxis.min` / `yAxis.max` pin either end of a value axis on `TimeSeriesLineChart` (the primary one here; see the multi-axis entry below for secondary axes) (`config.valueDomain: { min, max }` on the lower-level `LineChart` — the same option that carries `include`, since a capped axis still has to stretch to reach an off-scale goal line; `mergeValueDomains` combines them field by field). How many ends are set decides the behavior: **both** pins the axis (skips `nice()`, discards `include`, overrides percent layout), **one** clamps that end and leaves the other automatic. A single clamp composes with auto-scaling — it runs after `include` folding, the zero-baseline clamp and `nice()`, so only the extreme label is the raw bound while interior ticks stay round — and is ignored under a percent layout, where the domain is already 0..1. On a log scale a non-positive bound is dropped. A non-finite bound counts as unset, so `{ min: 0, max: Math.max(...[]) }` floors at zero rather than collapsing. An inverted `min >= max` pair falls back to the automatic domain rather than swapping. Overlays positioned off the value scale hide themselves outside the bounded window rather than painting over the chrome: a goal line drops out, and so does the value label of a clipped point (a point sitting exactly on the bound keeps its label). Bar and combo charts deliberately ignore `min`/`max`, even though they take the same `yAxis` config: a bar encodes magnitude as length from zero, so a bounded baseline misreads it — 10 vs 11 would draw as 1 vs 2. Pin `valueDomain` there instead, which rescales the bars rather than truncating them.+- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. Duration formatters accept seconds (`duration`), milliseconds (`duration_ms`), or nanoseconds (`duration_ns`). `hide`, `startAtZero`, and `min`/`max` are honored per entry (bar-series axes keep their zero baseline). Pin `min`/`max` on a secondary axis whose meaning fixes its range rather than letting it float to its data — a 0-1 probability, a 0-100 percentage — otherwise a reference line above every point on that axis falls outside the plot, where it doesn't draw at all (see the overlay note under y-axis min/max above). On the primary axis the same bounds arrive as the chart-level `valueDomain`, merged with the goal-line stretch, so they compose rather than override. A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. More than two axes work too (trends `showMultipleYAxes`): they stack outward per side and alternate sides. Each entry's `label` renders that axis's title at its own gutter — every axis is titled the same way (a single-object `yAxis`/scalar `yAxisLabel` is just the one left axis), driven by the shared `computeYAxisGutters` layout that `AxisLabels` (ticks) and `AxisTitles` (titles) both read so the two can't drift. `TimeSeriesBarChart`/`TimeSeriesComboChart` take the same `yAxis` array; a sole axis pinned `right` renders on the right on every chart type.- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/`BarChart`/`TimeSeriesBarChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. Despite the name it is label-generic — it resolves the drag against label positions, so it works the same on categorical labels (weekdays, duration buckets) as on dates. A drag whose edges both snap to the same label (common on sparse charts, e.g. a 3-bar monthly chart) selects that single bucket, provided the drag spans enough horizontal distance to read as intentional. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis (`axisOrientation: 'horizontal'` bars, where the core disables the gesture).- `onAreaSelect` (base `Chart`, chart-type adapters only) is the 2D-brush sibling of `onDateRangeZoom`: the drag tracks both axes, the selection rect clamps to the dragged vertical range, and the completed gesture reports the x label range plus the raw x and y pixel spans (with the committed scales, so the adapter maps pixels onto its own bands). `Heatmap` exposes it as `onBrush` with row/column index ranges; a near-horizontal drag (<8px vertical) spans every row. `ScatterChart` exposes it as its own `onAreaSelect`, inverting the pixel spans through its continuous scales — the label range is meaningless there, since it snaps to whichever points sit near the drag edges. Each edge is clamped to its axis first, so a drag that overshoots the plot (routine when brushing into a corner) reports the rectangle the user saw rather than an extrapolated one. Takes precedence over `onDateRangeZoom` when both are set.- `ScatterChart` takes `series: ScatterSeries[]` — each `{ key, label, points: { x, y, label?, radius?, color?, meta? }[], color?, pointRadius?, shape? }` — and no `labels`, since both axes are continuous. `config.xAxis` / `config.yAxis` are symmetric `ScatterAxisConfig`s (`scaleType: 'linear' | 'log'`, `domain` to pin the range, `label`, `tickFormatter`, `hide`, `startAtZero`); unlike a trend, both axes float to their data range by default, because forcing either to zero squashes the correlation into a corner. On a log axis, points with a non-positive coordinate can't be placed and are dropped from the chart. A pinned `domain` narrows the chart rather than just its viewport: points outside it are dropped too, so nothing is drawn out in the axis gutters or piled onto the plot edge at a value it doesn't have. `shape` (`circle` | `square` | `triangle` | `cross`) separates series without relying on color alone, and markers fill at `config.fillOpacity` (0.7) over an opaque outline so a dense cloud reads as density. Hit-testing is 2D and edge-based: the tooltip resolves the marker nearest the cursor in both axes (a large marker the cursor sits inside beats a small one whose center is nearer), and empty plot area resolves to nothing at all rather than to the nearest column. `onPointClick` and the `tooltip` render prop both receive the resolved point (`ScatterPointDatum`, with its series and `meta`) rather than a data index; `config.legend` and `config.tooltip` (`enabled`, `placement`, `labelFormatter`, `xFormatter`, `yFormatter`) work as elsewhere. The default tooltip labels its two rows from the axis titles, falling back to the hovered point's series label for y (so a chart with one column per series still names the measure) and to `X` for x; a header that would just repeat the y row is dropped, leaving a single-series scatter reading as two labeled coordinates. The chrome toggles are the same keys every other chart takes — `showGrid`, `showAxisLines`, `showTickMarks`, `showCrosshair`, all off by default — so a host's shared config defaults reach a scatter the same way they reach a line chart. Its x ticks are resolved once per layout, so the grid lines, the tick marks, and the labels are the same set rather than three that can drift. `showBestFit` draws a dashed least-squares line per series, in that series' color, spanning only that series' own points so it doesn't extrapolate a relationship over empty space. It is canvas (over the markers, clipped to the plot), not the SVG `TrendLineOverlay`, whose regression fits y against the array index and so means nothing where x is a measure. The fit runs over the points' pixel positions, which minimizes the same residuals as fitting the raw values on a linear axis and the log values on a log one, and it sees only drawn points — so a series left with fewer than two, or with all of them stacked at a single x, gets no line.diff --git a/packages/quill/packages/charts/src/core/scales.test.ts b/packages/quill/packages/charts/src/core/scales.test.tsindex 20b439c57a81..e08b4ddedc44 100644--- a/packages/quill/packages/charts/src/core/scales.test.ts+++ b/packages/quill/packages/charts/src/core/scales.test.ts@@ -479,6 +479,19 @@ describe('hog-charts scales', () => {expect(result.yAxes!.y1.scale.domain()[1]).toBe(1000)})+ // A reference line outside its axis's domain doesn't render, so an axis whose meaning fixes+ // its range (a 0-1 probability) has to say so — the chart-level valueDomain above only+ // reaches the primary axis.+ it('honors a secondary axis own valueDomain', () => {+ const value = makeSeries({ key: 'value', data: [0, 1000], yAxisId: DEFAULT_Y_AXIS_ID })+ const score = makeSeries({ key: 'score', data: [0, 0.25], yAxisId: 'y1' })+ const result = createScales([value, score], ['a', 'b'], dimensions, {+ axes: [{ id: 'y1', valueDomain: { min: 0, max: 1 } }],+ })+ expect(result.yAxes!.y1.scale.domain()).toEqual([0, 1])+ expect(result.yAxes![DEFAULT_Y_AXIS_ID].scale.domain()[1]).toBe(1000)+ })+it.each([['DEFAULT_Y_AXIS_ID first', [DEFAULT_Y_AXIS_ID, 'y1']],['non-default first', ['y1', DEFAULT_Y_AXIS_ID]],diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.tsindex 3e2fd177cc09..e83c69bac55c 100644--- a/packages/quill/packages/charts/src/core/scales.ts+++ b/packages/quill/packages/charts/src/core/scales.ts@@ -440,12 +440,18 @@ export function createScales(options: {scaleType?: 'linear' | 'log'percentStack?: boolean- /** Applied to the primary y-axis only — goal lines (`{ include }`) render against the- * primary axis, so secondary axes keep their own data-derived scale. */+ /** Applied to the primary y-axis only. A secondary axis takes its domain from+ * `axes[].valueDomain` instead. */valueDomain?: ValueDomain/** Per-axis overrides — explicit values win over the alternating-side default and the* scalar `scaleType`/`floatBaseline` options (which only reach the primary axis). */- axes?: { id: string; position?: 'left' | 'right'; scaleType?: 'linear' | 'log'; startAtZero?: boolean }[]+ axes?: {+ id: string+ position?: 'left' | 'right'+ scaleType?: 'linear' | 'log'+ startAtZero?: boolean+ valueDomain?: ValueDomain+ }[]/** Float the primary axis to its data range instead of clamping the baseline to 0. Applied to* the primary axis only, like `valueDomain`. See {@link buildValueScale}. */floatBaseline?: boolean@@ -479,7 +485,7 @@ export function createScales(const scale = createYScale(byAxis.get(axisId) ?? [], dimensions, {scaleType: override?.scaleType ?? options.scaleType,percentStack: options.percentStack,- valueDomain: axisIndex === 0 ? options.valueDomain : undefined,+ valueDomain: override?.valueDomain ?? (axisIndex === 0 ? options.valueDomain : undefined),floatBaseline:override?.startAtZero != null? override.startAtZero === falsediff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex b7168ba88cff..e278843046b6 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -315,6 +315,9 @@ export interface YAxis {hide?: boolean/** `false` floats this axis to its data range instead of clamping a non-negative domain to 0. */startAtZero?: boolean+ /** Domain control for this axis. Set on secondary axes only: the primary axis takes the+ * chart-level `valueDomain`, already merged with the goal-line stretch. See {@link ValueDomain}. */+ valueDomain?: ValueDomain}/** Built-in legend config for the multi-series charts. The chart renders a {@link Legend} and,diff --git a/packages/quill/packages/charts/src/utils/use-axis-formatters.ts b/packages/quill/packages/charts/src/utils/use-axis-formatters.tsindex 8d8773fe9634..7714e143a073 100644--- a/packages/quill/packages/charts/src/utils/use-axis-formatters.ts+++ b/packages/quill/packages/charts/src/utils/use-axis-formatters.ts@@ -38,9 +38,10 @@ export interface YAxisConfig extends YFormatterConfig {* series, which always draw from 0. */startAtZero?: boolean/** Pins the low end of the axis, overriding both the data-derived bound and `startAtZero`. Omit- * for an automatic bound. Primary axis only; ignored under a percent layout, and dropped when- * non-positive on a log scale. Read by the line charts only: this config is shared, but bar and- * combo charts ignore it, since a bar encodes magnitude as length from zero. */+ * for an automatic bound. Honored per axis in the array (multi-axis) form; ignored under a+ * percent layout, and dropped when non-positive on a log scale. Read by the line charts only:+ * this config is shared, but bar and combo charts ignore it, since a bar encodes magnitude as+ * length from zero. */min?: number/** Pins the high end of the axis. Omit for an automatic bound. See {@link YAxisConfig.min}. */max?: number@@ -136,6 +137,9 @@ export function normalizeYAxisList(yAxis: YAxisConfig | YAxisConfig[] | undefine/** Resolve a normalized axis list into the {@link YAxis}es the base chart consumes —* each axis's id, side, scale, label, and resolved tick formatter. */export function buildYAxes(axisList: NormalizedYAxis[]): YAxis[] {+ // The primary axis's bounds reach it as the chart-level `valueDomain`, already merged with the+ // goal-line stretch; carrying them here too would override that merge and drop the goal lines.+ const primary = primaryYAxisConfig(axisList)return axisList.map(({ id, position, config }) => ({id,position,@@ -144,6 +148,10 @@ export function buildYAxes(axisList: NormalizedYAxis[]): YAxis[] {label: config.label,hide: config.hide,startAtZero: config.startAtZero,+ valueDomain:+ config !== primary && (config.min != null || config.max != null)+ ? { min: config.min, max: config.max }+ : undefined,}))}diff --git a/products/alerts/frontend/views/SimulationSummary.stories.tsx b/products/alerts/frontend/views/SimulationSummary.stories.tsxnew file mode 100644index 000000000000..eb3719906fa5--- /dev/null+++ b/products/alerts/frontend/views/SimulationSummary.stories.tsx@@ -0,0 +1,70 @@+import type { Meta, StoryObj } from '@storybook/react'++import { DetectorConfig } from '~/queries/schema/schema-general'++import type { AlertSimulationResult } from '../types'+import { SimulationSummary } from './SimulationSummary'++const DATES = Array.from({ length: 14 }, (_, i) => `2026-06-${String(i + 1).padStart(2, '0')}`)+const VALUES = [42, 48, 51, 47, 90, 53, 55, 60, 120, 58, 54, 57, 95, 61]+const SCORES = [0.1, 0.15, 0.2, 0.12, 0.82, 0.18, 0.22, 0.3, 0.94, 0.25, 0.2, 0.24, 0.86, 0.28]+const TRIGGERED = [4, 8, 12]++// getThreshold reads `threshold` off any non-ensemble/threshold detector.+const DETECTOR_CONFIG = { type: 'zscore', threshold: 0.5 } as unknown as DetectorConfig++const SINGLE_RESULT: AlertSimulationResult = {+ data: VALUES,+ dates: DATES,+ scores: SCORES,+ triggered_indices: TRIGGERED,+ triggered_dates: TRIGGERED.map((i) => DATES[i]),+ interval: 'day',+ total_points: VALUES.length,+ anomaly_count: TRIGGERED.length,+}++const SUB_SCORES_RESULT: AlertSimulationResult = {+ ...SINGLE_RESULT,+ sub_detector_scores: [+ { type: 'z-score', scores: SCORES },+ { type: 'seasonality', scores: SCORES.map((s) => Math.max(0, s - 0.15)) },+ { type: 'trend', scores: SCORES.map((s) => Math.min(1, s + 0.1)) },+ ],+}++function StoryFrame({ children }: { children: JSX.Element }): JSX.Element {+ return <div className="max-w-2xl border rounded bg-surface-primary p-4">{children}</div>+}++const meta: Meta = {+ title: 'Products/Alerts/Simulation summary',+ parameters: { layout: 'fullscreen' },+ decorators: [+ (Story): JSX.Element => (+ <div className="min-h-screen bg-bg-primary p-4">+ <Story />+ </div>+ ),+ ],+}++export default meta++type Story = StoryObj<typeof meta>++export const SingleScore: Story = {+ render: () => (+ <StoryFrame>+ <SimulationSummary result={SINGLE_RESULT} detectorConfig={DETECTOR_CONFIG} />+ </StoryFrame>+ ),+}++export const SubDetectorScores: Story = {+ render: () => (+ <StoryFrame>+ <SimulationSummary result={SUB_SCORES_RESULT} detectorConfig={DETECTOR_CONFIG} />+ </StoryFrame>+ ),+}diff --git a/products/alerts/frontend/views/SimulationSummary.tsx b/products/alerts/frontend/views/SimulationSummary.tsxindex 8ba426693b73..e8eead3732f7 100644--- a/products/alerts/frontend/views/SimulationSummary.tsx+++ b/products/alerts/frontend/views/SimulationSummary.tsx@@ -1,15 +1,29 @@-import annotationPlugin from 'chartjs-plugin-annotation'import { useState } from 'react'-import { Chart } from 'lib/Chart'-import { useChart } from 'lib/hooks/useChart'+import {+ type AnomalyMarker,+ AnomalyPointsLayer,+ DEFAULT_Y_AXIS_ID,+ ReferenceLine,+ type Series,+ TimeSeriesLineChart,+ useChartTheme,+} from '@posthog/quill-charts'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { humanFriendlyNumber } from 'lib/utils/numbers'import { DetectorConfig } from '~/queries/schema/schema-general'+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'+import { AlertSimulationResult, BreakdownSimulationResult } from '../types'-Chart.register(annotationPlugin)+const handleChartError = makeChartErrorHandler('alerts-simulation-chart')++interface SimSeriesMeta {+ isScore: boolean+}/** Format a date string compactly: "Mar 16, 11:00" or "Mar 16" if midnight. */function formatSimDate(dateStr: string): string {@@ -40,6 +54,15 @@ function getThreshold(config: DetectorConfig | null | undefined): number | nullreturn typeof c.threshold === 'number' ? c.threshold : null}+// Sub-detector score line colors.+const SCORE_COLORS = [+ 'rgba(245, 158, 11, 0.7)', // amber+ 'rgba(16, 185, 129, 0.7)', // green+ 'rgba(139, 92, 246, 0.7)', // purple+ 'rgba(236, 72, 153, 0.7)', // pink+ 'rgba(6, 182, 212, 0.7)', // cyan+]+function SimulationChart({result,detectorConfig,@@ -47,167 +70,93 @@ function SimulationChart({result: AlertSimulationResultdetectorConfig?: DetectorConfig | null}): JSX.Element {+ const theme = useChartTheme()const triggeredSet = new Set(result.triggered_indices)const threshold = getThreshold(detectorConfig)const subScores = result.sub_detector_scores- const hasSubScores = subScores && subScores.length > 0+ const hasSubScores = !!subScores && subScores.length > 0- // Colors for sub-detector score lines- const scoreColors = [- 'rgba(245, 158, 11, 0.7)', // amber- 'rgba(16, 185, 129, 0.7)', // green- 'rgba(139, 92, 246, 0.7)', // purple- 'rgba(236, 72, 153, 0.7)', // pink- 'rgba(6, 182, 212, 0.7)', // cyan- ]+ // SQL insights carry no dates (their rows aren't a time axis) — label by row position.+ const labels = result.dates.length > 0 ? result.dates : result.data.map((_, i) => `Row ${i + 1}`)- const scoreDatasets = hasSubScores+ const scoreSeries: Series<SimSeriesMeta>[] = hasSubScores? subScores.map((sub, i) => ({+ key: `score-${i}`,label: sub.type,- data: sub.scores.map((s) => (s != null ? s : 0)),- borderColor: scoreColors[i % scoreColors.length],- borderWidth: 1,- backgroundColor: 'transparent',- fill: false,- pointRadius: 0,- yAxisID: 'yScore' as const,+ data: sub.scores.map((s) => s ?? 0),+ color: SCORE_COLORS[i % SCORE_COLORS.length],+ yAxisId: 'yScore',+ meta: { isScore: true },})): [{+ key: 'score',label: 'Score',- data: result.scores.map((s) => (s != null ? s : 0)),- borderColor: 'rgba(245, 158, 11, 0.6)',- borderWidth: 1,- backgroundColor: 'rgba(245, 158, 11, 0.1)',- fill: true,- pointRadius: 0,- yAxisID: 'yScore' as const,+ data: result.scores.map((s) => s ?? 0),+ color: 'rgba(245, 158, 11, 0.8)',+ yAxisId: 'yScore',+ fill: { opacity: 0.1 },+ meta: { isScore: true },},]- const { canvasRef } = useChart({- getConfig: () => ({- type: 'line' as const,- data: {- // SQL insights carry no dates (their rows aren't a time axis) — label by row position.- labels: result.dates.length > 0 ? result.dates : result.data.map((_, i) => `Row ${i + 1}`),- datasets: [- // Data series (left y-axis)- {- label: 'Value',- data: result.data,- borderColor: 'rgba(99, 102, 241, 0.8)',- borderWidth: 1.5,- pointRadius: result.data.map((_, i) => (triggeredSet.has(i) ? 3 : 0)),- pointBackgroundColor: result.data.map((_, i) =>- triggeredSet.has(i) ? 'rgba(220, 38, 38, 0.9)' : 'transparent'- ),- pointBorderColor: result.data.map((_, i) =>- triggeredSet.has(i) ? 'rgba(153, 27, 27, 1)' : 'transparent'- ),- pointBorderWidth: result.data.map((_, i) => (triggeredSet.has(i) ? 1 : 0)),- fill: false,- yAxisID: 'y',- },- ...scoreDatasets,- ],- },- options: {- responsive: true,- maintainAspectRatio: false,- plugins: {- legend: hasSubScores- ? {- display: true,- position: 'bottom' as const,- labels: {- filter: (item: any) => item.text !== 'Value',- boxWidth: 8,- boxHeight: 2,- font: { size: 9 },- padding: 6,- },- }- : { display: false },- tooltip: {- enabled: true,- callbacks: {- label: (ctx) => {- if (ctx.datasetIndex === 0) {- const idx = ctx.dataIndex- const score = result.scores[idx]- const base = `Value: ${ctx.parsed.y}`- if (triggeredSet.has(idx) && score != null) {- return `${base} — Anomaly: ${Math.round(score * 100)}%`- }- return base- }- const label = ctx.dataset.label || 'Score'- return `${label}: ${((ctx.parsed.y ?? 0) * 100).toFixed(0)}%`- },- },- },- annotation: threshold- ? {- annotations: {- thresholdLine: {- type: 'line' as const,- yMin: threshold,- yMax: threshold,- yScaleID: 'yScore',- borderColor: 'rgba(220, 38, 38, 0.5)',- borderWidth: 1.5,- borderDash: [4, 4],- label: {- content: `Threshold ${Math.round(threshold * 100)}%`,- display: true,- position: 'start' as const,- font: { size: 9 },- color: 'rgba(220, 38, 38, 0.8)',- backgroundColor: 'transparent',- },- },- },- }- : undefined,- },- scales: {- x: { display: false },- y: {- display: true,- position: 'left' as const,- ticks: { maxTicksLimit: 3, font: { size: 10 } },- grid: { drawTicks: false },- },- yScore: {- display: true,- position: 'right' as const,- min: 0,- max: 1,- title: {- display: true,- text: 'Anomaly score',- font: { size: 9 },- padding: 0,- },- ticks: {- maxTicksLimit: 3,- font: { size: 9 },- callback: (value: string | number) => `${Math.round(Number(value) * 100)}%`,- },- grid: { display: false },- },- },- elements: { line: { tension: 0 } },- },- }),- deps: [result, threshold],- })+ const series: Series<SimSeriesMeta>[] = [+ { key: 'value', label: 'Value', data: result.data, color: 'rgba(99, 102, 241, 0.9)', meta: { isScore: false } },+ ...scoreSeries,+ ]++ const anomalyMarkers: AnomalyMarker[] = result.data.flatMap((value, index) =>+ triggeredSet.has(index)+ ? [{ dataIndex: index, value, color: 'rgba(220, 38, 38, 0.9)', yAxisId: DEFAULT_Y_AXIS_ID }]+ : []+ )return (- <div className="h-32">- <canvas ref={canvasRef} />+ <div className="h-32 flex flex-col">+ <TimeSeriesLineChart<SimSeriesMeta>+ series={series}+ labels={labels}+ theme={theme}+ config={{+ xAxis: { hide: true },+ yAxis: [+ { id: DEFAULT_Y_AXIS_ID, position: 'left', tickFormatter: (v) => humanFriendlyNumber(v) },+ {+ id: 'yScore',+ position: 'right',+ format: 'percentage_scaled',+ label: 'Anomaly score',+ // Scores are probabilities, so the axis is 0-100% whatever the data does.+ // Floating it to the data max drops a threshold above every score: an+ // off-plot reference line doesn't draw at all.+ min: 0,+ max: 1,+ },+ ],+ showGrid: true,+ legend: hasSubScores ? { show: true, position: 'bottom' } : undefined,+ tooltip: {+ valueFormatter: (value, entry) =>+ (entry.series.meta as SimSeriesMeta | undefined)?.isScore+ ? `${Math.round(value * 100)}%`+ : humanFriendlyNumber(value),+ },+ }}+ onError={handleChartError}+ >+ <AnomalyPointsLayer markers={anomalyMarkers} />+ {threshold != null && (+ <ReferenceLine+ value={threshold}+ orientation="horizontal"+ yAxisId="yScore"+ variant="alert"+ label={`Threshold ${Math.round(threshold * 100)}%`}+ labelPosition="start"+ />+ )}+ </TimeSeriesLineChart></div>)}