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(engineering-analytics): CI cost clarity, shared window, focus lens (#67001)

Julian Bez065d3ccd795e
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index ba3fdac796d4..82ac2ec1b06c 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -275,7 +275,8 @@ class PRCostSummary:
"""
jobs_available: bool
- # Wall-clock minutes consumed on billable (self-hosted) runners (sum of elapsed across costed jobs).
+ # Billable CI minutes: each costed (self-hosted) job's elapsed time, summed. Parallel jobs add up, so
+ # this is compute time spent, not wall-clock run duration.
billable_minutes: float
# Estimated dollar cost (sum of per-job estimates), or None when no job was costable.
estimated_cost_usd: float | None
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index 3ce53a7286e1..739ae8e338c5 100644
--- a/products/engineering_analytics/backend/presentation/serializers.py
+++ b/products/engineering_analytics/backend/presentation/serializers.py
@@ -237,8 +237,8 @@ class PRCostSummarySerializer(DataclassSerializer):
"figure is then zero/null and the cost cards should be hidden.",
},
"billable_minutes": {
- "help_text": "Wall-clock minutes consumed on billable (self-hosted) runners, summed across "
- "costed jobs.",
+ "help_text": "Billable CI minutes: each costed (self-hosted) job's elapsed time, summed. "
+ "Parallel jobs add up, so this is compute time spent, not wall-clock run duration.",
},
"estimated_cost_usd": {
"help_text": "Estimated dollar cost (sum of per-job estimates: elapsed x tier multiplier x "
diff --git a/products/engineering_analytics/frontend/components/PullRequestTable.tsx b/products/engineering_analytics/frontend/components/PullRequestTable.tsx
index 46aaae34c2cb..e9075f14b853 100644
--- a/products/engineering_analytics/frontend/components/PullRequestTable.tsx
+++ b/products/engineering_analytics/frontend/components/PullRequestTable.tsx
@@ -161,7 +161,7 @@ export function PullRequestTable({
width: 130,
align: 'right',
tooltip:
- 'Billable minutes + estimated cost across this PR’s jobs (self-hosted runners). "—" when the job-level source isn’t synced.',
+ 'Billable minutes + estimated cost across this PR’s jobs (self-hosted runners) over its full history — not the selected window. Excludes still-running jobs, so it can rise as they settle. "—" when the job-level source isn’t synced.',
sorter: (a, b) => (a.estimatedCostUsd ?? -1) - (b.estimatedCostUsd ?? -1),
render: (_, row) => (
<BillableBadge minutes={row.billableMinutes} costUsd={row.estimatedCostUsd} />
diff --git a/products/engineering_analytics/frontend/components/RunActivityChart.tsx b/products/engineering_analytics/frontend/components/RunActivityChart.tsx
index 432fba989e35..ab69aa7c4aa8 100644
--- a/products/engineering_analytics/frontend/components/RunActivityChart.tsx
+++ b/products/engineering_analytics/frontend/components/RunActivityChart.tsx
@@ -1,3 +1,5 @@
+import { type PointerEvent as ReactPointerEvent, useEffect, useRef, useState } from 'react'
+
import { Tooltip } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
@@ -5,6 +7,7 @@ import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { cn } from 'lib/utils/css-classes'
import { humanFriendlyDuration } from 'lib/utils/durations'
+import { TimeRange, clampFocus, defaultFocus, panFocus, pxToTime, resizeFocus, timeToFrac } from '../lib/brush'
import { isDecisiveFailure } from '../lib/lifecycle'
import { percentileSorted } from '../lib/runHealth'
import { verdictTag } from '../lib/runStatus'
@@ -46,10 +49,22 @@ const LEGEND_ORDER = ['success', 'danger', 'muted', 'warning']
const SCATTER_HEIGHT = 156
const BAND_HEIGHT = 56
+const STRIP_HEIGHT = 26
const Y_TICK_COUNT = 4
const X_TICK_COUNT = 5
// A scatter of one point says nothing; only draw once there's a spread to read.
const MIN_POINTS = 2
+// The focus lens defaults to the most recent day — the "live" view — over a window that's wider than that.
+// Below this much total span there's nothing to pan over, so the brush is hidden and the chart shows it all.
+const LENS_MS = 24 * 60 * 60 * 1000
+// The lens never narrows below 15 min, so it stays grabbable and the zoomed axis keeps a readable span.
+const MIN_LENS_MS = 15 * 60 * 1000
+// A run with no final duration is treated as in flight up to now — but only up to this cap. A run that
+// started longer ago than this and still hasn't settled almost certainly never will (its completion webhook
+// was missed); without the cap its interval would stretch to now and inflate the in-flight band — and the
+// time axis — by hours or days. Capping bounds that phantom load while still counting a genuinely-running
+// recent run right up to now.
+const MAX_IN_FLIGHT_MS = 60 * 60 * 1000
/** Round up to a "nice" number (1/2/5 × 10ⁿ) so axis ticks land on readable values. */
function niceStep(rough: number): number {
@@ -88,6 +103,123 @@ interface Point {
tooltip: JSX.Element
}
+/** The focus lens: a thin strip spanning the whole loaded window with a draggable window selecting the
+ * sub-range the scatter and band zoom into. Drag the body to pan back to older runs; drag an edge to widen
+ * or narrow (zoom). The geometry (pan/resize/clamp) lives in lib/brush so it's unit-tested without a DOM. */
+function RunActivityBrush({
+ fullMin,
+ fullMax,
+ view,
+ onChange,
+ onReset,
+ isDefault,
+}: {
+ fullMin: number
+ fullMax: number
+ view: TimeRange
+ onChange: (range: TimeRange) => void
+ onReset: () => void
+ isDefault: boolean
+}): JSX.Element {
+ const stripRef = useRef<HTMLDivElement>(null)
+ // The extent is frozen at pointer-down: on a live workflow fullMax tracks `now` and would otherwise
+ // drift every render mid-drag, churning the listeners and applying the pan against a moving span.
+ const dragRef = useRef<{ x: number; view: TimeRange; fullMin: number; fullMax: number } | null>(null)
+ const [dragMode, setDragMode] = useState<null | 'pan' | 'start' | 'end'>(null)
+
+ // Track the pointer on the window (not just the lens) so a fast drag that outruns the cursor keeps
+ // panning; the listeners attach once per drag (deps don't include the moving bounds — they're frozen in
+ // dragRef) and tear down on pointer-up.
+ useEffect(() => {
+ if (!dragMode) {
+ return
+ }
+ const onMove = (e: PointerEvent): void => {
+ const strip = stripRef.current
+ const start = dragRef.current
+ if (!strip || !start) {
+ return
+ }
+ const width = strip.clientWidth
+ if (dragMode === 'pan') {
+ const deltaMs = ((e.clientX - start.x) / Math.max(1, width)) * (start.fullMax - start.fullMin)
+ onChange(panFocus(start.view, deltaMs, start.fullMin, start.fullMax))
+ } else {
+ const t = pxToTime(e.clientX - strip.getBoundingClientRect().left, width, start.fullMin, start.fullMax)
+ onChange(resizeFocus(start.view, dragMode, t, start.fullMin, start.fullMax, MIN_LENS_MS))
+ }
+ }
+ const onUp = (): void => setDragMode(null)
+ window.addEventListener('pointermove', onMove)
+ window.addEventListener('pointerup', onUp)
+ return () => {
+ window.removeEventListener('pointermove', onMove)
+ window.removeEventListener('pointerup', onUp)
+ }
+ }, [dragMode, onChange])
+
+ const begin =
+ (mode: 'pan' | 'start' | 'end') =>
+ (e: ReactPointerEvent): void => {
+ e.preventDefault()
+ e.stopPropagation()
+ dragRef.current = { x: e.clientX, view, fullMin, fullMax }
+ setDragMode(mode)
+ }
+
+ const leftPct = timeToFrac(view.start, fullMin, fullMax) * 100
+ const widthPct = Math.max(
+ 2,
+ (timeToFrac(view.end, fullMin, fullMax) - timeToFrac(view.start, fullMin, fullMax)) * 100
+ )
+
+ return (
+ <div className="mt-1 flex items-center gap-2">
+ <div
+ ref={stripRef}
+ className="relative flex-1 overflow-hidden rounded border border-border"
+ style={{ height: STRIP_HEIGHT }}
+ >
+ <div
+ className="absolute inset-y-0 cursor-grab touch-none border active:cursor-grabbing"
+ style={{
+ left: `${leftPct}%`,
+ width: `${widthPct}%`,
+ borderColor: 'var(--brand-blue)',
+ background: 'color-mix(in srgb, var(--brand-blue) 18%, transparent)',
+ }}
+ onPointerDown={begin('pan')}
+ role="slider"
+ aria-label="Zoom window"
+ aria-valuemin={fullMin}
+ aria-valuemax={fullMax}
+ aria-valuenow={view.start}
+ >
+ <div
+ className="absolute inset-y-0 left-0 w-1.5 cursor-ew-resize touch-none"
+ style={{ background: 'var(--brand-blue)' }}
+ onPointerDown={begin('start')}
+ />
+ <div
+ className="absolute inset-y-0 right-0 w-1.5 cursor-ew-resize touch-none"
+ style={{ background: 'var(--brand-blue)' }}
+ onPointerDown={begin('end')}
+ />
+ </div>
+ </div>
+ {!isDefault && (
+ <button
+ type="button"
+ className="text-xs whitespace-nowrap text-secondary hover:underline"
+ onClick={onReset}
+ >
+ Reset
+ </button>
+ )}
+ </div>
+ )
+}
+
/**
* Two views of one workflow's runs on a shared time axis: a scatter of each completed run by start time
* (X) and wall-clock duration (Y), colored by verdict with a dashed median line; and below it an
@@ -101,8 +233,17 @@ export function RunActivityChart({
truncated = false,
className,
}: RunActivityChartProps): JSX.Element | null {
+ // The lens sub-range the scatter/band zoom into; null = the default (most recent day). Declared before
+ // the early return so the hook order is stable when there aren't enough points to draw.
+ const [focus, setFocus] = useState<TimeRange | null>(null)
+ // Drop a manual pan when the runs change (e.g. the shared window changed and reloaded) so the lens
+ // returns to the live default instead of clamping a stale range onto an unrelated slice of new data.
+ useEffect(() => {
+ setFocus(null)
+ }, [runs])
const now = dayjs().valueOf()
- // Every run with a start contributes an interval to the band; a still-running run extends to now.
+ // Every run with a start contributes an interval to the band; a still-running run extends to now, but
+ // only up to MAX_IN_FLIGHT_MS so an abandoned run that never settled doesn't stretch the band by days.
const intervals: Interval[] = runs
.filter((run): run is ActivityRun & { startedAt: string } => run.startedAt != null)
.map((run) => {
@@ -110,7 +251,9 @@ export function RunActivityChart({
const completed = run.durationSeconds != null && run.durationSeconds >= 0
return {
start,
- end: completed ? start + (run.durationSeconds as number) * 1000 : now,
+ end: completed
+ ? start + (run.durationSeconds as number) * 1000
+ : Math.min(now, start + MAX_IN_FLIGHT_MS),
conclusion: run.conclusion,
completed,
}
@@ -125,8 +268,15 @@ export function RunActivityChart({
return null
}
- const tMin = Math.min(...intervals.map((iv) => iv.start))
- const tMax = Math.max(...intervals.map((iv) => iv.end))
+ // Full extent of the loaded runs, then the focus lens the scatter/band actually render. tMin/tMax below
+ // are the lens bounds, so the existing x-axis/band code zooms to the focus without further changes; the
+ // y (duration) scale and median stay over the full set, so panning never jumps the vertical axis.
+ const fullMin = Math.min(...intervals.map((iv) => iv.start))
+ const fullMax = Math.max(...intervals.map((iv) => iv.end))
+ const brushable = fullMax - fullMin > LENS_MS
+ const view = clampFocus(focus ?? defaultFocus(fullMin, fullMax, LENS_MS), fullMin, fullMax, MIN_LENS_MS)
+ const tMin = view.start
+ const tMax = view.end
const tSpan = Math.max(1, tMax - tMin)
const xPct = (ms: number): number => ((ms - tMin) / tSpan) * 100
@@ -142,9 +292,16 @@ export function RunActivityChart({
const sortedMin = [...durationsMin].sort((a, b) => a - b)
const medianMin = percentileSorted(sortedMin, 0.5) ?? 0
+ // Only the runs inside the focus lens are plotted; the duration scale and median above stay over the
+ // full set so the y-axis holds still while you pan.
+ const visible = plottable.filter((run) => {
+ const t = dayjs(run.startedAt).valueOf()
+ return t >= tMin && t <= tMax
+ })
+
// Collected here so the legend reuses the per-run verdict instead of re-deriving it for every type.
const presentTypeSet = new Set<string>()
- const points: Point[] = plottable.map((run, i) => {
+ const points: Point[] = visible.map((run, i) => {
const tag = verdictTag(run.conclusion)
presentTypeSet.add(tag.type)
return {
@@ -178,10 +335,16 @@ export function RunActivityChart({
label: dayjs(tMin + (tSpan * i) / (X_TICK_COUNT - 1)).format(xFormat),
}))
+ // Clip each interval to the focus lens so the band shows concurrency within the zoomed window, sharing
+ // the scatter's x-axis. Intervals that don't overlap the focus drop out.
+ const focusIntervals = intervals
+ .map((iv) => ({ ...iv, start: Math.max(iv.start, tMin), end: Math.min(iv.end, tMax) }))
+ .filter((iv) => iv.end > iv.start)
+
// In-flight band: exact concurrency via a sweep line over each run's start/end. Sampling fixed instants
// misses any run that begins and ends between two samples (minute-long runs on a 30-day window) — those
// would never be counted, so the band could read empty with the wrong peak even with runs on the scatter.
- const bandEvents = intervals.flatMap((iv) => {
+ const bandEvents = focusIntervals.flatMap((iv) => {
const failDelta = isDecisiveFailure(iv.conclusion) ? 1 : 0
return [
{ t: iv.start, dTotal: 1, dFailing: failDelta },
@@ -200,9 +363,12 @@ export function RunActivityChart({
steps.push({ t: event.t, total: runningTotal, failing: runningFailing })
}
})
- const peak = Math.max(1, ...steps.map((s) => s.total))
+ // True peak concurrency for the label — 0 when the lens covers a gap with no runs. The band height
+ // divides by it, so use a separate denominator that's never 0.
+ const peak = steps.length ? Math.max(...steps.map((s) => s.total)) : 0
+ const bandScale = Math.max(1, peak)
const bandX = (t: number): string => (((t - tMin) / tSpan) * 1000).toFixed(1)
- const bandY = (v: number): string => (BAND_HEIGHT - (v / peak) * (BAND_HEIGHT - 2)).toFixed(1)
+ const bandY = (v: number): string => (BAND_HEIGHT - (v / bandScale) * (BAND_HEIGHT - 2)).toFixed(1)
// Concurrency is piecewise-constant, so draw step areas: hold the prior level to the event's x, then jump.
const stepArea = (key: 'total' | 'failing'): string => {
let d = `M0,${bandY(0)}`
@@ -240,7 +406,8 @@ export function RunActivityChart({
>
<span className="text-xs whitespace-nowrap text-secondary tabular-nums">
{truncated ? 'recent ' : ''}
- {plottable.length} runs · median {formatAxisMinutes(medianMin)} · peak {peak} in flight
+ {brushable ? `${visible.length} of ${plottable.length}` : plottable.length} runs · median{' '}
+ {formatAxisMinutes(medianMin)} · peak {peak} in flight
</span>
</Tooltip>
</div>
@@ -333,6 +500,17 @@ export function RunActivityChart({
)
})}
</div>
+ {/* Focus lens over the full window — drag to pan to older runs, drag an edge to zoom. */}
+ {brushable && (
+ <RunActivityBrush
+ fullMin={fullMin}
+ fullMax={fullMax}
+ view={view}
+ onChange={setFocus}
+ onReset={() => setFocus(null)}
+ isDefault={focus === null}
+ />
+ )}
</div>
</div>
<div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1">
diff --git a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
index fb28cc9e88cf..e2e309f013a5 100644
--- a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
+++ b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
@@ -3,7 +3,8 @@
// (`WorkflowHealthRow`) and sparkline series are the same in both; only the bucket axis and the
// optional row expansion differ — passed in by the caller.
-import { combineUrl } from 'kea-router'
+import { useValues } from 'kea'
+import { combineUrl, router } from 'kea-router'
import { ReactNode } from 'react'
import { IconTrending } from '@posthog/icons'
@@ -140,6 +141,13 @@ export function WorkflowHealthTable({
emptyState,
dataAttr = 'engineering-analytics-workflow-table',
}: WorkflowHealthTableProps): JSX.Element {
+ const { searchParams } = useValues(router)
+ // Carry the active CI-analytics window into the drill-down so opening a workflow from a non-default
+ // window keeps it instead of snapping back to the default (the tab links already preserve it this way).
+ const windowParams: Record<string, string> = {
+ ...(searchParams.date_from ? { date_from: searchParams.date_from } : {}),
+ ...(searchParams.date_to ? { date_to: searchParams.date_to } : {}),
+ }
const columns: LemonTableColumns<WorkflowHealthRow> = [
{
title: 'Workflow',
@@ -152,7 +160,7 @@ export function WorkflowHealthTable({
to={
combineUrl(
urls.engineeringAnalyticsWorkflowRuns(row.repoOwner, row.repoName, row.workflowName),
- sourceId ? { source: sourceId } : {}
+ { ...windowParams, ...(sourceId ? { source: sourceId } : {}) }
).url
}
className="font-medium"
@@ -195,6 +203,8 @@ export function WorkflowHealthTable({
? [
{
title: 'Cost',
+ tooltip:
+ "CI minutes spent (each job's time summed — parallel jobs add up) plus the estimated $ at the reference rate. This is compute spent, not wall-clock run time. Excludes still-running jobs, so it can rise as they settle.",
key: 'cost',
width: CI_GRID.cost,
align: 'right',
@@ -233,6 +243,7 @@ export function WorkflowHealthTable({
},
{
title: 'p50',
+ tooltip: 'Median run duration (wall-clock) over completed runs in the window.',
key: 'p50Seconds',
width: CI_GRID.p50,
align: 'right',
@@ -243,6 +254,7 @@ export function WorkflowHealthTable({
},
{
title: 'p95',
+ tooltip: '95th-percentile run duration (wall-clock) over completed runs in the window.',
key: 'p95Seconds',
width: CI_GRID.p95,
align: 'right',
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index bcb82a8d4b3d..2ee5610b8705 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -57,7 +57,7 @@ export interface PRCostSummaryApi {
by_run: RunCostApi[]
/** False when the job-level source (github_workflow_jobs) isn't synced — every figure is then zero/null and the cost cards should be hidden. */
jobs_available: boolean
- /** Wall-clock minutes consumed on billable (self-hosted) runners, summed across costed jobs. */
+ /** Billable CI minutes: each costed (self-hosted) job's elapsed time, summed. Parallel jobs add up, so this is compute time spent, not wall-clock run duration. */
billable_minutes: number
/**
* Estimated dollar cost (sum of per-job estimates: elapsed x tier multiplier x reference rate). Null when no job was costable.
diff --git a/products/engineering_analytics/frontend/generated/api.zod.schemas.ts b/products/engineering_analytics/frontend/generated/api.zod.schemas.ts
index 3e2702e97e62..1e2b9f6cb6a5 100644
--- a/products/engineering_analytics/frontend/generated/api.zod.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.zod.schemas.ts
@@ -91,7 +91,9 @@ export const PRCostSummaryApi = zod.object({
),
billable_minutes: zod
.number()
- .describe('Wall-clock minutes consumed on billable (self-hosted) runners, summed across costed jobs.'),
+ .describe(
+ "Billable CI minutes: each costed (self-hosted) job's elapsed time, summed. Parallel jobs add up, so this is compute time spent, not wall-clock run duration."
+ ),
estimated_cost_usd: zod
.number()
.nullable()
diff --git a/products/engineering_analytics/frontend/lib/brush.test.ts b/products/engineering_analytics/frontend/lib/brush.test.ts
new file mode 100644
index 000000000000..4061aa3c1fc8
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/brush.test.ts
@@ -0,0 +1,51 @@
+import { clampFocus, defaultFocus, panFocus, pxToTime, resizeFocus, timeToFrac } from './brush'
+
+const HOUR = 3_600_000
+const DAY = 24 * HOUR
+
+describe('brush geometry', () => {
+ it('defaultFocus picks the most recent lens-width, or the whole window when shorter', () => {
+ // 7-day window, 24h lens → most recent day.
+ expect(defaultFocus(0, 7 * DAY, DAY)).toEqual({ start: 6 * DAY, end: 7 * DAY })
+ // Window already shorter than the lens → no sub-range to pan, focus the whole thing.
+ expect(defaultFocus(0, 6 * HOUR, DAY)).toEqual({ start: 0, end: 6 * HOUR })
+ })
+
+ it('clampFocus slides a range back inside bounds while preserving its width', () => {
+ // A day-wide range pushed past the right edge slides left to fit, keeping its width.
+ expect(clampFocus({ start: 7 * DAY, end: 8 * DAY }, 0, 7 * DAY, HOUR)).toEqual({
+ start: 6 * DAY,
+ end: 7 * DAY,
+ })
+ // Past the left edge slides right.
+ expect(clampFocus({ start: -DAY, end: 0 }, 0, 7 * DAY, HOUR)).toEqual({ start: 0, end: DAY })
+ })
+
+ it('clampFocus caps width at the window and floors it at the minimum span', () => {
+ // Wider than the window → clamped to the whole window.
+ expect(clampFocus({ start: -DAY, end: 9 * DAY }, 0, 7 * DAY, HOUR)).toEqual({ start: 0, end: 7 * DAY })
+ // Narrower than the floor → widened to the floor.
+ expect(clampFocus({ start: DAY, end: DAY + 60_000 }, 0, 7 * DAY, HOUR).end).toBe(DAY + HOUR)
+ })
+
+ it('panFocus shifts within bounds and slides (not shrinks) at an edge', () => {
+ const range = { start: 3 * DAY, end: 4 * DAY }
+ expect(panFocus(range, DAY, 0, 7 * DAY)).toEqual({ start: 4 * DAY, end: 5 * DAY })
+ // Panning past the right edge slides flush to it, keeping the day width.
+ expect(panFocus(range, 10 * DAY, 0, 7 * DAY)).toEqual({ start: 6 * DAY, end: 7 * DAY })
+ })
+
+ it('resizeFocus drags one edge but never crosses the other past the minimum span', () => {
+ const range = { start: 2 * DAY, end: 5 * DAY }
+ expect(resizeFocus(range, 'start', 3 * DAY, 0, 7 * DAY, HOUR)).toEqual({ start: 3 * DAY, end: 5 * DAY })
+ // Dragging start past end is capped to end - minSpan.
+ expect(resizeFocus(range, 'start', 6 * DAY, 0, 7 * DAY, HOUR)).toEqual({ start: 5 * DAY - HOUR, end: 5 * DAY })
+ })
+
+ it('pxToTime and timeToFrac are inverse mappings, clamped to the strip', () => {
+ expect(pxToTime(500, 1000, 0, 7 * DAY)).toBe(3.5 * DAY)
+ expect(pxToTime(-50, 1000, 0, 7 * DAY)).toBe(0) // clamps below 0
+ expect(timeToFrac(3.5 * DAY, 0, 7 * DAY)).toBe(0.5)
+ expect(timeToFrac(0, 0, 0)).toBe(0) // degenerate window doesn't divide by zero
+ })
+})
diff --git a/products/engineering_analytics/frontend/lib/brush.ts b/products/engineering_analytics/frontend/lib/brush.ts
new file mode 100644
index 000000000000..a7b1da4494a9
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/brush.ts
@@ -0,0 +1,73 @@
+// Pure geometry for the run-activity chart's focus lens — a context strip that shows the whole loaded
+// window with a draggable lens selecting the sub-range the scatter and band zoom into. The default lens is
+// the most recent 24h (the live view), pannable back over older days and resizable up to the full window.
+// Kept here, DOM-free, so the math (default placement, clamping, panning, resizing, px<->time) is unit-tested
+// without rendering.
+
+export interface TimeRange {
+ start: number
+ end: number
+}
+
+/** The lens's initial position: the most recent `lensMs` of the window, or the whole window when it's
+ * already shorter than the lens (nothing to pan over). */
+export function defaultFocus(tMin: number, tMax: number, lensMs: number): TimeRange {
+ if (tMax - tMin <= lensMs) {
+ return { start: tMin, end: tMax }
+ }
+ return { start: tMax - lensMs, end: tMax }
+}
+
+/** Keep a range inside [tMin, tMax] and at least `minSpanMs` wide, preserving its width where possible so a
+ * pan that hits an edge slides rather than shrinks. */
+export function clampFocus(range: TimeRange, tMin: number, tMax: number, minSpanMs: number): TimeRange {
+ const fullSpan = Math.max(0, tMax - tMin)
+ // Never wider than the window, never narrower than the floor.
+ const span = Math.min(Math.max(range.end - range.start, minSpanMs), Math.max(fullSpan, minSpanMs))
+ let start = range.start
+ if (start + span > tMax) {
+ start = tMax - span
+ }
+ if (start < tMin) {
+ start = tMin
+ }
+ return { start, end: start + span }
+}
+
+/** Shift a range by `deltaMs`, keeping its width and staying within bounds (a pan, not a resize). */
+export function panFocus(range: TimeRange, deltaMs: number, tMin: number, tMax: number): TimeRange {
+ return clampFocus({ start: range.start + deltaMs, end: range.end + deltaMs }, tMin, tMax, range.end - range.start)
+}
+
+/** Drag one edge of a range to `timeMs`, keeping start<end by at least `minSpanMs` and staying in bounds. */
+export function resizeFocus(
+ range: TimeRange,
+ edge: 'start' | 'end',
+ timeMs: number,
+ tMin: number,
+ tMax: number,
+ minSpanMs: number
+): TimeRange {
+ const t = Math.min(Math.max(timeMs, tMin), tMax)
+ if (edge === 'start') {
+ return { start: Math.min(t, range.end - minSpanMs), end: range.end }
+ }
+ return { start: range.start, end: Math.max(t, range.start + minSpanMs) }
+}
+
+/** Map a pixel offset within a strip of `width` px to a timestamp in [tMin, tMax]. */
+export function pxToTime(px: number, width: number, tMin: number, tMax: number): number {
+ if (width <= 0) {
+ return tMin
+ }
+ const frac = Math.min(1, Math.max(0, px / width))
+ return tMin + frac * (tMax - tMin)
+}
+
+/** Fraction (0..1) of the way `t` sits through [tMin, tMax], for positioning the lens on the strip. */
+export function timeToFrac(t: number, tMin: number, tMax: number): number {
+ if (tMax <= tMin) {
+ return 0
+ }
+ return Math.min(1, Math.max(0, (t - tMin) / (tMax - tMin)))
+}
diff --git a/products/engineering_analytics/frontend/lib/runHealth.test.ts b/products/engineering_analytics/frontend/lib/runHealth.test.ts
index f9eb38482af6..396a958c8fdd 100644
--- a/products/engineering_analytics/frontend/lib/runHealth.test.ts
+++ b/products/engineering_analytics/frontend/lib/runHealth.test.ts
@@ -1,4 +1,4 @@
-import { computeFleetSummary, computeHealthSummary } from './runHealth'
+import { CostableJob, RunCostSummary, computeFleetSummary, computeHealthSummary, summarizeRunCost } from './runHealth'
const at = (hour: number): string => `2026-06-24T${String(hour).padStart(2, '0')}:00:00Z`
@@ -96,4 +96,49 @@ describe('runHealth', () => {
expect(summary.estimatedCostUsd).toBe(6)
expect(summary.billableMinutes).toBe(150)
})
+
+ const job = (
+ runner_provider: string,
+ duration_seconds: number | null,
+ estimated_cost_usd: number | null
+ ): CostableJob => ({ runner_provider, duration_seconds, estimated_cost_usd })
+
+ it.each<[string, CostableJob[], RunCostSummary | null]>([
+ // Nothing billable (all free / unknown) → null so the caller omits the tile instead of showing $0.
+ ['no billable jobs → null', [job('github_hosted', 600, null), job('unknown', 600, null)], null],
+ // Settled self-hosted jobs sum; free runners are ignored.
+ [
+ 'sums settled self-hosted, ignores free',
+ [job('self_hosted', 120, 0.5), job('self_hosted', 60, 0.25), job('github_hosted', 600, null)],
+ { billableMinutes: 3, estimatedCostUsd: 0.75, unsettledJobs: 0 },
+ ],
+ // A still-running (no duration) billable job is excluded from the total and counted as unsettled —
+ // counting it would understate $/min or report a bogus 0.
+ [
+ 'in-flight billable job is unsettled, not in the total',
+ [job('self_hosted', 120, 0.5), job('self_hosted', null, null)],
+ { billableMinutes: 2, estimatedCostUsd: 0.5, unsettledJobs: 1 },
+ ],
+ // Every billable job still in flight → keep the tile (null value) plus the unsettled caveat.
+ [
+ 'all in flight → null value, caveat only',
+ [job('self_hosted', null, null)],
+ { billableMinutes: null, estimatedCostUsd: null, unsettledJobs: 1 },
+ ],
+ // A finished self-hosted job with no cost is an unpriced tier (non-Linux Depot), excluded — NOT
+ // unsettled. It must not keep the "unsettled job excluded" caveat alive on a completed run.
+ [
+ 'finished uncostable self-hosted job is excluded, not unsettled',
+ [job('self_hosted', 120, 0.5), job('self_hosted', 300, null)],
+ { billableMinutes: 2, estimatedCostUsd: 0.5, unsettledJobs: 0 },
+ ],
+ // Every billable job finished on an unpriced tier → nothing to show, omit the tile (no dangling "—").
+ [
+ 'all billable jobs finished but unpriced → null',
+ [job('self_hosted', 300, null), job('self_hosted', 120, null)],
+ null,
+ ],
+ ])('summarizeRunCost: %s', (_name, jobs, expected) => {
+ expect(summarizeRunCost(jobs)).toEqual(expected)
+ })
})
diff --git a/products/engineering_analytics/frontend/lib/runHealth.ts b/products/engineering_analytics/frontend/lib/runHealth.ts
index 2c81f95f99a2..78bb051b4858 100644
--- a/products/engineering_analytics/frontend/lib/runHealth.ts
+++ b/products/engineering_analytics/frontend/lib/runHealth.ts
@@ -19,6 +19,18 @@ export interface CostSummary {
estimatedCostUsd: number | null
}
+/** A single run's cost rolled up from its jobs, plus the count of billable jobs still in flight. */
+export interface RunCostSummary extends CostSummary {
+ unsettledJobs: number
+}
+
+/** Minimal job shape the run-cost roll-up needs; WorkflowJobApi satisfies it. */
+export interface CostableJob {
+ runner_provider: string
+ duration_seconds: number | null
+ estimated_cost_usd: number | null
+}
+
export type WorkflowState = 'healthy' | 'degraded' | 'failing' | 'unknown'
export interface HealthSummary {
@@ -188,3 +200,34 @@ export function computeFleetSummary(rows: FleetRow[]): FleetSummary {
estimatedCostUsd,
}
}
+
+/**
+ * Roll a run's jobs up to a single cost figure, mirroring the backend cost model (logic/cost.py): only
+ * self-hosted runners are billable, and a job contributes once it has settled (a non-null estimated cost).
+ * `unsettledJobs` counts only billable jobs that haven't finished yet (no duration) — excluded from the
+ * total and surfaced as a caveat so the number never silently inflates. A finished self-hosted job with no
+ * cost is an excluded tier (the backend doesn't price non-Linux Depot runners), not "unsettled", so it's
+ * left out of both. Returns null when there's nothing to show — no priced jobs and nothing still running
+ * (every job free, or every billable job finished on an unpriced tier) — so the caller omits the tile rather
+ * than render a dangling "—".
+ */
+export function summarizeRunCost(jobs: CostableJob[]): RunCostSummary | null {
+ const billable = jobs.filter((job) => job.runner_provider === 'self_hosted')
+ const costed = billable.filter((job) => job.estimated_cost_usd != null)
+ // A null cost on a finished job means an unpriced tier (excluded), not "still running" — only a job
+ // with no duration is genuinely unsettled.
+ const unsettledJobs = billable.filter((job) => job.duration_seconds == null).length
+ if (costed.length === 0 && unsettledJobs === 0) {
+ // Nothing to report: no priced jobs and nothing still running (all free, or every billable job
+ // finished on an unpriced tier). Omit the tile rather than render a dangling "—".
+ return null
+ }
+ if (costed.length === 0) {
+ // Billable jobs are still running but none has settled yet — keep the tile (with a "—" value +
+ // caveat) rather than reporting a misleading $0.00 / 0 min for a run whose cost hasn't landed.
+ return { billableMinutes: null, estimatedCostUsd: null, unsettledJobs }
+ }
+ const billableMinutes = costed.reduce((sum, job) => sum + (job.duration_seconds ?? 0) / 60, 0)
+ const estimatedCostUsd = costed.reduce((sum, job) => sum + (job.estimated_cost_usd ?? 0), 0)
+ return { billableMinutes, estimatedCostUsd, unsettledJobs }
+}
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
index e85700cd219c..8666504534b8 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
@@ -12,6 +12,7 @@ import { PullRequestTable } from '../components/PullRequestTable'
import { formatCost, formatMinutes } from '../components/runTables'
import { StatTile } from '../components/StatTile'
import { AuthorLogicProps, authorLogic } from './authorLogic'
+import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
// date_from only (the list floors on it); "all time" / week+month snaps are out. All options are within
// the list's load window so the tile scope is always a subset of the visible PRs.
@@ -31,9 +32,10 @@ export const scene: SceneExport<AuthorLogicProps> = {
}
export function EngineeringAnalyticsAuthorScene(): JSX.Element {
- const { handle, prs, prsLoading, dateFrom, windowedRows, totalCostUsd, totalBillableMinutes, sourceId } =
+ const { handle, prs, prsLoading, windowedRows, totalCostUsd, totalBillableMinutes, sourceId } =
useValues(authorLogic)
- const { setDateFrom } = useActions(authorLogic)
+ const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)
+ const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
return (
<SceneContent>
@@ -46,7 +48,8 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
<span className="text-xs text-tertiary">for PRs opened in</span>
<DateFilter
dateFrom={dateFrom}
- onChange={(from) => setDateFrom(from ?? '-30d')}
+ dateTo={dateTo}
+ onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
dateOptions={AUTHOR_DATE_OPTIONS}
size="small"
/>
@@ -65,7 +68,7 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
<StatTile
label="Estimated CI cost"
value={formatCost(totalCostUsd)}
- sub="self-hosted runners only"
+ sub="self-hosted runners; excludes still-running jobs"
/>
</div>
</div>
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
index 4365e785f37b..1edd7873e23a 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
@@ -9,6 +9,7 @@ import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
import { WorkflowHealthTable } from '../components/WorkflowHealthTable'
import { WorkflowsHealthHeader } from '../components/WorkflowsHealthHeader'
+import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
// The endpoint caps the window at 366 days, so "All time" and week/month snaps are out.
@@ -31,15 +32,15 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
workflowHealthLoading,
notConnected,
workflowHealthLoadError,
- workflowDateFrom,
- workflowDateTo,
branchInput,
appliedBranch,
sourceId,
fleetSummary,
fleetTruncated,
} = useValues(engineeringAnalyticsLogic)
- const { setWorkflowDateRange, setBranchFilter, applyBranchFilter, refresh } = useActions(engineeringAnalyticsLogic)
+ const { setBranchFilter, applyBranchFilter, refresh } = useActions(engineeringAnalyticsLogic)
+ const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)
+ const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
if (notConnected) {
return <ConnectGitHubSource />
@@ -48,7 +49,7 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
return <CIAnalyticsLoadError onRetry={refresh} />
}
- const windowLabel = dateFilterToText(workflowDateFrom, workflowDateTo, 'Last 24 hours') ?? 'Last 24 hours'
+ const windowLabel = dateFilterToText(dateFrom, dateTo, 'Last 7 days') ?? 'Last 7 days'
// Stage + apply a branch in one click (the chips). Clicking the active chip clears back to all branches.
const selectBranch = (branch: string): void => {
@@ -60,9 +61,9 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
<div className="flex flex-col gap-4">
<div className="flex items-center gap-2">
<DateFilter
- dateFrom={workflowDateFrom}
- dateTo={workflowDateTo}
- onChange={setWorkflowDateRange}
+ dateFrom={dateFrom}
+ dateTo={dateTo}
+ onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
dateOptions={WORKFLOW_DATE_OPTIONS}
/>
<LemonInput
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
index d187d4cd7fcc..de6ab50f05f6 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
@@ -7,13 +7,15 @@ import { LemonButton, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { humanFriendlyDuration } from 'lib/utils/durations'
+import { pluralize } from 'lib/utils/strings'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import { RunJobsTable } from '../components/runTables'
+import { RunJobsTable, formatCost, formatMinutes } from '../components/runTables'
+import { StatTile } from '../components/StatTile'
import { githubCommitUrl, githubRunUrl } from '../lib/github'
import { verdictTag } from '../lib/runStatus'
import { WorkflowRunDetailLogicProps, workflowRunDetailLogic } from './workflowRunDetailLogic'
@@ -39,7 +41,8 @@ function DetailRow({ label, children }: { label: string; children: React.ReactNo
}
export function WorkflowRunDetailScene(): JSX.Element {
- const { run, runLoading, loadFailed, sourceId, jobs, jobsLoading, isValidRunId } = useValues(workflowRunDetailLogic)
+ const { run, runLoading, loadFailed, sourceId, jobs, jobsLoading, runCost, isValidRunId } =
+ useValues(workflowRunDetailLogic)
const { loadRun } = useActions(workflowRunDetailLogic)
if (!isValidRunId) {
@@ -107,6 +110,25 @@ export function WorkflowRunDetailScene(): JSX.Element {
</span>
</div>
+ {runCost && (
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonTag type="warning">estimate · wall-clock × reference rate</LemonTag>
+ {runCost.unsettledJobs > 0 && (
+ <LemonTag type="muted">
+ {pluralize(runCost.unsettledJobs, 'unsettled job')} excluded
+ </LemonTag>
+ )}
+ </div>
+ <StatTile
+ label="Billable CI minutes"
+ value={formatMinutes(runCost.billableMinutes)}
+ sub={<>≈ {formatCost(runCost.estimatedCostUsd)} estimated</>}
+ className="max-w-72"
+ />
+ </div>
+ )}
+
<LemonCard hoverEffect={false} className="divide-y p-0">
<DetailRow label="Status">
<span className="capitalize">{run.status || '—'}</span>
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
index bf89c2374f04..8e2dfbcae905 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
@@ -20,6 +20,7 @@ import { RunnerBadge, RunsTable, formatCost } from '../components/runTables'
import { WorkflowHealthHeader } from '../components/WorkflowHealthHeader'
import type { WorkflowRunnerCostApi } from '../generated/api.schemas'
import { githubWorkflowUrl } from '../lib/github'
+import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import { WorkflowRunRow, WorkflowRunsLogicProps, workflowRunsLogic } from './workflowRunsLogic'
/** Where a workflow's CI spend goes, split by runner tier — a small table (not bespoke chips) so it reads
@@ -107,7 +108,6 @@ export function WorkflowRunsScene(): JSX.Element {
runJobs,
runJobsLoading,
expandedRunKeys,
- dateFrom,
loadFailed,
sourceId,
repoOwner,
@@ -117,7 +117,9 @@ export function WorkflowRunsScene(): JSX.Element {
costSummary,
runsTruncated,
} = useValues(workflowRunsLogic)
- const { loadRuns, setRunExpanded, setDateRange } = useActions(workflowRunsLogic)
+ const { loadRuns, setRunExpanded } = useActions(workflowRunsLogic)
+ const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)
+ const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
const githubUrl = githubWorkflowUrl(repoOwner, repoName, workflowName)
@@ -210,7 +212,8 @@ export function WorkflowRunsScene(): JSX.Element {
<span className="text-xs font-semibold tracking-wide text-secondary uppercase">Window</span>
<DateFilter
dateFrom={dateFrom}
- onChange={(from, to) => setDateRange(from ?? '-30d', to ?? null)}
+ dateTo={dateTo}
+ onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
dateOptions={WORKFLOW_DATE_OPTIONS}
size="small"
/>
diff --git a/products/engineering_analytics/frontend/scenes/authorLogic.ts b/products/engineering_analytics/frontend/scenes/authorLogic.ts
index b5129309abab..b04626c864cc 100644
--- a/products/engineering_analytics/frontend/scenes/authorLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/authorLogic.ts
@@ -1,4 +1,4 @@
-import { actions, afterMount, kea, key, path, props, reducers, selectors } from 'kea'
+import { afterMount, connect, kea, key, path, props, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { ApiConfig } from 'lib/api'
@@ -10,6 +10,7 @@ import { Breadcrumb } from '~/types'
import { engineeringAnalyticsPullRequests } from '../generated/api'
import type { authorLogicType } from './authorLogicType'
+import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import { PullRequestRow, toPullRequestRow } from './engineeringAnalyticsLogic'
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
@@ -30,15 +31,11 @@ export const authorLogic = kea<authorLogicType>([
props({} as AuthorLogicProps),
key((props) => `author/${props.handle}@${props.sourceId ?? ''}`),
- actions({
- // Window for the cost tiles only — the PR list below is not re-scoped by it.
- setDateFrom: (dateFrom: string) => ({ dateFrom }),
- }),
-
- reducers({
- // Tile window; default last 30 days. Drives the client-side filter in `windowedRows`, never a reload.
- dateFrom: ['-30d', { setDateFrom: (_, { dateFrom }) => dateFrom }],
- }),
+ // Shares the CI-analytics window, but only to scope the cost tiles (a client-side filter over the
+ // already-loaded PRs) — the PR list below is never re-scoped, so changing the window never reloads here.
+ connect(() => ({
+ values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo']],
+ })),
loaders(({ props }) => ({
prs: [
@@ -62,15 +59,16 @@ export const authorLogic = kea<authorLogicType>([
sourceId: [() => [(_, p: AuthorLogicProps) => p.sourceId], (sourceId): string | null => sourceId],
handle: [() => [(_, p: AuthorLogicProps) => p.handle], (handle): string => handle],
// The tile scope: PRs opened within the selected window. The list shows every loaded PR; only the
- // cost KPIs narrow to this subset, so the date picker reads as "cost of PRs opened in the last N days".
+ // cost KPIs narrow to this subset, so the date picker reads as "cost of PRs opened in the window".
windowedRows: [
- (s) => [s.prs, s.dateFrom],
- (prs: PullRequestRow[], dateFrom: string): PullRequestRow[] => {
- const cutoff = dateStringToDayJs(dateFrom)
- if (!cutoff) {
- return prs
- }
- return prs.filter((pr) => dayjs(pr.createdAt).isAfter(cutoff))
+ (s) => [s.prs, s.dateFrom, s.dateTo],
+ (prs: PullRequestRow[], dateFrom: string | null, dateTo: string | null): PullRequestRow[] => {
+ const from = dateFrom ? dateStringToDayJs(dateFrom) : null
+ const to = dateTo ? dateStringToDayJs(dateTo) : null
+ return prs.filter((pr) => {
+ const created = dayjs(pr.createdAt)
+ return (!from || created.isAfter(from)) && (!to || created.isBefore(to))
+ })
},
],
// Author totals across the in-window PRs — null when nothing was costable / the job source is unsynced.
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts
new file mode 100644
index 000000000000..b73fa1dfee9d
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts
@@ -0,0 +1,60 @@
+import { actions, kea, path, reducers } from 'kea'
+import { actionToUrl, router, urlToAction } from 'kea-router'
+
+import type { engineeringAnalyticsFiltersLogicType } from './engineeringAnalyticsFiltersLogicType'
+
+// One window shared by every CI-analytics surface that's scoped by time — the Workflows tab, a single
+// workflow's runs/cost page, and an author's cost tiles — so a window picked on one carries to the others
+// instead of each page snapping back to its own default. 7 days balances the two needs the pages used to
+// split on (-24h health vs -30d spend): long enough to read a week of spend, short enough that health still
+// reads as recent. Nothing live is lost — the "is CI red now" verdict is window-independent and bucket
+// granularity auto-follows the window, so narrowing to 24h still gives the live hourly view on demand.
+export const SHARED_DEFAULT_DATE_FROM = '-7d'
+
+export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersLogicType>([
+ path(['products', 'engineering_analytics', 'frontend', 'scenes', 'engineeringAnalyticsFiltersLogic']),
+
+ actions({
+ setDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
+ }),
+
+ reducers({
+ dateFrom: [SHARED_DEFAULT_DATE_FROM as string | null, { setDateRange: (_, { dateFrom }) => dateFrom }],
+ dateTo: [null as string | null, { setDateRange: (_, { dateTo }) => dateTo }],
+ }),
+
+ actionToUrl(({ values }) => ({
+ // Encode the window in the URL so tab links and drill-down links (which preserve query params) carry
+ // it, and a shared link reopens it. Replace, not push — nudging a date shouldn't stack back-history.
+ // The default is omitted so a pristine URL stays clean.
+ setDateRange: () => {
+ const { pathname, searchParams, hashParams } = router.values.currentLocation
+ const next = { ...searchParams }
+ if (values.dateFrom && values.dateFrom !== SHARED_DEFAULT_DATE_FROM) {
+ next.date_from = values.dateFrom
+ } else {
+ delete next.date_from
+ }
+ if (values.dateTo) {
+ next.date_to = values.dateTo
+ } else {
+ delete next.date_to
+ }
+ return [pathname, next, hashParams, { replace: true }]
+ },
+ })),
+
+ urlToAction(({ actions, values }) => ({
+ // Hydrate from the URL on any CI-analytics route — a shared link, a reload, or a drill-down link that
+ // carried the params. Guarded so we only dispatch on a real change, which also breaks the actionToUrl
+ // loop. '*' is safe here: the logic is only mounted while a CI-analytics scene connects it, so this
+ // never fires for unrelated routes. Handler params are inferred (kea-router types them).
+ '*': (_, searchParams) => {
+ const dateFrom = searchParams.date_from ?? SHARED_DEFAULT_DATE_FROM
+ const dateTo = searchParams.date_to ?? null
+ if (dateFrom !== values.dateFrom || dateTo !== values.dateTo) {
+ actions.setDateRange(dateFrom, dateTo)
+ }
+ },
+ })),
+])
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
index b8707e94aff8..54eee93ab2eb 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
@@ -23,6 +23,7 @@ import type {
} from '../generated/api.schemas'
import { ciStatusOf } from '../lib/ci'
import { summarizeLifecycle, workflowRuns } from '../lib/lifecycle'
+import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import {
DEFAULT_FILTERS,
DEFAULT_QUARANTINE_FILTERS,
@@ -326,17 +327,19 @@ describe('engineeringAnalyticsLogic', () => {
expect(logic.values.workflowHealthLoadError).toBe(false)
})
- it('reloads workflow health when the date range changes', async () => {
+ it('reloads workflow health when the shared date range changes', async () => {
logic = engineeringAnalyticsLogic()
logic.mount()
+ const filters = engineeringAnalyticsFiltersLogic()
+ filters.mount()
await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
- expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-24h' })
+ expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d' })
- logic.actions.setWorkflowDateRange('-90d', null)
+ filters.actions.setDateRange('-90d', null)
await expectLogic(logic).toDispatchActions(['loadWorkflowHealth', 'loadWorkflowHealthSuccess'])
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-90d' })
- logic.actions.setWorkflowDateRange('2026-01-01', '2026-03-01')
+ filters.actions.setDateRange('2026-01-01', '2026-03-01')
await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '2026-01-01', date_to: '2026-03-01' })
})
@@ -344,8 +347,10 @@ describe('engineeringAnalyticsLogic', () => {
it('filters workflow health by branch server-side, only reloading on a real change', async () => {
logic = engineeringAnalyticsLogic()
logic.mount()
+ const filters = engineeringAnalyticsFiltersLogic()
+ filters.mount()
await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
- expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-24h' })
+ expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d' })
// Typing only stages the value — no reload until applied.
logic.actions.setBranchFilter('main')
@@ -357,7 +362,7 @@ describe('engineeringAnalyticsLogic', () => {
logic.actions.applyBranchFilter()
await expectLogic(logic).toDispatchActions(['loadWorkflowHealth', 'loadWorkflowHealthSuccess'])
expect(logic.values.appliedBranch).toBe('main')
- expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-24h', branch: 'main' })
+ expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d', branch: 'main' })
// Re-applying an unchanged value (e.g. a blur with no edit) does not reload.
mockWorkflowHealth.mockClear()
@@ -366,7 +371,7 @@ describe('engineeringAnalyticsLogic', () => {
expect(mockWorkflowHealth).not.toHaveBeenCalled()
// The applied branch persists across a date-range reload.
- logic.actions.setWorkflowDateRange('-90d', null)
+ filters.actions.setDateRange('-90d', null)
await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-90d', branch: 'main' })
@@ -423,7 +428,7 @@ describe('engineeringAnalyticsLogic', () => {
expect(logic.values.sourceId).toBe('src-newer')
expect(mockCiCards).toHaveBeenLastCalledWith('1', { source_id: 'src-newer' })
expect(mockPullRequests).toHaveBeenLastCalledWith('1', { source_id: 'src-newer' })
- expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-24h', source_id: 'src-newer' })
+ expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d', source_id: 'src-newer' })
})
it('resetFilters returns every filter to defaults and clears hasActiveFilters', async () => {
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
index 8f0e02bcb85d..815451174f8c 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
@@ -1,4 +1,4 @@
-import { LogicWrapper, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
+import { LogicWrapper, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
@@ -17,6 +17,7 @@ import {
import type { GitHubSourceApi, PullRequestListItemApi } from '../generated/api.schemas'
import { CIStatus, ciStatusOf } from '../lib/ci'
import { type FleetSummary, computeFleetSummary } from '../lib/runHealth'
+import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import type { engineeringAnalyticsLogicType } from './engineeringAnalyticsLogicType'
// Safety bound on the PR table (mirrors the endpoint's server-side limit). Surfaced
@@ -40,9 +41,6 @@ export type CardFilter = 'open' | 'failing' | 'stuck'
/** Mirrors the ci_cards "stuck" rule: open, non-draft, non-bot, older than 7 days. */
export const STUCK_AFTER_DAYS = 7
-/** Mirrors the workflow_health endpoint's default window — CI health is a "right now" question. */
-export const DEFAULT_WORKFLOW_DATE_FROM = '-24h'
-
export interface PullRequestRow {
number: number
title: string
@@ -420,6 +418,11 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
kea<engineeringAnalyticsLogicType>([
path(['products', 'engineering_analytics', 'frontend', 'scenes', 'engineeringAnalyticsLogic']),
+ // The Workflows tab reads the shared CI-analytics window; the loader and reload listener use it.
+ connect(() => ({
+ values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo']],
+ })),
+
actions({
setStateFilter: (state: PRStateFilter) => ({ state }),
setAuthor: (author: string | null) => ({ author }),
@@ -427,7 +430,6 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
setCiStatusFilter: (ciStatus: CIStatusFilter) => ({ ciStatus }),
setSearch: (search: string) => ({ search }),
setStuckOnly: (stuckOnly: boolean) => ({ stuckOnly }),
- setWorkflowDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
// Branch is filtered server-side (it's aggregated away in workflow health), so typing only
// stages the value in branchInput; applyBranchFilter promotes it to appliedBranch and reloads.
setBranchFilter: (branch: string) => ({ branch }),
@@ -479,8 +481,8 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
{
loadWorkflowHealth: async (): Promise<WorkflowHealthRow[]> => {
const items = await engineeringAnalyticsWorkflowHealth(projectId(), {
- date_from: values.workflowDateFrom ?? undefined,
- date_to: values.workflowDateTo ?? undefined,
+ date_from: values.dateFrom ?? undefined,
+ date_to: values.dateTo ?? undefined,
branch: values.appliedBranch || undefined,
source_id: values.sourceId ?? undefined,
})
@@ -577,11 +579,6 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
DEFAULT_FILTERS.search,
{ setSearch: (_, { search }) => search, resetFilters: () => DEFAULT_FILTERS.search },
],
- workflowDateFrom: [
- DEFAULT_WORKFLOW_DATE_FROM as string | null,
- { setWorkflowDateRange: (_, { dateFrom }) => dateFrom },
- ],
- workflowDateTo: [null as string | null, { setWorkflowDateRange: (_, { dateTo }) => dateTo }],
// Exact git branch to scope workflow health to; '' means all branches. branchInput is the
// staged text in the box; appliedBranch is what the loader sends. Server-side filter, so
// appliedBranch persists across date reloads (e.g. "main on last 30d" → "main on last 90d").
@@ -812,7 +809,8 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
},
// Cards, the PR list, workflow health, and the quarantine repo are all per-source — reload them all.
setSourceId: () => actions.refresh(),
- setWorkflowDateRange: () => {
+ // The shared window scopes workflow health; reload it when the window changes.
+ [engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
actions.loadWorkflowHealth()
},
setBranchFilter: ({ branch }) => {
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
index 909c6a5bf040..9f501a1847ee 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
@@ -8,6 +8,7 @@ import { Breadcrumb } from '~/types'
import { engineeringAnalyticsWorkflowJobs, engineeringAnalyticsWorkflowRun } from '../generated/api'
import type { WorkflowJobApi, WorkflowRunDetailApi } from '../generated/api.schemas'
+import { RunCostSummary, summarizeRunCost } from '../lib/runHealth'
import type { workflowRunDetailLogicType } from './workflowRunDetailLogicType'
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
@@ -68,6 +69,9 @@ export const workflowRunDetailLogic = kea<workflowRunDetailLogicType>([
selectors({
// Exposed so the scene can preserve `?source=` when linking out to the PR detail.
sourceId: [() => [(_, p: WorkflowRunDetailLogicProps) => p.sourceId], (sourceId): string | null => sourceId],
+ // The run's own CI cost, summed from the jobs already loaded for the breakdown table — no extra
+ // query. null until jobs load or when nothing on the run is billable. Mirrors the PR page's tile.
+ runCost: [(s) => [s.jobs], (jobs): RunCostSummary | null => (jobs ? summarizeRunCost(jobs) : null)],
// A non-numeric path segment yields NaN — the scene shows a clean "not found" instead of a load error.
isValidRunId: [
() => [(_, p: WorkflowRunDetailLogicProps) => p.runId],
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
index 1a9970b6cc43..e7ef62a51373 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
@@ -1,4 +1,4 @@
-import { actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { ApiConfig } from 'lib/api'
@@ -14,6 +14,7 @@ import {
import type { WorkflowJobApi, WorkflowRunDetailApi, WorkflowRunnerCostApi } from '../generated/api.schemas'
import { jobCacheKey } from '../lib/jobs'
import { type CostSummary, type HealthSummary, computeHealthSummary } from '../lib/runHealth'
+import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import type { workflowRunsLogicType } from './workflowRunsLogicType'
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
@@ -50,6 +51,12 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
props({} as WorkflowRunsLogicProps),
key((props) => `${props.repoOwner}/${props.repoName}/${props.workflowName}@${props.sourceId ?? ''}`),
+ // The shared CI-analytics window scopes both the runs list and the runner-cost breakdown — one window,
+ // never all-time, and the same one the Workflows tab and author page use.
+ connect(() => ({
+ values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo']],
+ })),
+
actions({
// Row expansion is keyed by a per-row key (re-runs share a run_id); jobs are fetched per run+attempt.
setRunExpanded: (rowKey: string, expanded: boolean, runId: number | null, runAttempt: number | null) => ({
@@ -58,8 +65,6 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
runId,
runAttempt,
}),
- // One window scopes both the runs list and the runner-cost breakdown — cost is never all-time.
- setDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
}),
loaders(({ props, values }) => ({
@@ -114,9 +119,6 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
})),
reducers({
- // Default to the last 30 days — a useful spend window, and the same default the endpoint applies.
- dateFrom: ['-30d' as string | null, { setDateRange: (_, { dateFrom }) => dateFrom }],
- dateTo: [null as string | null, { setDateRange: (_, { dateTo }) => dateTo }],
loadFailed: [
false,
{
@@ -219,8 +221,8 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
actions.loadJobs({ runId, runAttempt })
}
},
- // The window scopes both lists — reload them together.
- setDateRange: () => {
+ // The shared window scopes both lists — reload them together when it changes.
+ [engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
actions.loadRuns()
actions.loadRunnerCosts()
},
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d015c0456176..261bd97647b6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -30552,7 +30552,7 @@ export namespace Schemas {
by_run: RunCost[];
/** False when the job-level source (github_workflow_jobs) isn't synced — every figure is then zero/null and the cost cards should be hidden. */
jobs_available: boolean;
- /** Wall-clock minutes consumed on billable (self-hosted) runners, summed across costed jobs. */
+ /** Billable CI minutes: each costed (self-hosted) job's elapsed time, summed. Parallel jobs add up, so this is compute time spent, not wall-clock run duration. */
billable_minutes: number;
/**
* Estimated dollar cost (sum of per-job estimates: elapsed x tier multiplier x reference rate). Null when no job was costable.