Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay-vision): draw the spend trajectory with quill-charts (#96173)

Sam Pennington839949481001
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 7f6929f30b9b..c2b2ba0d68b5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8853,9 +8853,29 @@ snapshots:
scenes-app-replay-vision--summarizer-overview--light:
hash: v1.k794b7964.c5df0e640d994a9c2ec8cbb2e383be1eb5fcf06dadb62b0f7523a90257dc2144.nIYMWvHWhAM9lExklaJV7toaICXFw_o16NgM684nV5o
scenes-app-replay-vision--usage-tab--dark:
- hash: v1.k794b7964.adcd33918c09bfe0779ee7a51b77ee173de0cdd74d66300ea01d173280068d48.ib0BfEMTsMIEACC9iavsKKP4h8jNle7YTt9dvkkw4-o
+ hash: v1.k794b7964.aab9212ef24367842f0c4b5c6e0b5568efa7b02455e0b762a0dae56f7a251ded.Vis7Q1vljRgKviTHYsDV5sgLm5fLA8DqNHkJ-26wpBE
scenes-app-replay-vision--usage-tab--light:
- hash: v1.k794b7964.7b90e21b832f5814c53519accdedab8896288bc69795b4d5e1e7b1b1bfee0de4.piIPzkfkOn_qr72FuSJWIOwB8VcVKZg6ryIg44FdsoI
+ hash: v1.k794b7964.2ef3c1068703daaae8c960f5efde14f65aa0a0db64a5125d06beca44abd35433.H06_UO_8eRcWCyB1p55hCLxFFDlj-5Av13ZGRDpbPaQ
+ scenes-app-replay-vision-spendtrajectorychart--hits-the-limit--dark:
+ hash: v1.k794b7964.cf96414912c6d8f0d73808db3f1d833c661d12b3b0449cdd49b95d4dc8059e80.3sA2mn18MksUWQQ4mq6wEPbkJhGP3O258Y6Q2fTWhgM
+ scenes-app-replay-vision-spendtrajectorychart--hits-the-limit--light:
+ hash: v1.k794b7964.567f651ada81f93bdedf54efdb000b23f130ad35ad7f6b1b150df0c0e9d19149.BT8sxvNKrDklTOvhv1imraRCxLXlwWaFqAE8QWpMLKA
+ scenes-app-replay-vision-spendtrajectorychart--hits-the-limit-narrow--dark:
+ hash: v1.k794b7964.d277a1227c59b77b04d03798856f3f163c034d40b47e8917dee2d9752d6e10f6.jEudf7CIOxoF9PnfMG-LC3Aw4eAbRbrBoz2_2OW4XAc
+ scenes-app-replay-vision-spendtrajectorychart--hits-the-limit-narrow--light:
+ hash: v1.k794b7964.0641273086a324a2faf8d4ab17c14da628fbabf58c447ab3cb8792f9294c6950.VXjfOE98pma33p4ngJa4XwtpyBV_5iZdNeank8ClZSM
+ scenes-app-replay-vision-spendtrajectorychart--no-limit--dark:
+ hash: v1.k794b7964.8cbf8fa86d556bd56fd3971dab1259132caec465be29f20ae63b7ecea430f76f.N3M5AA-9hE3V-efmqa-RUSwLxa6Rdbx_jy8UWzQskxU
+ scenes-app-replay-vision-spendtrajectorychart--no-limit--light:
+ hash: v1.k794b7964.3744a61406e48d92259647485e1c41297f30805121db6097fb1ca3e3d443cd70.-f2WgZy-vhBBqQEm2qdcCx6DDEX6xMdeX6vDLZcF0gs
+ scenes-app-replay-vision-spendtrajectorychart--on-track--dark:
+ hash: v1.k794b7964.9bed129722b316ce67374ea37443ca280a2bf92af26d9caf7163f8a94f08f553.aPCzqGaJUNVWagdedAqoJjEjCfUwrymCbKxt-Z0_jPc
+ scenes-app-replay-vision-spendtrajectorychart--on-track--light:
+ hash: v1.k794b7964.68fba9804381d6b92c528b5cc5df048acab7b1646e2262abd0be3e3127f185d6._4BG8AWDjTw2wSMYHO0anAD_DEe0cpEOuhL3zkOTCDw
+ scenes-app-replay-vision-spendtrajectorychart--paused-at-the-limit--dark:
+ hash: v1.k794b7964.dda7de0ce66d8560cfa23373e2945f6f67e52a737959f1bc9f13ada15350d5e2.liov66k1E402O2zlfgHqZkMuzczKp_H-snBDI2-ooc4
+ scenes-app-replay-vision-spendtrajectorychart--paused-at-the-limit--light:
+ hash: v1.k794b7964.5519427fad631ebc75aba832b787eba17bd6359b934bebe947c8cdb2e2683d0a.Kq7yYGkrCJF4yp3eK4S5v_zJVqwk4EngNIrM-6cO9qI
scenes-app-replay-vision-test-account-filter-settings-dialog--default--dark:
hash: v1.k794b7964.57289f977a42e43a6b70a0718959bc995a7a45245b20fda636e880beec7cc2e8.2CONzn8joR8LZgN9VOcNokIFUUJmtzE-TJTbprVGmt8
scenes-app-replay-vision-test-account-filter-settings-dialog--default--light:
diff --git a/packages/quill/packages/charts/src/overlays/ReferenceLine.test.tsx b/packages/quill/packages/charts/src/overlays/ReferenceLine.test.tsx
index cfd98a632904..c671beb52633 100644
--- a/packages/quill/packages/charts/src/overlays/ReferenceLine.test.tsx
+++ b/packages/quill/packages/charts/src/overlays/ReferenceLine.test.tsx
@@ -87,6 +87,15 @@ describe('ReferenceLine', () => {
expect(queryByText('50')).toBeNull()
})
+ it('stays inert to hover when showValueOnHover is false', () => {
+ const { container, getByText, queryByText } = renderInChart(
+ <ReferenceLine value={50} label="Target" showValueOnHover={false} />
+ )
+ expect(container.querySelector('[data-attr="hog-chart-reference-line-hit-area"]')).toBeNull()
+ fireEvent.mouseEnter(getByText('Target'))
+ expect(queryByText('Target: 50')).toBeNull()
+ })
+
it('anchors the label at the start when labelPosition="start"', () => {
const { getByText } = renderInChart(<ReferenceLine value={50} label="T" labelPosition="start" />)
const label = getByText('T') as HTMLDivElement
diff --git a/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx b/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx
index d0e0088e32b8..6ae56833c287 100644
--- a/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx
+++ b/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx
@@ -42,6 +42,10 @@ export interface ReferenceLineProps {
variant?: ReferenceLineVariant
/** Which y-axis this line references. Only used for horizontal lines. Defaults to the primary axis. */
yAxisId?: string
+ /** Reveal the numeric value in the label bubble when the line or its label is hovered. Defaults to
+ * true. `false` also drops the invisible hover target, so the line is inert to the pointer. Vertical
+ * (label-positioned) lines never reveal a value. */
+ showValueOnHover?: boolean
/** Chart axis orientation. When `'horizontal'`, a `'horizontal'`-orientation reference
* line at a numeric value is drawn as a vertical stripe at `scales.y(value)` — matching
* the value axis of horizontal bar charts. Defaults to the chart's own axis orientation
@@ -112,7 +116,10 @@ export function ReferenceLine(props: ReferenceLineProps): React.ReactElement | n
label: props.label,
labelPosition: props.labelPosition ?? 'end',
// Numeric lines (goal thresholds) reveal their value on hover; vertical marker lines don't.
- valueText: typeof props.value === 'number' ? props.value.toLocaleString() : undefined,
+ valueText:
+ typeof props.value === 'number' && props.showValueOnHover !== false
+ ? props.value.toLocaleString()
+ : undefined,
}
if (orientation === 'horizontal') {
diff --git a/packages/quill/packages/charts/src/utils/goal-lines.test.ts b/packages/quill/packages/charts/src/utils/goal-lines.test.ts
index 49ac1a575c2b..41921e575939 100644
--- a/packages/quill/packages/charts/src/utils/goal-lines.test.ts
+++ b/packages/quill/packages/charts/src/utils/goal-lines.test.ts
@@ -64,6 +64,7 @@ describe('goal-lines', () => {
['propagates color via style.color', { color: 'var(--danger)' }, { style: { color: 'var(--danger)' } }],
['omits label when displayLabel is false', { displayLabel: false }, { label: undefined }],
['respects explicit labelPosition', { labelPosition: 'start' as const }, { labelPosition: 'start' }],
+ ['forwards showValueOnHover', { showValueOnHover: false }, { showValueOnHover: false }],
] as const)('%s', (_, lineOverrides, expectedProps) => {
const lines: GoalLineConfig[] = [{ label: 'X', value: 50, ...lineOverrides }]
expect(buildGoalLineReferenceLines(lines, series)[0]).toMatchObject(expectedProps)
diff --git a/packages/quill/packages/charts/src/utils/goal-lines.ts b/packages/quill/packages/charts/src/utils/goal-lines.ts
index f565d16cf1be..aeb2423e4f46 100644
--- a/packages/quill/packages/charts/src/utils/goal-lines.ts
+++ b/packages/quill/packages/charts/src/utils/goal-lines.ts
@@ -8,6 +8,8 @@ export interface GoalLineConfig {
color?: string
labelPosition?: 'start' | 'end'
displayIfCrossed?: boolean
+ /** Forwarded to {@link ReferenceLineProps.showValueOnHover}; defaults to true. */
+ showValueOnHover?: boolean
}
export function computeSeriesNonZeroMax(series: Series[]): number {
@@ -47,6 +49,7 @@ export function buildGoalLineReferenceLines(
labelPosition: line.labelPosition ?? 'end',
variant: 'goal',
style: line.color ? { color: line.color } : undefined,
+ showValueOnHover: line.showValueOnHover,
}))
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/SpendReferenceCaption.tsx b/products/replay_vision/frontend/replay_scanners/components/SpendReferenceCaption.tsx
new file mode 100644
index 000000000000..1289ff8272be
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/SpendReferenceCaption.tsx
@@ -0,0 +1,37 @@
+/* eslint-disable react/forbid-dom-props -- dynamic pixel positions from the chart scales */
+import { useChartLayout } from '@posthog/quill-charts'
+
+import { LABEL_INSET, SPEND_TONE_CLASS } from './spendTrajectoryCaptionLayout'
+import type { SpendReferenceLabel } from './spendTrajectoryTransforms'
+
+const LABEL_LINE_GAP = 3
+
+interface SpendReferenceCaptionProps {
+ line: SpendReferenceLabel
+ /** Set once the caption has been measured and placed clear of the markers. */
+ measuredLeft: number | undefined
+}
+
+export function SpendReferenceCaption({ line, measuredLeft }: SpendReferenceCaptionProps): JSX.Element | null {
+ const { scales, dimensions } = useChartLayout()
+ const y = scales.y(line.value)
+ if (!isFinite(y) || y < dimensions.plotTop || y > dimensions.plotTop + dimensions.plotHeight) {
+ return null
+ }
+ const plotRight = dimensions.plotLeft + dimensions.plotWidth
+ const atEnd = measuredLeft === undefined && line.position === 'end'
+ return (
+ <span
+ data-attr={`spend-trajectory-reference-label-${line.key}`}
+ className={`absolute text-xs leading-none whitespace-nowrap font-semibold -translate-y-full ${
+ atEnd ? '-translate-x-full' : ''
+ } ${SPEND_TONE_CLASS[line.tone]}`}
+ style={{
+ left: measuredLeft ?? (atEnd ? plotRight - LABEL_INSET : dimensions.plotLeft + LABEL_INSET),
+ top: y - LABEL_LINE_GAP,
+ }}
+ >
+ {line.text}
+ </span>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.stories.tsx b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.stories.tsx
new file mode 100644
index 000000000000..6abbd2b9061b
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.stories.tsx
@@ -0,0 +1,102 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { dayjs } from 'lib/dayjs'
+
+import type { VisionQuotaApi } from '../../generated/api.schemas'
+import { verdictColorVar } from '../../utils/spendVerdict'
+import type { SpendSeries } from '../visionUsageLogic'
+import { SpendTrajectoryChart } from './SpendTrajectoryChart'
+
+const meta: Meta<typeof SpendTrajectoryChart> = {
+ title: 'Scenes-App/Replay Vision/SpendTrajectoryChart',
+ component: SpendTrajectoryChart,
+ parameters: {
+ layout: 'centered',
+ mockDate: '2026-05-12',
+ testOptions: { snapshotBrowsers: ['chromium'] },
+ },
+ decorators: [
+ (Story) => (
+ // eslint-disable-next-line react/forbid-dom-props
+ <div style={{ width: 720 }}>
+ <Story />
+ </div>
+ ),
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof SpendTrajectoryChart>
+
+const quota: VisionQuotaApi = {
+ credit_limit: 10_000,
+ credits_used: 2_400,
+ remaining: 7_600,
+ exhausted: false,
+ projected_monthly_credits: 5_200,
+ scanners_monthly_credits: 5_200,
+ backfills_committed_credits: 0,
+ free_monthly_credits: 2_500,
+ credits_settled: 2_400,
+ credits_reserved: 0,
+ period_start: '2026-05-01T00:00:00Z',
+ period_end: '2026-06-01T00:00:00Z',
+}
+
+const dailyCredits: SpendSeries = [150, 190, 230, 260, 90, 80, 250, 280, 310, 120, 440].map((credits, i) => ({
+ date: `2026-05-${String(i + 1).padStart(2, '0')}`,
+ credits,
+}))
+
+export const OnTrack: Story = {
+ args: {
+ quota,
+ dailyCredits,
+ projectedTotal: 5_900,
+ capReachDate: null,
+ statusVar: verdictColorVar('safe'),
+ },
+}
+
+export const HitsTheLimit: Story = {
+ args: {
+ quota: { ...quota, scanners_monthly_credits: 16_000, projected_monthly_credits: 16_000 },
+ dailyCredits,
+ projectedTotal: 10_000,
+ capReachDate: dayjs.utc('2026-05-26T12:00:00Z'),
+ statusVar: verdictColorVar('danger'),
+ },
+}
+
+// A 1280px window with the nav and side panel open leaves the scene about 520px.
+export const HitsTheLimitNarrow: Story = {
+ args: HitsTheLimit.args,
+ decorators: [
+ (Story) => (
+ // eslint-disable-next-line react/forbid-dom-props
+ <div style={{ width: 520 }}>
+ <Story />
+ </div>
+ ),
+ ],
+}
+
+export const PausedAtTheLimit: Story = {
+ args: {
+ quota: { ...quota, credits_used: 10_000, credits_settled: 10_000, remaining: 0, exhausted: true },
+ dailyCredits: dailyCredits.map((day) => ({ ...day, credits: day.credits * 4 })),
+ projectedTotal: 10_000,
+ capReachDate: null,
+ statusVar: verdictColorVar('paused'),
+ },
+}
+
+export const NoLimit: Story = {
+ args: {
+ quota: { ...quota, credit_limit: null, remaining: null },
+ dailyCredits,
+ projectedTotal: 5_900,
+ capReachDate: null,
+ statusVar: verdictColorVar('uncapped'),
+ },
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.test.tsx b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.test.tsx
index e774bcf97262..34df18909bb1 100644
--- a/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.test.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.test.tsx
@@ -1,4 +1,7 @@
-import { render } from '@testing-library/react'
+import { cleanup, render, screen } from '@testing-library/react'
+import type { ComponentProps } from 'react'
+
+import { type HogChart, ensureJsdom, getHogChart } from '@posthog/quill-charts/testing'
import { dayjs } from 'lib/dayjs'
@@ -6,7 +9,8 @@ import { makeQuota } from '../../utils/quotaTestUtils'
import type { SpendSeries } from '../visionUsageLogic'
import { SpendTrajectoryChart } from './SpendTrajectoryChart'
-/** Daily spend over the fixture's period, oldest first, splitting `total` evenly across `days`. */
+type Props = ComponentProps<typeof SpendTrajectoryChart>
+
function series(total: number, days: number, periodStart: string): SpendSeries {
const start = dayjs.utc(periodStart)
return Array.from({ length: days }, (_, i) => ({
@@ -15,45 +19,35 @@ function series(total: number, days: number, periodStart: string): SpendSeries {
}))
}
-describe('SpendTrajectoryChart', () => {
- const renderChart = (overrides: Parameters<typeof makeQuota>[0] = {}, spend?: SpendSeries): HTMLElement => {
- const quota = makeQuota(overrides)
- return render(
- <SpendTrajectoryChart
- quota={quota}
- dailyCredits={spend ?? series(quota.credits_used, 5, quota.period_start)}
- projectedTotal={quota.credits_used}
- capReachDate={null}
- statusVar="var(--success)"
- />
- ).container
- }
-
- // A free allocation this small sits on the axis, where the line reads as the axis and its label
- // lands on the period end date.
- it('hides the free-credits line when it would sit on the axis', () => {
- const container = renderChart({ credit_limit: 240_000, credits_used: 168_000, free_monthly_credits: 1_000 })
- expect(container.textContent).not.toContain('Free credits')
- })
+function renderChart(overrides: Partial<Props> = {}): HogChart {
+ const quota = makeQuota({ credit_limit: 10_000, credits_used: 4_000, free_monthly_credits: 2_500 })
+ const { container } = render(
+ <SpendTrajectoryChart
+ quota={quota}
+ dailyCredits={series(4_000, 5, quota.period_start)}
+ projectedTotal={4_000}
+ capReachDate={null}
+ statusVar="var(--success)"
+ {...overrides}
+ />
+ )
+ return getHogChart(container)
+}
- it('keeps the free-credits line when it clears the axis', () => {
- const container = renderChart({ credit_limit: 10_000, credits_used: 4_000, free_monthly_credits: 2_500 })
- expect(container.textContent).toContain('Free credits')
- })
+describe('SpendTrajectoryChart', () => {
+ beforeEach(() => ensureJsdom())
+ afterEach(() => cleanup())
- // The series and the quota are fetched together, so the series can be a moment newer. Today has to
- // read the same number the card header shows rather than the higher of the two.
- it('reports today at the quota total even when the ledger series runs ahead', () => {
- const quota = makeQuota({ credit_limit: 10_000, credits_used: 4_000 })
- const { container } = render(
- <SpendTrajectoryChart
- quota={quota}
- dailyCredits={series(4_400, 4, quota.period_start)}
- projectedTotal={4_000}
- capReachDate={null}
- statusVar="var(--success)"
- />
- )
- expect(container.textContent).toContain('Today · 4,000')
+ it('draws captioned limit and free-credit lines and labels today at the quota total', () => {
+ const chart = renderChart()
+ const [limit, free] = chart.referenceLines()
+ expect(chart.referenceLines().map((line) => line.label)).toEqual([null, null])
+ expect(limit.position).not.toBeNull()
+ expect(free.position).not.toBeNull()
+ expect(limit.position!).toBeLessThan(free.position!)
+ expect(document.querySelector('[data-attr="hog-chart-reference-line-hit-area"]')).toBeNull()
+ expect(screen.getByText('Monthly limit · 10,000')).toBeTruthy()
+ expect(screen.getByText('Free credits · 2,500')).toBeTruthy()
+ expect(screen.getByText('Today · 4,000')).toBeTruthy()
})
})
diff --git a/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.tsx b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.tsx
index c76a7906b8d0..4f91af3ce098 100644
--- a/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.tsx
@@ -1,22 +1,33 @@
-import { memo } from 'react'
+import { memo, useMemo } from 'react'
+import { TimeSeriesLineChart } from '@posthog/quill-charts'
+
+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
import { dayjs } from 'lib/dayjs'
-import { clamp, compactNumber } from 'lib/utils/numbers'
+
+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
import type { VisionQuotaApi } from '../../generated/api.schemas'
import { formatCreditCount, formatCreditNumber } from '../../utils/credits'
import type { SpendSeries } from '../visionUsageLogic'
+import { SpendTrajectoryMarkers } from './SpendTrajectoryMarkers'
+import { type SpendMarkerTone, type SpendReferenceLabel, buildSpendTrajectory } from './spendTrajectoryTransforms'
+
+const DANGER_VAR = 'var(--danger)'
+
+const REFERENCE_LINE_VAR: Record<SpendMarkerTone, string> = {
+ default: 'var(--primary)',
+ muted: 'var(--muted)',
+ danger: DANGER_VAR,
+}
+
+const handleChartError = makeChartErrorHandler('replay-vision-spend-trajectory')
+
+const formatTooltipValue = (value: number): string => formatCreditCount(value)
-const WIDTH = 640
-const HEIGHT = 200
-const PAD_LEFT = 34
-const PAD_X = 8
-const TOP = 34
-const BASE = HEIGHT - 20
-const LABEL_CLEARANCE = 12
-// A reference line closer than this to the baseline reads as part of the axis.
-const AXIS_CLEARANCE = 10
-const ABOVE = -6
+// The canvas cannot paint `var(--x)`, so series colours resolve through the computed style.
+const cssVarName = (value: string): string => value.replace(/^var\(--(.+)\)$/, '$1')
interface SpendTrajectoryChartProps {
quota: VisionQuotaApi
@@ -26,72 +37,10 @@ interface SpendTrajectoryChartProps {
projectedTotal: number
/** When demand crosses the limit inside the period, the date the verdict computed for it. */
capReachDate: dayjs.Dayjs | null
- /** Hex/token-resolved colour for the projection line, matching the verdict status. */
+ /** CSS variable reference (`var(--success)`) for the projection line, matching the verdict status. */
statusVar: string
}
-interface Point {
- x: number
- y: number
-}
-
-function pointsAttr(points: Point[]): string {
- return points.map((p) => `${Math.round(p.x * 10) / 10},${Math.round(p.y * 10) / 10}`).join(' ')
-}
-
-/** Labels live in HTML so they keep their font size while the SVG scales with the card. */
-function Label({
- x,
- y,
- anchor = 'start',
- className = '',
- style,
- children,
-}: {
- x: number
- y: number
- anchor?: 'start' | 'end' | 'middle'
- className?: string
- style?: React.CSSProperties
- children: React.ReactNode
-}): JSX.Element {
- const translateX = anchor === 'end' ? '-100%' : anchor === 'middle' ? '-50%' : '0'
- return (
- <span
- className={`absolute text-xs leading-none whitespace-nowrap ${className}`}
- style={{
- left: `${(x / WIDTH) * 100}%`,
- top: `${(y / HEIGHT) * 100}%`,
- transform: `translate(${translateX}, -50%)`,
- ...style,
- }}
- >
- {children}
- </span>
- )
-}
-
-/** Marks a point on the line. HTML, so a stretched viewBox cannot flatten it into an ellipse. */
-function Dot({ x, y, color }: { x: number; y: number; color: string }): JSX.Element {
- return (
- <span
- className="absolute size-1.5 rounded-full"
- style={{
- left: `${(x / WIDTH) * 100}%`,
- top: `${(y / HEIGHT) * 100}%`,
- transform: 'translate(-50%, -50%)',
- background: color,
- }}
- />
- )
-}
-
-/**
- * Cumulative spend across the period against the limit: a solid line to today, a dashed projection
- * to period end, and a dashed line where the limit sits. Spend pauses at the limit, so the drawn
- * projection never exceeds it: when demand crosses, the line flattens at the crossing and the
- * crossing carries the date. Percentages stay off the chart.
- */
function SpendTrajectoryChartInner({
quota,
dailyCredits,
@@ -99,301 +48,87 @@ function SpendTrajectoryChartInner({
capReachDate,
statusVar,
}: SpendTrajectoryChartProps): JSX.Element {
- // The ledger is bucketed by UTC day, so the axis is UTC too; a local axis would shift the curve by a day.
- const periodStart = dayjs.utc(quota.period_start)
- const periodEnd = dayjs.utc(quota.period_end)
- const periodDays = Math.max(periodEnd.diff(periodStart, 'day', true), 1)
- const todayDay = clamp(dayjs.utc().diff(periodStart, 'day', true), 0, periodDays)
-
- let runningTotal = 0
- const cumulative: { day: number; value: number }[] = []
- for (const entry of dailyCredits) {
- runningTotal += entry.credits
- // A day's bucket is complete at its end; today's is only as complete as the clock.
- const dayEnd = dayjs.utc(entry.date).diff(periodStart, 'day', true) + 1
- cumulative.push({ day: clamp(dayEnd, 0, todayDay), value: runningTotal })
- }
- // The card header reads `credits_used`, so today's point is that number and the ledger only gives the
- // curve its shape. The series is fetched alongside the quota and can be a moment newer, so only the
- // tail is pulled down to it: clamping every point would draw days of zero spend that never happened.
- const spentTotal = quota.credits_used
- if (cumulative.length > 0) {
- for (let i = cumulative.length - 1; i >= 0 && cumulative[i].value > spentTotal; i--) {
- cumulative[i] = { ...cumulative[i], value: spentTotal }
+ const theme = useChartTheme()
+
+ const trajectory = useMemo(
+ () =>
+ buildSpendTrajectory({
+ quota,
+ dailyCredits,
+ projectedTotal,
+ capReachDate,
+ statusColor: getColorVar(cssVarName(statusVar)),
+ dangerColor: getColorVar(cssVarName(DANGER_VAR)),
+ }),
+ // `theme` re-resolves the colours when light and dark mode flip.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [quota, dailyCredits, projectedTotal, capReachDate, statusVar, theme]
+ )
+ const { cap, freeCredits, spentTotal, endValue, crossing, pausedAtLimit, periodEnd } = trajectory
+
+ const referenceLabels = useMemo(() => {
+ const labels: SpendReferenceLabel[] = []
+ if (cap !== null) {
+ labels.push({
+ key: 'limit',
+ value: cap,
+ text: `Monthly limit · ${formatCreditNumber(cap)}`,
+ tone: 'danger',
+ position: 'start',
+ })
}
- cumulative[cumulative.length - 1] = { ...cumulative[cumulative.length - 1], value: spentTotal }
- }
-
- // A zero or missing limit draws no cap; spend stops at a real one, so the drawn end never
- // exceeds it and demand only decides the slope. Cumulative spend cannot go down, so it never dips below today either.
- const cap = quota.credit_limit !== null && quota.credit_limit > 0 ? quota.credit_limit : null
- const demand = Math.max(projectedTotal, spentTotal)
- const endValue = cap !== null ? Math.min(demand, cap) : demand
- // The free allocation gets its own quieter line, unless it IS the limit (the free plan).
- const freeCredits = quota.free_monthly_credits
- const drawFreeLine = freeCredits > 0 && (cap === null || freeCredits < cap)
- const maxValue = Math.max(cap ?? 0, endValue, spentTotal, drawFreeLine ? freeCredits : 0, 1)
- const xForDay = (day: number): number => PAD_LEFT + (day / periodDays) * (WIDTH - PAD_LEFT - PAD_X)
- const yForCredits = (credits: number): number => BASE - (credits / maxValue) * (BASE - TOP)
-
- const spentPoints: Point[] =
- cumulative.length > 0
- ? cumulative.map((c) => ({ x: xForDay(c.day), y: yForCredits(c.value) }))
- : [{ x: xForDay(todayDay), y: yForCredits(spentTotal) }]
- const origin: Point = { x: xForDay(0), y: yForCredits(0) }
- const today: Point = spentPoints[spentPoints.length - 1]
- // A day-old period leaves no width to draw a line in; a lone dot reads better than a vertical stroke.
- const drawSpentLine = today.x - origin.x >= 1.5
- const end: Point = { x: xForDay(periodDays), y: yForCredits(endValue) }
-
- // The crossing sits on the verdict's date, so the dot, its label and the tile all name the same day.
- const crossingDay = capReachDate ? capReachDate.diff(periodStart, 'day', true) : null
- const crossingDate = capReachDate?.format('MMM D')
- const crossing: Point | null =
- cap !== null && crossingDay !== null && spentTotal < cap && crossingDay > todayDay && crossingDay <= periodDays
- ? { x: xForDay(crossingDay), y: yForCredits(cap) }
- : null
- const pausedAtLimit = cap !== null && spentTotal >= cap
-
- // Round tick steps (1/2/2.5/5 per decade) so y labels land on friendly numbers.
- const rawStep = maxValue / 4
- const magnitude = Math.pow(10, Math.floor(Math.log10(rawStep)))
- const stepChoice = [1, 2, 2.5, 5, 10].find((m) => m * magnitude >= rawStep) ?? 10
- const yStep = stepChoice * magnitude
- const yTicks: number[] = []
- for (let v = yStep; v <= maxValue; v += yStep) {
- yTicks.push(v)
- }
- const xTicks: number[] = []
- for (let day = 7; day <= periodDays - 3; day += 7) {
- xTicks.push(day)
- }
-
- const dangerVar = 'var(--danger)'
- const mutedVar = 'var(--muted)'
- const projectionLabel = `${periodEnd.format('MMM D')} · ~${formatCreditNumber(endValue)}`
- const limitY = cap !== null ? yForCredits(cap) : null
- const freeY = drawFreeLine ? yForCredits(freeCredits) : null
- // Two dotted reference lines an em apart read as one; drop the free one when it nearly touches the
- // limit line, or when it sits so low against the limit that it merges with the axis and its date labels.
- const showFreeLine =
- freeY !== null &&
- (limitY === null || Math.abs(freeY - limitY) >= LABEL_CLEARANCE) &&
- BASE - freeY >= AXIS_CLEARANCE
-
- // Labels sit above their anchor. Below a point is the filled area and the rising curve, so a label
- // blocked by a reference line climbs past it instead of dropping into the fill.
- const referenceYs = [limitY, freeY].filter((y): y is number => y !== null)
- const labelY = (anchorY: number): number => {
- let candidate = anchorY + ABOVE
- // Lowest line first, so a label pushed past one is then tested against the next one up.
- for (const reference of [...referenceYs].sort((a, b) => b - a)) {
- if (Math.abs(candidate - reference) < LABEL_CLEARANCE) {
- candidate = reference - LABEL_CLEARANCE
- }
+ if (freeCredits !== null) {
+ labels.push({
+ key: 'free',
+ value: freeCredits,
+ text: `Free credits · ${formatCreditNumber(freeCredits)}`,
+ tone: 'muted',
+ position: 'end',
+ })
}
- return Math.max(candidate, 10)
- }
- // Today's label sits left of its dot unless the point hugs the axis, where it would run off the edge.
- const todayLabelLeft = today.x >= 60
- const todayLabelX = todayLabelLeft ? today.x - 9 : today.x + 9
- const todayLabelY = labelY(today.y)
- const endLabelY = labelY(end.y)
- const crossingLabelRight = crossing !== null && crossing.x + 90 <= WIDTH - PAD_X
+ return labels
+ }, [cap, freeCredits])
+
+ const config = useChartConfig(
+ () => ({
+ xAxis: { timezone: 'UTC', interval: 'day' as const },
+ yAxis: { format: 'short' as const },
+ goalLines: referenceLabels.map((line) => ({
+ value: line.value,
+ color: REFERENCE_LINE_VAR[line.tone],
+ showValueOnHover: false,
+ })),
+ curve: 'linear' as const,
+ tooltip: { valueFormatter: formatTooltipValue },
+ }),
+ [referenceLabels]
+ )
- const caption = crossing
- ? `Hits the limit around ${crossingDate}. Scanning pauses until ${periodEnd.format('MMM D')}.`
+ const resetDay = periodEnd.format('MMM D')
+ const crossingDay = crossing?.date.format('MMM D')
+ const caption = crossingDay
+ ? `Hits the limit around ${crossingDay}. Scanning pauses until ${resetDay}.`
: pausedAtLimit
- ? `Scanning is paused at the limit until ${periodEnd.format('MMM D')}.`
+ ? `Scanning is paused at the limit until ${resetDay}.`
: null
+ const summary = crossing
+ ? `Cumulative spend this period: ${formatCreditCount(spentTotal)} so far, projected to reach the ${formatCreditCount(crossing.value)} limit around ${crossingDay}`
+ : `Cumulative spend this period: ${formatCreditCount(spentTotal)} so far, projected ${formatCreditCount(endValue)} by ${periodEnd.format('MMMM D')}${cap !== null ? `, limit ${formatCreditCount(cap)}` : ''}`
return (
<div className="flex flex-col gap-1">
- <div className="relative w-full">
- {/* The box stretches to the card's width at a fixed height, so the chart stays wide and short. */}
- <svg
- viewBox={`0 0 ${WIDTH} ${HEIGHT}`}
- preserveAspectRatio="none"
- className="block h-[200px] w-full"
- role="img"
- aria-label={
- crossing
- ? `Cumulative spend this period: ${formatCreditCount(spentTotal)} so far, projected to reach the ${formatCreditCount(cap ?? 0)} limit around ${crossingDate}`
- : `Cumulative spend this period: ${formatCreditCount(spentTotal)} so far, projected ${formatCreditCount(endValue)} by ${periodEnd.format('MMMM D')}${cap !== null ? `, limit ${formatCreditCount(cap)}` : ''}`
- }
+ <p className="sr-only">{summary}</p>
+ <div className="flex h-52 w-full flex-col">
+ <TimeSeriesLineChart
+ series={trajectory.series}
+ labels={trajectory.labels}
+ theme={theme}
+ config={config}
+ dataAttr="spend-trajectory-chart"
+ onError={handleChartError}
>
- {yTicks.map((v) => (
- <line
- key={v}
- x1={PAD_LEFT}
- y1={yForCredits(v)}
- x2={WIDTH - PAD_X}
- y2={yForCredits(v)}
- stroke="var(--border)"
- vectorEffect="non-scaling-stroke"
- strokeWidth={0.5}
- opacity={0.6}
- />
- ))}
- <line
- x1={PAD_LEFT}
- y1={TOP - 14}
- x2={PAD_LEFT}
- y2={BASE}
- stroke="var(--border)"
- vectorEffect="non-scaling-stroke"
- strokeWidth={1}
- />
- {xTicks.map((day) => (
- <line
- key={day}
- x1={xForDay(day)}
- y1={BASE}
- x2={xForDay(day)}
- y2={BASE + 3}
- stroke="var(--border)"
- vectorEffect="non-scaling-stroke"
- strokeWidth={1}
- />
- ))}
- {limitY !== null && (
- <line
- x1={PAD_LEFT}
- y1={limitY}
- x2={WIDTH - PAD_X}
- y2={limitY}
- stroke={dangerVar}
- vectorEffect="non-scaling-stroke"
- strokeWidth={1}
- strokeDasharray="2 3"
- />
- )}
- {showFreeLine && freeY !== null && (
- <line
- x1={PAD_LEFT}
- y1={freeY}
- x2={WIDTH - PAD_X}
- y2={freeY}
- stroke={mutedVar}
- vectorEffect="non-scaling-stroke"
- strokeWidth={1}
- strokeDasharray="2 3"
- opacity={0.7}
- />
- )}
- <line
- x1={PAD_LEFT}
- y1={BASE}
- x2={WIDTH - PAD_X}
- y2={BASE}
- stroke="var(--border)"
- vectorEffect="non-scaling-stroke"
- strokeWidth={1}
- />
- {drawSpentLine && (
- <>
- <polygon
- points={pointsAttr([origin, ...spentPoints, { x: today.x, y: BASE }])}
- fill="currentColor"
- opacity={0.06}
- />
- <polyline
- points={pointsAttr([origin, ...spentPoints])}
- fill="none"
- stroke="currentColor"
- vectorEffect="non-scaling-stroke"
- strokeWidth={1.5}
- strokeLinecap="round"
- />
- </>
- )}
- {crossing ? (
- <>
- <polyline
- points={pointsAttr([today, crossing])}
- fill="none"
- stroke={dangerVar}
- vectorEffect="non-scaling-stroke"
- strokeWidth={1.5}
- strokeDasharray="4 4"
- strokeLinecap="round"
- />
- </>
- ) : (
- <>
- <polyline
- points={pointsAttr([today, end])}
- fill="none"
- stroke={pausedAtLimit ? dangerVar : statusVar}
- vectorEffect="non-scaling-stroke"
- strokeWidth={1.5}
- strokeDasharray="4 4"
- strokeLinecap="round"
- />
- </>
- )}
- </svg>
- <div className="absolute inset-0 pointer-events-none" aria-hidden>
- <Dot x={today.x} y={today.y} color="currentColor" />
- {crossing ? (
- <Dot x={crossing.x} y={crossing.y} color={dangerVar} />
- ) : (
- <Dot x={end.x} y={end.y} color={pausedAtLimit ? dangerVar : statusVar} />
- )}
- {yTicks.map((v) => (
- <Label key={v} x={PAD_LEFT - 4} y={yForCredits(v)} anchor="end" className="text-muted">
- {compactNumber(v)}
- </Label>
- ))}
- <Label x={PAD_LEFT - 4} y={BASE} anchor="end" className="text-muted">
- 0
- </Label>
- {xTicks.map((day) => (
- <Label key={day} x={xForDay(day)} y={HEIGHT - 8} anchor="middle" className="text-muted">
- {periodStart.add(day, 'day').format('MMM D')}
- </Label>
- ))}
- <Label x={PAD_LEFT} y={HEIGHT - 8} className="text-muted">
- {periodStart.format('MMM D')}
- </Label>
- <Label x={WIDTH - PAD_X} y={HEIGHT - 8} anchor="end" className="text-muted">
- {periodEnd.format('MMM D')}
- </Label>
- {limitY !== null && (
- <Label x={PAD_LEFT + 4} y={limitY - 8} className="font-semibold text-danger">
- Monthly limit · {formatCreditNumber(cap ?? 0)}
- </Label>
- )}
- {showFreeLine && freeY !== null && (
- <Label x={WIDTH - PAD_X} y={freeY - 8} anchor="end" className="font-semibold text-muted">
- Free credits · {formatCreditNumber(freeCredits)}
- </Label>
- )}
- {crossing && (
- <Label
- x={crossingLabelRight ? crossing.x + 8 : crossing.x - 8}
- y={crossing.y - 8}
- anchor={crossingLabelRight ? 'start' : 'end'}
- className="font-semibold text-danger"
- >
- Limit · {crossingDate}
- </Label>
- )}
- {!crossing && (
- <Label x={end.x - 8} y={endLabelY} anchor="end" className="font-semibold text-muted">
- {projectionLabel}
- </Label>
- )}
- <Label
- x={todayLabelX}
- y={todayLabelY}
- anchor={todayLabelLeft ? 'end' : 'start'}
- className="font-semibold"
- style={{ color: 'currentColor' }}
- >
- Today · {formatCreditNumber(spentTotal)}
- </Label>
- </div>
+ <SpendTrajectoryMarkers markers={trajectory.markers} referenceLabels={referenceLabels} />
+ </TimeSeriesLineChart>
</div>
{caption && <p className="m-0 text-xs text-danger">{caption}</p>}
</div>
diff --git a/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryMarker.tsx b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryMarker.tsx
new file mode 100644
index 000000000000..894fdab049e6
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryMarker.tsx
@@ -0,0 +1,49 @@
+/* eslint-disable react/forbid-dom-props -- dynamic pixel positions from the chart scales */
+import { useChartLayout } from '@posthog/quill-charts'
+
+import { SPEND_TONE_CLASS, resolveLabelTop } from './spendTrajectoryCaptionLayout'
+import type { SpendMarker } from './spendTrajectoryTransforms'
+
+const LABEL_GAP = 9
+const MIN_LEFT_TEXT_ROOM = 60
+const CROSSING_TEXT_WIDTH = 90
+
+interface SpendTrajectoryMarkerProps {
+ marker: SpendMarker
+ /** Pixel rows of the reference lines, lowest first, that the text must not sit on. */
+ referenceYs: number[]
+}
+
+export function SpendTrajectoryMarker({ marker, referenceYs }: SpendTrajectoryMarkerProps): JSX.Element | null {
+ const { scales, dimensions, series } = useChartLayout()
+ const x = scales.x(marker.label)
+ const y = scales.y(marker.value)
+ if (x === undefined || !isFinite(x) || !isFinite(y)) {
+ return null
+ }
+ const plotRight = dimensions.plotLeft + dimensions.plotWidth
+ const color = series.find((s) => s.key === marker.seriesKey)?.color
+ const textLeft =
+ marker.key === 'crossing'
+ ? x + CROSSING_TEXT_WIDTH > plotRight
+ : marker.key === 'end' || x - dimensions.plotLeft >= MIN_LEFT_TEXT_ROOM
+ return (
+ <div data-attr={`spend-trajectory-marker-${marker.key}`}>
+ <span
+ className="absolute size-1.5 rounded-full -translate-x-1/2 -translate-y-1/2"
+ style={{ left: x, top: y, background: color }}
+ />
+ <span
+ className={`absolute text-xs leading-none whitespace-nowrap font-semibold -translate-y-1/2 ${
+ textLeft ? '-translate-x-full' : ''
+ } ${SPEND_TONE_CLASS[marker.tone]}`}
+ style={{
+ left: textLeft ? x - LABEL_GAP : x + LABEL_GAP,
+ top: resolveLabelTop(y, referenceYs),
+ }}
+ >
+ {marker.text}
+ </span>
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryMarkers.tsx b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryMarkers.tsx
new file mode 100644
index 000000000000..8dfe9a68f420
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryMarkers.tsx
@@ -0,0 +1,49 @@
+import { useLayoutEffect, useRef, useState } from 'react'
+
+import { useChartLayout } from '@posthog/quill-charts'
+
+import { SpendReferenceCaption } from './SpendReferenceCaption'
+import { type CaptionLefts, LABEL_INSET, measureCaptionLefts } from './spendTrajectoryCaptionLayout'
+import { SpendTrajectoryMarker } from './SpendTrajectoryMarker'
+import type { SpendMarker, SpendReferenceLabel } from './spendTrajectoryTransforms'
+
+interface SpendTrajectoryMarkersProps {
+ markers: SpendMarker[]
+ /** Drawn here instead of through the library label, whose background bubble would hide the line. */
+ referenceLabels: SpendReferenceLabel[]
+}
+
+export function SpendTrajectoryMarkers({ markers, referenceLabels }: SpendTrajectoryMarkersProps): JSX.Element {
+ const { scales, dimensions } = useChartLayout()
+ const rootRef = useRef<HTMLDivElement>(null)
+ const [captionLefts, setCaptionLefts] = useState<CaptionLefts>({})
+ // Lowest line first, so a label pushed past one is then tested against the next one up.
+ const referenceYs = referenceLabels.map((line) => scales.y(line.value)).sort((a, b) => b - a)
+
+ // Text widths are only known once rendered, so captions are measured after layout and a covered one
+ // moves along its line. Candidates come from the measured width, so this settles in one extra render.
+ useLayoutEffect(() => {
+ const root = rootRef.current
+ if (!root) {
+ return
+ }
+ const lineStart = dimensions.plotLeft + LABEL_INSET
+ const lineEnd = dimensions.plotLeft + dimensions.plotWidth - LABEL_INSET
+ const next = measureCaptionLefts(root, referenceLabels, lineStart, lineEnd)
+ if (!next) {
+ return
+ }
+ setCaptionLefts((prev) => (referenceLabels.some((line) => next[line.key] !== prev[line.key]) ? next : prev))
+ }, [markers, referenceLabels, scales, dimensions])
+
+ return (
+ <div ref={rootRef} className="contents">
+ {referenceLabels.map((line) => (
+ <SpendReferenceCaption key={line.key} line={line} measuredLeft={captionLefts[line.key]} />
+ ))}
+ {markers.map((marker) => (
+ <SpendTrajectoryMarker key={marker.key} marker={marker} referenceYs={referenceYs} />
+ ))}
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryCaptionLayout.test.ts b/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryCaptionLayout.test.ts
new file mode 100644
index 000000000000..ad7f3314d568
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryCaptionLayout.test.ts
@@ -0,0 +1,11 @@
+import { LABEL_HEIGHT, resolveLabelTop } from './spendTrajectoryCaptionLayout'
+
+describe('spendTrajectoryCaptionLayout', () => {
+ it('keeps a top-edge marker label clear of its reference line', () => {
+ const referenceY = 16
+ const top = resolveLabelTop(referenceY, [referenceY])
+
+ expect(top - LABEL_HEIGHT / 2).toBeGreaterThanOrEqual(0)
+ expect(top + LABEL_HEIGHT / 2).toBeLessThan(referenceY)
+ })
+})
diff --git a/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryCaptionLayout.ts b/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryCaptionLayout.ts
new file mode 100644
index 000000000000..d3e531c7a79a
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryCaptionLayout.ts
@@ -0,0 +1,123 @@
+import type { SpendMarkerTone, SpendReferenceLabel } from './spendTrajectoryTransforms'
+
+export const LABEL_CLEARANCE = 12
+export const LABEL_HEIGHT = 12
+export const LABEL_ABOVE = 6
+export const LABEL_INSET = 4
+const COLLISION_PADDING = 2
+
+export const SPEND_TONE_CLASS: Record<SpendMarkerTone, string> = {
+ default: 'text-primary',
+ muted: 'text-muted',
+ danger: 'text-danger',
+}
+
+export interface Box {
+ left: number
+ right: number
+ top: number
+ bottom: number
+}
+
+export type CaptionLefts = Partial<Record<SpendReferenceLabel['key'], number>>
+
+export function toBox(rect: DOMRect, origin: DOMRect): Box {
+ return {
+ left: rect.left - origin.left - COLLISION_PADDING,
+ right: rect.right - origin.left + COLLISION_PADDING,
+ top: rect.top - origin.top - COLLISION_PADDING,
+ bottom: rect.bottom - origin.top + COLLISION_PADDING,
+ }
+}
+
+export function overlaps(a: Box, b: Box): boolean {
+ return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom
+}
+
+// Labels sit above their anchor. Below a point is the filled area and the rising curve, so a label
+// blocked by a reference line climbs past it instead of dropping into the fill.
+export function resolveLabelTop(anchorY: number, referenceYs: number[]): number {
+ let candidate = anchorY - LABEL_ABOVE
+ for (const reference of referenceYs) {
+ if (Math.abs(candidate - reference) < LABEL_CLEARANCE) {
+ candidate = reference - LABEL_CLEARANCE
+ }
+ }
+ return Math.max(candidate, LABEL_HEIGHT / 2)
+}
+
+interface CaptionPlacement {
+ strip: Box
+ width: number
+ position: SpendReferenceLabel['position']
+ markerBoxes: Box[]
+ lineStart: number
+ lineEnd: number
+}
+
+// Preferred end first, then the other end, then the widest gaps between markers along the line.
+export function resolveCaptionLeft({
+ strip,
+ width,
+ position,
+ markerBoxes,
+ lineStart,
+ lineEnd,
+}: CaptionPlacement): number {
+ const boxAt = (left: number): Box => ({
+ ...strip,
+ left: left - COLLISION_PADDING,
+ right: left + width + COLLISION_PADDING,
+ })
+ const atStart = lineStart
+ const atEnd = lineEnd - width
+ const candidates = position === 'end' ? [atEnd, atStart] : [atStart, atEnd]
+ const blockers = markerBoxes
+ .filter((marker) => overlaps(marker, { ...strip, left: lineStart, right: lineEnd }))
+ .sort((a, b) => a.left - b.left)
+ const gaps: [number, number][] = []
+ let cursor = lineStart
+ for (const blocker of blockers) {
+ gaps.push([cursor, blocker.left])
+ cursor = Math.max(cursor, blocker.right)
+ }
+ gaps.push([cursor, lineEnd])
+ for (const [from, to] of gaps.sort((a, b) => b[1] - b[0] - (a[1] - a[0]))) {
+ if (to - from >= width) {
+ candidates.push(from + (to - from - width) / 2)
+ }
+ }
+ return candidates.find((left) => !markerBoxes.some((marker) => overlaps(marker, boxAt(left)))) ?? candidates[0]
+}
+
+export function measureCaptionLefts(
+ root: HTMLElement,
+ referenceLabels: SpendReferenceLabel[],
+ lineStart: number,
+ lineEnd: number
+): CaptionLefts | null {
+ const origin = root.parentElement?.getBoundingClientRect()
+ if (!origin) {
+ return null
+ }
+ const markerBoxes = Array.from(
+ root.querySelectorAll<HTMLElement>('[data-attr^="spend-trajectory-marker-"] > span:last-child')
+ ).map((el) => toBox(el.getBoundingClientRect(), origin))
+ const lefts: CaptionLefts = {}
+ for (const line of referenceLabels) {
+ const el = root.querySelector<HTMLElement>(`[data-attr="spend-trajectory-reference-label-${line.key}"]`)
+ if (!el) {
+ continue
+ }
+ const measured = el.getBoundingClientRect()
+ lefts[line.key] = resolveCaptionLeft({
+ strip: toBox(measured, origin),
+ width: measured.width,
+ position: line.position,
+ markerBoxes,
+ lineStart,
+ lineEnd,
+ })
+ }
+ return lefts
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryTransforms.test.ts b/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryTransforms.test.ts
new file mode 100644
index 000000000000..d369c82fc256
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryTransforms.test.ts
@@ -0,0 +1,219 @@
+import { dayjs } from 'lib/dayjs'
+
+import { makeQuota } from '../../utils/quotaTestUtils'
+import type { SpendSeries } from '../visionUsageLogic'
+import {
+ PROJECTED_SERIES_KEY,
+ type SpendCrossing,
+ type SpendMarker,
+ type SpendTrajectory,
+ buildProjectedSeries,
+ buildSpendMarkers,
+ buildSpendPeriodAxis,
+ buildSpendTrajectory,
+ buildSpentSeries,
+ resolveFreeCreditsLine,
+ resolveSpendCrossing,
+} from './spendTrajectoryTransforms'
+
+const PERIOD_START = '2026-05-01T00:00:00Z'
+const PERIOD_END = '2026-06-01T00:00:00Z'
+const NOW = dayjs.utc('2026-05-12T10:00:00Z')
+const AXIS = buildSpendPeriodAxis(PERIOD_START, PERIOD_END, NOW)
+const TODAY_INDEX = 11
+const END_INDEX = 31
+const STATUS = 'var(--success)'
+const DANGER = 'var(--danger)'
+const CROSSING: SpendCrossing = { index: 19, value: 10_000, date: dayjs.utc('2026-05-20T06:00:00Z') }
+
+function ledger(total: number, days: number): SpendSeries {
+ return Array.from({ length: days }, (_, i) => ({
+ date: dayjs.utc(PERIOD_START).add(i, 'day').format('YYYY-MM-DD'),
+ credits: Math.round(total / days),
+ }))
+}
+
+function markerByKey(markers: SpendMarker[], key: SpendMarker['key']): SpendMarker {
+ const marker = markers.find((m) => m.key === key)
+ expect(marker).not.toBeUndefined()
+ return marker as SpendMarker
+}
+
+function projectedSeries(trajectory: SpendTrajectory): { data: number[]; color?: string } {
+ const series = trajectory.series.find((s) => s.key === PROJECTED_SERIES_KEY)
+ expect(series).not.toBeUndefined()
+ return { data: series!.data as number[], color: series!.color }
+}
+
+describe('spendTrajectoryTransforms', () => {
+ describe('buildSpendPeriodAxis', () => {
+ it('lays one UTC day per label across the period and places today on its UTC day', () => {
+ expect(AXIS.labels).toHaveLength(END_INDEX + 1)
+ expect(AXIS.labels[0]).toBe('2026-05-01')
+ expect(AXIS.labels[END_INDEX]).toBe('2026-06-01')
+ expect(AXIS.todayIndex).toBe(TODAY_INDEX)
+ expect(AXIS.endIndex).toBe(END_INDEX)
+ })
+
+ it('clamps today into the period', () => {
+ expect(buildSpendPeriodAxis(PERIOD_START, PERIOD_END, dayjs.utc('2026-07-01')).todayIndex).toBe(END_INDEX)
+ expect(buildSpendPeriodAxis(PERIOD_START, PERIOD_END, dayjs.utc('2026-04-01')).todayIndex).toBe(0)
+ })
+ })
+
+ describe('buildSpentSeries', () => {
+ it('accumulates the ledger up to today and leaves the rest empty', () => {
+ const spent = buildSpentSeries(ledger(4_000, 4), 4_000, AXIS)
+ expect(spent[0]).toBe(1_000)
+ expect(spent[3]).toBe(4_000)
+ expect(spent[TODAY_INDEX]).toBe(4_000)
+ expect(spent[TODAY_INDEX + 1]).toBeNaN()
+ })
+
+ it('pins today to the quota total when the ledger runs ahead', () => {
+ const spent = buildSpentSeries(ledger(4_400, 4), 4_000, AXIS)
+ expect(spent[2]).toBe(3_300)
+ expect(spent[3]).toBe(4_000)
+ expect(spent[TODAY_INDEX]).toBe(4_000)
+ })
+
+ it('draws only today when there is no ledger', () => {
+ const spent = buildSpentSeries([], 4_000, AXIS)
+ expect(spent[0]).toBeNaN()
+ expect(spent[TODAY_INDEX]).toBe(4_000)
+ })
+ })
+
+ describe('resolveSpendCrossing', () => {
+ it('lands the crossing on the UTC day of the verdict date', () => {
+ const crossing = resolveSpendCrossing(dayjs.utc('2026-05-20T06:00:00Z'), 10_000, 4_000, AXIS)
+ expect(crossing).not.toBeNull()
+ expect(crossing!.index).toBe(19)
+ expect(crossing!.value).toBe(10_000)
+ expect(crossing!.date.format('YYYY-MM-DD')).toBe('2026-05-20')
+ })
+
+ it.each([
+ ['there is no limit', dayjs.utc('2026-05-20'), null, 4_000],
+ ['spend is already at the limit', dayjs.utc('2026-05-20'), 10_000, 10_000],
+ ['the crossing is today', dayjs.utc('2026-05-12T18:00:00Z'), 10_000, 4_000],
+ ['the crossing is after the period', dayjs.utc('2026-06-02'), 10_000, 4_000],
+ ])('returns null when %s', (_, capReachDate, cap, spentTotal) => {
+ expect(resolveSpendCrossing(capReachDate, cap, spentTotal, AXIS)).toBeNull()
+ })
+ })
+
+ describe('buildProjectedSeries', () => {
+ it('runs from today to the crossing and stops there', () => {
+ const projected = buildProjectedSeries(4_000, 10_000, CROSSING, AXIS)
+ expect(projected[TODAY_INDEX - 1]).toBeNaN()
+ expect(projected[TODAY_INDEX]).toBe(4_000)
+ expect(projected[19]).toBe(10_000)
+ expect(projected[20]).toBeNaN()
+ })
+
+ it('runs from today to period end otherwise', () => {
+ const projected = buildProjectedSeries(4_000, 6_000, null, AXIS)
+ expect(projected[TODAY_INDEX]).toBe(4_000)
+ expect(projected[END_INDEX]).toBe(6_000)
+ })
+ })
+
+ describe('resolveFreeCreditsLine', () => {
+ it.each([
+ ['it would sit on the axis', 1_000, 240_000, 240_000, null],
+ ['it clears the axis and the limit', 2_500, 10_000, 10_000, 2_500],
+ ['it is the limit itself', 2_500, 2_500, 2_500, null],
+ ['there is no limit', 2_500, null, 6_000, 2_500],
+ ])('draws the free-credits line only when %s', (_, free, cap, axisMax, expected) => {
+ expect(resolveFreeCreditsLine(free, cap, axisMax)).toBe(expected)
+ })
+ })
+
+ describe('buildSpendMarkers', () => {
+ it('names the crossing day when demand crosses the limit', () => {
+ const markers = buildSpendMarkers(4_000, 10_000, CROSSING, AXIS)
+ expect(markerByKey(markers, 'today')).toMatchObject({ label: '2026-05-12', text: 'Today · 4,000' })
+ expect(markerByKey(markers, 'crossing')).toMatchObject({
+ label: '2026-05-20',
+ value: 10_000,
+ text: 'Limit · May 20',
+ })
+ })
+
+ it('names the period end otherwise', () => {
+ const markers = buildSpendMarkers(4_000, 6_000, null, AXIS)
+ expect(markerByKey(markers, 'end')).toMatchObject({ label: '2026-06-01', text: 'Jun 1 · ~6,000' })
+ })
+ })
+
+ describe('buildSpendTrajectory', () => {
+ it('colours the projection danger and stops it at the crossing when demand hits the limit', () => {
+ const trajectory = buildSpendTrajectory({
+ quota: makeQuota({
+ period_start: PERIOD_START,
+ period_end: PERIOD_END,
+ credit_limit: 10_000,
+ credits_used: 4_000,
+ }),
+ dailyCredits: ledger(4_000, TODAY_INDEX + 1),
+ projectedTotal: 16_000,
+ capReachDate: dayjs.utc('2026-05-20T06:00:00Z'),
+ statusColor: STATUS,
+ dangerColor: DANGER,
+ now: NOW,
+ })
+ const projected = projectedSeries(trajectory)
+ expect(projected.color).toBe(DANGER)
+ expect(projected.data[19]).toBe(10_000)
+ expect(projected.data[20]).toBeNaN()
+ expect(trajectory.crossing).not.toBeNull()
+ expect(trajectory.crossing!.date.format('YYYY-MM-DD')).toBe('2026-05-20')
+ expect(trajectory.endValue).toBe(10_000)
+ })
+
+ it('holds the projection flat at the limit once spend has reached it', () => {
+ const trajectory = buildSpendTrajectory({
+ quota: makeQuota({
+ period_start: PERIOD_START,
+ period_end: PERIOD_END,
+ credit_limit: 10_000,
+ credits_used: 10_000,
+ }),
+ dailyCredits: ledger(10_000, TODAY_INDEX + 1),
+ projectedTotal: 14_000,
+ capReachDate: null,
+ statusColor: STATUS,
+ dangerColor: DANGER,
+ now: NOW,
+ })
+ const projected = projectedSeries(trajectory)
+ expect(trajectory.pausedAtLimit).toBe(true)
+ expect(projected.color).toBe(DANGER)
+ expect(projected.data[TODAY_INDEX]).toBe(10_000)
+ expect(projected.data[END_INDEX]).toBe(10_000)
+ })
+
+ it('runs the projection to demand in the status colour when there is no limit', () => {
+ const trajectory = buildSpendTrajectory({
+ quota: makeQuota({
+ period_start: PERIOD_START,
+ period_end: PERIOD_END,
+ credit_limit: null,
+ credits_used: 4_000,
+ }),
+ dailyCredits: ledger(4_000, TODAY_INDEX + 1),
+ projectedTotal: 6_000,
+ capReachDate: null,
+ statusColor: STATUS,
+ dangerColor: DANGER,
+ now: NOW,
+ })
+ const projected = projectedSeries(trajectory)
+ expect(trajectory.cap).toBeNull()
+ expect(projected.color).toBe(STATUS)
+ expect(projected.data[END_INDEX]).toBe(6_000)
+ expect(markerByKey(trajectory.markers, 'end').text).toBe('Jun 1 · ~6,000')
+ })
+ })
+})
diff --git a/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryTransforms.ts b/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryTransforms.ts
new file mode 100644
index 000000000000..f6a11886cf16
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/spendTrajectoryTransforms.ts
@@ -0,0 +1,240 @@
+import type { Series } from '@posthog/quill-charts'
+
+import { dayjs } from 'lib/dayjs'
+import { clamp } from 'lib/utils/numbers'
+
+import type { VisionQuotaApi } from '../../generated/api.schemas'
+import { formatCreditNumber } from '../../utils/credits'
+import type { SpendSeries } from '../visionUsageLogic'
+
+export const SPENT_SERIES_KEY = 'spent'
+export const PROJECTED_SERIES_KEY = 'projected'
+
+// Lines closer than this share of the axis, to each other or to zero, read as one.
+const MIN_LINE_GAP_RATIO = 0.08
+
+export type SpendMarkerTone = 'default' | 'muted' | 'danger'
+
+export interface SpendMarker {
+ key: 'today' | 'end' | 'crossing'
+ seriesKey: string
+ label: string
+ value: number
+ text: string
+ tone: SpendMarkerTone
+}
+
+export interface SpendReferenceLabel {
+ key: 'limit' | 'free'
+ value: number
+ text: string
+ tone: SpendMarkerTone
+ position: 'start' | 'end'
+}
+
+export interface SpendPeriodAxis {
+ firstDay: dayjs.Dayjs
+ periodEnd: dayjs.Dayjs
+ endIndex: number
+ todayIndex: number
+ labels: string[]
+}
+
+export interface SpendCrossing {
+ index: number
+ value: number
+ date: dayjs.Dayjs
+}
+
+export interface SpendTrajectoryInput {
+ quota: VisionQuotaApi
+ /** Settled credits per UTC day of the period, oldest first. */
+ dailyCredits: SpendSeries
+ /** Credits the period is projected to end on, already held at the limit where one applies. */
+ projectedTotal: number
+ /** When demand crosses the limit inside the period, the date the verdict computed for it. */
+ capReachDate: dayjs.Dayjs | null
+ statusColor: string
+ dangerColor: string
+ now?: dayjs.Dayjs
+}
+
+export interface SpendTrajectory {
+ labels: string[]
+ series: Series[]
+ markers: SpendMarker[]
+ cap: number | null
+ freeCredits: number | null
+ spentTotal: number
+ endValue: number
+ crossing: SpendCrossing | null
+ pausedAtLimit: boolean
+ periodEnd: dayjs.Dayjs
+}
+
+// The ledger is bucketed by UTC day, so the axis is UTC too: a local axis would shift the curve by a day.
+export function buildSpendPeriodAxis(periodStart: string, periodEnd: string, now: dayjs.Dayjs): SpendPeriodAxis {
+ const firstDay = dayjs.utc(periodStart).startOf('day')
+ const end = dayjs.utc(periodEnd)
+ const endIndex = Math.max(end.startOf('day').diff(firstDay, 'day'), 1)
+ return {
+ firstDay,
+ periodEnd: end,
+ endIndex,
+ todayIndex: clamp(now.utc().startOf('day').diff(firstDay, 'day'), 0, endIndex),
+ labels: Array.from({ length: endIndex + 1 }, (_, i) => firstDay.add(i, 'day').format('YYYY-MM-DD')),
+ }
+}
+
+function emptySeries(axis: SpendPeriodAxis): number[] {
+ return Array.from({ length: axis.labels.length }, () => NaN)
+}
+
+// Today reads `credits_used`, the number the card header shows. The ledger only shapes the curve: it is
+// fetched alongside the quota and can be a moment newer, so only the days that overshoot are pulled down.
+export function buildSpentSeries(dailyCredits: SpendSeries, spentTotal: number, axis: SpendPeriodAxis): number[] {
+ const spent = emptySeries(axis)
+ if (dailyCredits.length > 0) {
+ const creditsByIndex = Array.from({ length: axis.todayIndex + 1 }, () => 0)
+ for (const entry of dailyCredits) {
+ const index = clamp(dayjs.utc(entry.date).diff(axis.firstDay, 'day'), 0, axis.todayIndex)
+ creditsByIndex[index] += entry.credits
+ }
+ let runningTotal = 0
+ for (let i = 0; i <= axis.todayIndex; i++) {
+ runningTotal += creditsByIndex[i]
+ spent[i] = runningTotal
+ }
+ for (let i = axis.todayIndex; i >= 0 && spent[i] > spentTotal; i--) {
+ spent[i] = spentTotal
+ }
+ }
+ spent[axis.todayIndex] = spentTotal
+ return spent
+}
+
+export function resolveSpendCrossing(
+ capReachDate: dayjs.Dayjs | null,
+ cap: number | null,
+ spentTotal: number,
+ axis: SpendPeriodAxis
+): SpendCrossing | null {
+ if (cap === null || capReachDate === null || spentTotal >= cap) {
+ return null
+ }
+ // Floored to its UTC day, so the dot sits on the day its own label names.
+ const date = capReachDate.utc()
+ const index = date.startOf('day').diff(axis.firstDay, 'day')
+ return index > axis.todayIndex && index <= axis.endIndex ? { index, value: cap, date } : null
+}
+
+export function buildProjectedSeries(
+ spentTotal: number,
+ endValue: number,
+ crossing: SpendCrossing | null,
+ axis: SpendPeriodAxis
+): number[] {
+ const projected = emptySeries(axis)
+ const toIndex = crossing?.index ?? axis.endIndex
+ const toValue = crossing?.value ?? endValue
+ const span = toIndex - axis.todayIndex
+ for (let i = axis.todayIndex; i <= toIndex; i++) {
+ projected[i] = span === 0 ? toValue : spentTotal + ((toValue - spentTotal) * (i - axis.todayIndex)) / span
+ }
+ return projected
+}
+
+// The free allocation gets its own quieter line, unless it is the limit (the free plan) or too close to read.
+export function resolveFreeCreditsLine(free: number, cap: number | null, axisMax: number): number | null {
+ const minLineGap = axisMax * MIN_LINE_GAP_RATIO
+ return free >= minLineGap && (cap === null || cap - free >= minLineGap) ? free : null
+}
+
+export function buildSpendMarkers(
+ spentTotal: number,
+ endValue: number,
+ crossing: SpendCrossing | null,
+ axis: SpendPeriodAxis
+): SpendMarker[] {
+ const today: SpendMarker = {
+ key: 'today',
+ seriesKey: SPENT_SERIES_KEY,
+ label: axis.labels[axis.todayIndex],
+ value: spentTotal,
+ text: `Today · ${formatCreditNumber(spentTotal)}`,
+ tone: 'default',
+ }
+ const projectionEnd: SpendMarker = crossing
+ ? {
+ key: 'crossing',
+ seriesKey: PROJECTED_SERIES_KEY,
+ label: axis.labels[crossing.index],
+ value: crossing.value,
+ text: `Limit · ${crossing.date.format('MMM D')}`,
+ tone: 'danger',
+ }
+ : {
+ key: 'end',
+ seriesKey: PROJECTED_SERIES_KEY,
+ label: axis.labels[axis.endIndex],
+ value: endValue,
+ text: `${axis.periodEnd.format('MMM D')} · ~${formatCreditNumber(endValue)}`,
+ tone: 'muted',
+ }
+ return [today, projectionEnd]
+}
+
+/**
+ * Cumulative spend across the period against the limit: a solid line to today and a dashed projection
+ * to period end. Spend pauses at the limit, so the projection never exceeds it: when demand crosses,
+ * the line stops at the crossing and the crossing carries the date.
+ */
+export function buildSpendTrajectory({
+ quota,
+ dailyCredits,
+ projectedTotal,
+ capReachDate,
+ statusColor,
+ dangerColor,
+ now = dayjs.utc(),
+}: SpendTrajectoryInput): SpendTrajectory {
+ const axis = buildSpendPeriodAxis(quota.period_start, quota.period_end, now)
+ const spentTotal = quota.credits_used
+ const cap = quota.credit_limit !== null && quota.credit_limit > 0 ? quota.credit_limit : null
+ // Cumulative spend cannot go down, so the projection never dips below today.
+ const demand = Math.max(projectedTotal, spentTotal)
+ const endValue = cap !== null ? Math.min(demand, cap) : demand
+ const pausedAtLimit = cap !== null && spentTotal >= cap
+ const crossing = resolveSpendCrossing(capReachDate, cap, spentTotal, axis)
+ const free = quota.free_monthly_credits
+ const freeCredits = resolveFreeCreditsLine(free, cap, Math.max(cap ?? 0, endValue, spentTotal, free, 1))
+
+ const series: Series[] = [
+ {
+ key: SPENT_SERIES_KEY,
+ label: 'Spent',
+ data: buildSpentSeries(dailyCredits, spentTotal, axis),
+ fill: { opacity: 0.08 },
+ },
+ {
+ key: PROJECTED_SERIES_KEY,
+ label: 'Projected',
+ data: buildProjectedSeries(spentTotal, endValue, crossing, axis),
+ color: crossing || pausedAtLimit ? dangerColor : statusColor,
+ stroke: { pattern: [4, 4] },
+ },
+ ]
+
+ return {
+ labels: axis.labels,
+ series,
+ markers: buildSpendMarkers(spentTotal, endValue, crossing, axis),
+ cap,
+ freeCredits,
+ spentTotal,
+ endValue,
+ crossing,
+ pausedAtLimit,
+ periodEnd: axis.periodEnd,
+ }
+}