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): add run activity chart and health headers (#66210)

Julian Bez6a3a4fb98d2c
diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.py
index 371de59e79cc..19e14235dfb9 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py
@@ -24,11 +24,21 @@ from products.engineering_analytics.backend.facade.contracts import (
from products.engineering_analytics.backend.logic.cost import PRCostAggregate, aggregate_pr_cost, runner_descriptor
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+# Pre-aggregated per (workflow, run, attempt, runner-label) — a raw per-job SELECT has no LIMIT, so HogQL
+# caps it at DEFAULT_RETURNED_ROWS (100) and silently drops the rest, undercounting any PR with >100 jobs.
+# Each group carries finished/elapsed/unfinished, expanded back into per-job tuples (cost is linear in
+# elapsed) so the run- and workflow-level rollups stay exact. Same shape as the PR-list cost query.
_SELECT = """
- SELECT r.workflow_name, r.id AS run_id, r.run_attempt, j.labels, j.duration_seconds
+ SELECT
+ r.workflow_name, r.id AS run_id, r.run_attempt, j.labels,
+ countIf(j.duration_seconds IS NOT NULL) AS finished,
+ sumIf(j.duration_seconds, j.duration_seconds IS NOT NULL) AS elapsed,
+ countIf(j.duration_seconds IS NULL) AS unfinished
FROM __JOBS_SOURCE__ AS j
INNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt
WHERE r.pr_number = {pr_number} AND r.repo_owner = {repo_owner} AND r.repo_name = {repo_name}
+ GROUP BY r.workflow_name, r.id, r.run_attempt, j.labels
+ LIMIT 1000000
"""
_EMPTY = PRCostSummary(
@@ -65,16 +75,15 @@ def query_pr_cost(
},
)
rows = response.results or []
- overall = aggregate_pr_cost(
- (_parse_labels(labels), _duration(duration)) for _workflow, _run_id, _run_attempt, labels, duration in rows
- )
-
+ all_jobs: list[tuple[list[str], float | None]] = []
by_workflow_jobs: dict[str, list[tuple[list[str], float | None]]] = defaultdict(list)
by_run_jobs: dict[tuple[int, int], list[tuple[list[str], float | None]]] = defaultdict(list)
- for workflow, run_id, run_attempt, labels, duration in rows:
- job = (_parse_labels(labels), _duration(duration))
- by_workflow_jobs[workflow or ""].append(job)
- by_run_jobs[(int(run_id), int(run_attempt))].append(job)
+ for workflow, run_id, run_attempt, labels, finished, elapsed, unfinished in rows:
+ jobs = _expand_jobs(_parse_labels(labels), int(finished or 0), float(elapsed or 0.0), int(unfinished or 0))
+ all_jobs.extend(jobs)
+ by_workflow_jobs[workflow or ""].extend(jobs)
+ by_run_jobs[(int(run_id), int(run_attempt))].extend(jobs)
+ overall = aggregate_pr_cost(all_jobs)
by_workflow = [
_to_workflow_cost(workflow, aggregate_pr_cost(jobs)) for workflow, jobs in sorted(by_workflow_jobs.items())
]
@@ -299,10 +308,6 @@ def _to_workflow_cost(workflow_name: str, aggregate: PRCostAggregate) -> Workflo
)
-def _duration(value: Any) -> float | None:
- return float(value) if value is not None else None
-
-
def _parse_labels(raw: Any) -> list[str]:
if not raw:
return []
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_jobs.py b/products/engineering_analytics/backend/logic/queries/workflow_jobs.py
index 2a03a67051fb..2b38a8ef532d 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_jobs.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_jobs.py
@@ -21,11 +21,15 @@ from products.engineering_analytics.backend.facade.contracts import WorkflowJob
from products.engineering_analytics.backend.logic.cost import estimate_job_cost_usd, runner_descriptor
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+# Explicit high LIMIT: without it HogQL caps at DEFAULT_RETURNED_ROWS (100), and since the rows are ordered
+# by start, a run with >100 jobs (matrix builds, re-run attempts) would silently drop its latest-starting
+# jobs — the breakdown would then miss jobs and not add up to the run's cost.
_SELECT = """
SELECT id, run_id, run_attempt, name, status, conclusion, labels, runner_name, started_at, completed_at, duration_seconds
FROM __JOBS_SOURCE__ AS j
WHERE run_id = {run_id}
ORDER BY started_at ASC, id ASC
+ LIMIT 1000000
"""
_LATEST_ATTEMPT_SELECT = """
diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.py
index 1695206b9fa9..0102ce7a7997 100644
--- a/products/engineering_analytics/backend/tests/test_logic.py
+++ b/products/engineering_analytics/backend/tests/test_logic.py
@@ -619,6 +619,34 @@ class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):
assert item.estimated_cost_usd is not None and item.estimated_cost_usd > 0
assert item.billable_minutes is not None and item.billable_minutes > 0
+ def test_pr_cost_sums_all_jobs_past_the_default_row_cap(self) -> None:
+ # A PR with more jobs than HogQL's default 100-row cap: the detail cost must sum every job, not
+ # silently truncate to the first 100 (the truncation that made PR detail cost disagree with the list).
+ self._create_table(
+ "github_pull_requests",
+ _PULL_REQUESTS_COLUMNS,
+ [_pr_row(71, "alice", "open", 0, _ago(1), head_sha="sha71")],
+ )
+ self._create_table(
+ "github_workflow_runs",
+ _WORKFLOW_RUNS_COLUMNS,
+ [_run_row(9700, "CI", "sha71", "completed", "success", _ago(1), _ago(1), pr_number=71)],
+ )
+ job_count = 150
+ self._create_table(
+ "github_workflow_jobs",
+ WORKFLOW_JOBS_COLUMNS,
+ [
+ _job_row(97000 + i, 9700, f"job-{i}", "success", labels='["depot-ubuntu-22.04-4"]')
+ for i in range(job_count)
+ ],
+ )
+ cost = api.get_pr_cost(team=self.team, pr_number=71, repo="PostHog/posthog")
+ # Every job counts; before the LIMIT fix this capped at 100. 150 jobs x 120s = 300 min, depot
+ # 4-core (2x) at $0.004/min = 300 x 0.004 x 2 = $2.40.
+ assert cost.costed_jobs == job_count
+ assert cost.estimated_cost_usd == pytest.approx(2.40)
+
def test_pull_request_list_author_filter(self) -> None:
# The author filter scopes the list to one author's PRs (drives the author page).
self._create_table(
diff --git a/products/engineering_analytics/frontend/components/DistributionBar.tsx b/products/engineering_analytics/frontend/components/DistributionBar.tsx
new file mode 100644
index 000000000000..ce327156d0a7
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/DistributionBar.tsx
@@ -0,0 +1,63 @@
+import { ReactNode } from 'react'
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+export interface DistributionSegment {
+ key: string
+ label: ReactNode
+ value: number
+ /** Any CSS color (e.g. a `getSeriesColor(i)` result). */
+ color: string
+ /** Extra tooltip line under the label (e.g. the formatted amount). */
+ caption?: ReactNode
+}
+
+/**
+ * One horizontal bar split into colored segments sized by share of the total — a whole distribution
+ * (cost by runner tier, jobs by status, …) read at a glance, each segment hover-able for its share.
+ * Adapted from LLM analytics' cluster distribution bar. Segments under 0.5% are dropped as visual noise.
+ */
+export function DistributionBar({
+ segments,
+ className,
+}: {
+ segments: DistributionSegment[]
+ className?: string
+}): JSX.Element | null {
+ const total = segments.reduce((sum, seg) => sum + Math.max(0, seg.value), 0)
+ if (total <= 0) {
+ return null
+ }
+ return (
+ <div className={cn('flex h-2.5 w-full overflow-hidden rounded-sm bg-border-light', className)}>
+ {segments.map((seg) => {
+ const percent = (Math.max(0, seg.value) / total) * 100
+ if (percent < 0.5) {
+ return null
+ }
+ return (
+ <Tooltip
+ key={seg.key}
+ title={
+ <div className="text-xs">
+ <div className="font-semibold">{seg.label}</div>
+ <div>
+ {seg.caption != null && <>{seg.caption} · </>}
+ {Math.round(percent)}%
+ </div>
+ </div>
+ }
+ >
+ {/* eslint-disable-next-line react/forbid-dom-props */}
+ <div
+ className="h-full transition-all hover:opacity-80"
+ style={{ width: `${percent}%`, backgroundColor: seg.color }}
+ />
+ </Tooltip>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/RangeBar.tsx b/products/engineering_analytics/frontend/components/RangeBar.tsx
new file mode 100644
index 000000000000..5c66ad4ea773
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/RangeBar.tsx
@@ -0,0 +1,56 @@
+import { ReactNode } from 'react'
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+/**
+ * A compact horizontal bar with a fill and an optional tick marker — for showing a value within a range
+ * at a glance (e.g. median duration as the fill, p95 as the tick). Adapted from LLM analytics' sentiment
+ * bar; the tick triangle and fill width are positioned inline because they're data-driven.
+ */
+export function RangeBar({
+ fraction,
+ tickFraction,
+ fillColor = 'var(--brand-blue)',
+ tickColor = 'var(--muted)',
+ className,
+ tooltip,
+}: {
+ /** 0–1 — how far the bar fills. */
+ fraction: number
+ /** 0–1 — optional marker (a small triangle above the bar); omit for a plain fill. */
+ tickFraction?: number | null
+ fillColor?: string
+ tickColor?: string
+ className?: string
+ tooltip?: ReactNode
+}): JSX.Element {
+ const fill = Math.max(0, Math.min(100, fraction * 100))
+ const tick = tickFraction == null ? null : Math.max(0, Math.min(100, tickFraction * 100))
+ const bar = (
+ <span className={cn('relative inline-block', className)}>
+ <span className="block h-1.5 overflow-hidden rounded-full bg-border-light">
+ {/* eslint-disable-next-line react/forbid-dom-props */}
+ <span className="block h-full rounded-full" style={{ width: `${fill}%`, backgroundColor: fillColor }} />
+ </span>
+ {tick != null && (
+ <span
+ className="absolute"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ left: `${tick}%`,
+ top: -4,
+ marginLeft: -3,
+ width: 0,
+ height: 0,
+ borderLeft: '3px solid transparent',
+ borderRight: '3px solid transparent',
+ borderTop: `4px solid ${tickColor}`,
+ }}
+ />
+ )}
+ </span>
+ )
+ return tooltip ? <Tooltip title={tooltip}>{bar}</Tooltip> : bar
+}
diff --git a/products/engineering_analytics/frontend/components/RunActivityChart.tsx b/products/engineering_analytics/frontend/components/RunActivityChart.tsx
new file mode 100644
index 000000000000..432fba989e35
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/RunActivityChart.tsx
@@ -0,0 +1,359 @@
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+
+import { isDecisiveFailure } from '../lib/lifecycle'
+import { percentileSorted } from '../lib/runHealth'
+import { verdictTag } from '../lib/runStatus'
+
+// A run reduced to what the chart needs. Both WorkflowRunRow and PrRunRow satisfy this, so either page
+// can drop the chart in over its own run list; the optional branch/PR fields enrich the hover card.
+export interface ActivityRun {
+ runId: number | null
+ conclusion: string | null
+ startedAt: string | null
+ durationSeconds: number | null
+ headBranch?: string | null
+ prNumber?: number | null
+}
+
+interface RunActivityChartProps {
+ runs: ActivityRun[]
+ title?: string
+ /** The runs list was capped server-side, so the chart shows the most recent runs, not the full window. */
+ truncated?: boolean
+ className?: string
+}
+
+// Dot/series color from the verdict mapping the run tables' StatusDot uses, so colors agree across the page.
+const DOT_COLOR: Record<string, string> = {
+ success: 'var(--success)',
+ danger: 'var(--danger)',
+ warning: 'var(--warning)',
+ muted: 'var(--muted)',
+}
+
+const LEGEND_LABEL: Record<string, string> = {
+ success: 'Passed',
+ danger: 'Failed',
+ muted: 'Cancelled / skipped',
+ warning: 'Other',
+}
+const LEGEND_ORDER = ['success', 'danger', 'muted', 'warning']
+
+const SCATTER_HEIGHT = 156
+const BAND_HEIGHT = 56
+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
+
+/** Round up to a "nice" number (1/2/5 × 10ⁿ) so axis ticks land on readable values. */
+function niceStep(rough: number): number {
+ if (rough <= 0) {
+ return 1
+ }
+ const pow = Math.pow(10, Math.floor(Math.log10(rough)))
+ const n = rough / pow
+ const step = n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10
+ return step * pow
+}
+
+/** Compact minutes label for the duration axis: "45m", "1h", "1h 30m". */
+function formatAxisMinutes(min: number): string {
+ const rounded = Math.round(min)
+ if (rounded < 60) {
+ return `${rounded}m`
+ }
+ const h = Math.floor(rounded / 60)
+ const m = rounded % 60
+ return m ? `${h}h ${m}m` : `${h}h`
+}
+
+interface Interval {
+ start: number
+ end: number
+ conclusion: string | null
+ completed: boolean
+}
+
+interface Point {
+ key: string
+ leftPct: number
+ topPx: number
+ color: string
+ tooltip: JSX.Element
+}
+
+/**
+ * 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
+ * "in-flight" band showing how many runs were executing at once (the red fill is the failing share, the
+ * peak is labeled). The scatter answers "are runs slow / failing?"; the band answers "how much parallel
+ * load?". Renders nothing below `MIN_POINTS` completed runs, so callers drop it in unconditionally.
+ */
+export function RunActivityChart({
+ runs,
+ title = 'Run activity',
+ truncated = false,
+ className,
+}: RunActivityChartProps): JSX.Element | null {
+ const now = dayjs().valueOf()
+ // Every run with a start contributes an interval to the band; a still-running run extends to now.
+ const intervals: Interval[] = runs
+ .filter((run): run is ActivityRun & { startedAt: string } => run.startedAt != null)
+ .map((run) => {
+ const start = dayjs(run.startedAt).valueOf()
+ const completed = run.durationSeconds != null && run.durationSeconds >= 0
+ return {
+ start,
+ end: completed ? start + (run.durationSeconds as number) * 1000 : now,
+ conclusion: run.conclusion,
+ completed,
+ }
+ })
+
+ // Only completed runs land on the scatter — a still-running run has no final duration to place on Y.
+ const plottable = runs.filter(
+ (run): run is ActivityRun & { startedAt: string; durationSeconds: number } =>
+ run.startedAt != null && run.durationSeconds != null && run.durationSeconds >= 0
+ )
+ if (plottable.length < MIN_POINTS) {
+ return null
+ }
+
+ const tMin = Math.min(...intervals.map((iv) => iv.start))
+ const tMax = Math.max(...intervals.map((iv) => iv.end))
+ const tSpan = Math.max(1, tMax - tMin)
+ const xPct = (ms: number): number => ((ms - tMin) / tSpan) * 100
+
+ const durationsMin = plottable.map((run) => run.durationSeconds / 60)
+ const maxMin = Math.max(...durationsMin)
+ // Tick interval is a "nice" number ~maxMin/4; the axis top is the smallest multiple of it that clears
+ // the slowest run, so ticks read as round values and there's little dead space above the points.
+ const step = niceStep(maxMin / Y_TICK_COUNT)
+ const niceMaxMin = Math.max(step, Math.ceil(maxMin / step) * step)
+ const yPx = (min: number): number => SCATTER_HEIGHT * (1 - min / niceMaxMin)
+
+ // Same median as the health summary's medianSeconds (one implementation), so chart and KPIs agree.
+ const sortedMin = [...durationsMin].sort((a, b) => a - b)
+ const medianMin = percentileSorted(sortedMin, 0.5) ?? 0
+
+ // 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 tag = verdictTag(run.conclusion)
+ presentTypeSet.add(tag.type)
+ return {
+ key: `${run.runId ?? 'run'}-${i}`,
+ leftPct: xPct(dayjs(run.startedAt).valueOf()),
+ topPx: Math.max(3, Math.min(SCATTER_HEIGHT - 3, yPx(run.durationSeconds / 60))),
+ color: DOT_COLOR[tag.type] ?? DOT_COLOR.muted,
+ tooltip: (
+ <div className="flex flex-col gap-0.5 text-xs">
+ <span className="font-semibold" style={{ color: DOT_COLOR[tag.type] ?? DOT_COLOR.muted }}>
+ {tag.label}
+ </span>
+ <span>Duration {humanFriendlyDuration(run.durationSeconds)}</span>
+ <span>Started {dayjs(run.startedAt).format('MMM D, HH:mm')}</span>
+ {run.headBranch && <span className="font-mono">{run.headBranch}</span>}
+ {run.prNumber != null && run.prNumber > 0 && <span>PR #{run.prNumber}</span>}
+ </div>
+ ),
+ }
+ })
+
+ const yTicks = Array.from({ length: Math.round(niceMaxMin / step) + 1 }, (_, i) => {
+ const min = step * i
+ return { min, topPx: yPx(min), label: formatAxisMinutes(min) }
+ })
+
+ // Span under ~36h reads as time-of-day; a wider window reads as calendar days.
+ const xFormat = tSpan / 3_600_000 <= 36 ? 'HH:mm' : 'MMM D'
+ const xTicks = Array.from({ length: X_TICK_COUNT }, (_, i) => ({
+ leftPct: (i / (X_TICK_COUNT - 1)) * 100,
+ label: dayjs(tMin + (tSpan * i) / (X_TICK_COUNT - 1)).format(xFormat),
+ }))
+
+ // 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 failDelta = isDecisiveFailure(iv.conclusion) ? 1 : 0
+ return [
+ { t: iv.start, dTotal: 1, dFailing: failDelta },
+ { t: iv.end, dTotal: -1, dFailing: -failDelta },
+ ]
+ })
+ bandEvents.sort((a, b) => a.t - b.t)
+ // Walk the events, holding each concurrency level until the next; coalesce events at the same instant.
+ const steps: { t: number; total: number; failing: number }[] = []
+ let runningTotal = 0
+ let runningFailing = 0
+ bandEvents.forEach((event, i) => {
+ runningTotal += event.dTotal
+ runningFailing += event.dFailing
+ if (i + 1 === bandEvents.length || bandEvents[i + 1].t !== event.t) {
+ steps.push({ t: event.t, total: runningTotal, failing: runningFailing })
+ }
+ })
+ const peak = Math.max(1, ...steps.map((s) => s.total))
+ 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)
+ // 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)}`
+ let level = 0
+ for (const s of steps) {
+ const x = bandX(s.t)
+ d += ` L${x},${bandY(level)} L${x},${bandY(s[key])}`
+ level = s[key]
+ }
+ return `${d} L1000,${bandY(level)} L1000,${BAND_HEIGHT} L0,${BAND_HEIGHT} Z`
+ }
+ const areaTotal = stepArea('total')
+ const areaFailing = stepArea('failing')
+ let line = `M0,${bandY(0)}`
+ let lineLevel = 0
+ for (const s of steps) {
+ const x = bandX(s.t)
+ line += ` L${x},${bandY(lineLevel)} L${x},${bandY(s.total)}`
+ lineLevel = s.total
+ }
+ line += ` L1000,${bandY(lineLevel)}`
+
+ const presentTypes = LEGEND_ORDER.filter((type) => presentTypeSet.has(type))
+
+ return (
+ <div className={cn('flex flex-col gap-2', className)}>
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
+ <h3 className="mb-0">{title}</h3>
+ <Tooltip
+ title={
+ truncated
+ ? `Over the most recent ${plottable.length} runs — the list is capped, so this isn't the full window.`
+ : undefined
+ }
+ >
+ <span className="text-xs whitespace-nowrap text-secondary tabular-nums">
+ {truncated ? 'recent ' : ''}
+ {plottable.length} runs · median {formatAxisMinutes(medianMin)} · peak {peak} in flight
+ </span>
+ </Tooltip>
+ </div>
+ <LemonCard hoverEffect={false} className="p-4">
+ <div className="flex gap-2">
+ {/* Y axis: duration tick labels in their own gutter, aligned to the scatter gridlines. */}
+ <div className="relative w-12 shrink-0" style={{ height: SCATTER_HEIGHT }}>
+ {yTicks.map((tick) => (
+ <span
+ key={tick.min}
+ className="absolute right-1 -translate-y-1/2 font-mono text-[9px] text-tertiary"
+ style={{ top: tick.topPx }}
+ >
+ {tick.label}
+ </span>
+ ))}
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="relative" style={{ height: SCATTER_HEIGHT }}>
+ {yTicks.map((tick) => (
+ <div
+ key={tick.min}
+ className="absolute inset-x-0 h-px bg-border"
+ style={{ top: tick.topPx }}
+ />
+ ))}
+ <div
+ className="absolute inset-x-0 border-t border-dashed border-secondary"
+ style={{ top: yPx(medianMin) }}
+ />
+ <span
+ className="absolute right-0 -translate-y-1/2 rounded bg-surface-primary px-1 text-[9px] text-secondary"
+ style={{ top: yPx(medianMin) }}
+ >
+ median {formatAxisMinutes(medianMin)}
+ </span>
+ {points.map((p) => (
+ <Tooltip key={p.key} title={p.tooltip} delayMs={60} placement="top">
+ <div
+ className="absolute h-[7px] w-[7px] -translate-x-1/2 -translate-y-1/2 cursor-default rounded-full transition-transform hover:scale-150"
+ style={{
+ left: `${p.leftPct}%`,
+ top: p.topPx,
+ background: p.color,
+ opacity: 0.6,
+ }}
+ />
+ </Tooltip>
+ ))}
+ </div>
+ {/* In-flight concurrency band, sharing the scatter's time axis. */}
+ <div className="relative mt-2" style={{ height: BAND_HEIGHT }}>
+ <span
+ className="absolute left-1 top-0 z-10 text-[10px] font-medium"
+ style={{ color: 'var(--brand-blue)' }}
+ >
+ In flight · peak {peak}
+ </span>
+ <svg
+ viewBox={`0 0 1000 ${BAND_HEIGHT}`}
+ preserveAspectRatio="none"
+ width="100%"
+ height={BAND_HEIGHT}
+ className="block"
+ role="img"
+ aria-label="Runs in flight over time"
+ >
+ <path d={areaTotal} fill="var(--brand-blue)" fillOpacity={0.14} />
+ <path d={areaFailing} fill="var(--danger)" fillOpacity={0.3} />
+ <path d={line} fill="none" stroke="var(--brand-blue)" strokeWidth={1.5} />
+ </svg>
+ </div>
+ {/* X axis: time ticks; first/last anchor to the edges so labels don't clip. */}
+ <div className="relative mt-1 h-4">
+ {xTicks.map((tick, i) => {
+ const isEdge = i === 0 || i === xTicks.length - 1
+ return (
+ <span
+ key={i}
+ className={cn(
+ 'absolute top-0 text-[9.5px] text-tertiary tabular-nums',
+ i === 0 && 'left-0',
+ i === xTicks.length - 1 && 'right-0',
+ !isEdge && '-translate-x-1/2'
+ )}
+ style={isEdge ? undefined : { left: `${tick.leftPct}%` }}
+ >
+ {tick.label}
+ </span>
+ )
+ })}
+ </div>
+ </div>
+ </div>
+ <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1">
+ {presentTypes.map((type) => (
+ <span key={type} className="flex items-center gap-1.5 text-xs text-secondary">
+ <span
+ className="h-1.5 w-1.5 shrink-0 rounded-full"
+ style={{ background: DOT_COLOR[type] }}
+ />
+ {LEGEND_LABEL[type]}
+ </span>
+ ))}
+ <span className="flex items-center gap-1.5 text-xs text-secondary">
+ <span
+ className="h-1.5 w-3 shrink-0 rounded-sm"
+ style={{ background: 'var(--brand-blue)', opacity: 0.5 }}
+ />
+ In flight
+ </span>
+ </div>
+ </LemonCard>
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/StatTile.tsx b/products/engineering_analytics/frontend/components/StatTile.tsx
new file mode 100644
index 000000000000..f2974aa041ea
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/StatTile.tsx
@@ -0,0 +1,26 @@
+import { ReactNode } from 'react'
+
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { cn } from 'lib/utils/css-classes'
+
+/** A plain headline metric tile: small label, big number, muted caption for the caveat/breakdown.
+ * For the clickable variant that doubles as a quick-filter toggle, use StatCard. */
+export function StatTile({
+ label,
+ value,
+ sub,
+ className,
+}: {
+ label: string
+ value: string
+ sub: ReactNode
+ className?: string
+}): JSX.Element {
+ return (
+ <LemonCard hoverEffect={false} className={cn('flex min-w-44 flex-1 flex-col gap-1 px-5 py-4', className)}>
+ <span className="text-xs text-secondary">{label}</span>
+ <span className="text-2xl font-semibold leading-none tabular-nums">{value}</span>
+ <span className="text-xs text-tertiary">{sub}</span>
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/WorkflowHealthHeader.tsx b/products/engineering_analytics/frontend/components/WorkflowHealthHeader.tsx
new file mode 100644
index 000000000000..164898e0b041
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/WorkflowHealthHeader.tsx
@@ -0,0 +1,131 @@
+import { LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { percentage } from 'lib/utils/numbers'
+
+import type { CostSummary, HealthSummary } from '../lib/runHealth'
+import { HealthKpi, STATE_META } from './healthVerdict'
+import { RangeBar } from './RangeBar'
+import { formatCost } from './runTables'
+
+function formatDuration(seconds: number | null): string {
+ return seconds == null ? '—' : humanFriendlyDuration(seconds, { maxUnits: 2 })
+}
+
+/** Duration spread as a compact range bar: the median is the fill, p95 the tick — "typically fast, with
+ * a long tail" reads in one glance, where two separate p50/p95 numbers didn't. */
+function DurationRange({ median, p95 }: { median: number | null; p95: number | null }): JSX.Element {
+ // Scale a touch past p95 so its tick sits inside the bar rather than hard against the end.
+ const scale = p95 ? p95 * 1.25 : 0
+ return (
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-tertiary">Duration p50 → p95</span>
+ <div className="flex items-center gap-2">
+ <RangeBar
+ className="w-20"
+ fraction={scale ? Math.min(1, (median ?? 0) / scale) : 0}
+ tickFraction={scale ? p95! / scale : null}
+ tooltip={`median ${formatDuration(median)} · p95 ${formatDuration(p95)}`}
+ />
+ <span className="text-xs whitespace-nowrap tabular-nums text-secondary">
+ {formatDuration(median)} → {formatDuration(p95)}
+ </span>
+ </div>
+ </div>
+ )
+}
+
+interface WorkflowHealthHeaderProps {
+ summary: HealthSummary
+ /** Cost rollup for the window; null (or all-null fields) hides the cost KPI when jobs aren't synced. */
+ cost: CostSummary | null
+ /** Runs list was capped server-side — run rollups are over the most recent runs, not the full window. */
+ truncated?: boolean
+ className?: string
+}
+
+/**
+ * The verdict strip above a workflow's runs: a colored state word + pass rate carry the answer (is this
+ * workflow ok?) before the eye reaches the chart, with the headline rollups the chart can't show —
+ * re-run rate (flakiness) and total CI cost — alongside. Adapted from the CI master-health design to a
+ * single workflow over the selected window.
+ */
+export function WorkflowHealthHeader({ summary, cost, truncated, className }: WorkflowHealthHeaderProps): JSX.Element {
+ const meta = STATE_META[summary.state]
+ const passRateLabel = summary.passRate == null ? '—' : percentage(summary.passRate, 0)
+ const hasCost = cost?.estimatedCostUsd != null
+
+ return (
+ <LemonCard
+ hoverEffect={false}
+ // Left accent in the state color (border-l-4 + the state's token class) — the strip reads as
+ // healthy/degraded/failing at the edge.
+ className={cn(
+ 'flex flex-wrap items-center gap-x-6 gap-y-4 border-l-4 px-5 py-4',
+ meta.borderClass,
+ className
+ )}
+ >
+ <div className="flex flex-col">
+ <div className="flex items-center gap-2">
+ <span className={cn('h-2.5 w-2.5 shrink-0 rounded-full', meta.dotClass)} />
+ <span className={cn('text-xl font-semibold leading-none', meta.wordClass)}>{meta.word}</span>
+ {summary.running > 0 && <LemonTag type={meta.tag}>{summary.running} running</LemonTag>}
+ </div>
+ <span className="mt-1.5 text-xs text-secondary">
+ {summary.state === 'unknown' ? (
+ 'No completed runs in this window'
+ ) : summary.state === 'failing' ? (
+ <>
+ Latest run failed
+ {summary.lastFailureAt && (
+ <>
+ {' · '}
+ <TZLabel time={summary.lastFailureAt} />
+ </>
+ )}
+ </>
+ ) : (
+ `${summary.passedRuns} of ${summary.completedRuns}${truncated ? ' recent' : ''} runs passed`
+ )}
+ </span>
+ </div>
+
+ <div className="flex flex-col border-l border-primary pl-6">
+ <span className="text-2xl font-semibold leading-7 tabular-nums">{passRateLabel}</span>
+ <span className="text-xs text-tertiary">
+ pass rate · {truncated ? 'recent ' : ''}
+ {summary.completedRuns} {truncated ? 'runs' : 'completed'}
+ </span>
+ </div>
+
+ <div className="flex-1" />
+
+ {/* Rollups the chart doesn't already show — median is the chart's dashed line, so it's omitted
+ here; p95 (tail latency), re-run rate, and total cost aren't anywhere on the scatter. */}
+ <div className="flex flex-wrap items-start gap-x-6 gap-y-3">
+ <HealthKpi
+ label="Runs"
+ value={
+ truncated ? (
+ <Tooltip
+ title={`Showing the most recent ${summary.totalRuns} runs. Failures and pass rate cover these; CI cost reflects the full window.`}
+ >
+ <span>{summary.totalRuns.toLocaleString()}+</span>
+ </Tooltip>
+ ) : (
+ summary.totalRuns.toLocaleString()
+ )
+ }
+ />
+ <HealthKpi label="Failures" value={summary.failures.toLocaleString()} danger={summary.failures > 0} />
+ <HealthKpi label="Re-runs" value={summary.reruns.toLocaleString()} danger={summary.reruns > 0} />
+ <DurationRange median={summary.medianSeconds} p95={summary.p95Seconds} />
+ {hasCost && <HealthKpi label="CI cost" value={`≈ ${formatCost(cost?.estimatedCostUsd ?? null)}`} />}
+ </div>
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
index e8bc6453a996..8d7ce8eed40b 100644
--- a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
+++ b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
@@ -27,6 +27,7 @@ import {
} from '../scenes/engineeringAnalyticsLogic'
import { BillableBadge } from './BillableBadge'
import { FailureSparkline } from './FailureSparkline'
+import { CI_GRID } from './runTables'
// Reserved bar slots for push-bucketed sparklines (PR view): a small floor keeps a single push from
// stretching fat, while staying low enough that 2–3 pushes read as clearly separate, visible bars on
@@ -91,22 +92,24 @@ function StatusTag({ failed, conclusion }: { failed: boolean | null; conclusion:
}
function TrendArrow({ direction }: { direction: WorkflowTrendDirection }): JSX.Element {
+ // The column reads "Health", so the arrow tracks health, not failures: rising failures = health
+ // declining = red arrow down; falling failures = health improving = green arrow up.
if (direction === 'up') {
return (
- <Tooltip title="Failures rising">
- <IconTrending className="text-danger shrink-0" />
+ <Tooltip title="Health declining — failures rising">
+ <IconTrendingDown className="text-danger shrink-0" />
</Tooltip>
)
}
if (direction === 'down') {
return (
- <Tooltip title="Failures falling">
- <IconTrendingDown className="text-success shrink-0" />
+ <Tooltip title="Health improving — failures falling">
+ <IconTrending className="text-success shrink-0" />
</Tooltip>
)
}
return (
- <Tooltip title="No change in failures">
+ <Tooltip title="Health steady — no change in failures">
<IconTrendingFlat className="text-muted shrink-0" />
</Tooltip>
)
@@ -163,6 +166,7 @@ export function WorkflowHealthTable({
{
title: 'Status',
key: 'status',
+ width: CI_GRID.status,
// Failing first when sorted: failing (2) > unknown (1) > passing (0).
sorter: (a, b) => statusRank(a.latestRunFailed) - statusRank(b.latestRunFailed),
render: (_, row) => <StatusTag failed={row.latestRunFailed} conclusion={row.latestRunConclusion} />,
@@ -170,6 +174,7 @@ export function WorkflowHealthTable({
{
title: 'Runs',
key: 'runCount',
+ width: CI_GRID.runs,
align: 'right',
sorter: (a, b) => a.runCount - b.runCount,
render: (_, row) => <span className="text-xs tabular-nums">{humanFriendlyNumber(row.runCount)}</span>,
@@ -177,6 +182,7 @@ export function WorkflowHealthTable({
{
title: 'Success rate',
key: 'successRate',
+ width: CI_GRID.successRate,
align: 'right',
sorter: (a, b) => (a.successRate ?? -1) - (b.successRate ?? -1),
render: (_, row) => (
@@ -190,6 +196,7 @@ export function WorkflowHealthTable({
{
title: 'Cost',
key: 'cost',
+ width: CI_GRID.cost,
align: 'right',
sorter: (a, b) => (a.estimatedCostUsd ?? -1) - (b.estimatedCostUsd ?? -1),
render: (_, row) => (
@@ -202,7 +209,7 @@ export function WorkflowHealthTable({
title: 'Health',
key: 'trend',
// Pinned so the layout doesn't shift when sorting reorders rows with and without history.
- width: 272,
+ width: CI_GRID.health,
render: function RenderTrend(_, row) {
if (row.buckets.length === 0) {
return <span className="text-xs text-secondary">—</span>
@@ -227,6 +234,7 @@ export function WorkflowHealthTable({
{
title: 'p50',
key: 'p50Seconds',
+ width: CI_GRID.p50,
align: 'right',
sorter: (a, b) => (a.p50Seconds ?? -1) - (b.p50Seconds ?? -1),
render: (_, row) => (
@@ -236,6 +244,7 @@ export function WorkflowHealthTable({
{
title: 'p95',
key: 'p95Seconds',
+ width: CI_GRID.p95,
align: 'right',
sorter: (a, b) => (a.p95Seconds ?? -1) - (b.p95Seconds ?? -1),
render: (_, row) => (
@@ -245,6 +254,7 @@ export function WorkflowHealthTable({
{
title: 'Last failure',
key: 'lastFailureAt',
+ width: CI_GRID.lastFailure,
align: 'right',
render: (_, row) =>
row.lastFailureAt ? (
@@ -259,6 +269,9 @@ export function WorkflowHealthTable({
return (
<LemonTable
+ // Fixed layout honors the CI_GRID widths exactly (auto layout lets empty spacer cells collapse),
+ // so the run/job tables nested inside line their columns up to the pixel. Cascades to them too.
+ className="[&_table]:table-fixed"
data-attr={dataAttr}
size="small"
columns={columns}
diff --git a/products/engineering_analytics/frontend/components/WorkflowsHealthHeader.tsx b/products/engineering_analytics/frontend/components/WorkflowsHealthHeader.tsx
new file mode 100644
index 000000000000..8e010155769b
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/WorkflowsHealthHeader.tsx
@@ -0,0 +1,94 @@
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { cn } from 'lib/utils/css-classes'
+import { percentage } from 'lib/utils/numbers'
+
+import type { FleetSummary } from '../lib/runHealth'
+import { HealthKpi, STATE_META } from './healthVerdict'
+import { formatCost } from './runTables'
+
+interface WorkflowsHealthHeaderProps {
+ summary: FleetSummary
+ /** Workflow list was capped server-side — totals cover the top N by run count, not the whole fleet. */
+ truncated?: boolean
+ className?: string
+}
+
+/**
+ * Fleet verdict strip above the all-workflows table: the same colored state word + a "% green" headline
+ * as the single-workflow header, but rolled up across every workflow in the window — how many are red
+ * right now, total runs, and total CI spend. The duration scatter has no place here (no single run
+ * list), so this strip is the at-a-glance answer for the whole page.
+ */
+export function WorkflowsHealthHeader({ summary, truncated, className }: WorkflowsHealthHeaderProps): JSX.Element {
+ const meta = STATE_META[summary.state]
+ const greenNow = summary.settledWorkflows - summary.failingNow
+ const greenRateLabel = summary.settledWorkflows > 0 ? percentage(greenNow / summary.settledWorkflows, 0) : '—'
+ const hasCost = summary.estimatedCostUsd != null
+
+ return (
+ <LemonCard
+ hoverEffect={false}
+ // Left accent in the state color (border-l-4 + the state's token class).
+ className={cn(
+ 'flex flex-wrap items-center gap-x-6 gap-y-4 border-l-4 px-5 py-4',
+ meta.borderClass,
+ className
+ )}
+ >
+ <div className="flex flex-col">
+ <div className="flex items-center gap-2">
+ <span className={cn('h-2.5 w-2.5 shrink-0 rounded-full', meta.dotClass)} />
+ <span className={cn('text-xl font-semibold leading-none', meta.wordClass)}>{meta.word}</span>
+ </div>
+ <span className="mt-1.5 text-xs text-secondary">
+ {summary.workflowCount === 0
+ ? 'No workflow runs in this window'
+ : summary.settledWorkflows === 0
+ ? `${summary.workflowCount} workflows · none settled yet`
+ : summary.failingNow > 0
+ ? `${summary.failingNow} of ${summary.workflowCount} workflows failing right now`
+ : summary.flakyNow > 0
+ ? `${summary.flakyNow} flaky · below 90% pass rate`
+ : summary.settledWorkflows < summary.workflowCount
+ ? `${summary.settledWorkflows} of ${summary.workflowCount} settled · all green`
+ : truncated
+ ? `Top ${summary.workflowCount} by runs · all green`
+ : `All ${summary.workflowCount} workflows healthy`}
+ </span>
+ </div>
+
+ <div className="flex flex-col border-l border-primary pl-6">
+ <span className="text-2xl font-semibold leading-7 tabular-nums">{greenRateLabel}</span>
+ <span className="text-xs text-tertiary">green now · {summary.settledWorkflows} settled</span>
+ </div>
+
+ <div className="flex-1" />
+
+ <div className="flex flex-wrap items-start gap-x-6 gap-y-3">
+ <HealthKpi
+ label="Workflows"
+ value={
+ truncated ? (
+ <Tooltip
+ title={`Showing the top ${summary.workflowCount} workflows by run count. Total runs, CI cost, and the verdict cover these — lower-volume workflows beyond the cap aren't included.`}
+ >
+ <span>{summary.workflowCount.toLocaleString()}+</span>
+ </Tooltip>
+ ) : (
+ summary.workflowCount.toLocaleString()
+ )
+ }
+ />
+ <HealthKpi
+ label="Failing now"
+ value={summary.failingNow.toLocaleString()}
+ danger={summary.failingNow > 0}
+ />
+ <HealthKpi label="Total runs" value={summary.totalRuns.toLocaleString()} />
+ {hasCost && <HealthKpi label="CI cost" value={`≈ ${formatCost(summary.estimatedCostUsd)}`} />}
+ </div>
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/healthVerdict.tsx b/products/engineering_analytics/frontend/components/healthVerdict.tsx
new file mode 100644
index 000000000000..a52b9ee34c19
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/healthVerdict.tsx
@@ -0,0 +1,64 @@
+import { ReactNode } from 'react'
+
+import { LemonTagType } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { WorkflowState } from '../lib/runHealth'
+
+// Verdict word + tag type + the matching accent classes per state, matching the run tables' StatusDot
+// palette: green healthy, amber degraded, red failing. Shared by the single-workflow and all-workflows
+// (fleet) headers so both read identically. Classes are literal token utilities (not built from a string)
+// so Tailwind keeps them and the theme tracks automatically — border-l for the strip edge, bg for the
+// status dot, text for the state word.
+export const STATE_META: Record<
+ WorkflowState,
+ { word: string; tag: LemonTagType; borderClass: string; dotClass: string; wordClass: string }
+> = {
+ healthy: {
+ word: 'Healthy',
+ tag: 'success',
+ borderClass: 'border-l-success',
+ dotClass: 'bg-success',
+ wordClass: 'text-success',
+ },
+ degraded: {
+ word: 'Degraded',
+ tag: 'warning',
+ borderClass: 'border-l-warning',
+ dotClass: 'bg-warning',
+ wordClass: 'text-warning',
+ },
+ failing: {
+ word: 'Failing',
+ tag: 'danger',
+ borderClass: 'border-l-danger',
+ dotClass: 'bg-danger',
+ wordClass: 'text-danger',
+ },
+ unknown: {
+ word: 'No data',
+ tag: 'muted',
+ borderClass: 'border-l-muted',
+ dotClass: 'bg-muted',
+ wordClass: 'text-muted',
+ },
+}
+
+/** One headline rollup in a verdict strip: small label over a big tabular number. */
+export function HealthKpi({
+ label,
+ value,
+ danger,
+}: {
+ label: string
+ value: ReactNode
+ danger?: boolean
+}): JSX.Element {
+ return (
+ <div className="flex flex-col">
+ <span className="text-xs text-tertiary">{label}</span>
+ <span className={cn('text-lg font-semibold leading-6 tabular-nums', danger && 'text-danger')}>{value}</span>
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/runTables.test.tsx b/products/engineering_analytics/frontend/components/runTables.test.tsx
new file mode 100644
index 000000000000..4a50877c777e
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/runTables.test.tsx
@@ -0,0 +1,16 @@
+import { formatCost } from './runTables'
+
+describe('formatCost', () => {
+ it.each([
+ [null, '—'],
+ [0, '$0.00'],
+ // Sub-cent positives must not read as free — a short self-hosted job at the reference rate.
+ [0.004, '<$0.01'],
+ [0.009, '<$0.01'],
+ [0.01, '$0.01'],
+ [0.38, '$0.38'],
+ [12.5, '$12.50'],
+ ])('formats %p as %p', (usd, expected) => {
+ expect(formatCost(usd)).toBe(expected)
+ })
+})
diff --git a/products/engineering_analytics/frontend/components/runTables.tsx b/products/engineering_analytics/frontend/components/runTables.tsx
index 6080a22e90cb..879a78cf931f 100644
--- a/products/engineering_analytics/frontend/components/runTables.tsx
+++ b/products/engineering_analytics/frontend/components/runTables.tsx
@@ -5,7 +5,7 @@
import { ReactNode } from 'react'
-import { LemonTable, LemonTableColumns, LemonTag, LemonTagType } from '@posthog/lemon-ui'
+import { LemonTable, LemonTableColumns, LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
@@ -66,6 +66,7 @@ export function GanttBar({
conclusion,
axisStart,
axisEnd,
+ showDuration = true,
}: {
startedAt: string | null
finishedAt: string | null
@@ -73,6 +74,8 @@ export function GanttBar({
conclusion: string | null
axisStart: number | null
axisEnd: number | null
+ // Hidden in the aligned grid, where duration has its own column under p50.
+ showDuration?: boolean
}): JSX.Element {
if (!startedAt || axisStart == null || axisEnd == null) {
return <span className="text-xs text-secondary">—</span>
@@ -91,21 +94,50 @@ export function GanttBar({
style={{ left: `${left}%`, width: `${width}%` }}
/>
</div>
- <span className="w-14 shrink-0 text-right text-xs whitespace-nowrap tabular-nums text-secondary">
- {durationSeconds == null ? '—' : humanFriendlyDuration(durationSeconds)}
- </span>
+ {showDuration && (
+ <span className="w-14 shrink-0 text-right text-xs whitespace-nowrap tabular-nums text-secondary">
+ {durationSeconds == null ? '—' : humanFriendlyDuration(durationSeconds)}
+ </span>
+ )}
</div>
)
}
export function formatCost(usd: number | null): string {
- return usd == null ? '—' : `$${usd.toFixed(2)}`
+ if (usd == null) {
+ return '—'
+ }
+ // A short self-hosted job costs a fraction of a cent at the reference rate, so rounding to 2 dp would
+ // print "$0.00" and make a real cost read as free — and a run's jobs then look like they don't sum to
+ // the run total. Show sub-cent positives as "<$0.01"; only a measured zero is "$0.00".
+ if (usd > 0 && usd < 0.01) {
+ return '<$0.01'
+ }
+ return `$${usd.toFixed(2)}`
}
export function formatMinutes(minutes: number | null): string {
return minutes == null ? '—' : `${Math.round(minutes).toLocaleString()} min`
}
+// THE canonical CI grid. The workflow (L1) table defines these column slots; the run (L2) and job (L3)
+// tables reuse the exact same widths so every column lines up vertically as you drill in — cost under
+// Cost, verdict under Success rate, duration under p50/p95, started under Last failure, timeline under
+// Health. Each level fills the slots it has an analog for and leaves the rest blank. Single source of
+// truth shared by WorkflowHealthTable, RunsTable and RunJobsTable; change a width once, all levels move.
+// Widths fit the widest header in each slot (fixed layout clips overflow): "SUCCESS RATE" + sort caret,
+// "DURATION" under p50, etc.
+export const CI_GRID = {
+ status: 116, // L1 Passing/Failing tag · L3 runner tier
+ runs: 80, // L1 run count · blank below
+ successRate: 140, // L1 "Success rate" · L2/L3 verdict/status dot
+ cost: 132, // shared "min · $" billable badge
+ health: 220, // L1 failure sparkline · L3 job timeline
+ p50: 108, // L1 p50 · L2/L3 "Duration"
+ p95: 92, // L1 p95 · blank below
+ lastFailure: 124, // L1 last-failure time · L2/L3 started
+} as const
+
// Muted grey for GitHub-hosted (free), blue for billable self-hosted — kept off the green/red verdict
// palette so a runner badge never reads as a pass/fail status.
const RUNNER_BADGE: Record<string, { label: string; type: LemonTagType }> = {
@@ -127,12 +159,34 @@ export function RunnerBadge({ provider, label }: { provider: string; label: stri
)
}
-/** GitHub-hosted runners are free (open source); self-hosted shows the modeled estimate. */
+/** GitHub-hosted runners are free (open source); self-hosted shows the modeled estimate — same
+ * "min · $" badge as the run/workflow rows so cost reads identically at every depth. */
function jobCostCell(job: WorkflowJobApi): JSX.Element {
if (job.runner_provider === 'github_hosted') {
return <span className="text-xs text-secondary">Free</span>
}
- return <span className="text-xs tabular-nums">{formatCost(job.estimated_cost_usd)}</span>
+ const minutes = job.duration_seconds != null ? job.duration_seconds / 60 : null
+ return <BillableBadge minutes={minutes} costUsd={job.estimated_cost_usd} />
+}
+
+function formatSeconds(seconds: number | null): string {
+ return seconds == null ? '—' : humanFriendlyDuration(seconds)
+}
+
+/** Runner in the tight aligned grid: just the tier tag, colored by provider, full name on hover —
+ * the verbose "Self-hosted 16-core" badge won't fit the canonical Status slot. */
+function compactRunnerCell(job: WorkflowJobApi): JSX.Element {
+ const badge = RUNNER_BADGE[job.runner_provider] ?? RUNNER_BADGE.unknown
+ if (job.runner_provider === 'unknown' && !job.runner_label) {
+ return <span className="text-xs text-secondary">—</span>
+ }
+ return (
+ <Tooltip title={`${badge.label}${job.runner_label ? ` · ${job.runner_label}` : ''}`}>
+ <LemonTag type={badge.type} size="small">
+ {job.runner_label || badge.label}
+ </LemonTag>
+ </Tooltip>
+ )
}
/**
@@ -145,11 +199,14 @@ export function RunJobsTable({
jobs,
loading,
embedded = false,
+ aligned = false,
}: {
// null/undefined = not loaded (kea coerces an undefined loader default to null); [] = source unsynced.
jobs: WorkflowJobApi[] | null | undefined
loading: boolean
embedded?: boolean
+ // Render onto the canonical CI_GRID so columns line up under the run/workflow tables (PR detail).
+ aligned?: boolean
}): JSX.Element {
if (jobs == null) {
return <div className="px-3 py-2 text-xs text-secondary">{loading ? 'Loading jobs…' : 'No job data yet.'}</div>
@@ -165,53 +222,124 @@ export function RunJobsTable({
const { axisStart, axisEnd } = timeAxis(
jobs.map((job) => ({ startedAt: job.started_at, finishedAt: job.completed_at }))
)
- const jobColumns: LemonTableColumns<WorkflowJobApi> = [
- { title: 'Job', key: 'name', render: (_, job) => <span className="font-medium">{job.name}</span> },
- {
- title: 'Status',
- key: 'status',
- width: 110,
- render: (_, job) => <StatusDot conclusion={job.conclusion} />,
- },
- {
- title: 'Runner',
- key: 'runner',
- width: 180,
- render: (_, job) => <RunnerBadge provider={job.runner_provider} label={job.runner_label} />,
- },
- {
- title: 'Timeline',
- key: 'timeline',
- width: 200,
- render: (_, job) => (
- <GanttBar
- startedAt={job.started_at}
- finishedAt={job.completed_at}
- durationSeconds={job.duration_seconds}
- conclusion={job.conclusion}
- axisStart={axisStart}
- axisEnd={axisEnd}
- />
- ),
- },
- {
- title: 'Cost',
- key: 'cost',
- width: 90,
- align: 'right',
- render: (_, job) => jobCostCell(job),
- },
- ]
- return (
+ const nameColumn = {
+ title: 'Job',
+ key: 'name',
+ sorter: (a: WorkflowJobApi, b: WorkflowJobApi) => a.name.localeCompare(b.name),
+ render: (_: unknown, job: WorkflowJobApi) => <span className="font-medium">{job.name}</span>,
+ }
+ const timelineCell = (job: WorkflowJobApi): JSX.Element => (
+ <GanttBar
+ startedAt={job.started_at}
+ finishedAt={job.completed_at}
+ durationSeconds={job.duration_seconds}
+ conclusion={job.conclusion}
+ axisStart={axisStart}
+ axisEnd={axisEnd}
+ showDuration={!aligned}
+ />
+ )
+ // Aligned: job data drops into the canonical L1 slots (Runner→Status, dot→Success rate, timeline→
+ // Health, duration→p50, started→Last failure). Natural: the standalone run page's own layout.
+ const jobColumns: LemonTableColumns<WorkflowJobApi> = aligned
+ ? [
+ nameColumn,
+ { title: 'Runner', key: 'status', width: CI_GRID.status, render: (_, job) => compactRunnerCell(job) },
+ { title: '', key: 'runs', width: CI_GRID.runs, render: () => null },
+ {
+ title: 'Status',
+ key: 'successRate',
+ width: CI_GRID.successRate,
+ render: (_, job) => <StatusDot conclusion={job.conclusion} />,
+ },
+ {
+ title: 'Cost',
+ key: 'cost',
+ width: CI_GRID.cost,
+ align: 'right',
+ render: (_, job) => jobCostCell(job),
+ },
+ {
+ title: 'Timeline',
+ key: 'health',
+ width: CI_GRID.health,
+ sorter: (a, b) => (a.started_at ?? '').localeCompare(b.started_at ?? ''),
+ render: (_, job) => timelineCell(job),
+ },
+ {
+ title: 'Duration',
+ key: 'p50',
+ width: CI_GRID.p50,
+ align: 'right',
+ render: (_, job) => (
+ <span className="text-xs tabular-nums">{formatSeconds(job.duration_seconds)}</span>
+ ),
+ },
+ { title: '', key: 'p95', width: CI_GRID.p95, render: () => null },
+ {
+ title: 'Started',
+ key: 'lastFailure',
+ width: CI_GRID.lastFailure,
+ align: 'right',
+ render: (_, job) =>
+ job.started_at ? (
+ <span className="text-xs whitespace-nowrap">
+ <TZLabel time={job.started_at} />
+ </span>
+ ) : (
+ <span className="text-xs text-secondary">—</span>
+ ),
+ },
+ ]
+ : [
+ nameColumn,
+ {
+ title: 'Status',
+ key: 'status',
+ width: 110,
+ sorter: (a, b) => (a.conclusion ?? '').localeCompare(b.conclusion ?? ''),
+ render: (_, job) => <StatusDot conclusion={job.conclusion} />,
+ },
+ {
+ title: 'Runner',
+ key: 'runner',
+ width: 180,
+ sorter: (a, b) => a.runner_label.localeCompare(b.runner_label),
+ render: (_, job) => <RunnerBadge provider={job.runner_provider} label={job.runner_label} />,
+ },
+ {
+ title: 'Timeline',
+ key: 'timeline',
+ width: 200,
+ sorter: (a, b) => (a.started_at ?? '').localeCompare(b.started_at ?? ''),
+ render: (_, job) => timelineCell(job),
+ },
+ {
+ title: 'Cost',
+ key: 'cost',
+ width: 110,
+ align: 'right',
+ sorter: (a, b) => (a.estimated_cost_usd ?? -1) - (b.estimated_cost_usd ?? -1),
+ render: (_, job) => jobCostCell(job),
+ },
+ ]
+ const table = (
<LemonTable
embedded={embedded}
size="small"
columns={jobColumns}
dataSource={jobs}
rowKey={(job) => job.id}
+ useURLForSorting={false}
+ // Sort by start (the timeline column, keyed 'health' when aligned) so bars read top-to-bottom.
+ defaultSorting={{ columnKey: aligned ? 'health' : 'timeline', order: 1 }}
nouns={['job', 'jobs']}
/>
)
+ // No indent: the job table has no expand-toggle column of its own, so its name column absorbs that
+ // width and the rows read flush-left under the parent run instead of behind an empty indent (which
+ // reads as a stray gap in front of the jobs).
+ return table
}
// The minimum a run row needs to drive the shared columns + job expansion. Callers add their own lead
@@ -238,6 +366,8 @@ export interface RunsTableProps<T extends RunRowBase> {
/** Per-run cost keyed by jobCacheKey; pass with showCost to add the trailing Cost column. */
runCostByKey?: Record<string, { minutes: number | null; cost: number | null }>
showCost?: boolean
+ /** Render onto the canonical CI_GRID so columns line up under the workflow table (PR detail). */
+ aligned?: boolean
defaultSorting?: { columnKey: string; order: 1 | -1 }
emptyState?: ReactNode
dataAttr?: string
@@ -259,63 +389,94 @@ export function RunsTable<T extends RunRowBase>({
setExpanded,
runCostByKey,
showCost = false,
+ aligned = false,
defaultSorting = { columnKey: 'started', order: 1 },
emptyState = 'No CI runs match.',
dataAttr = 'engineering-analytics-runs-table',
}: RunsTableProps<T>): JSX.Element {
- const columns: LemonTableColumns<T> = [
- ...leadColumns,
- {
- title: 'Verdict',
- key: 'verdict',
- width: 110,
- sorter: (a, b) => verdictTag(a.conclusion).label.localeCompare(verdictTag(b.conclusion).label),
- render: (_, run) => <StatusDot conclusion={run.conclusion} />,
- },
- {
- title: 'Duration',
- key: 'duration',
- width: 90,
- align: 'right',
- sorter: (a, b) => (a.durationSeconds ?? -1) - (b.durationSeconds ?? -1),
- render: (_, run) => (
- <span className="text-xs tabular-nums whitespace-nowrap">
- {run.durationSeconds == null ? '—' : humanFriendlyDuration(run.durationSeconds)}
- </span>
- ),
- },
- {
- title: 'Started',
- key: 'started',
- width: 130,
- align: 'right',
- sorter: (a, b) => (a.startedAt ?? '').localeCompare(b.startedAt ?? ''),
- render: (_, run) =>
- run.startedAt ? (
- <span className="text-xs whitespace-nowrap">
- <TZLabel time={run.startedAt} />
- </span>
- ) : (
- <span className="text-xs text-secondary">—</span>
- ),
- },
- // Per-run cost, trailing + right-aligned so it lines up with the job table below it — cost reads in
- // the same spot at every depth instead of jumping across the row as you drill in.
- ...((showCost
- ? [
- {
- title: 'Cost',
- key: 'cost',
- width: 110,
- align: 'right',
- render: (_: unknown, run: T) => {
- const cost = run.runId != null ? runCostByKey?.[jobCacheKey(run.runId, run.runAttempt)] : null
- return <BillableBadge minutes={cost?.minutes ?? null} costUsd={cost?.cost ?? null} />
- },
- },
- ]
- : []) as LemonTableColumns<T>),
- ]
+ const verdictColumn = {
+ title: 'Verdict',
+ key: 'verdict',
+ sorter: (a: T, b: T) => verdictTag(a.conclusion).label.localeCompare(verdictTag(b.conclusion).label),
+ render: (_: unknown, run: T) => <StatusDot conclusion={run.conclusion} />,
+ }
+ const durationCell = (run: T): JSX.Element => (
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ {run.durationSeconds == null ? '—' : humanFriendlyDuration(run.durationSeconds)}
+ </span>
+ )
+ const startedCell = (run: T): JSX.Element =>
+ run.startedAt ? (
+ <span className="text-xs whitespace-nowrap">
+ <TZLabel time={run.startedAt} />
+ </span>
+ ) : (
+ <span className="text-xs text-secondary">—</span>
+ )
+ const costCell = (run: T): JSX.Element => {
+ const cost = run.runId != null ? runCostByKey?.[jobCacheKey(run.runId, run.runAttempt)] : null
+ return <BillableBadge minutes={cost?.minutes ?? null} costUsd={cost?.cost ?? null} />
+ }
+ // Aligned: run data drops into the canonical L1 slots (verdict→Success rate, cost→Cost, duration→p50,
+ // started→Last failure), with blank spacers under the slots a run has no analog for (Status, Runs,
+ // Health, p95). Natural: the standalone workflow-runs page's own compact layout.
+ const columns: LemonTableColumns<T> = aligned
+ ? [
+ ...leadColumns,
+ { title: '', key: 'slotStatus', width: CI_GRID.status, render: () => null },
+ { title: '', key: 'slotRuns', width: CI_GRID.runs, render: () => null },
+ { ...verdictColumn, width: CI_GRID.successRate },
+ { title: 'Cost', key: 'cost', width: CI_GRID.cost, align: 'right', render: (_, run) => costCell(run) },
+ { title: '', key: 'slotHealth', width: CI_GRID.health, render: () => null },
+ {
+ title: 'Duration',
+ key: 'duration',
+ width: CI_GRID.p50,
+ align: 'right',
+ sorter: (a, b) => (a.durationSeconds ?? -1) - (b.durationSeconds ?? -1),
+ render: (_, run) => durationCell(run),
+ },
+ { title: '', key: 'slotP95', width: CI_GRID.p95, render: () => null },
+ {
+ title: 'Started',
+ key: 'started',
+ width: CI_GRID.lastFailure,
+ align: 'right',
+ sorter: (a, b) => (a.startedAt ?? '').localeCompare(b.startedAt ?? ''),
+ render: (_, run) => startedCell(run),
+ },
+ ]
+ : [
+ ...leadColumns,
+ { ...verdictColumn, width: 110 },
+ {
+ title: 'Duration',
+ key: 'duration',
+ width: 90,
+ align: 'right',
+ sorter: (a, b) => (a.durationSeconds ?? -1) - (b.durationSeconds ?? -1),
+ render: (_, run) => durationCell(run),
+ },
+ {
+ title: 'Started',
+ key: 'started',
+ width: 130,
+ align: 'right',
+ sorter: (a, b) => (a.startedAt ?? '').localeCompare(b.startedAt ?? ''),
+ render: (_, run) => startedCell(run),
+ },
+ ...((showCost
+ ? [
+ {
+ title: 'Cost',
+ key: 'cost',
+ width: 110,
+ align: 'right',
+ render: (_: unknown, run: T) => costCell(run),
+ },
+ ]
+ : []) as LemonTableColumns<T>),
+ ]
return (
<LemonTable
@@ -349,6 +510,7 @@ export function RunsTable<T extends RunRowBase>({
jobs={run.runId != null ? runJobs[jobCacheKey(run.runId, run.runAttempt)] : undefined}
loading={runJobsLoading}
embedded
+ aligned={aligned}
/>
),
}}
diff --git a/products/engineering_analytics/frontend/lib/lifecycle.ts b/products/engineering_analytics/frontend/lib/lifecycle.ts
index 30169e70faf9..e31193569999 100644
--- a/products/engineering_analytics/frontend/lib/lifecycle.ts
+++ b/products/engineering_analytics/frontend/lib/lifecycle.ts
@@ -43,6 +43,11 @@ export function isPassingConclusion(conclusion: string): boolean {
return PASSING_CONCLUSIONS.has(conclusion)
}
+/** A decisive failure — the verdict that turns a run red. Cancelled/skipped/neutral are not failures. */
+export function isDecisiveFailure(conclusion: string | null): boolean {
+ return conclusion === 'failure' || conclusion === 'timed_out'
+}
+
/**
* ci_finished detail is "workflow name: conclusion" (the name itself may contain ": "), assembled
* by backend/logic/queries/pr_lifecycle.py from structured fields the API then flattens.
diff --git a/products/engineering_analytics/frontend/lib/runHealth.test.ts b/products/engineering_analytics/frontend/lib/runHealth.test.ts
new file mode 100644
index 000000000000..f9eb38482af6
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/runHealth.test.ts
@@ -0,0 +1,99 @@
+import { computeFleetSummary, computeHealthSummary } from './runHealth'
+
+const at = (hour: number): string => `2026-06-24T${String(hour).padStart(2, '0')}:00:00Z`
+
+describe('runHealth', () => {
+ it.each([
+ ['no completed runs → unknown', [{ conclusion: null, durationSeconds: null, startedAt: at(9) }], 'unknown'],
+ [
+ 'latest settled run failed → failing',
+ [
+ { conclusion: 'success', durationSeconds: 600, startedAt: at(9) },
+ { conclusion: 'failure', durationSeconds: 600, startedAt: at(10) },
+ ],
+ 'failing',
+ ],
+ [
+ 'below pass-rate floor but latest passed → degraded',
+ [
+ { conclusion: 'failure', durationSeconds: 600, startedAt: at(9) },
+ { conclusion: 'failure', durationSeconds: 600, startedAt: at(10) },
+ { conclusion: 'success', durationSeconds: 600, startedAt: at(11) },
+ ],
+ 'degraded',
+ ],
+ [
+ 'cancelled is not a failure → healthy',
+ [
+ { conclusion: 'cancelled', durationSeconds: 600, startedAt: at(9) },
+ { conclusion: 'success', durationSeconds: 600, startedAt: at(10) },
+ ],
+ 'healthy',
+ ],
+ ])('classifies state: %s', (_name, runs, expected) => {
+ expect(computeHealthSummary(runs).state).toBe(expected)
+ })
+
+ it('counts only conclusion=success as a pass, matching the backend success_rate', () => {
+ // Skipped/neutral are completed but not successes — the header must not inflate pass rate past
+ // what the Workflows table shows for the same window.
+ const summary = computeHealthSummary([
+ { conclusion: 'success', durationSeconds: 600, startedAt: at(9) },
+ { conclusion: 'skipped', durationSeconds: 600, startedAt: at(10) },
+ ])
+ expect(summary.completedRuns).toBe(2)
+ expect(summary.passedRuns).toBe(1)
+ expect(summary.passRate).toBe(0.5)
+ expect(summary.failures).toBe(0)
+ expect(summary.state).toBe('healthy')
+ })
+
+ it('excludes still-running runs from rates and durations, and counts re-runs', () => {
+ const summary = computeHealthSummary([
+ { conclusion: 'success', durationSeconds: 120, startedAt: at(9), runAttempt: 1 },
+ { conclusion: 'failure', durationSeconds: 240, startedAt: at(10), runAttempt: 2 },
+ { conclusion: null, durationSeconds: null, startedAt: at(11), runAttempt: 1 },
+ ])
+ expect(summary.completedRuns).toBe(2)
+ expect(summary.running).toBe(1)
+ expect(summary.passRate).toBe(0.5)
+ expect(summary.failures).toBe(1)
+ expect(summary.reruns).toBe(1)
+ })
+
+ const fleetRow = (
+ latestRunFailed: boolean | null,
+ successRate: number | null = 1,
+ lastFailureAt: string | null = null
+ ): {
+ runCount: number
+ successRate: number | null
+ latestRunFailed: boolean | null
+ lastFailureAt: string | null
+ } => ({ runCount: 5, successRate, latestRunFailed, lastFailureAt })
+
+ it.each([
+ ['no workflows → unknown', [], 'unknown'],
+ ['workflows present but none settled → unknown', [fleetRow(null), fleetRow(null)], 'unknown'],
+ ['every settled workflow failing → failing', [fleetRow(true), fleetRow(true)], 'failing'],
+ ['some failing, some green → degraded', [fleetRow(true), fleetRow(false)], 'degraded'],
+ ['green but flaky (low success + a real failure) → degraded', [fleetRow(false, 0.7, at(9))], 'degraded'],
+ // Low success driven by skips/cancels, never a decisive failure → healthy, not flaky (matches the
+ // single-workflow verdict).
+ ['green, low success, no failures → healthy', [fleetRow(false, 0.7, null)], 'healthy'],
+ ['all green and healthy → healthy', [fleetRow(false, 0.99), fleetRow(false)], 'healthy'],
+ ])('classifies fleet state: %s', (_name, rows, expected) => {
+ expect(computeFleetSummary(rows).state).toBe(expected)
+ })
+
+ it('sums runs and cost across workflows', () => {
+ const summary = computeFleetSummary([
+ { runCount: 10, successRate: 1, latestRunFailed: false, billableMinutes: 100, estimatedCostUsd: 4 },
+ { runCount: 5, successRate: 1, latestRunFailed: true, billableMinutes: 50, estimatedCostUsd: 2 },
+ ])
+ expect(summary.totalRuns).toBe(15)
+ expect(summary.failingNow).toBe(1)
+ expect(summary.estimatedCostUsd).toBe(6)
+ expect(summary.billableMinutes).toBe(150)
+ })
+})
diff --git a/products/engineering_analytics/frontend/lib/runHealth.ts b/products/engineering_analytics/frontend/lib/runHealth.ts
new file mode 100644
index 000000000000..2c81f95f99a2
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/runHealth.ts
@@ -0,0 +1,190 @@
+// Rolls a flat list of one workflow's runs up into the health facts the verdict header renders. Kept
+// separate from the kea logic so both the workflow-runs page and (later) the PR page can derive the same
+// summary, and so the math is unit-testable without a logic harness.
+
+import { isDecisiveFailure } from './lifecycle'
+
+// The minimum a run needs to score its health. Both WorkflowRunRow and PrRunRow satisfy this.
+export interface HealthRun {
+ conclusion: string | null
+ startedAt: string | null
+ durationSeconds: number | null
+ /** Re-run attempt (1 for the first); a 2nd+ attempt is a re-run. */
+ runAttempt?: number | null
+}
+
+/** Billable minutes + estimated cost rolled up across the window; null fields when jobs aren't synced. */
+export interface CostSummary {
+ billableMinutes: number | null
+ estimatedCostUsd: number | null
+}
+
+export type WorkflowState = 'healthy' | 'degraded' | 'failing' | 'unknown'
+
+export interface HealthSummary {
+ state: WorkflowState
+ totalRuns: number
+ completedRuns: number
+ passedRuns: number
+ failures: number
+ running: number
+ /** Runs that were a 2nd+ attempt — re-runs, a flakiness signal the chart doesn't show. */
+ reruns: number
+ /** Passes ÷ completed runs (null when nothing has settled). */
+ passRate: number | null
+ medianSeconds: number | null
+ p95Seconds: number | null
+ lastFailureAt: string | null
+ latestConclusion: string | null
+}
+
+// At or above this decisive-failure rate a workflow whose latest run still passed reads as "degraded".
+// Keyed off failures, not pass rate, so cancellations (neither pass nor failure) don't drag the verdict.
+const DEGRADED_FAILURE_RATE = 0.1
+// Below this success rate a currently-green workflow counts as flaky in the fleet rollup.
+const FLAKY_SUCCESS_RATE = 0.9
+
+// One workflow's row in the all-workflows table, reduced to what the fleet rollup needs.
+export interface FleetRow {
+ runCount: number
+ successRate: number | null
+ /** Most recent completed run failed; null when nothing has completed for that workflow. */
+ latestRunFailed: boolean | null
+ /** Last decisive failure in the window, or null if there was none — so a low success rate driven by
+ * skips/cancels (not failures) isn't mistaken for flakiness. */
+ lastFailureAt?: string | null
+ billableMinutes?: number | null
+ estimatedCostUsd?: number | null
+}
+
+export interface FleetSummary {
+ state: WorkflowState
+ workflowCount: number
+ /** Workflows whose latest run has settled (so they're either green or red right now). */
+ settledWorkflows: number
+ failingNow: number
+ /** Currently green but below the success-rate floor — flaky. */
+ flakyNow: number
+ totalRuns: number
+ billableMinutes: number | null
+ estimatedCostUsd: number | null
+}
+
+/** Nearest-rank percentile over an ascending-sorted sample. */
+export function percentileSorted(sortedAsc: number[], q: number): number | null {
+ if (sortedAsc.length === 0) {
+ return null
+ }
+ return sortedAsc[Math.min(sortedAsc.length - 1, Math.max(0, Math.ceil(q * sortedAsc.length) - 1))]
+}
+
+/**
+ * Verdict + headline stats for one workflow's runs. State mirrors the run tables: the latest settled run
+ * failing is "failing"; an otherwise-passing workflow whose decisive-failure rate is elevated is
+ * "degraded"; everything else is "healthy". Durations and rates are over completed runs only — a run that
+ * hasn't settled is excluded, never counted as a failure.
+ */
+export function computeHealthSummary(runs: HealthRun[]): HealthSummary {
+ const completed = runs.filter((run) => run.conclusion !== null)
+ const running = runs.length - completed.length
+ // Strictly conclusion === 'success', mirroring the workflow-health endpoint's success_rate
+ // (skipped/neutral don't count as passes) so this header and the Workflows table agree.
+ const passed = completed.filter((run) => run.conclusion === 'success').length
+ const failures = completed.filter((run) => isDecisiveFailure(run.conclusion)).length
+ const reruns = runs.filter((run) => (run.runAttempt ?? 1) > 1).length
+ const passRate = completed.length ? passed / completed.length : null
+
+ const durations = completed
+ .map((run) => run.durationSeconds)
+ .filter((d): d is number => d != null)
+ .sort((a, b) => a - b)
+
+ const byStartDesc = [...completed].sort((a, b) => (b.startedAt ?? '').localeCompare(a.startedAt ?? ''))
+ const latestConclusion = byStartDesc[0]?.conclusion ?? null
+ const lastFailureAt =
+ completed
+ .filter((run) => isDecisiveFailure(run.conclusion))
+ .map((run) => run.startedAt)
+ .filter((at): at is string => !!at)
+ .sort()
+ .at(-1) ?? null
+
+ let state: WorkflowState
+ if (completed.length === 0) {
+ state = 'unknown'
+ } else if (isDecisiveFailure(latestConclusion)) {
+ state = 'failing'
+ } else if (failures / completed.length >= DEGRADED_FAILURE_RATE) {
+ state = 'degraded'
+ } else {
+ state = 'healthy'
+ }
+
+ return {
+ state,
+ totalRuns: runs.length,
+ completedRuns: completed.length,
+ passedRuns: passed,
+ failures,
+ running,
+ reruns,
+ passRate,
+ medianSeconds: percentileSorted(durations, 0.5),
+ p95Seconds: percentileSorted(durations, 0.95),
+ lastFailureAt,
+ latestConclusion,
+ }
+}
+
+/**
+ * Fleet verdict + rollups across all workflows in the window (the all-workflows page). State is the
+ * worst the fleet is right now: every settled workflow red is "failing"; any red or flaky is "degraded";
+ * otherwise "healthy". Runs and cost are summed across workflows; cost is null until any row carries it.
+ */
+export function computeFleetSummary(rows: FleetRow[]): FleetSummary {
+ const workflowCount = rows.length
+ const settledWorkflows = rows.filter((row) => row.latestRunFailed != null).length
+ const failingNow = rows.filter((row) => row.latestRunFailed === true).length
+ // Flaky = currently green but below the success-rate floor AND it has actually failed in the window.
+ // The `lastFailureAt` gate keeps this aligned with the single-workflow verdict: a low success rate that
+ // comes from skips/cancels (no decisive failures) reads as healthy, not flaky.
+ const flakyNow = rows.filter(
+ (row) =>
+ row.latestRunFailed === false &&
+ row.successRate != null &&
+ row.successRate < FLAKY_SUCCESS_RATE &&
+ row.lastFailureAt != null
+ ).length
+ const totalRuns = rows.reduce((sum, row) => sum + row.runCount, 0)
+
+ // Gate each cost field on whether any row carries a real value — free runners report null, and a
+ // bare sum would turn "no cost data" into a misleading $0.00 / 0 min.
+ const hasBillable = rows.some((row) => row.billableMinutes != null)
+ const hasEstimatedCost = rows.some((row) => row.estimatedCostUsd != null)
+ const billableMinutes = hasBillable ? rows.reduce((sum, row) => sum + (row.billableMinutes ?? 0), 0) : null
+ const estimatedCostUsd = hasEstimatedCost ? rows.reduce((sum, row) => sum + (row.estimatedCostUsd ?? 0), 0) : null
+
+ let state: WorkflowState
+ if (workflowCount === 0 || settledWorkflows === 0) {
+ // Workflows exist but none has a completed run yet — no evidence either way, same as the
+ // single-workflow "unknown".
+ state = 'unknown'
+ } else if (failingNow > 0 && failingNow === settledWorkflows) {
+ state = 'failing'
+ } else if (failingNow > 0 || flakyNow > 0) {
+ state = 'degraded'
+ } else {
+ state = 'healthy'
+ }
+
+ return {
+ state,
+ workflowCount,
+ settledWorkflows,
+ failingNow,
+ flakyNow,
+ totalRuns,
+ billableMinutes,
+ estimatedCostUsd,
+ }
+}
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
index 61a021986c87..e85700cd219c 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
@@ -10,6 +10,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { PullRequestTable } from '../components/PullRequestTable'
import { formatCost, formatMinutes } from '../components/runTables'
+import { StatTile } from '../components/StatTile'
import { AuthorLogicProps, authorLogic } from './authorLogic'
// date_from only (the list floors on it); "all time" / week+month snaps are out. All options are within
@@ -29,16 +30,6 @@ export const scene: SceneExport<AuthorLogicProps> = {
}),
}
-function StatCard({ label, value, sub }: { label: string; value: string; sub: string }): JSX.Element {
- return (
- <div className="flex min-w-44 flex-1 flex-col gap-1 rounded-lg border bg-surface-primary px-5 py-4">
- <span className="text-xs text-secondary">{label}</span>
- <span className="text-2xl leading-none font-semibold tabular-nums">{value}</span>
- <span className="text-xs text-tertiary">{sub}</span>
- </div>
- )
-}
-
export function EngineeringAnalyticsAuthorScene(): JSX.Element {
const { handle, prs, prsLoading, dateFrom, windowedRows, totalCostUsd, totalBillableMinutes, sourceId } =
useValues(authorLogic)
@@ -61,17 +52,17 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
/>
</div>
<div className="flex flex-wrap gap-3">
- <StatCard
+ <StatTile
label="Pull requests opened"
value={windowedRows.length.toLocaleString()}
sub="in the selected window"
/>
- <StatCard
+ <StatTile
label="Billable CI minutes"
value={formatMinutes(totalBillableMinutes)}
sub={totalCostUsd != null ? `≈ ${formatCost(totalCostUsd)} estimated` : 'no cost data yet'}
/>
- <StatCard
+ <StatTile
label="Estimated CI cost"
value={formatCost(totalCostUsd)}
sub="self-hosted runners only"
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
index 1228d23b8f75..4365e785f37b 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
@@ -8,6 +8,7 @@ import { dateFilterToText, dateMapping } from 'lib/utils/dateFilters'
import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
import { WorkflowHealthTable } from '../components/WorkflowHealthTable'
+import { WorkflowsHealthHeader } from '../components/WorkflowsHealthHeader'
import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
// The endpoint caps the window at 366 days, so "All time" and week/month snaps are out.
@@ -35,6 +36,8 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
branchInput,
appliedBranch,
sourceId,
+ fleetSummary,
+ fleetTruncated,
} = useValues(engineeringAnalyticsLogic)
const { setWorkflowDateRange, setBranchFilter, applyBranchFilter, refresh } = useActions(engineeringAnalyticsLogic)
@@ -86,6 +89,7 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
</LemonButton>
))}
</div>
+ {workflowHealth.length > 0 && <WorkflowsHealthHeader summary={fleetSummary} truncated={fleetTruncated} />}
<WorkflowHealthTable
rows={workflowHealth}
loading={workflowHealthLoading}
diff --git a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
index d9deb25f99ec..af9e8798ec3a 100644
--- a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
@@ -15,6 +15,7 @@ import {
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { cn } from 'lib/utils/css-classes'
import { humanFriendlyDuration } from 'lib/utils/durations'
import { pluralize } from 'lib/utils/strings'
@@ -25,6 +26,7 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { RunJobsTable, RunsTable, formatCost } from '../components/runTables'
+import { StatTile } from '../components/StatTile'
import { WorkflowHealthTable } from '../components/WorkflowHealthTable'
import type { PRCostSummaryApi, PullRequestApi } from '../generated/api.schemas'
import { githubCommitUrl, githubPrUrl } from '../lib/github'
@@ -198,7 +200,7 @@ function LifecycleStrip({ summary, openedAt, commitGroups }: LifecycleStripProps
const minGrow = totalSeconds * 0.04
return (
- <div className="rounded-lg border bg-surface-primary px-5 py-4">
+ <LemonCard hoverEffect={false} className="px-5 py-4">
<div className="mb-3 flex items-baseline gap-2">
<span className="text-xs font-semibold tracking-wide text-secondary uppercase">Lifecycle</span>
<span className="text-xs text-tertiary">{subtitle}</span>
@@ -266,7 +268,7 @@ function LifecycleStrip({ summary, openedAt, commitGroups }: LifecycleStripProps
</span>
</div>
</div>
- </div>
+ </LemonCard>
)
}
@@ -309,17 +311,6 @@ function formatMinutes(minutes: number): string {
return `${Math.round(minutes).toLocaleString()} min`
}
-/** One headline stat: small label, big number, a muted subline for the caveat/breakdown. */
-function StatCard({ label, value, sub }: { label: string; value: string; sub: ReactNode }): JSX.Element {
- return (
- <div className="flex min-w-44 flex-1 flex-col gap-1 rounded-lg border bg-surface-primary px-5 py-4">
- <span className="text-xs text-secondary">{label}</span>
- <span className="text-2xl font-semibold leading-7 tabular-nums">{value}</span>
- <span className="text-xs text-tertiary">{sub}</span>
- </div>
- )
-}
-
const VERDICT_LEGEND: { key: 'passed' | 'failed' | 'running'; dot: string; label: string }[] = [
{ key: 'passed', dot: 'bg-success', label: 'passed' },
{ key: 'failed', dot: 'bg-danger', label: 'failed' },
@@ -447,7 +438,7 @@ function PrSummaryCards({
)}
<div className="flex flex-wrap items-stretch gap-3">
{runsTotal > 0 && (
- <div className="flex min-w-72 flex-1 flex-col gap-2 rounded-lg border bg-surface-primary px-5 py-4">
+ <LemonCard hoverEffect={false} className="flex min-w-72 flex-1 flex-col gap-2 px-5 py-4">
<span className="text-xs text-secondary">Run verdicts · all commits &amp; re-runs</span>
<div className="flex items-center gap-4">
<VerdictDonut counts={counts} />
@@ -464,24 +455,24 @@ function PrSummaryCards({
<span className="text-xs text-tertiary">
{pluralize(runsTotal, 'run')} · {pluralize(commits, 'commit')}
</span>
- </div>
+ </LemonCard>
)}
{costLoading && !cost ? (
<LemonSkeleton className="h-24 w-44" />
) : showCost ? (
- <StatCard
+ <StatTile
label="Billable CI minutes"
value={formatMinutes(cost.billable_minutes)}
sub={<>≈ {formatCost(cost.estimated_cost_usd)} estimated</>}
/>
) : null}
- <StatCard
+ <StatTile
label="Pushes (CI triggers)"
value={pushes.toLocaleString()}
sub={rerunCycles > 0 ? pluralize(rerunCycles, 're-run cycle') : 'no re-runs'}
/>
{openedAt && (
- <StatCard
+ <StatTile
label={openLabel}
value={gapBetween(openedAt, openTo)}
sub={
@@ -724,6 +715,7 @@ export function PullRequestDetailScene(): JSX.Element {
}
loading={runJobsLoading}
embedded
+ aligned
/>
)
}
@@ -740,6 +732,7 @@ export function PullRequestDetailScene(): JSX.Element {
setExpanded={setRunExpanded}
runCostByKey={runCostByKey}
showCost={prCost?.jobs_available ?? false}
+ aligned
// Oldest push first so rows read in the same order as the sparkline.
defaultSorting={{ columnKey: 'started', order: 1 }}
dataAttr="engineering-analytics-pr-runs-table"
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
index 818a8f6663bd..d187d4cd7fcc 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
@@ -5,6 +5,7 @@ import { IconExternal } from '@posthog/icons'
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 { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -106,7 +107,7 @@ export function WorkflowRunDetailScene(): JSX.Element {
</span>
</div>
- <div className="divide-y rounded-lg border bg-surface-primary">
+ <LemonCard hoverEffect={false} className="divide-y p-0">
<DetailRow label="Status">
<span className="capitalize">{run.status || '—'}</span>
</DetailRow>
@@ -158,7 +159,7 @@ export function WorkflowRunDetailScene(): JSX.Element {
<span className="text-secondary">—</span>
)}
</DetailRow>
- </div>
+ </LemonCard>
<div className="flex flex-col gap-2">
<h3 className="mb-0">Jobs</h3>
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
index 17364695668b..bf89c2374f04 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
@@ -4,6 +4,7 @@ import { combineUrl } from 'kea-router'
import { IconExternal } from '@posthog/icons'
import { LemonButton, LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'
+import { getSeriesColor } from 'lib/colors'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { dateMapping } from 'lib/utils/dateFilters'
import { SceneExport } from 'scenes/sceneTypes'
@@ -13,7 +14,10 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { BillableBadge } from '../components/BillableBadge'
-import { RunnerBadge, RunsTable } from '../components/runTables'
+import { DistributionBar } from '../components/DistributionBar'
+import { RunActivityChart } from '../components/RunActivityChart'
+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 { WorkflowRunRow, WorkflowRunsLogicProps, workflowRunsLogic } from './workflowRunsLogic'
@@ -42,12 +46,22 @@ function RunnerCostTable({ costs }: { costs: WorkflowRunnerCostApi[] }): JSX.Ele
render: (_, cost) => <BillableBadge minutes={cost.billable_minutes} costUsd={cost.estimated_cost_usd} />,
},
]
+ // Where the money goes — one stacked bar over the table, a segment per tier sized by its $ share.
+ // Free (GitHub-hosted) runners are $0, so they don't take a slice; the bar reads as "billable spend".
+ const costSegments = costs.map((cost, i) => ({
+ key: `${cost.provider}:${cost.runner_label}`,
+ label: cost.runner_label || cost.provider,
+ value: cost.estimated_cost_usd ?? 0,
+ color: getSeriesColor(i),
+ caption: formatCost(cost.estimated_cost_usd ?? null),
+ }))
return (
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-baseline gap-2">
<h3 className="mb-0">Cost by runner</h3>
<LemonTag type="warning">estimate · wall-clock × reference rate</LemonTag>
</div>
+ <DistributionBar segments={costSegments} />
<LemonTable
data-attr="engineering-analytics-workflow-runner-costs"
size="small"
@@ -99,6 +113,9 @@ export function WorkflowRunsScene(): JSX.Element {
repoOwner,
repoName,
workflowName,
+ healthSummary,
+ costSummary,
+ runsTruncated,
} = useValues(workflowRunsLogic)
const { loadRuns, setRunExpanded, setDateRange } = useActions(workflowRunsLogic)
@@ -198,6 +215,8 @@ export function WorkflowRunsScene(): JSX.Element {
size="small"
/>
</div>
+ <WorkflowHealthHeader summary={healthSummary} cost={costSummary} truncated={runsTruncated} />
+ <RunActivityChart runs={runRows} truncated={runsTruncated} />
{runnerCosts.length > 0 && <RunnerCostTable costs={runnerCosts} />}
<div className="flex flex-col gap-2">
<h3 className="mb-0">Runs</h3>
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
index 731f12aa4520..8f0e02bcb85d 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
@@ -16,12 +16,17 @@ import {
} from '../generated/api'
import type { GitHubSourceApi, PullRequestListItemApi } from '../generated/api.schemas'
import { CIStatus, ciStatusOf } from '../lib/ci'
+import { type FleetSummary, computeFleetSummary } from '../lib/runHealth'
import type { engineeringAnalyticsLogicType } from './engineeringAnalyticsLogicType'
// Safety bound on the PR table (mirrors the endpoint's server-side limit). Surfaced
// in copy when hit so a truncated list is never mistaken for the whole picture.
export const PR_TABLE_LIMIT = 1000
+// The workflow-health endpoint returns the top workflows by run count (`workflow_health.py` `_LIMIT`).
+// When hit, the fleet header labels its totals as "top N" so they're never read as the whole fleet.
+export const WORKFLOW_HEALTH_LIMIT = 100
+
// The endpoints are project-scoped; the generated client takes the id as a string.
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
@@ -666,6 +671,17 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
}),
selectors({
+ // Fleet verdict + rollups across every workflow row, for the all-workflows health strip.
+ fleetSummary: [
+ (s) => [s.workflowHealth],
+ (workflowHealth): FleetSummary => computeFleetSummary(workflowHealth),
+ ],
+ // The endpoint caps at the top workflows by run count; when hit, the header's totals cover only
+ // those, so it labels them as "top N" rather than fleet-wide.
+ fleetTruncated: [
+ (s) => [s.workflowHealth],
+ (workflowHealth): boolean => workflowHealth.length >= WORKFLOW_HEALTH_LIMIT,
+ ],
filters: [
(s) => [s.stateFilter, s.author, s.repo, s.ciStatusFilter, s.search, s.stuckOnly],
(stateFilter, author, repo, ciStatus, search, stuckOnly): PullRequestFilters => ({
diff --git a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
index 9c0cd7fe92f8..0f3d69963d12 100644
--- a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
@@ -14,7 +14,13 @@ import {
} from '../generated/api'
import type { PRCostSummaryApi, PRLifecycleApi, WorkflowJobApi, WorkflowRunDetailApi } from '../generated/api.schemas'
import { jobCacheKey } from '../lib/jobs'
-import { LifecycleSummary, WorkflowRun, isPassingConclusion, summarizeLifecycle } from '../lib/lifecycle'
+import {
+ LifecycleSummary,
+ WorkflowRun,
+ isDecisiveFailure,
+ isPassingConclusion,
+ summarizeLifecycle,
+} from '../lib/lifecycle'
import type { WorkflowHealthBucket, WorkflowHealthRow } from './engineeringAnalyticsLogic'
import type { pullRequestDetailLogicType } from './pullRequestDetailLogicType'
@@ -50,8 +56,6 @@ export interface PrRunRow extends WorkflowRun {
headBranch: string
}
-const isDecisiveFailure = (conclusion: string | null): boolean => conclusion === 'failure' || conclusion === 'timed_out'
-
/** Nearest-rank percentile over a small sample (the PR's per-workflow run durations). */
function percentile(values: number[], q: number): number | null {
if (values.length === 0) {
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
index 4117e1a20494..1a9970b6cc43 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
@@ -13,10 +13,15 @@ import {
} from '../generated/api'
import type { WorkflowJobApi, WorkflowRunDetailApi, WorkflowRunnerCostApi } from '../generated/api.schemas'
import { jobCacheKey } from '../lib/jobs'
+import { type CostSummary, type HealthSummary, computeHealthSummary } from '../lib/runHealth'
import type { workflowRunsLogicType } from './workflowRunsLogicType'
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
+// Mirrors the backend runs-list cap (`workflow_run_list.py` `_LIMIT`). When the list comes back this full
+// it's almost certainly truncated, so the header labels its run rollups as "recent" rather than full-window.
+const RUN_LIST_LIMIT = 200
+
/** A workflow run mapped to the shared RunsTable shape: the RunRowBase fields the table needs, plus the
* lead-column data this page shows (run id, branch, attributed PR). */
export interface WorkflowRunRow {
@@ -157,6 +162,32 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
repoName: run.repo.name,
})),
],
+ // Verdict + headline stats for the health strip above the chart.
+ healthSummary: [(s) => [s.runRows], (runRows): HealthSummary => computeHealthSummary(runRows)],
+ // The runs list is capped server-side; when hit, the header's run rollups are over the most recent
+ // runs only (cost still comes from the full-window aggregate), so it labels them as such.
+ runsTruncated: [(s) => [s.runRows], (runRows): boolean => runRows.length >= RUN_LIST_LIMIT],
+ // Billable minutes + estimated cost summed across runner tiers, for the strip's cost rollup.
+ costSummary: [
+ (s) => [s.runnerCosts],
+ (runnerCosts): CostSummary | null => {
+ if (runnerCosts.length === 0) {
+ return null
+ }
+ // Free (GitHub-hosted) runners report null cost; gate each field so an all-free workflow
+ // shows no cost rather than a misleading $0.00 / 0 min from summing nulls as zero.
+ const hasBillable = runnerCosts.some((cost) => cost.billable_minutes != null)
+ const hasEstimatedCost = runnerCosts.some((cost) => cost.estimated_cost_usd != null)
+ return {
+ billableMinutes: hasBillable
+ ? runnerCosts.reduce((sum, cost) => sum + (cost.billable_minutes ?? 0), 0)
+ : null,
+ estimatedCostUsd: hasEstimatedCost
+ ? runnerCosts.reduce((sum, cost) => sum + (cost.estimated_cost_usd ?? 0), 0)
+ : null,
+ }
+ },
+ ],
breadcrumbs: [
(_, p) => [p.repoOwner, p.repoName, p.workflowName],
(repoOwner, repoName, workflowName): Breadcrumb[] => [