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(eng-analytics): redesign hub, prs, workflows + detail pages (#69516)

Raúl Negrón-Oteroe99d21916f66
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c2e349839624..f6366d3b4d52 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5531,9 +5531,9 @@ snapshots:
scenes-app-data-warehouse-sql-editor--top-tools-per-server--light:
hash: v1.k794b7964.e6420f44b86930d43085b575192d3c26ac0401919a4af6f8d7bd1c799e964836.pZmiZ4w-9QbQ60TFc6Sx94NT0YmU4EULydWdqDqxDmY
scenes-app-engineering-analytics-repo-overview--repo-overview--dark:
- hash: v1.k794b7964.33da23b1f44fdfb476c70040adf6a0e7cd3181d4ebc4104e3170f1168e87a762.FBj2-1IKmG64f7qR9LToBEf74I5uJ-wQVVSFZT1YTMA
+ hash: v1.k794b7964.c6f38d08b3c59294a9443a62fdf1b76fab8f2a026d3c3bb169f8ec86575e2296.xPQhtO1OrkOaRa8V_fKsaZMyJ9CM9iW_HTB3w5wa9r8
scenes-app-engineering-analytics-repo-overview--repo-overview--light:
- hash: v1.k794b7964.00d52e2e14ce7b78fb3e4cd387a816133386735f031a42f08af19e6e36d858f5.mgSfjwCtQfkr2xtrBUL8L-CPJX9vNKVwcN1ROVbFzo8
+ hash: v1.k794b7964.10713695bfff7d1fe091a19db8a951832946f61cc5711f41edf479cdc443e071.j1YL510Wvt_XUK4isWUN7pSluY0kL7yvzokjkR1P1es
scenes-app-engineering-analytics-test-health--flaky-test-leaderboard--dark:
hash: v1.k794b7964.b80842e3c1fcc9321fbd781d1c7aa06bdd243479eff1b407ad94466b48625e7f.vSCnKb5GwJzPTNMCRmvYw6f3fYfPbJcDlNia1tEc22E
scenes-app-engineering-analytics-test-health--flaky-test-leaderboard--light:
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 3579f2d50b76..9e348f77fd8b 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -251,23 +251,23 @@ export const productRoutes: Record<string, [string, string]> = {
'/early_access_features/:id': ['EarlyAccessFeature', 'earlyAccessFeature'],
'/endpoints': ['EndpointsScene', 'endpoints'],
'/endpoints/:name': ['EndpointScene', 'endpoint'],
- '/engineering-analytics': ['EngineeringAnalytics', 'engineeringAnalytics'],
- '/engineering-analytics/pulls': ['EngineeringAnalytics', 'engineeringAnalyticsPullRequestList'],
+ '/engineering-analytics/overview': ['EngineeringAnalytics', 'engineeringAnalytics'],
+ '/engineering-analytics/pull-requests': ['EngineeringAnalytics', 'engineeringAnalyticsPullRequestList'],
'/engineering-analytics/workflows': ['EngineeringAnalytics', 'engineeringAnalyticsWorkflows'],
'/engineering-analytics/test-health': ['EngineeringAnalytics', 'engineeringAnalyticsTestHealth'],
- '/engineering-analytics/:repoOwner/:repoName/pull/:number': [
+ '/engineering-analytics/repos/:repoOwner/:repoName/pull-requests/:number': [
'EngineeringAnalyticsPullRequest',
'engineeringAnalyticsPullRequest',
],
- '/engineering-analytics/:repoOwner/:repoName/actions/runs/:runId': [
+ '/engineering-analytics/repos/:repoOwner/:repoName/actions/runs/:runId': [
'EngineeringAnalyticsWorkflowRun',
'engineeringAnalyticsWorkflowRun',
],
- '/engineering-analytics/:repoOwner/:repoName/actions/workflows/:workflowName': [
+ '/engineering-analytics/repos/:repoOwner/:repoName/actions/workflows/:workflowName': [
'EngineeringAnalyticsWorkflowRuns',
'engineeringAnalyticsWorkflowRuns',
],
- '/engineering-analytics/author/:handle': ['EngineeringAnalyticsAuthor', 'engineeringAnalyticsAuthor'],
+ '/engineering-analytics/authors/:handle': ['EngineeringAnalyticsAuthor', 'engineeringAnalyticsAuthor'],
'/error_tracking': ['ErrorTracking', 'errorTracking'],
'/error_tracking/:id': ['ErrorTrackingIssue', 'errorTrackingIssue'],
'/error_tracking/:id/fingerprints': ['ErrorTrackingIssueFingerprints', 'errorTrackingIssueFingerprints'],
@@ -473,7 +473,8 @@ export const productRedirects: Record<
'/data-warehouse/sources': () => urls.sources(),
'/data-warehouse/sources/:id': ({ id }) => urls.dataWarehouseSource(id, 'schemas'),
'/data-warehouse/sources/:id/:tab': ({ id, tab }) => urls.dataWarehouseSource(id, tab as SourceSceneTab),
- '/engineering-analytics/authors': '/engineering-analytics',
+ '/engineering-analytics': '/engineering-analytics/overview',
+ '/engineering-analytics/authors': '/engineering-analytics/overview',
'/error_tracking/configuration': (_params, searchParams, hashParams) => {
const { tab, ...restSearchParams } = searchParams
return combineUrl(
@@ -1135,18 +1136,18 @@ export const productUrls = {
}
return combineUrl('/endpoints', { tab: 'usage', ...searchParams }).url
},
- engineeringAnalytics: (): string => '/engineering-analytics',
- engineeringAnalyticsPullRequestList: (): string => '/engineering-analytics/pulls',
+ engineeringAnalytics: (): string => '/engineering-analytics/overview',
+ engineeringAnalyticsPullRequestList: (): string => '/engineering-analytics/pull-requests',
engineeringAnalyticsWorkflows: (): string => '/engineering-analytics/workflows',
engineeringAnalyticsTestHealth: (): string => '/engineering-analytics/test-health',
engineeringAnalyticsPullRequest: (repoOwner: string, repoName: string, number: number | string): string =>
- `/engineering-analytics/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/pull/${number}`,
+ `/engineering-analytics/repos/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/pull-requests/${number}`,
engineeringAnalyticsWorkflowRun: (repoOwner: string, repoName: string, runId: number | string): string =>
- `/engineering-analytics/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/runs/${runId}`,
+ `/engineering-analytics/repos/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/runs/${runId}`,
engineeringAnalyticsWorkflowRuns: (repoOwner: string, repoName: string, workflowName: string): string =>
- `/engineering-analytics/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/workflows/${encodeURIComponent(workflowName)}`,
+ `/engineering-analytics/repos/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/workflows/${encodeURIComponent(workflowName)}`,
engineeringAnalyticsAuthor: (handle: string): string =>
- `/engineering-analytics/author/${encodeURIComponent(handle)}`,
+ `/engineering-analytics/authors/${encodeURIComponent(handle)}`,
errorTracking: (params = {}): string => combineUrl('/error_tracking', params).url,
errorTrackingConfiguration: (params = {}): string =>
combineUrl('/error_tracking', { ...params, activeTab: 'configuration' }).url,
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index d82400fa7e27..3ba39600ca2f 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -242,6 +242,8 @@ class WorkflowRunActivityPoint:
head_branch: str
# Attributed pull request number, or 0 when unattributed.
pr_number: int
+ # Head commit SHA — lets a chart point link to the commit (e.g. the repo-health bar → GitHub commit).
+ head_sha: str
@dataclass(frozen=True)
@@ -492,6 +494,23 @@ class CIStatusRollup:
failing_workflows: list[str] = field(default_factory=list)
+@dataclass(frozen=True)
+class PushCISample:
+ """One CI round (push) on a pull request, for the compact push-history sparkline:
+ when the round started, its wall-clock CI time, and its verdict.
+ """
+
+ head_sha: str
+ # Earliest run start on this push.
+ started_at: datetime
+ # First run start → last completed run end on this push; None while nothing has completed.
+ wall_seconds: int | None
+ # Any latest-per-workflow run on this push concluded 'failure' or 'timed_out'.
+ failed: bool
+ # Any latest-per-workflow run on this push hasn't completed yet.
+ pending: bool
+
+
@dataclass(frozen=True)
class PullRequestListItem:
"""One row of the PR list: the PR plus its head-SHA CI rollup. No ``id`` or
@@ -520,6 +539,9 @@ class PullRequestListItem:
estimated_cost_usd: float | None = None
# Billable (self-hosted) minutes summed over this PR's jobs; None when the job source isn't synced.
billable_minutes: float | None = None
+ # This PR's CI rounds oldest-first, capped to the most recent pushes (see the list query) — the
+ # push-history sparkline. ``pushes`` stays the uncapped count.
+ push_history: list[PushCISample] = field(default_factory=list)
@dataclass(frozen=True)
@@ -701,6 +723,50 @@ class CostPerMergeBucket:
cost_per_merge_usd: float | None
+@dataclass(frozen=True)
+class TimeToGreenBucket:
+ """One time bucket of the repo's median time-to-green: the p50 wall-clock duration of *successful*
+ CI runs attributed to pull requests (default-branch runs excluded), started in this bucket. Cancelled
+ and failed runs end early and would bias the percentile low, so they are excluded — the same
+ success-only population the workflow-health percentiles use. ``p50_seconds`` is None for a bucket with
+ no successful PR run (a gap, not instant CI); the UI carries the last known value forward rather than
+ dipping the trend to zero.
+ """
+
+ # Bucket start, aligned to the granularity (top of hour / midnight / Monday).
+ bucket_start: datetime
+ # Median wall-clock seconds of successful PR-attributed CI runs started in this bucket. None when the
+ # bucket had no successful PR run.
+ p50_seconds: float | None
+
+
+@dataclass(frozen=True)
+class PassRateBucket:
+ """One time bucket of the repo's CI pass rate: the fraction of completed runs (all branches) started in
+ this bucket that succeeded. ``success_rate`` is None for a bucket with no completed run (a gap, not a
+ 0% pass rate); the UI carries the last known value forward rather than dipping the trend to zero.
+ """
+
+ # Bucket start, aligned to the granularity (top of hour / midnight / Monday).
+ bucket_start: datetime
+ # Fraction (0-1) of completed runs started in this bucket that succeeded. None when none completed.
+ success_rate: float | None
+
+
+@dataclass(frozen=True)
+class OpenToMergeBucket:
+ """One time bucket of the repo's median time-to-merge: the p50 of ``merged_at - created_at`` over PRs
+ merged in this bucket, bots and drafts excluded (the locked cycle-time recipe). Coarse by design (draft
+ and ready time fused). ``p50_seconds`` is None for a bucket where nothing merged (a gap, not instant
+ merges); the UI carries the last known value forward rather than dipping the trend to zero.
+ """
+
+ # Bucket start, aligned to the granularity (top of hour / midnight / Monday). Keyed on merge time.
+ bucket_start: datetime
+ # Median merged_at - created_at seconds over PRs merged in this bucket. None when nothing merged.
+ p50_seconds: float | None
+
+
@dataclass(frozen=True)
class RepoOverview:
"""Repo-level headline aggregates for the landing page, each with its previous-window twin
@@ -730,6 +796,21 @@ class RepoOverview:
cost_series: list[CostPerMergeBucket]
# Bucket width of `cost_series`, chosen to fit the window: 'hour', 'day', or 'week'.
cost_series_granularity: str
+ # Time-to-green trend: median CI duration of successful PR-attributed runs per bucket, oldest first,
+ # bucketed by `time_to_green_series_granularity`. Empty buckets carry None (no successful PR run).
+ time_to_green_series: list[TimeToGreenBucket]
+ # Bucket width of `time_to_green_series`, chosen to fit the window: 'hour', 'day', or 'week'.
+ time_to_green_series_granularity: str
+ # Pass-rate trend: fraction of completed runs (all branches) that succeeded per bucket, oldest first,
+ # bucketed by `success_rate_series_granularity`. Empty buckets carry None (no completed run).
+ success_rate_series: list[PassRateBucket]
+ # Bucket width of `success_rate_series`, chosen to fit the window: 'hour', 'day', or 'week'.
+ success_rate_series_granularity: str
+ # Time-to-merge trend: median open_to_merge_seconds over PRs merged per bucket (bots/drafts excluded),
+ # oldest first, bucketed by `open_to_merge_series_granularity`. Empty buckets carry None (nothing merged).
+ open_to_merge_series: list[OpenToMergeBucket]
+ # Bucket width of `open_to_merge_series`, chosen to fit the window: 'hour', 'day', or 'week'.
+ open_to_merge_series_granularity: str
@dataclass(frozen=True)
diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_list.py b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
index abfcf6288349..893b36308b8a 100644
--- a/products/engineering_analytics/backend/logic/queries/pull_request_list.py
+++ b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
@@ -17,6 +17,7 @@ from products.engineering_analytics.backend.facade.contracts import (
PRState,
PullRequestList,
PullRequestListItem,
+ PushCISample,
RepoRef,
)
from products.engineering_analytics.backend.logic.cost import PRCostAggregate
@@ -24,6 +25,8 @@ from products.engineering_analytics.backend.logic.queries._curated import Curate
from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_list_costs
_LIMIT = 1000
+# Sparkline cap: enough to read a PR's CI history at a glance without bloating a 1000-row page.
+_PUSH_HISTORY_LIMIT = 20
_SELECT = f"""
SELECT
@@ -52,6 +55,73 @@ _SELECT = f"""
"""
+# Per-push CI rounds for the visible PRs, for the push-history sparkline. Verdicts collapse like
+# ``ci_rollup``: latest run per (push, workflow) via argMax, then any decisive failure turns the
+# round red and any not-yet-completed run marks it pending. Wall time is the round's earliest run
+# start to its latest completed run end (``updated_at`` is the end time the duration column uses).
+#
+# ``LIMIT __PUSH_HISTORY_LIMIT__ BY (repo_owner, repo_name, pr_number)`` bounds the scan to the most
+# recent N pushes per PR *in ClickHouse* (rows are ordered newest-first, so the cap keeps the newest),
+# rather than fetching every push and slicing in Python — a PR with hundreds of pushes never ships more
+# than the sparkline shows. The trailing ``LIMIT`` is the overall ceiling (≤ 1000 PRs × N); without it
+# HogQL applies its default 100-row limit and silently truncates the whole result.
+_PUSH_HISTORY_SELECT = """
+ SELECT
+ repo_owner, repo_name, pr_number, head_sha,
+ min(first_start) AS started_at,
+ if(countIf(last_end IS NOT NULL) = 0, NULL, dateDiff('second', min(first_start), max(last_end))) AS wall_seconds,
+ countIf(s = 'completed' AND c IN ('failure', 'timed_out')) > 0 AS failed,
+ countIf(s IS NULL OR s != 'completed') > 0 AS pending
+ FROM (
+ SELECT
+ repo_owner, repo_name, pr_number, head_sha, workflow_name,
+ min(run_started_at) AS first_start,
+ max(if(status = 'completed', updated_at, NULL)) AS last_end,
+ argMax(status, run_started_at) AS s,
+ argMax(conclusion, run_started_at) AS c
+ FROM __RUNS_SOURCE__ AS r
+ WHERE pr_number IN {pr_numbers}
+ GROUP BY repo_owner, repo_name, pr_number, head_sha, workflow_name
+ )
+ GROUP BY repo_owner, repo_name, pr_number, head_sha
+ ORDER BY started_at DESC
+ LIMIT __PUSH_HISTORY_LIMIT__ BY (repo_owner, repo_name, pr_number)
+ LIMIT 100000
+"""
+
+
+def query_pr_push_history(
+ *, curated: CuratedGitHubSource, pr_numbers: list[int]
+) -> dict[tuple[str, str, int], list[PushCISample]]:
+ """Per-PR push rounds keyed by (repo_owner, repo_name, pr_number), oldest first, capped in
+ ClickHouse to the most recent ``_PUSH_HISTORY_LIMIT`` per PR. Scoped to the visible PR numbers so
+ the scan tracks the page (same shape as ``query_pr_list_costs``)."""
+ if not pr_numbers:
+ return {}
+ sql = _PUSH_HISTORY_SELECT.replace("__RUNS_SOURCE__", curated.run_source()).replace(
+ "__PUSH_HISTORY_LIMIT__", str(_PUSH_HISTORY_LIMIT)
+ )
+ response = curated.run(
+ sql,
+ query_type="engineering_analytics.pr_push_history",
+ placeholders={"pr_numbers": ast.Constant(value=pr_numbers)},
+ )
+ by_pr: dict[tuple[str, str, int], list[PushCISample]] = {}
+ for repo_owner, repo_name, pr_number, head_sha, started_at, wall_seconds, failed, pending in response.results or []:
+ by_pr.setdefault((repo_owner, repo_name, int(pr_number)), []).append(
+ PushCISample(
+ head_sha=head_sha,
+ started_at=started_at,
+ wall_seconds=int(wall_seconds) if wall_seconds is not None else None,
+ failed=bool(failed),
+ pending=bool(pending),
+ )
+ )
+ # The query returns newest-first (so the per-PR cap keeps the newest pushes); the contract is
+ # oldest-first, so reverse each PR's list back to chronological order.
+ return {key: samples[::-1] for key, samples in by_pr.items()}
+
+
def query_pull_request_list(
*, curated: CuratedGitHubSource, date_from: datetime, author: str | None = None
) -> PullRequestList:
@@ -68,15 +138,20 @@ def query_pull_request_list(
rows = response.results or []
truncated = len(rows) > _LIMIT
visible = rows[:_LIMIT]
- # Scope the cost rollup to exactly the PRs we're about to show (row[0] is pr.number), so the
- # jobs×runs join tracks the page instead of scanning the team's whole CI history.
+ # Scope the cost and push-history rollups to exactly the PRs we're about to show (row[0] is
+ # pr.number), so the scans track the page instead of the team's whole CI history.
pr_numbers = sorted({int(row[0]) for row in visible})
cost_by_pr = query_pr_list_costs(curated=curated, pr_numbers=pr_numbers)
- items = [_map_row(row, cost_by_pr) for row in visible]
+ pushes_by_pr = query_pr_push_history(curated=curated, pr_numbers=pr_numbers)
+ items = [_map_row(row, cost_by_pr, pushes_by_pr) for row in visible]
return PullRequestList(items=items, truncated=truncated, limit=_LIMIT)
-def _map_row(row: tuple, cost_by_pr: dict[tuple[str, str, int], PRCostAggregate]) -> PullRequestListItem:
+def _map_row(
+ row: tuple,
+ cost_by_pr: dict[tuple[str, str, int], PRCostAggregate],
+ pushes_by_pr: dict[tuple[str, str, int], list[PushCISample]],
+) -> PullRequestListItem:
(
number,
title,
@@ -129,4 +204,5 @@ def _map_row(row: tuple, cost_by_pr: dict[tuple[str, str, int], PRCostAggregate]
rerun_cycles=rerun_cycles,
estimated_cost_usd=cost.estimated_cost_usd if cost else None,
billable_minutes=(cost.billable_seconds / 60) if cost else None,
+ push_history=pushes_by_pr.get((repo_owner, repo_name, number), []),
)
diff --git a/products/engineering_analytics/backend/logic/queries/repo_overview.py b/products/engineering_analytics/backend/logic/queries/repo_overview.py
index 90536f8573e8..a729559d27c2 100644
--- a/products/engineering_analytics/backend/logic/queries/repo_overview.py
+++ b/products/engineering_analytics/backend/logic/queries/repo_overview.py
@@ -10,12 +10,20 @@ from datetime import datetime
from posthog.hogql import ast
-from products.engineering_analytics.backend.facade.contracts import RepoOverview
+from products.engineering_analytics.backend.facade.contracts import OpenToMergeBucket, PassRateBucket, RepoOverview
+from products.engineering_analytics.backend.logic.queries._buckets import (
+ Granularity,
+ bucket_expr,
+ normalize_bucket,
+ pick_granularity,
+ window_buckets,
+)
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float
from products.engineering_analytics.backend.logic.queries.pr_cost import (
query_cost_per_merge_series,
query_workflow_window_costs_with_prev,
)
+from products.engineering_analytics.backend.logic.queries.workflow_health import query_time_to_green_series
_RUNS_SELECT = """
SELECT
@@ -69,6 +77,93 @@ def query_default_branch(
return "main" if (main_runs or 0) > (master_runs or 0) else "master"
+# Pass rate per bucket over completed runs, all branches — the population the headline pass rate uses.
+# Division through nullIf yields NULL for a bucket with no completed run (a gap, not 0%).
+_PASS_RATE_SERIES_SELECT = """
+ SELECT
+ __BUCKET_FN__ AS bucket_start,
+ countIf(status = 'completed' AND conclusion = 'success') / nullIf(countIf(status = 'completed'), 0) AS success_rate
+ FROM __RUNS_SOURCE__ AS r
+ WHERE run_started_at >= {date_from} __DATE_TO__
+ GROUP BY bucket_start
+ LIMIT 40000
+"""
+
+# Median open->merge per bucket over PRs merged in it, bots and drafts excluded (the locked recipe). ``n``
+# guards the false zero: quantileIf over no matching rows returns 0, so a bucket whose only merges were
+# bots/drafts would draw a false dip — treat it as a gap (None) instead.
+_OPEN_TO_MERGE_SERIES_SELECT = """
+ SELECT
+ __BUCKET_FN__ AS bucket_start,
+ quantileIf(0.5)(open_to_merge_seconds, NOT is_bot AND NOT is_draft) AS p50,
+ countIf(NOT is_bot AND NOT is_draft) AS n
+ FROM __PR_SOURCE__ AS pr
+ WHERE merged_at IS NOT NULL AND merged_at >= {date_from} __DATE_TO_MERGED__
+ GROUP BY bucket_start
+ LIMIT 40000
+"""
+
+
+def query_success_rate_series(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+) -> tuple[Granularity, list[PassRateBucket]]:
+ """Pass rate per bucket across the window, oldest first: completed runs that succeeded, all branches —
+ the same population as the headline pass rate. Empty buckets carry ``success_rate`` None (a gap)."""
+ granularity = pick_granularity(date_from, date_to)
+ placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}
+ date_to_clause = "AND run_started_at <= {date_to}" if date_to is not None else ""
+ if date_to is not None:
+ placeholders["date_to"] = ast.Constant(value=date_to)
+ sql = (
+ _PASS_RATE_SERIES_SELECT.replace("__RUNS_SOURCE__", curated.run_source())
+ .replace("__DATE_TO__", date_to_clause)
+ .replace("__BUCKET_FN__", bucket_expr(granularity, "run_started_at"))
+ )
+ response = curated.run(sql, query_type="engineering_analytics.success_rate_series", placeholders=placeholders)
+ rate_by_bucket = {
+ normalize_bucket(bucket_start, granularity): opt_float(success_rate)
+ for bucket_start, success_rate in response.results or []
+ }
+ buckets = [
+ PassRateBucket(bucket_start=bucket, success_rate=rate_by_bucket.get(bucket))
+ for bucket in window_buckets(date_from, date_to, granularity)
+ ]
+ return granularity, buckets
+
+
+def query_open_to_merge_series(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+) -> tuple[Granularity, list[OpenToMergeBucket]]:
+ """Median time-to-merge per bucket across the window, oldest first: p50 merged_at - created_at over PRs
+ merged in the bucket, bots and drafts excluded. Empty buckets carry ``p50_seconds`` None (a gap)."""
+ granularity = pick_granularity(date_from, date_to)
+ placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}
+ date_to_clause = "AND merged_at <= {date_to}" if date_to is not None else ""
+ if date_to is not None:
+ placeholders["date_to"] = ast.Constant(value=date_to)
+ sql = (
+ _OPEN_TO_MERGE_SERIES_SELECT.replace("__PR_SOURCE__", curated.pr_source())
+ .replace("__DATE_TO_MERGED__", date_to_clause)
+ .replace("__BUCKET_FN__", bucket_expr(granularity, "merged_at"))
+ )
+ response = curated.run(sql, query_type="engineering_analytics.open_to_merge_series", placeholders=placeholders)
+ p50_by_bucket = {
+ normalize_bucket(bucket_start, granularity): (opt_float(p50) if (n or 0) > 0 else None)
+ for bucket_start, p50, n in response.results or []
+ }
+ buckets = [
+ OpenToMergeBucket(bucket_start=bucket, p50_seconds=p50_by_bucket.get(bucket))
+ for bucket in window_buckets(date_from, date_to, granularity)
+ ]
+ return granularity, buckets
+
+
def query_repo_overview(
*,
curated: CuratedGitHubSource,
@@ -124,6 +219,15 @@ def query_repo_overview(
cost_series_granularity, cost_series = query_cost_per_merge_series(
curated=curated, date_from=date_from, date_to=date_to
)
+ ttg_series_granularity, ttg_series = query_time_to_green_series(
+ curated=curated, date_from=date_from, date_to=date_to
+ )
+ pass_rate_series_granularity, pass_rate_series = query_success_rate_series(
+ curated=curated, date_from=date_from, date_to=date_to
+ )
+ open_to_merge_series_granularity, open_to_merge_series = query_open_to_merge_series(
+ curated=curated, date_from=date_from, date_to=date_to
+ )
return RepoOverview(
run_count=run_count,
@@ -142,4 +246,10 @@ def query_repo_overview(
default_branch=default_branch,
cost_series=cost_series,
cost_series_granularity=cost_series_granularity,
+ time_to_green_series=ttg_series,
+ time_to_green_series_granularity=ttg_series_granularity,
+ success_rate_series=pass_rate_series,
+ success_rate_series_granularity=pass_rate_series_granularity,
+ open_to_merge_series=open_to_merge_series,
+ open_to_merge_series_granularity=open_to_merge_series_granularity,
)
diff --git a/products/engineering_analytics/backend/logic/queries/repo_run_activity.py b/products/engineering_analytics/backend/logic/queries/repo_run_activity.py
index b046c915688d..d44121a34188 100644
--- a/products/engineering_analytics/backend/logic/queries/repo_run_activity.py
+++ b/products/engineering_analytics/backend/logic/queries/repo_run_activity.py
@@ -48,7 +48,8 @@ _SELECT = f"""
min(w.run_started_at) AS run_started_at,
if(countIf(w.status != 'completed') = 0, dateDiff('second', min(w.run_started_at), max(w.updated_at)), NULL)
AS duration_seconds,
- any(w.head_branch) AS head_branch
+ any(w.head_branch) AS head_branch,
+ w.head_sha AS head_sha
FROM (
SELECT
argMax(r.id, r.run_started_at) AS id,
@@ -95,7 +96,7 @@ def query_repo_run_activity(
def _to_point(row: tuple) -> WorkflowRunActivityPoint:
- run_id, conclusion, run_started_at, duration_seconds, head_branch = row
+ run_id, conclusion, run_started_at, duration_seconds, head_branch, head_sha = row
return WorkflowRunActivityPoint(
run_id=int(run_id),
# '' is the in-flight sentinel from the multiIf (not every workflow settled) — normalize to None.
@@ -105,4 +106,5 @@ def _to_point(row: tuple) -> WorkflowRunActivityPoint:
head_branch=head_branch or "",
# Default-branch commits aren't attributed to a single PR — the chart hides the PR line at 0.
pr_number=0,
+ head_sha=head_sha or "",
)
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_health.py b/products/engineering_analytics/backend/logic/queries/workflow_health.py
index ab492dc5e831..7e5a847d1894 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_health.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_health.py
@@ -19,6 +19,7 @@ from posthog.hogql import ast
from products.engineering_analytics.backend.facade.contracts import (
RepoRef,
+ TimeToGreenBucket,
WorkflowHealthBucket,
WorkflowHealthItem,
WorkflowHealthRunScope,
@@ -94,6 +95,49 @@ _BUCKET_SELECT = f"""
"""
+_TIME_TO_GREEN_SELECT = f"""
+ SELECT
+ __BUCKET_FN__ AS bucket_start,
+ quantileIf(0.5)(duration_seconds, {DURATION_PERCENTILE_CONDITION}) AS p50_seconds
+ FROM __RUNS_SOURCE__ AS r
+ WHERE run_started_at >= {{date_from}} __DATE_TO__ __RUN_SCOPE__
+ GROUP BY bucket_start
+ LIMIT {_BUCKET_LIMIT}
+"""
+
+
+def query_time_to_green_series(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+) -> tuple[str, list[TimeToGreenBucket]]:
+ """Median time-to-green per bucket across the window, oldest first: the p50 wall-clock duration of
+ successful, PR-attributed CI runs (default-branch runs excluded). Success-only + PR-scoped — the same
+ population workflow-health's percentiles use — so it answers "how long until CI passes on a PR", not
+ master build time. Empty buckets carry ``p50_seconds`` None (a gap, not instant CI)."""
+ granularity = pick_granularity(date_from, date_to)
+ placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}
+ date_to_clause = date_to_filter_clause(date_to, placeholders)
+ run_scope_clause = run_scope_filter_clause(WorkflowHealthRunScope.PULL_REQUEST)
+ sql = (
+ _TIME_TO_GREEN_SELECT.replace("__RUNS_SOURCE__", curated.run_source())
+ .replace("__DATE_TO__", date_to_clause)
+ .replace("__RUN_SCOPE__", run_scope_clause)
+ .replace("__BUCKET_FN__", bucket_expr(granularity))
+ )
+ response = curated.run(sql, query_type="engineering_analytics.time_to_green_series", placeholders=placeholders)
+ p50_by_bucket = {
+ normalize_bucket(bucket_start, granularity): opt_float(p50_seconds)
+ for bucket_start, p50_seconds in response.results or []
+ }
+ buckets = [
+ TimeToGreenBucket(bucket_start=bucket, p50_seconds=p50_by_bucket.get(bucket))
+ for bucket in window_buckets(date_from, date_to, granularity)
+ ]
+ return granularity, buckets
+
+
def query_workflow_health(
*,
curated: CuratedGitHubSource,
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_run_activity.py b/products/engineering_analytics/backend/logic/queries/workflow_run_activity.py
index 8950ae393c44..c00127e404da 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_run_activity.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_run_activity.py
@@ -31,7 +31,7 @@ _LIMIT = 2000
_SELECT = f"""
SELECT
- id, conclusion, run_started_at, duration_seconds, head_branch, pr_number
+ id, conclusion, run_started_at, duration_seconds, head_branch, pr_number, head_sha
FROM __RUNS_SOURCE__ AS r
WHERE repo_owner = {{repo_owner}} AND repo_name = {{repo_name}} AND workflow_name = {{workflow_name}}
AND run_started_at >= {{date_from}} __DATE_TO__ __BRANCH__
@@ -72,7 +72,7 @@ def query_workflow_run_activity(
def _to_point(row: tuple) -> WorkflowRunActivityPoint:
- run_id, conclusion, run_started_at, duration_seconds, head_branch, pr_number = row
+ run_id, conclusion, run_started_at, duration_seconds, head_branch, pr_number, head_sha = row
return WorkflowRunActivityPoint(
run_id=int(run_id),
# Empty string means "no conclusion yet" (still running) — normalize to None for the contract.
@@ -81,4 +81,5 @@ def _to_point(row: tuple) -> WorkflowRunActivityPoint:
duration_seconds=int(duration_seconds) if duration_seconds is not None else None,
head_branch=head_branch or "",
pr_number=int(pr_number) if pr_number is not None else 0,
+ head_sha=head_sha or "",
)
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index 57816a77acba..3db04493f96a 100644
--- a/products/engineering_analytics/backend/presentation/serializers.py
+++ b/products/engineering_analytics/backend/presentation/serializers.py
@@ -21,12 +21,15 @@ from products.engineering_analytics.backend.facade.contracts import (
FlakyTestList,
GitHubSource,
MasterFailureGroup,
+ OpenToMergeBucket,
+ PassRateBucket,
PRCostSummary,
PRLifecycle,
PRLifecycleEvent,
PullRequest,
PullRequestList,
PullRequestListItem,
+ PushCISample,
QuarantineEntry,
QuarantineFile,
QuarantineRequest,
@@ -35,6 +38,7 @@ from products.engineering_analytics.backend.facade.contracts import (
RepoRef,
RunCost,
RunFailureLogs,
+ TimeToGreenBucket,
WorkflowCost,
WorkflowHealthBucket,
WorkflowHealthItem,
@@ -236,6 +240,7 @@ class WorkflowRunActivityPointSerializer(DataclassSerializer):
},
"head_branch": {"help_text": "Git branch the run was triggered on, or '' when unknown."},
"pr_number": {"help_text": "Attributed pull request number, or 0 when unattributed."},
+ "head_sha": {"help_text": "Head commit SHA of the run/commit, or '' when unknown."},
}
@@ -433,10 +438,33 @@ class CIStatusRollupSerializer(DataclassSerializer):
}
+class PushCISampleSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = PushCISample
+ extra_kwargs = {
+ "head_sha": {"help_text": "Head commit SHA of this push (CI round)."},
+ "started_at": {"help_text": "Earliest workflow-run start on this push."},
+ "wall_seconds": {
+ "help_text": "Wall-clock CI seconds for this push: earliest run start to latest completed "
+ "run end. Null while nothing has completed.",
+ "allow_null": True,
+ },
+ "failed": {
+ "help_text": "True when any latest-per-workflow run on this push concluded 'failure' or 'timed_out'.",
+ },
+ "pending": {"help_text": "True when any latest-per-workflow run on this push hasn't completed yet."},
+ }
+
+
class PullRequestListItemSerializer(DataclassSerializer):
author = AuthorSerializer(help_text="The pull request author.")
repo = RepoRefSerializer(help_text="Repository the pull request belongs to.")
ci = CIStatusRollupSerializer(help_text="CI status from the latest workflow runs on the head SHA.")
+ push_history = PushCISampleSerializer(
+ many=True,
+ help_text="This PR's CI rounds oldest-first, capped to the most recent pushes - one sample per "
+ "push for the push-history sparkline. `pushes` stays the uncapped count.",
+ )
class Meta:
dataclass = PullRequestListItem
@@ -725,12 +753,72 @@ class CostPerMergeBucketSerializer(DataclassSerializer):
}
+class TimeToGreenBucketSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = TimeToGreenBucket
+ extra_kwargs = {
+ "bucket_start": {
+ "help_text": "Bucket start, aligned to time_to_green_series_granularity (top of hour, midnight, or Monday)."
+ },
+ "p50_seconds": {
+ "help_text": "Median wall-clock seconds of successful PR-attributed CI runs started in this bucket. "
+ "Null when the bucket had no successful PR run (a gap, not instant CI).",
+ "allow_null": True,
+ },
+ }
+
+
+class PassRateBucketSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = PassRateBucket
+ extra_kwargs = {
+ "bucket_start": {
+ "help_text": "Bucket start, aligned to success_rate_series_granularity (top of hour, midnight, or Monday)."
+ },
+ "success_rate": {
+ "help_text": "Fraction (0-1) of completed runs started in this bucket that succeeded. "
+ "Null when the bucket had no completed run (a gap, not a 0% pass rate).",
+ "allow_null": True,
+ },
+ }
+
+
+class OpenToMergeBucketSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = OpenToMergeBucket
+ extra_kwargs = {
+ "bucket_start": {
+ "help_text": "Bucket start, aligned to open_to_merge_series_granularity (top of hour, midnight, or Monday)."
+ },
+ "p50_seconds": {
+ "help_text": "Median merged_at - created_at seconds over PRs merged in this bucket, bots and "
+ "drafts excluded. Null when nothing merged in the bucket (a gap, not instant merges).",
+ "allow_null": True,
+ },
+ }
+
+
class RepoOverviewSerializer(DataclassSerializer):
cost_series = CostPerMergeBucketSerializer(
many=True,
help_text="CI cost per merged PR across the window, oldest first, zero-filled, bucketed by "
"cost_series_granularity. Empty when the job-level source isn't synced.",
)
+ time_to_green_series = TimeToGreenBucketSerializer(
+ many=True,
+ help_text="Median time-to-green (p50 successful PR-attributed CI run duration) per bucket across the "
+ "window, oldest first, bucketed by time_to_green_series_granularity. Empty buckets carry null.",
+ )
+ success_rate_series = PassRateBucketSerializer(
+ many=True,
+ help_text="CI pass rate (completed runs that succeeded, all branches) per bucket across the window, "
+ "oldest first, bucketed by success_rate_series_granularity. Empty buckets carry null.",
+ )
+ open_to_merge_series = OpenToMergeBucketSerializer(
+ many=True,
+ help_text="Median time-to-merge (p50 open_to_merge_seconds, bots/drafts excluded) per bucket across "
+ "the window, oldest first, bucketed by open_to_merge_series_granularity. Empty buckets carry null.",
+ )
class Meta:
dataclass = RepoOverview
@@ -781,6 +869,15 @@ class RepoOverviewSerializer(DataclassSerializer):
"cost_series_granularity": {
"help_text": "Bucket width of the cost_series trend, chosen to fit the window: 'hour', 'day', or 'week'."
},
+ "time_to_green_series_granularity": {
+ "help_text": "Bucket width of the time_to_green_series trend: 'hour', 'day', or 'week'."
+ },
+ "success_rate_series_granularity": {
+ "help_text": "Bucket width of the success_rate_series trend: 'hour', 'day', or 'week'."
+ },
+ "open_to_merge_series_granularity": {
+ "help_text": "Bucket width of the open_to_merge_series trend: 'hour', 'day', or 'week'."
+ },
}
diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.py
index c12b8209df82..c346ba1de649 100644
--- a/products/engineering_analytics/backend/tests/test_logic.py
+++ b/products/engineering_analytics/backend/tests/test_logic.py
@@ -62,6 +62,18 @@ def _resp(results: list[tuple]) -> SimpleNamespace:
return SimpleNamespace(results=results)
+def _pr_list_run(rows: list[tuple], push_rows: list[tuple] | None = None):
+ """Mocked ``curated.run`` for the PR-list path, which now issues two queries: the list
+ query returns ``rows``; the scoped push-history query returns ``push_rows``."""
+
+ def run(sql: str, *, query_type: str, **kwargs) -> SimpleNamespace:
+ if query_type == "engineering_analytics.pr_push_history":
+ return _resp(push_rows or [])
+ return _resp(rows)
+
+ return run
+
+
def _dt(value: str) -> datetime:
return datetime.fromisoformat(value).replace(tzinfo=UTC)
@@ -284,7 +296,13 @@ class TestEndpointMapping(BaseTest):
5,
2,
)
- with mock.patch(_RUN_QUERY, return_value=_resp([row])):
+ # The query returns newest-first (its per-PR LIMIT BY keeps the most recent pushes); the mapper
+ # reverses to the oldest-first contract, so the mock is ordered newest-first to match.
+ push_rows = [
+ ("PostHog", "posthog", 10, "sha-new", _dt("2026-01-11T10:00:00"), None, 0, 1),
+ ("PostHog", "posthog", 10, "sha-old", _dt("2026-01-10T10:00:00"), 900, 1, 0),
+ ]
+ with mock.patch(_RUN_QUERY, side_effect=_pr_list_run([row], push_rows)):
result = api.list_pull_requests(team=self.team, date_from="-30d")
assert result.truncated is False
@@ -300,6 +318,10 @@ class TestEndpointMapping(BaseTest):
assert item.ci.failing_workflows == ["E2E CI"]
assert (item.pushes, item.rerun_cycles) == (5, 2)
assert item.estimated_cost_usd is None
+ assert [(p.head_sha, p.wall_seconds, p.failed, p.pending) for p in item.push_history] == [
+ ("sha-old", 900, True, False),
+ ("sha-new", None, False, True),
+ ]
def test_pull_request_list_flags_truncation(self) -> None:
# Cap patched low; return more rows than the cap to exercise the N+1 overflow
@@ -326,7 +348,10 @@ class TestEndpointMapping(BaseTest):
0,
0,
)
- with mock.patch(f"{_PR_LIST}._LIMIT", 2), mock.patch(_RUN_QUERY, return_value=_resp([row, row, row])):
+ with (
+ mock.patch(f"{_PR_LIST}._LIMIT", 2),
+ mock.patch(_RUN_QUERY, side_effect=_pr_list_run([row, row, row])),
+ ):
result = api.list_pull_requests(team=self.team, date_from="-30d")
assert result.truncated is True
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 754d26c2a80b..3da7127e8482 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -212,6 +212,7 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
duration_seconds=180,
head_branch="main",
pr_number=0,
+ head_sha="a1b2c3d4e5f60718293a4b5c6d7e8f9012345678",
)
],
truncated=False,
diff --git a/products/engineering_analytics/frontend/components/CIStatusTag.tsx b/products/engineering_analytics/frontend/components/CIStatusTag.tsx
index 027bb8bc889d..8b1f4607de5f 100644
--- a/products/engineering_analytics/frontend/components/CIStatusTag.tsx
+++ b/products/engineering_analytics/frontend/components/CIStatusTag.tsx
@@ -1,14 +1,7 @@
import { IconCheck, IconClock, IconX } from '@posthog/icons'
-import { LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'
+import { LemonTag, Tooltip } from '@posthog/lemon-ui'
-import { CIRollup, CIStatus, ciStatusOf } from '../lib/ci'
-
-const STATUS_CONFIG: Record<CIStatus, { label: string; type: LemonTagType }> = {
- passing: { label: 'Passing', type: 'success' },
- failing: { label: 'Failing', type: 'danger' },
- running: { label: 'Running', type: 'warning' },
- none: { label: 'No CI', type: 'muted' },
-}
+import { CIRollup } from '../lib/ci'
function Count({ count, icon, className }: { count: number; icon: JSX.Element; className: string }): JSX.Element {
return (
@@ -19,28 +12,21 @@ function Count({ count, icon, className }: { count: number; icon: JSX.Element; c
)
}
+// Just the run tallies — passed / failed / still-running — as colored icon counts. At row height the marks
+// carry the state, so there's no word label; the tooltip has the detail. "No CI" is the one case with no marks.
export function CIStatusTag({ rollup }: { rollup: CIRollup }): JSX.Element {
- const config = STATUS_CONFIG[ciStatusOf(rollup)]
+ if (rollup.runs === 0) {
+ return <LemonTag type="muted">No CI</LemonTag>
+ }
return (
- <div className="flex items-center gap-2">
- <LemonTag type={config.type}>{config.label}</LemonTag>
- {rollup.runs > 0 && (
- <Tooltip
- title={`${rollup.passing} passed, ${rollup.failing} failed, ${rollup.pending} still running. Workflow-level status for the PR's latest commit, not per-check.`}
- >
- <span className="flex items-center gap-1.5">
- {rollup.passing > 0 && (
- <Count count={rollup.passing} icon={<IconCheck />} className="text-success" />
- )}
- {rollup.failing > 0 && (
- <Count count={rollup.failing} icon={<IconX />} className="text-danger" />
- )}
- {rollup.pending > 0 && (
- <Count count={rollup.pending} icon={<IconClock />} className="text-secondary" />
- )}
- </span>
- </Tooltip>
- )}
- </div>
+ <Tooltip
+ title={`${rollup.passing} passed, ${rollup.failing} failed, ${rollup.pending} still running. Workflow-level status for the PR's latest commit, not per-check.`}
+ >
+ <span className="flex items-center gap-1.5">
+ {rollup.passing > 0 && <Count count={rollup.passing} icon={<IconCheck />} className="text-success" />}
+ {rollup.failing > 0 && <Count count={rollup.failing} icon={<IconX />} className="text-danger" />}
+ {rollup.pending > 0 && <Count count={rollup.pending} icon={<IconClock />} className="text-secondary" />}
+ </span>
+ </Tooltip>
)
}
diff --git a/products/engineering_analytics/frontend/components/EntityHeader.tsx b/products/engineering_analytics/frontend/components/EntityHeader.tsx
index c1fad97c97b2..2da173e94eab 100644
--- a/products/engineering_analytics/frontend/components/EntityHeader.tsx
+++ b/products/engineering_analytics/frontend/components/EntityHeader.tsx
@@ -2,6 +2,9 @@
import { ReactNode } from 'react'
+import { IconBox } from '@posthog/icons'
+import { Link } from '@posthog/lemon-ui'
+
import { cn } from 'lib/utils/css-classes'
export type VerdictKind = 'success' | 'danger' | 'warning' | 'muted'
@@ -39,6 +42,32 @@ export function VerdictPill({ kind, children }: { kind: VerdictKind; children: R
)
}
+/** The repo's identity header, shared across the hub and secondary tabs so the subject reads the same
+ * everywhere: box icon · repo name · owner/name slug with a GitHub link. `right` docks the source
+ * picker on multi-source teams. */
+export function RepoEntityHeader({ repoFullName, right }: { repoFullName: string; right?: ReactNode }): JSX.Element {
+ const name = repoFullName.split('/')[1] || repoFullName || 'GitHub repository'
+ return (
+ <EntityHeader
+ icon={<IconBox />}
+ title={name}
+ // No slug line when the source hasn't reported a repo name yet.
+ slug={
+ repoFullName ? (
+ <>
+ {repoFullName}
+ {' · '}
+ <Link to={`https://github.com/${repoFullName}`} target="_blank" targetBlankIcon>
+ View on GitHub
+ </Link>
+ </>
+ ) : undefined
+ }
+ right={right}
+ />
+ )
+}
+
export function EntityHeader({
icon,
title,
diff --git a/products/engineering_analytics/frontend/components/JobAggregatesTable.tsx b/products/engineering_analytics/frontend/components/JobAggregatesTable.tsx
index 2ed333b2797e..a66fad438a64 100644
--- a/products/engineering_analytics/frontend/components/JobAggregatesTable.tsx
+++ b/products/engineering_analytics/frontend/components/JobAggregatesTable.tsx
@@ -14,6 +14,38 @@ function formatSeconds(seconds: number | null): string {
return seconds == null ? '—' : humanFriendlyDuration(seconds)
}
+/** The p50→p95 duration spread as a small bar, scaled to the slowest job so rows compare at a glance.
+ * Solid segment reaches the median (p50); the lighter extension is the tail out to p95 — a long light
+ * tail is a job whose worst case dwarfs its typical case. Two raw numbers ("3m … 20m") don't show that. */
+function DurationSpread({ p50, p95, max }: { p50: number | null; p95: number | null; max: number }): JSX.Element {
+ if (p50 == null && p95 == null) {
+ return <span className="text-xs text-tertiary">—</span>
+ }
+ const tail = p95 ?? p50 ?? 0
+ const median = p50 ?? tail
+ const tailPct = Math.min(100, Math.max(2, (tail / max) * 100))
+ const medianPct = Math.min(100, Math.max(1, (median / max) * 100))
+ return (
+ <Tooltip title={`median ${formatSeconds(p50)} · p95 ${formatSeconds(p95)}`}>
+ <div className="flex items-center gap-2">
+ <div className="relative h-1.5 w-24 shrink-0 overflow-hidden rounded-full bg-fill-tertiary">
+ <span
+ className="absolute inset-y-0 left-0 rounded-full opacity-30"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: `${tailPct}%`, backgroundColor: 'var(--data-color-1)' }}
+ />
+ <span
+ className="absolute inset-y-0 left-0 rounded-full"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: `${medianPct}%`, backgroundColor: 'var(--data-color-1)' }}
+ />
+ </div>
+ <span className="text-xs tabular-nums whitespace-nowrap text-tertiary">{formatSeconds(p50)}</span>
+ </div>
+ </Tooltip>
+ )
+}
+
export function JobAggregatesTable({
aggregates,
loading,
@@ -24,6 +56,8 @@ export function JobAggregatesTable({
/** The workflow's total window cost — the denominator of each job's cost share. */
totalCostUsd: number | null
}): JSX.Element {
+ // Scale every duration bar to the slowest job's p95, so bar lengths compare directly across rows.
+ const maxP95 = Math.max(1, ...aggregates.map((a) => a.p95_seconds ?? a.p50_seconds ?? 0))
return (
<LemonTable<WorkflowJobAggregateApi>
dataSource={aggregates}
@@ -74,26 +108,12 @@ export function JobAggregatesTable({
),
},
{
- title: 'P50',
+ title: 'Duration',
key: 'duration',
- align: 'right',
- tooltip: 'Median job duration over completed instances.',
+ tooltip:
+ 'Median (p50) out to 95th-percentile duration over successful instances, as a bar scaled to the slowest job. The solid part reaches the median; the light tail runs out to p95.',
sorter: (a, b) => (a.p50_seconds ?? -1) - (b.p50_seconds ?? -1),
- render: (_, row) => (
- <span className="text-xs tabular-nums whitespace-nowrap">{formatSeconds(row.p50_seconds)}</span>
- ),
- },
- {
- title: 'P95',
- key: 'p95',
- align: 'right',
- tooltip: '95th-percentile job duration over completed instances.',
- sorter: (a, b) => (a.p95_seconds ?? -1) - (b.p95_seconds ?? -1),
- render: (_, row) => (
- <span className="text-xs tabular-nums whitespace-nowrap text-secondary">
- {formatSeconds(row.p95_seconds)}
- </span>
- ),
+ render: (_, row) => <DurationSpread p50={row.p50_seconds} p95={row.p95_seconds} max={maxP95} />,
},
{
title: 'Failure rate',
@@ -152,7 +172,7 @@ export function JobAggregatesTable({
},
]}
defaultSorting={{ columnKey: 'cost', order: -1 }}
- pagination={{ pageSize: 50 }}
+ pagination={{ pageSize: 25 }}
emptyState="No jobs in the window. The job-level source may not be synced."
nouns={['job', 'jobs']}
/>
diff --git a/products/engineering_analytics/frontend/components/MetricTile.tsx b/products/engineering_analytics/frontend/components/MetricTile.tsx
index 92b5293634f3..57817b6bb266 100644
--- a/products/engineering_analytics/frontend/components/MetricTile.tsx
+++ b/products/engineering_analytics/frontend/components/MetricTile.tsx
@@ -4,7 +4,7 @@
import { ReactNode } from 'react'
-import { Tooltip } from '@posthog/lemon-ui'
+import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
import { MetricCard, type MetricChange } from '@posthog/quill-charts'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
@@ -99,6 +99,7 @@ export function MetricTile({
value,
delta,
sub,
+ loading = false,
className,
}: {
label: string
@@ -109,6 +110,9 @@ export function MetricTile({
delta?: TileDelta
/** Visible caption — only for an answer worth a glance (what's failing, why there's no value). */
sub?: ReactNode
+ /** Backend load in flight: skeleton the value so it doesn't flash a stale/zero number. Only for a
+ * genuine reload — client-side-instant derivations should never pass this. */
+ loading?: boolean
className?: string
}): JSX.Element {
const labelNode = tooltip ? (
@@ -123,17 +127,26 @@ export function MetricTile({
hoverEffect={false}
className={cn('flex min-w-44 flex-1 flex-col justify-center px-5 py-4', className)}
>
- <MetricCard
- title={labelNode}
- // These tiles have no series data and often a non-numeric headline ("3 / 5", "2h 10m"),
- // so the pre-formatted display string rides through MetricCard's formatter.
- value={0}
- formatValue={() => value}
- change={deltaToChange(delta)}
- goodDirection={delta?.goodWhenDown ? 'down' : 'up'}
- changeTooltip={delta ? (delta.vs ?? 'vs the previous window') : undefined}
- subtitle={sub}
- />
+ {/* MetricCard has no loading prop; skeleton the whole tile on a genuine reload so it never
+ flashes a stale/zero headline (the loading-states rule). */}
+ {loading ? (
+ <div className="flex flex-col gap-2 py-1">
+ <LemonSkeleton className="h-3 w-24" />
+ <LemonSkeleton className="h-7 w-20" />
+ </div>
+ ) : (
+ <MetricCard
+ title={labelNode}
+ // These tiles have no series data and often a non-numeric headline ("3 / 5", "2h 10m"),
+ // so the pre-formatted display string rides through MetricCard's formatter.
+ value={0}
+ formatValue={() => value}
+ change={deltaToChange(delta)}
+ goodDirection={delta?.goodWhenDown ? 'down' : 'up'}
+ changeTooltip={delta ? (delta.vs ?? 'vs the previous window') : undefined}
+ subtitle={sub}
+ />
+ )}
</LemonCard>
)
}
diff --git a/products/engineering_analytics/frontend/components/PullRequestTable.tsx b/products/engineering_analytics/frontend/components/PullRequestTable.tsx
index 4bb7d15cf5d8..ecdfc23c31cf 100644
--- a/products/engineering_analytics/frontend/components/PullRequestTable.tsx
+++ b/products/engineering_analytics/frontend/components/PullRequestTable.tsx
@@ -12,12 +12,14 @@ import { newInternalTab } from 'lib/utils/newInternalTab'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
-import { compactHoursLabel } from '../lib/format'
+import { compactAgeLabel, compactHoursLabel } from '../lib/format'
import { githubPrUrl } from '../lib/github'
+import { pushRoundFromSample } from '../lib/pushRounds'
import { PullRequestRow, prKeyOf } from '../scenes/engineeringAnalyticsLogic'
import { BillableBadge } from './BillableBadge'
import { CIStatusTag } from './CIStatusTag'
import { PullRequestStateTag } from './PullRequestStateTag'
+import { PushHistorySparkline } from './PushHistorySparkline'
/** The PR's detail page, carrying the active source so it opens scoped to the same one. */
function detailUrlOf(row: PullRequestRow, sourceId: string | null): string {
@@ -43,11 +45,11 @@ export interface PullRequestTableProps {
loading: boolean
/** Threaded into row links so the PR's detail page reads the same source. */
sourceId: string | null
- /** Show the pushes / re-runs / CI cost columns. */
- costLensEnabled: boolean
/** Author column is redundant on the author page (every row is the same author) — hide it there. */
showAuthor?: boolean
- /** Rows per page — the list page's 50 by default; the hub passes a small page to stay scannable. */
+ /** Show the Created date column and default the sort to newest-first. Off for the hub's triage order. */
+ showCreated?: boolean
+ /** Rows per page — the list page's 25 by default; the hub passes a small page to stay scannable. */
pageSize?: number
emptyState?: ReactNode
dataAttr?: string
@@ -59,9 +61,9 @@ export function PullRequestTable({
rows,
loading,
sourceId,
- costLensEnabled,
showAuthor = true,
- pageSize = 50,
+ showCreated = false,
+ pageSize = 25,
emptyState,
dataAttr = 'engineering-analytics-pr-table',
embedded = false,
@@ -80,9 +82,9 @@ export function PullRequestTable({
to={githubPrUrl(row.repoOwner, row.repoName, row.number)}
target="_blank"
targetBlankIcon
- className="font-mono text-[11px] text-tertiary"
+ className="font-mono text-[11px] text-tertiary hover:text-accent"
>
- {row.repoOwner}/{row.repoName} #{row.number}
+ #{row.number}
</Link>
{row.labels.slice(0, 3).map((label) => (
<LemonTag key={label} type="option">
@@ -130,67 +132,80 @@ export function PullRequestTable({
{
title: 'CI',
key: 'ci',
- width: 190,
+ width: 120,
+ render: (_, row) => <CIStatusTag rollup={row} />,
+ },
+ {
+ title: 'Pushes',
+ key: 'pushes',
+ width: 170,
+ align: 'right',
+ tooltip:
+ 'One bar per push (distinct head commit that triggered CI), oldest first: height is that push’s wall-clock CI time, red means it went red. Re-run cycles are the amber tag. Fork PRs are unattributed.',
+ sorter: (a, b) => a.pushes - b.pushes,
render: (_, row) => (
- <div className="flex flex-col gap-0.5">
- <CIStatusTag rollup={row} />
- {row.failingWorkflows.length > 0 && (
- <span className="text-[10.5px] leading-tight text-tertiary">
- {row.failingWorkflows.slice(0, 3).join(' · ')}
- {row.failingWorkflows.length > 3 && ` +${row.failingWorkflows.length - 3}`}
- </span>
- )}
+ <div className="flex items-center justify-end gap-2">
+ <PushHistorySparkline
+ rounds={row.pushHistory.map(pushRoundFromSample)}
+ minSlots={10}
+ className="w-24 shrink-0"
+ ariaLabel={`Push CI history for pull request #${row.number}`}
+ />
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ {humanFriendlyNumber(row.pushes)}
+ {row.rerunCycles > 0 && (
+ <LemonTag type="warning" className="ml-1.5">
+ +{row.rerunCycles}
+ </LemonTag>
+ )}
+ </span>
</div>
),
},
- ...(costLensEnabled
+ {
+ title: 'CI cost',
+ key: 'estimatedCostUsd',
+ width: 130,
+ align: 'right',
+ tooltip:
+ '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} />,
+ },
+ ...(showCreated
? ([
{
- title: 'Pushes',
- key: 'pushes',
- width: 100,
+ title: 'Created',
+ key: 'created',
+ width: 0,
align: 'right',
- tooltip:
- 'Distinct head commits that triggered CI for this PR, with re-run cycles as the amber tag. Fork PRs are unattributed.',
- sorter: (a, b) => a.pushes - b.pushes,
+ sorter: (a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt),
render: (_, row) => (
- <span className="text-xs tabular-nums whitespace-nowrap">
- {humanFriendlyNumber(row.pushes)}
- {row.rerunCycles > 0 && (
- <LemonTag type="warning" className="ml-1.5">
- +{row.rerunCycles}
- </LemonTag>
- )}
- </span>
+ <Tooltip title={dayjs(row.createdAt).format('MMM D, YYYY HH:mm')}>
+ <span className="text-xs tabular-nums whitespace-nowrap text-secondary">
+ {compactAgeLabel(dayjs().diff(dayjs(row.createdAt), 'second'))} ago
+ </span>
+ </Tooltip>
),
},
+ ] as LemonTableColumns<PullRequestRow>)
+ : ([
{
- title: 'CI cost',
- key: 'estimatedCostUsd',
- width: 130,
+ title: 'Open time',
+ key: 'age',
+ width: 100,
align: 'right',
- tooltip:
- '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),
+ tooltip: 'How long the pull request has been open (or was, until it merged).',
+ sorter: (a, b) => (openTimeOf(a)?.seconds ?? -1) - (openTimeOf(b)?.seconds ?? -1),
render: (_, row) => (
- <BillableBadge minutes={row.billableMinutes} costUsd={row.estimatedCostUsd} />
+ <Tooltip title={<>opened {dayjs(row.createdAt).format('MMM D, HH:mm')}</>}>
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ {openTimeOf(row)?.label ?? '—'}
+ </span>
+ </Tooltip>
),
},
- ] as LemonTableColumns<PullRequestRow>)
- : []),
- {
- title: 'Open time',
- key: 'age',
- width: 100,
- align: 'right',
- tooltip: 'How long the pull request has been open (or was, until it merged).',
- sorter: (a, b) => (openTimeOf(a)?.seconds ?? -1) - (openTimeOf(b)?.seconds ?? -1),
- render: (_, row) => (
- <Tooltip title={<>opened {dayjs(row.createdAt).format('MMM D, HH:mm')}</>}>
- <span className="text-xs tabular-nums whitespace-nowrap">{openTimeOf(row)?.label ?? '—'}</span>
- </Tooltip>
- ),
- },
+ ] as LemonTableColumns<PullRequestRow>)),
]
return (
@@ -226,6 +241,7 @@ export function PullRequestTable({
}
}}
useURLForSorting={false}
+ defaultSorting={showCreated ? { columnKey: 'created', order: -1 } : null}
pagination={{ pageSize }}
emptyState={emptyState ?? "No pull requests yet. They'll appear once the GitHub source syncs."}
nouns={['pull request', 'pull requests']}
diff --git a/products/engineering_analytics/frontend/components/PushHistorySparkline.tsx b/products/engineering_analytics/frontend/components/PushHistorySparkline.tsx
new file mode 100644
index 000000000000..4dd6365efd97
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/PushHistorySparkline.tsx
@@ -0,0 +1,90 @@
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+
+import { PushRound, pushRoundColor, pushRoundVerdictLabel } from '../lib/pushRounds'
+
+export interface PushHistorySparklineProps {
+ /** CI rounds oldest first — one bar per push. */
+ rounds: PushRound[]
+ /** Accessible name for the chart (role="img"); screen readers can't read the per-bar titles. */
+ ariaLabel?: string
+ /** Minimum bar slots; fewer pushes right-align as narrow bars instead of stretching fat. */
+ minSlots?: number
+ className?: string
+}
+
+// Same unit-grid-on-a-dotted-baseline language as FailureSparkline, but each bar is one push:
+// height = that push's wall-clock CI time (scaled to the slowest push), color = its verdict.
+const VIEW_HEIGHT = 100
+const BASELINE_Y = 96
+const TOP_PAD = 6
+// A push with runs is always a visible tick, even when its wall time rounds to nothing.
+const MIN_BAR_HEIGHT = 10
+const BAR_INSET = 0.18
+
+/**
+ * Push-history sparkline: one bar per CI round on a PR, oldest first. Bar height reads as "how long
+ * CI took on that push", color as "did it go red". Renders nothing without rounds, so callers can
+ * drop it in unconditionally.
+ */
+export function PushHistorySparkline({
+ rounds,
+ ariaLabel = 'Push CI history',
+ minSlots,
+ className,
+}: PushHistorySparklineProps): JSX.Element | null {
+ if (rounds.length === 0) {
+ return null
+ }
+ const maxWall = Math.max(...rounds.map((round) => round.wallSeconds ?? 0), 1)
+ const usableHeight = BASELINE_Y - TOP_PAD
+ const slots = Math.max(rounds.length, minSlots ?? 0, 1)
+ const offset = slots - rounds.length
+
+ return (
+ <svg
+ className={cn('h-7 w-full overflow-visible', className)}
+ viewBox={`0 0 ${slots} ${VIEW_HEIGHT}`}
+ preserveAspectRatio="none"
+ role="img"
+ aria-label={ariaLabel}
+ >
+ <line
+ x1={0}
+ y1={BASELINE_Y}
+ x2={slots}
+ y2={BASELINE_Y}
+ stroke="var(--muted)"
+ strokeWidth={1}
+ strokeDasharray="1 2"
+ vectorEffect="non-scaling-stroke"
+ />
+ {rounds.map((round, i) => {
+ const barHeight =
+ round.wallSeconds != null
+ ? Math.max(MIN_BAR_HEIGHT, (round.wallSeconds / maxWall) * usableHeight)
+ : MIN_BAR_HEIGHT
+ const label = `${round.headSha.slice(0, 7)} · ${
+ round.wallSeconds != null ? humanFriendlyDuration(round.wallSeconds) : 'no completed runs'
+ } · ${pushRoundVerdictLabel(round)}`
+ return (
+ <g key={round.headSha || i}>
+ <rect
+ x={offset + i + BAR_INSET}
+ y={BASELINE_Y - barHeight}
+ width={1 - BAR_INSET * 2}
+ height={barHeight}
+ fill={pushRoundColor(round)}
+ fillOpacity={round.failed ? 1 : round.pending ? 0.9 : 0.55}
+ className={cn(round.pending && 'animate-pulse')}
+ />
+ {/* Full-height transparent hit area so hovering a short bar still shows its title. */}
+ <rect x={offset + i} y={0} width={1} height={VIEW_HEIGHT} fill="transparent">
+ <title>{label}</title>
+ </rect>
+ </g>
+ )
+ })}
+ </svg>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/RunActivityChart.tsx b/products/engineering_analytics/frontend/components/RunActivityChart.tsx
index 08313cd21d9f..99d126f293a0 100644
--- a/products/engineering_analytics/frontend/components/RunActivityChart.tsx
+++ b/products/engineering_analytics/frontend/components/RunActivityChart.tsx
@@ -10,7 +10,7 @@ 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'
+import { VERDICT_COLOR, 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.
@@ -21,6 +21,7 @@ export interface ActivityRun {
durationSeconds: number | null
headBranch?: string | null
prNumber?: number | null
+ headSha?: string | null
}
interface RunActivityChartProps {
@@ -34,13 +35,8 @@ interface RunActivityChartProps {
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)',
-}
+// Dot/series color per verdict — the shared map so scatter, mini bars, and the run tables' StatusDot agree.
+const DOT_COLOR = VERDICT_COLOR
const LEGEND_LABEL: Record<string, string> = {
success: 'Passed',
@@ -58,7 +54,7 @@ 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
-const isPlottable = (run: ActivityRun): run is ActivityRun & { startedAt: string; durationSeconds: number } =>
+export const isPlottable = (run: ActivityRun): run is ActivityRun & { startedAt: string; durationSeconds: number } =>
run.startedAt != null && run.durationSeconds != null && run.durationSeconds >= 0
/** False when RunActivityChart would render null, so callers can show their empty state instead. */
@@ -87,7 +83,7 @@ function niceStep(rough: number): number {
}
/** Compact minutes label for the duration axis: "45m", "1h", "1h 30m". */
-function formatAxisMinutes(min: number): string {
+export function formatAxisMinutes(min: number): string {
const rounded = Math.round(min)
if (rounded < 60) {
return `${rounded}m`
diff --git a/products/engineering_analytics/frontend/components/RunActivityMiniBars.tsx b/products/engineering_analytics/frontend/components/RunActivityMiniBars.tsx
new file mode 100644
index 000000000000..39ca7b9635c7
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/RunActivityMiniBars.tsx
@@ -0,0 +1,136 @@
+import { type KeyboardEvent as ReactKeyboardEvent } from 'react'
+
+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 { percentileSorted } from '../lib/runHealth'
+import { VERDICT_COLOR, verdictTag } from '../lib/runStatus'
+import { type ActivityRun, formatAxisMinutes, isPlottable } from './RunActivityChart'
+
+interface RunActivityMiniBarsProps {
+ runs: ActivityRun[]
+ title?: string
+ /** The runs list was capped server-side, so the strip shows the most recent runs, not the full window. */
+ truncated?: boolean
+ /** Singular noun for each bar in the header count — 'run' by default, 'commit' on the repo-health view. */
+ noun?: string
+ /** When set, each bar becomes a button that calls this with its run — e.g. to open that commit's run. */
+ onBarClick?: (run: ActivityRun) => void
+ className?: string
+}
+
+const CHART_HEIGHT = 52
+const MIN_BAR_PX = 3
+// A hub preview, not the full record — keep the strip short so each bar stays legible. The full scatter
+// (start-time axis, in-flight band, zoom) lives on the workflow page for anyone who wants every run.
+const MAX_BARS = 48
+
+/**
+ * A compact, scannable version of {@link RunActivityChart} for hub previews: one bar per run, height =
+ * CI duration, color = verdict, with a dashed median line. Drops the scatter's time axis, in-flight band,
+ * and zoom brush. Renders nothing below 2 completed runs, so callers can drop it in unconditionally.
+ */
+export function RunActivityMiniBars({
+ runs,
+ title = 'Run activity',
+ truncated = false,
+ noun = 'run',
+ onBarClick,
+ className,
+}: RunActivityMiniBarsProps): JSX.Element | null {
+ const plottable = runs.filter(isPlottable)
+ if (plottable.length < 2) {
+ return null
+ }
+
+ // Oldest → newest so the strip reads left-to-right as a trend, then keep the most recent MAX_BARS.
+ const ordered = [...plottable].sort((a, b) => dayjs(a.startedAt).valueOf() - dayjs(b.startedAt).valueOf())
+ const shown = ordered.slice(-MAX_BARS)
+ const capped = truncated || shown.length < plottable.length
+
+ // Median over the full set (not just the shown bars), so it agrees with the scatter and the KPI tiles.
+ const sortedMin = plottable.map((run) => run.durationSeconds / 60).sort((a, b) => a - b)
+ const medianMin = percentileSorted(sortedMin, 0.5) ?? 0
+
+ const maxSeconds = Math.max(...shown.map((run) => run.durationSeconds))
+ const barHeight = (seconds: number): number =>
+ maxSeconds > 0 ? Math.max(MIN_BAR_PX, Math.round((seconds / maxSeconds) * CHART_HEIGHT)) : MIN_BAR_PX
+ const medianTopPx = maxSeconds > 0 ? CHART_HEIGHT * (1 - Math.min((medianMin * 60) / maxSeconds, 1)) : CHART_HEIGHT
+
+ 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>
+ <span className="text-xs whitespace-nowrap text-secondary tabular-nums">
+ {capped ? 'recent ' : ''}
+ {shown.length} {noun}s
+ </span>
+ </div>
+ <LemonCard hoverEffect={false} className="p-4">
+ <div className="relative flex items-end gap-px" style={{ height: CHART_HEIGHT }}>
+ <div
+ className="absolute inset-x-0 border-t border-dashed border-secondary"
+ style={{ top: medianTopPx }}
+ />
+ {/* Labels the dashed line and, by naming a duration, signals that bar height is CI time —
+ the job the dropped Y axis used to do. Anchored left: no Y axis here, so the eye meets
+ it first (left-to-right) and reads the line's meaning before scanning the bars. */}
+ <span
+ className="absolute left-0 z-10 -translate-y-1/2 rounded bg-surface-primary px-1 text-[9px] text-secondary"
+ style={{ top: Math.max(6, medianTopPx) }}
+ >
+ median {formatAxisMinutes(medianMin)}
+ </span>
+ {shown.map((run, i) => {
+ const tag = verdictTag(run.conclusion)
+ const color = VERDICT_COLOR[tag.type] ?? VERDICT_COLOR.muted
+ return (
+ <Tooltip
+ key={`${run.runId ?? 'run'}-${i}`}
+ delayMs={60}
+ placement="top"
+ title={
+ <div className="flex flex-col gap-0.5 text-xs">
+ <span className="font-semibold" style={{ color }}>
+ {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>
+ }
+ >
+ <div
+ className={cn(
+ 'min-w-[3px] flex-1 rounded-t-sm opacity-75 transition-opacity hover:opacity-100',
+ onBarClick && 'cursor-pointer'
+ )}
+ style={{ height: barHeight(run.durationSeconds), background: color }}
+ {...(onBarClick
+ ? {
+ role: 'button',
+ tabIndex: 0,
+ 'aria-label': `Open ${dayjs(run.startedAt).format('MMM D, HH:mm')} ${noun}`,
+ onClick: () => onBarClick(run),
+ onKeyDown: (e: ReactKeyboardEvent) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ onBarClick(run)
+ }
+ },
+ }
+ : {})}
+ />
+ </Tooltip>
+ )
+ })}
+ </div>
+ </LemonCard>
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/ScopeBar.tsx b/products/engineering_analytics/frontend/components/ScopeBar.tsx
index cc4fc83e771e..42ac946cc815 100644
--- a/products/engineering_analytics/frontend/components/ScopeBar.tsx
+++ b/products/engineering_analytics/frontend/components/ScopeBar.tsx
@@ -3,7 +3,7 @@
// one page carries to the next.
import { useActions, useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
+import { router } from 'kea-router'
import { Fragment, ReactNode, useState } from 'react'
import { IconX } from '@posthog/icons'
@@ -14,6 +14,7 @@ import { cn } from 'lib/utils/css-classes'
import { dateMapping } from 'lib/utils/dateFilters'
import { urls } from 'scenes/urls'
+import { withScope } from '../lib/scope'
import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from '../scenes/engineeringAnalyticsFiltersLogic'
import { engineeringAnalyticsLogic } from '../scenes/engineeringAnalyticsLogic'
import { workflowSwitcherLogic } from '../scenes/workflowSwitcherLogic'
@@ -116,10 +117,11 @@ export function WorkflowScopeChip({
setSearch('')
if (name !== workflowName) {
router.actions.push(
- combineUrl(
+ withScope(
urls.engineeringAnalyticsWorkflowRuns(repoOwner, repoName, name),
- sourceId ? { source: sourceId } : {}
- ).url
+ router.values.currentLocation.searchParams,
+ sourceId
+ )
)
}
}
@@ -185,30 +187,24 @@ export function WorkflowScopeChip({
)
}
-// Quick presets for the default branch. We can't tell main from master without another query, so offer
-// both — picking the active one clears back to all branches.
-const DEFAULT_BRANCHES = ['main', 'master']
-
-/** Branch chip opening a small picker — a server-side head_branch filter shared across pages. */
-function BranchScopeChip(): JSX.Element {
- const { branchInput, appliedBranch } = useValues(engineeringAnalyticsFiltersLogic)
- const { setBranchFilter, applyBranchFilter } = useActions(engineeringAnalyticsFiltersLogic)
+/** Branch chip opening a small picker — a shared CI scope: an exact head_branch, all branches, or the
+ * pull-request lens (non-default-branch runs). Only workflow health honors the PR lens; exact-branch
+ * surfaces fall back to all branches for it. No default-branch preset — the repo's default (master vs
+ * main) isn't known here, so type it exactly instead of guessing. */
+export function BranchScopeChip(): JSX.Element {
+ const { branchInput, appliedBranch, pullRequestScope } = useValues(engineeringAnalyticsFiltersLogic)
+ const { setBranchFilter, applyBranchFilter, setAppliedBranch, scopeToPullRequests } = useActions(
+ engineeringAnalyticsFiltersLogic
+ )
const [visible, setVisible] = useState(false)
- // Stage + apply a branch in one click; picking the active preset clears back to all branches.
- const selectBranch = (branch: string): void => {
- setBranchFilter(branch)
- applyBranchFilter()
- setVisible(false)
- }
-
return (
<LemonDropdown
visible={visible}
onVisibilityChange={setVisible}
closeOnClickInside={false}
overlay={
- <div className="flex w-64 flex-col gap-2 p-1">
+ <div className="flex w-72 flex-col gap-2 p-1">
<LemonInput
type="search"
size="small"
@@ -223,20 +219,24 @@ function BranchScopeChip(): JSX.Element {
data-attr="engineering-analytics-branch-filter"
/>
<div className="flex flex-wrap gap-1">
- {DEFAULT_BRANCHES.map((branch) => (
- <LemonButton
- key={branch}
- size="xsmall"
- type={appliedBranch === branch ? 'primary' : 'secondary'}
- onClick={() => selectBranch(appliedBranch === branch ? '' : branch)}
- >
- {branch}
- </LemonButton>
- ))}
<LemonButton
size="xsmall"
- type={appliedBranch === '' ? 'primary' : 'secondary'}
- onClick={() => selectBranch('')}
+ type={pullRequestScope ? 'primary' : 'secondary'}
+ onClick={() => {
+ scopeToPullRequests()
+ setVisible(false)
+ }}
+ tooltip="CI on pull-request branches, excluding master/main. Same-repo PRs only — fork PRs carry no attribution. Applies to workflow health."
+ >
+ Pull requests
+ </LemonButton>
+ <LemonButton
+ size="xsmall"
+ type={!pullRequestScope && !appliedBranch ? 'primary' : 'secondary'}
+ onClick={() => {
+ setAppliedBranch('')
+ setVisible(false)
+ }}
>
all branches
</LemonButton>
@@ -244,17 +244,39 @@ function BranchScopeChip(): JSX.Element {
</div>
}
>
- <span className={cn(CHIP_CLASS, 'cursor-pointer')} title="One branch scope for every section below">
- branch:{' '}
- <strong className={cn('font-semibold', appliedBranch ? 'text-primary' : 'text-tertiary')}>
- {appliedBranch || 'all'}
- </strong>
+ <span className={cn(CHIP_CLASS, 'cursor-pointer')} title="One CI scope for every section below">
+ {pullRequestScope ? (
+ <strong className="font-semibold text-primary">pull requests</strong>
+ ) : appliedBranch ? (
+ <>
+ {'branch: '}
+ <strong className="font-semibold text-primary">{appliedBranch}</strong>
+ </>
+ ) : (
+ <strong className="font-semibold text-tertiary">all branches</strong>
+ )}
<span className="text-[8px] text-tertiary">▼</span>
</span>
</LemonDropdown>
)
}
+/** The shared window picker, wired to the cross-page date scope. Standalone so pages can place it outside
+ * the scope bar (the hub docks it in the repo header). */
+export function ScopeDateFilter(): JSX.Element {
+ const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)
+ const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
+ return (
+ <DateFilter
+ dateFrom={dateFrom}
+ dateTo={dateTo}
+ onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
+ dateOptions={SCOPE_DATE_OPTIONS}
+ size="small"
+ />
+ )
+}
+
export function ScopeBar({
repoSlot,
crumbs = [],
@@ -273,9 +295,6 @@ export function ScopeBar({
showDate?: boolean
extra?: ReactNode
}): JSX.Element {
- const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)
- const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
-
return (
<div className="flex flex-wrap items-center gap-2">
{repoSlot}
@@ -306,15 +325,7 @@ export function ScopeBar({
</span>
)}
{showBranch && <BranchScopeChip />}
- {showDate && (
- <DateFilter
- dateFrom={dateFrom}
- dateTo={dateTo}
- onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
- dateOptions={SCOPE_DATE_OPTIONS}
- size="small"
- />
- )}
+ {showDate && <ScopeDateFilter />}
{extra}
</span>
</div>
diff --git a/products/engineering_analytics/frontend/components/Section.tsx b/products/engineering_analytics/frontend/components/Section.tsx
index 387a34ba1682..5f4e02e45397 100644
--- a/products/engineering_analytics/frontend/components/Section.tsx
+++ b/products/engineering_analytics/frontend/components/Section.tsx
@@ -1,8 +1,10 @@
-// Anchored page sections with a compact title row, plus a sticky jumper that scrolls between them.
+// Anchored page sections with a compact title row.
import { ReactNode } from 'react'
-import { LemonButton } from '@posthog/lemon-ui'
+import { Spinner } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
function sectionDomId(id: string): string {
return `ea-section-${id}`
@@ -17,6 +19,7 @@ export function Section({
title,
note,
right,
+ busy = false,
children,
}: {
id: string
@@ -25,29 +28,20 @@ export function Section({
* criteria, a legend) — never a restatement of the title or an interaction hint. */
note?: ReactNode
right?: ReactNode
+ /** Reloading with data already on screen (e.g. the window changed): a spinner by the title and dimmed
+ * content, so the stale data reads as "updating" instead of silently swapping. */
+ busy?: boolean
children: ReactNode
}): JSX.Element {
return (
- <section id={sectionDomId(id)} className="scroll-mt-14">
+ <section id={sectionDomId(id)} className="scroll-mt-14" aria-busy={busy}>
<div className="mb-2 flex items-baseline gap-2.5">
<h2 className="m-0 text-base font-semibold">{title}</h2>
{note && <span className="text-xs text-tertiary">{note}</span>}
+ {busy && <Spinner className="text-sm text-secondary" />}
{right && <span className="ml-auto text-xs">{right}</span>}
</div>
- {children}
+ <div className={cn('transition-opacity', busy && 'pointer-events-none opacity-60')}>{children}</div>
</section>
)
}
-
-export function SectionNav({ items }: { items: { id: string; label: string }[] }): JSX.Element {
- return (
- <div className="sticky top-0 z-10 -mx-1 flex flex-wrap items-center gap-0.5 bg-primary px-1 py-1.5">
- <span className="mr-1.5 text-xs text-tertiary">Jump to</span>
- {items.map((item) => (
- <LemonButton key={item.id} size="xsmall" onClick={() => scrollToSection(item.id)}>
- {item.label}
- </LemonButton>
- ))}
- </div>
- )
-}
diff --git a/products/engineering_analytics/frontend/components/ShareRow.tsx b/products/engineering_analytics/frontend/components/ShareRow.tsx
index 86246bd468cd..991b10ce6670 100644
--- a/products/engineering_analytics/frontend/components/ShareRow.tsx
+++ b/products/engineering_analytics/frontend/components/ShareRow.tsx
@@ -19,6 +19,7 @@ export function ShareRow({
color,
to,
avatar,
+ fullWidthBar = false,
}: {
rank?: number
label: ReactNode
@@ -30,6 +31,9 @@ export function ShareRow({
color?: string
to?: string
avatar?: string
+ /** Fixed-width label + a bar that fills the row, so bar lengths compare across rows (magnitude
+ * breakdown). Default keeps the compact narrow bar with a flexible label (leaderboard style). */
+ fullWidthBar?: boolean
}): JSX.Element {
const row = (
<div
@@ -42,7 +46,7 @@ export function ShareRow({
<span className="w-4 shrink-0 text-right text-xs tabular-nums text-tertiary">{rank}.</span>
)}
{avatar && <Lettermark name={avatar} />}
- <span className="min-w-0 flex-1">
+ <span className={cn('min-w-0', fullWidthBar ? 'w-48 shrink-0' : 'flex-1')}>
<span className="block truncate text-[13px] font-semibold text-primary">{label}</span>
{sub && <span className="block truncate text-[11px] text-tertiary">{sub}</span>}
</span>
@@ -52,7 +56,7 @@ export function ShareRow({
strokeColor={color ?? 'var(--brand-blue)'}
bgColor="var(--color-bg-fill-tertiary)"
smoothing={false}
- className="w-40 max-w-[30%] shrink-0"
+ className={fullWidthBar ? 'flex-1' : 'w-40 max-w-[30%] shrink-0'}
/>
)}
<span className="shrink-0 text-right">
diff --git a/products/engineering_analytics/frontend/components/StatCard.tsx b/products/engineering_analytics/frontend/components/StatCard.tsx
index 2b31f70c5aab..224fe6389718 100644
--- a/products/engineering_analytics/frontend/components/StatCard.tsx
+++ b/products/engineering_analytics/frontend/components/StatCard.tsx
@@ -3,6 +3,78 @@ import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
import { MetricCard } from '@posthog/quill-charts'
import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+export type StatTone = 'default' | 'danger' | 'warning' | 'success'
+
+/** A compact right-now count: number over a small label, colored only when it's a pressure. Optionally
+ * doubles as a filter toggle (onClick + active) — the compact sibling of StatCard, shared by the hub
+ * hero and the PR list strip so both read the same. */
+export function HeroStat({
+ label,
+ value,
+ tone = 'default',
+ align = 'end',
+ loading = false,
+ onClick,
+ active = false,
+ filterHint,
+}: {
+ label: string
+ value: number | null | undefined
+ tone?: StatTone
+ /** 'end' in the hub hero's right cluster; 'start' in the PR list's left strip. */
+ align?: 'start' | 'end'
+ loading?: boolean
+ onClick?: () => void
+ active?: boolean
+ /** What clicking filters the list to — surfaces in the tooltip. */
+ filterHint?: string
+}): JSX.Element {
+ const pressing = value != null && value > 0
+ const color =
+ pressing && tone === 'danger'
+ ? 'text-danger'
+ : pressing && tone === 'warning'
+ ? 'text-warning-dark'
+ : pressing && tone === 'success'
+ ? 'text-success'
+ : 'text-primary'
+ const alignCls = align === 'end' ? 'items-end' : 'items-start'
+ const body = (
+ <>
+ {loading ? (
+ <LemonSkeleton className="h-5 w-10" />
+ ) : (
+ <span className={cn('text-xl font-semibold leading-none tabular-nums', color)}>
+ {value == null ? '—' : humanFriendlyNumber(value)}
+ </span>
+ )}
+ <span className={cn('mt-1 text-[11px] whitespace-nowrap', active ? 'text-accent' : 'text-tertiary')}>
+ {label}
+ </span>
+ </>
+ )
+ if (!onClick) {
+ return <div className={cn('flex flex-col', alignCls)}>{body}</div>
+ }
+ return (
+ <Tooltip title={active ? 'Showing this view' : filterHint} placement="bottom">
+ <button
+ type="button"
+ onClick={onClick}
+ aria-pressed={active}
+ className={cn(
+ 'flex cursor-pointer flex-col rounded px-2.5 py-1.5 transition-colors',
+ alignCls,
+ active ? 'bg-accent-highlight-secondary' : 'hover:bg-surface-secondary'
+ )}
+ >
+ {body}
+ </button>
+ </Tooltip>
+ )
+}
/** A headline stat that doubles as a filter toggle for the table below it. */
export function StatCard({
diff --git a/products/engineering_analytics/frontend/components/TrendCard.tsx b/products/engineering_analytics/frontend/components/TrendCard.tsx
new file mode 100644
index 000000000000..cc34497f3445
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/TrendCard.tsx
@@ -0,0 +1,86 @@
+// A stat-plus-trend card for the repo hub's Trends strip: lead with the current value and its change
+// across the window (the answer), over a sentiment-colored sparkline (the context). `goodWhenDown` colors
+// both the delta and the line green when the metric is falling (time-to-green, cost), red when rising.
+
+import { ReactNode } from 'react'
+
+import { LemonCard, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { Sparkline } from 'lib/components/Sparkline'
+
+import { DeltaBadge, percentChange } from './MetricTile'
+
+export interface TrendSeries {
+ values: number[]
+ labels: string[]
+}
+
+export function TrendCard({
+ title,
+ series,
+ formatValue,
+ renderTooltipValue,
+ goodWhenDown = false,
+ caption,
+ loading = false,
+ emptyText,
+}: {
+ title: string
+ series: TrendSeries | null
+ /** Formats the headline (latest) value, e.g. minutes or USD. */
+ formatValue: (value: number) => string
+ renderTooltipValue: (value: number) => string
+ goodWhenDown?: boolean
+ caption: ReactNode
+ loading?: boolean
+ emptyText: string
+}): JSX.Element {
+ const values = series?.values ?? []
+ const latest = values.length ? values[values.length - 1] : null
+ // Baseline is the first point — the series builders already trim leading empty buckets and carry the
+ // last value forward, so values[0] is real data, not zero-fill. A genuine leading 0 (e.g. a 0% pass
+ // rate at the window's start) is a valid baseline: percentChange returns null off a zero baseline, so
+ // the card shows no delta rather than mis-baselining against a later bucket.
+ const first = values.length ? values[0] : null
+ const deltaPct = percentChange(latest, first)
+ // Line color follows the delta's sentiment so the card reads at a glance: green the good way, red the
+ // bad way, muted when flat or without a baseline.
+ const lineColor =
+ deltaPct == null || deltaPct === 0 ? 'muted' : deltaPct < 0 === goodWhenDown ? 'success' : 'danger'
+
+ return (
+ <LemonCard hoverEffect={false} className="flex flex-col p-4">
+ <h3 className="mb-1 text-xs font-semibold text-secondary">{title}</h3>
+ {loading ? (
+ <LemonSkeleton className="h-20 w-full" />
+ ) : values.length ? (
+ <>
+ <div className="mb-1 flex items-baseline gap-2">
+ <span className="text-2xl font-semibold leading-none tabular-nums">
+ {formatValue(latest as number)}
+ </span>
+ <DeltaBadge
+ value={deltaPct}
+ goodWhenDown={goodWhenDown}
+ vs="latest vs the start of the window"
+ />
+ </div>
+ <Sparkline
+ data={values}
+ labels={series?.labels}
+ name={title}
+ type="line"
+ color={lineColor}
+ maximumIndicator={false}
+ className="h-16 w-full"
+ renderLabel={(label) => label}
+ renderTooltipValue={renderTooltipValue}
+ />
+ </>
+ ) : (
+ <div className="flex h-20 items-center text-xs text-secondary">{emptyText}</div>
+ )}
+ <div className="mt-2 border-t border-primary pt-2 text-[11px] text-tertiary">{caption}</div>
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
index 0cd390286ab1..0c32fba5ff33 100644
--- a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
+++ b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
@@ -1,7 +1,7 @@
// Per-workflow CI health table, shared by the Workflows tab and the repo hub.
import { useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
+import { router } from 'kea-router'
import { ReactNode } from 'react'
import { LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'
@@ -9,10 +9,12 @@ import { LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui
import { TZLabel } from 'lib/components/TZLabel'
import { cn } from 'lib/utils/css-classes'
import { humanFriendlyDuration } from 'lib/utils/durations'
+import { newInternalTab } from 'lib/utils/newInternalTab'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
+import { withScope } from '../lib/scope'
import { WorkflowHealthRow, workflowFailureSeries } from '../scenes/engineeringAnalyticsLogic'
import { BillableBadge } from './BillableBadge'
import { FailureSparkline } from './FailureSparkline'
@@ -73,37 +75,54 @@ export interface WorkflowHealthTableProps {
loading?: boolean
/** Threaded into the Workflow-name link so it preserves the active source. */
sourceId?: string | null
- /** Default column sort. Alphabetical by workflow name by default; click Status for failing-first. */
- defaultSorting?: { columnKey: string; order: 1 | -1 }
+ /** Column sort override. Default (null) keeps the rows' failing-first-then-name order — the one
+ * convention shared with the PR page; pass a column to sort by it instead. */
+ defaultSorting?: { columnKey: string; order: 1 | -1 } | null
/** Show the billable cost column (needs per-workflow cost on the rows). */
showCost?: boolean
- /** Rows per page — 50 by default; the hub passes a small page to stay scannable. */
+ /** Rows per page — the shared 25 by default; the hub passes a small page to stay scannable. */
pageSize?: number
emptyState?: ReactNode
dataAttr?: string
/** Drop the table's own border when it sits inside a LemonCard (the hub) — avoids a double frame. */
embedded?: boolean
+ /** Hub preview variant: a focused column set (status · pass rate · Δ · cost · health) with the health
+ * sparkline given room. The full run/p50/p95/re-runs/last-failure columns stay on the Workflows tab. */
+ compact?: boolean
}
+// The compact (hub preview) column set, in display order: the health-and-cost story with pass rate next
+// to its own trend (Δ). Cost only appears when showCost adds it. Headers stay intact.
+const COMPACT_COLUMN_ORDER = ['workflowName', 'status', 'successRate', 'successRateDelta', 'cost', 'trend']
+
export function WorkflowHealthTable({
rows,
loading,
sourceId,
- defaultSorting = { columnKey: 'workflowName', order: 1 },
+ defaultSorting = null,
showCost = false,
- pageSize = 50,
+ pageSize = 25,
emptyState,
dataAttr = 'engineering-analytics-workflow-table',
embedded = false,
+ compact = false,
}: WorkflowHealthTableProps): JSX.Element {
const { searchParams } = useValues(router)
- // Carry the active window/branch scope into the drill-down; without `q` the detail page would
- // silently widen to all branches.
- const windowParams: Record<string, string> = {
- ...(searchParams.date_from ? { date_from: searchParams.date_from } : {}),
- ...(searchParams.date_to ? { date_to: searchParams.date_to } : {}),
- ...(searchParams.q ? { q: searchParams.q } : {}),
- }
+ // Each row opens the workflow's runs page, carrying the active window/branch scope + source so the
+ // drill-down doesn't silently widen to all branches.
+ const rowUrl = (row: WorkflowHealthRow): string =>
+ withScope(
+ urls.engineeringAnalyticsWorkflowRuns(row.repoOwner, row.repoName, row.workflowName),
+ searchParams,
+ sourceId
+ )
+ // Failing workflows first — the order a reviewer triages in — then everything else alphabetically by
+ // name. The one convention shared with the PR page; a passed defaultSorting still overrides on click.
+ const orderedRows = [...rows].sort(
+ (a, b) =>
+ Number(b.latestRunFailed === true) - Number(a.latestRunFailed === true) ||
+ a.workflowName.localeCompare(b.workflowName)
+ )
const columns: LemonTableColumns<WorkflowHealthRow> = [
{
title: 'Workflow',
@@ -111,16 +130,7 @@ export function WorkflowHealthTable({
sorter: (a, b) => a.workflowName.localeCompare(b.workflowName),
render: (_, row) => (
<div className="flex items-center gap-2">
- <Link
- to={
- combineUrl(
- urls.engineeringAnalyticsWorkflowRuns(row.repoOwner, row.repoName, row.workflowName),
- { ...windowParams, ...(sourceId ? { source: sourceId } : {}) }
- ).url
- }
- className="font-medium"
- onClick={(e) => e.stopPropagation()}
- >
+ <Link to={rowUrl(row)} className="font-medium" onClick={(e) => e.stopPropagation()}>
{row.workflowName}
</Link>
</div>
@@ -274,16 +284,46 @@ export function WorkflowHealthTable({
},
]
+ // Compact keeps the focused column set (in COMPACT_COLUMN_ORDER) and lets the health sparkline breathe.
+ const displayColumns = compact
+ ? COMPACT_COLUMN_ORDER.map((key) => columns.find((column) => String(column.key) === key))
+ .filter((column): column is (typeof columns)[number] => column !== undefined)
+ .map((column) => (column.key === 'trend' ? { ...column, title: 'Health', width: 220 } : column))
+ : columns
+
return (
<LemonTable
data-attr={dataAttr}
size="small"
embedded={embedded}
- columns={columns}
- dataSource={rows}
+ columns={displayColumns}
+ dataSource={orderedRows}
rowKey={(row) => `${row.repoOwner}/${row.repoName}:${row.workflowName}`}
// De-emphasize workflows with nothing settled — no pass/fail signal to read.
- rowClassName={(row) => (row.successRate === null ? 'opacity-60' : null)}
+ rowClassName={(row) => cn('cursor-pointer', row.successRate === null && 'opacity-60')}
+ onRow={(row) => {
+ const url = rowUrl(row)
+ return {
+ // Inner links (the workflow name) keep their own behavior.
+ onClick: (e: React.MouseEvent) => {
+ if ((e.target as HTMLElement).closest('a, button')) {
+ return
+ }
+ if (e.metaKey || e.ctrlKey) {
+ e.preventDefault()
+ newInternalTab(url)
+ } else {
+ router.actions.push(url)
+ }
+ },
+ onAuxClick: (e: React.MouseEvent) => {
+ if (e.button === 1 && !(e.target as HTMLElement).closest('a, button')) {
+ e.preventDefault()
+ newInternalTab(url)
+ }
+ },
+ }
+ }}
loading={loading}
useURLForSorting={false}
defaultSorting={defaultSorting}
diff --git a/products/engineering_analytics/frontend/components/WorkflowsHealthHeader.tsx b/products/engineering_analytics/frontend/components/WorkflowsHealthHeader.tsx
index 734fc5241887..4446f679662f 100644
--- a/products/engineering_analytics/frontend/components/WorkflowsHealthHeader.tsx
+++ b/products/engineering_analytics/frontend/components/WorkflowsHealthHeader.tsx
@@ -1,4 +1,4 @@
-import { Tooltip } from '@posthog/lemon-ui'
+import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { cn } from 'lib/utils/css-classes'
@@ -12,17 +12,48 @@ interface WorkflowsHealthHeaderProps {
summary: FleetSummary
/** Workflow list was capped server-side — totals cover the top N by run count, not the whole fleet. */
truncated?: boolean
+ /** Reloading on a window/branch change: show a skeleton so the old numbers don't read as current. */
+ loading?: boolean
className?: string
}
/** Verdict strip above the all-workflows table: state word, failing-now count, pass rate, re-runs,
* total runs, and CI spend rolled up across every workflow in the window. */
-export function WorkflowsHealthHeader({ summary, truncated, className }: WorkflowsHealthHeaderProps): JSX.Element {
+export function WorkflowsHealthHeader({
+ summary,
+ truncated,
+ loading,
+ className,
+}: WorkflowsHealthHeaderProps): JSX.Element {
const meta = STATE_META[summary.state]
- const greenNow = summary.settledWorkflows - summary.failingNow
- const greenRateLabel = summary.settledWorkflows > 0 ? percent(greenNow / summary.settledWorkflows) : '—'
+ const passingNow = summary.settledWorkflows - summary.failingNow
+ const passingRateLabel = summary.settledWorkflows > 0 ? percent(passingNow / summary.settledWorkflows) : '—'
+ // Name what's failing rather than restate the Failing-now / Workflows counts already in the KPI row.
+ const failingLabel =
+ summary.failingWorkflowNames.length > 0
+ ? `${summary.failingWorkflowNames.slice(0, 3).join(', ')}${
+ summary.failingNow > 3 ? ` +${summary.failingNow - 3} more` : ''
+ } failing`
+ : `${summary.failingNow} failing`
const hasCost = summary.estimatedCostUsd != null
+ if (loading) {
+ return (
+ <LemonCard
+ hoverEffect={false}
+ className={cn(
+ 'flex flex-wrap items-center gap-x-6 gap-y-4 border-l-4 border-l-transparent px-5 py-4',
+ className
+ )}
+ >
+ <LemonSkeleton className="h-7 w-40" />
+ <LemonSkeleton className="h-7 w-16" />
+ <div className="flex-1" />
+ <LemonSkeleton className="h-7 w-72" />
+ </LemonCard>
+ )
+ }
+
return (
<LemonCard
hoverEffect={false}
@@ -44,58 +75,27 @@ export function WorkflowsHealthHeader({ summary, truncated, className }: Workflo
: summary.settledWorkflows === 0
? `${summary.workflowCount} workflows · no completed runs yet`
: summary.failingNow > 0
- ? `${summary.failingNow} of ${summary.workflowCount} workflows failing right now`
+ ? failingLabel
: summary.flakyNow > 0
? `${summary.flakyNow} flaky · below 90% pass rate`
: truncated
- ? `Top ${summary.workflowCount} by runs · all green`
+ ? `Top ${summary.workflowCount} by runs · all passing`
: `All ${summary.workflowCount} workflows healthy`}
</span>
</div>
<div className="flex flex-col border-l border-primary pl-6">
<Tooltip
- title={`Share of workflows currently green, of the ${summary.settledWorkflows} whose latest run completed.`}
+ title={`Share of workflows whose latest run passed, of the ${summary.settledWorkflows} with a completed run. Workflow-level and current — distinct from the volume-weighted Run pass rate.`}
>
- <span className="self-start cursor-default text-xs text-tertiary">Green now</span>
+ <span className="self-start cursor-default text-xs text-tertiary">Passing now</span>
</Tooltip>
- <span className="text-2xl font-semibold leading-7 tabular-nums">{greenRateLabel}</span>
+ <span className="text-2xl font-semibold leading-7 tabular-nums">{passingRateLabel}</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 only; lower-volume workflows 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="Run pass rate"
- value={
- summary.passRate != null ? (
- <Tooltip title="Passes ÷ completed runs across all workflows, weighted by run volume, so busier workflows count for more.">
- <span>{percent(summary.passRate)}</span>
- </Tooltip>
- ) : (
- '—'
- )
- }
- />
<HealthKpi
label="Re-runs"
value={
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index e1de9c86bf3b..84cf902ec675 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -394,6 +394,22 @@ export interface CIStatusRollupApi {
failing_workflows?: string[]
}
+export interface PushCISampleApi {
+ /** Head commit SHA of this push (CI round). */
+ head_sha: string
+ /** Earliest workflow-run start on this push. */
+ started_at: string
+ /**
+ * Wall-clock CI seconds for this push: earliest run start to latest completed run end. Null while nothing has completed.
+ * @nullable
+ */
+ wall_seconds: number | null
+ /** True when any latest-per-workflow run on this push concluded 'failure' or 'timed_out'. */
+ failed: boolean
+ /** True when any latest-per-workflow run on this push hasn't completed yet. */
+ pending: boolean
+}
+
export interface PullRequestListItemApi {
/** The pull request author. */
author: AuthorApi
@@ -401,6 +417,8 @@ export interface PullRequestListItemApi {
repo: RepoRefApi
/** CI status from the latest workflow runs on the head SHA. */
ci: CIStatusRollupApi
+ /** This PR's CI rounds oldest-first, capped to the most recent pushes - one sample per push for the push-history sparkline. `pushes` stays the uncapped count. */
+ push_history: PushCISampleApi[]
/** Pull request number within the repository. */
number: number
/** Pull request title. */
@@ -619,9 +637,45 @@ export interface CostPerMergeBucketApi {
cost_per_merge_usd: number | null
}
+export interface TimeToGreenBucketApi {
+ /** Bucket start, aligned to time_to_green_series_granularity (top of hour, midnight, or Monday). */
+ bucket_start: string
+ /**
+ * Median wall-clock seconds of successful PR-attributed CI runs started in this bucket. Null when the bucket had no successful PR run (a gap, not instant CI).
+ * @nullable
+ */
+ p50_seconds: number | null
+}
+
+export interface PassRateBucketApi {
+ /** Bucket start, aligned to success_rate_series_granularity (top of hour, midnight, or Monday). */
+ bucket_start: string
+ /**
+ * Fraction (0-1) of completed runs started in this bucket that succeeded. Null when the bucket had no completed run (a gap, not a 0% pass rate).
+ * @nullable
+ */
+ success_rate: number | null
+}
+
+export interface OpenToMergeBucketApi {
+ /** Bucket start, aligned to open_to_merge_series_granularity (top of hour, midnight, or Monday). */
+ bucket_start: string
+ /**
+ * Median merged_at - created_at seconds over PRs merged in this bucket, bots and drafts excluded. Null when nothing merged in the bucket (a gap, not instant merges).
+ * @nullable
+ */
+ p50_seconds: number | null
+}
+
export interface RepoOverviewApi {
/** CI cost per merged PR across the window, oldest first, zero-filled, bucketed by cost_series_granularity. Empty when the job-level source isn't synced. */
cost_series: CostPerMergeBucketApi[]
+ /** Median time-to-green (p50 successful PR-attributed CI run duration) per bucket across the window, oldest first, bucketed by time_to_green_series_granularity. Empty buckets carry null. */
+ time_to_green_series: TimeToGreenBucketApi[]
+ /** CI pass rate (completed runs that succeeded, all branches) per bucket across the window, oldest first, bucketed by success_rate_series_granularity. Empty buckets carry null. */
+ success_rate_series: PassRateBucketApi[]
+ /** Median time-to-merge (p50 open_to_merge_seconds, bots/drafts excluded) per bucket across the window, oldest first, bucketed by open_to_merge_series_granularity. Empty buckets carry null. */
+ open_to_merge_series: OpenToMergeBucketApi[]
/** Workflow runs started in the window, all branches and workflows. */
run_count: number
/** Same count over the equal-length window immediately before date_from — the delta baseline. */
@@ -676,6 +730,12 @@ export interface RepoOverviewApi {
default_branch: string
/** Bucket width of the cost_series trend, chosen to fit the window: 'hour', 'day', or 'week'. */
cost_series_granularity: string
+ /** Bucket width of the time_to_green_series trend: 'hour', 'day', or 'week'. */
+ time_to_green_series_granularity: string
+ /** Bucket width of the success_rate_series trend: 'hour', 'day', or 'week'. */
+ success_rate_series_granularity: string
+ /** Bucket width of the open_to_merge_series trend: 'hour', 'day', or 'week'. */
+ open_to_merge_series_granularity: string
}
export interface WorkflowRunActivityPointApi {
@@ -697,6 +757,8 @@ export interface WorkflowRunActivityPointApi {
head_branch: string
/** Attributed pull request number, or 0 when unattributed. */
pr_number: number
+ /** Head commit SHA of the run/commit, or '' when unknown. */
+ head_sha: string
}
export interface WorkflowRunActivityApi {
diff --git a/products/engineering_analytics/frontend/lib/format.ts b/products/engineering_analytics/frontend/lib/format.ts
index b0bc9cb2dfef..cec4ffbb8de5 100644
--- a/products/engineering_analytics/frontend/lib/format.ts
+++ b/products/engineering_analytics/frontend/lib/format.ts
@@ -51,6 +51,17 @@ export function compactHoursLabel(seconds: number | null | undefined): string {
return `${compactHours(seconds)}${seconds / 3600 < HOURS_BEFORE_DAYS ? 'h' : 'd'}`
}
+/** Elapsed-time label with minute granularity under an hour: "20m", "27h", "3.2d". */
+export function compactAgeLabel(seconds: number | null | undefined): string {
+ if (seconds == null) {
+ return '—'
+ }
+ if (seconds < 3600) {
+ return `${Math.max(1, Math.round(seconds / 60))}m`
+ }
+ return compactHoursLabel(seconds)
+}
+
export function compactMinutes(minutes: number | null | undefined): string {
if (minutes == null) {
return '—'
diff --git a/products/engineering_analytics/frontend/lib/preview.ts b/products/engineering_analytics/frontend/lib/preview.ts
new file mode 100644
index 000000000000..18438f827669
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/preview.ts
@@ -0,0 +1,7 @@
+// Hub preview standard. The repo hub is a landing page: each table shows a short, scannable slice and
+// routes to its dedicated full view for the rest — it never restates the whole table. One standard so
+// every preview table starts the same length and grows by the same step on "Show more".
+// Typed as number (not the literal) so the reducer that grows the count keeps a widened number state.
+export const HUB_PREVIEW_ROWS: number = 5 // rows shown before any expansion
+export const HUB_PREVIEW_STEP: number = 5 // rows revealed per "Show more"
+export const HUB_PREVIEW_MAX: number = 15 // ceiling on the hub — past this, "View all" is the only way deeper
diff --git a/products/engineering_analytics/frontend/lib/pushRounds.ts b/products/engineering_analytics/frontend/lib/pushRounds.ts
new file mode 100644
index 000000000000..458f064b9dfd
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/pushRounds.ts
@@ -0,0 +1,62 @@
+// One push (head SHA) collapsed into a CI round: when it started, wall-clock CI time, verdict.
+// Mirrors the backend's push-history rule (pull_request_list.py): the latest run per workflow
+// decides the verdict; wall time is the earliest run start → the latest completed run end.
+
+import type { PushCISampleApi } from '../generated/api.schemas'
+import { WorkflowRun, isDecisiveFailure } from './lifecycle'
+import { VERDICT_COLOR } from './runStatus'
+
+export interface PushRound {
+ headSha: string
+ startedAt: string | null
+ /** Earliest run start → latest completed run end; null while nothing has completed. */
+ wallSeconds: number | null
+ failed: boolean
+ pending: boolean
+}
+
+export function pushRoundFromSample(sample: PushCISampleApi): PushRound {
+ return {
+ headSha: sample.head_sha,
+ startedAt: sample.started_at,
+ wallSeconds: sample.wall_seconds,
+ failed: sample.failed,
+ pending: sample.pending,
+ }
+}
+
+/** Collapse one push's runs into a round, client-side (the PR page already has the runs). */
+export function pushRoundOf(headSha: string, runs: WorkflowRun[]): PushRound {
+ const latestByWorkflow = new Map<string, WorkflowRun>()
+ for (const run of runs) {
+ const seen = latestByWorkflow.get(run.workflow)
+ if (!seen || (run.startedAt ?? '') > (seen.startedAt ?? '')) {
+ latestByWorkflow.set(run.workflow, run)
+ }
+ }
+ const latest = [...latestByWorkflow.values()]
+ const starts = runs.map((run) => run.startedAt).filter((at): at is string => !!at)
+ const ends = runs.map((run) => run.finishedAt).filter((at): at is string => !!at)
+ const startedAt = starts.length ? starts.reduce((min, at) => (at < min ? at : min)) : null
+ const lastEnd = ends.length ? ends.reduce((max, at) => (at > max ? at : max)) : null
+ return {
+ headSha,
+ startedAt,
+ wallSeconds:
+ startedAt && lastEnd ? Math.max(0, Math.round((Date.parse(lastEnd) - Date.parse(startedAt)) / 1000)) : null,
+ failed: latest.some((run) => isDecisiveFailure(run.conclusion)),
+ pending: latest.some((run) => run.conclusion === null),
+ }
+}
+
+/** Status color for a round: a decisive failure wins, then still-running amber, then green. */
+export function pushRoundColor(round: PushRound): string {
+ return round.failed ? VERDICT_COLOR.danger : round.pending ? VERDICT_COLOR.warning : VERDICT_COLOR.success
+}
+
+export function pushRoundVerdictLabel(round: PushRound): string {
+ if (round.failed) {
+ return round.pending ? 'failing · still running' : 'failed'
+ }
+ return round.pending ? 'running' : 'passed'
+}
diff --git a/products/engineering_analytics/frontend/lib/runHealth.ts b/products/engineering_analytics/frontend/lib/runHealth.ts
index a75135131a6f..f881e708ed99 100644
--- a/products/engineering_analytics/frontend/lib/runHealth.ts
+++ b/products/engineering_analytics/frontend/lib/runHealth.ts
@@ -56,6 +56,8 @@ const FLAKY_SUCCESS_RATE = 0.9
export interface FleetRow {
runCount: number
successRate: number | null
+ /** Workflow name — lets the fleet verdict name what's failing rather than restate the count. */
+ workflowName?: string
/** 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
@@ -75,6 +77,8 @@ export interface FleetSummary {
/** Workflows whose latest run has settled (so they're either green or red right now). */
settledWorkflows: number
failingNow: number
+ /** Names of the currently-failing workflows (what the verdict subline names). */
+ failingWorkflowNames: string[]
/** Currently green but below the success-rate floor — flaky. */
flakyNow: number
totalRuns: number
@@ -154,7 +158,9 @@ export function computeHealthSummary(runs: HealthRun[]): HealthSummary {
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
+ const failingRows = rows.filter((row) => row.latestRunFailed === true)
+ const failingNow = failingRows.length
+ const failingWorkflowNames = failingRows.map((row) => row.workflowName).filter((name): name is string => !!name)
// Flaky = currently green, below the success-rate floor, AND actually failed in the window. The
// lastFailureAt gate keeps a low success rate from skips/cancels (no real failures) reading as flaky.
const flakyNow = rows.filter(
@@ -200,6 +206,7 @@ export function computeFleetSummary(rows: FleetRow[]): FleetSummary {
workflowCount,
settledWorkflows,
failingNow,
+ failingWorkflowNames,
flakyNow,
totalRuns,
passRate,
diff --git a/products/engineering_analytics/frontend/lib/runStatus.ts b/products/engineering_analytics/frontend/lib/runStatus.ts
index 630515c9bca2..c02353677932 100644
--- a/products/engineering_analytics/frontend/lib/runStatus.ts
+++ b/products/engineering_analytics/frontend/lib/runStatus.ts
@@ -25,3 +25,12 @@ export function verdictTag(conclusion: string | null): { label: string; type: Le
}
return { label, type: 'warning' }
}
+
+// CSS color per verdict type, keyed by the `verdictTag` type above so every run-activity chart (scatter,
+// mini bars) and the run tables' StatusDot color the same conclusion identically.
+export const VERDICT_COLOR: Record<string, string> = {
+ success: 'var(--success)',
+ danger: 'var(--danger)',
+ warning: 'var(--warning)',
+ muted: 'var(--muted)',
+}
diff --git a/products/engineering_analytics/frontend/lib/scope.ts b/products/engineering_analytics/frontend/lib/scope.ts
new file mode 100644
index 000000000000..492293cf8bbc
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/scope.ts
@@ -0,0 +1,19 @@
+import { combineUrl } from 'kea-router'
+
+/** Carry the shared window + branch scope (and active source) onto an internal nav URL, so drilling in,
+ * switching workflows, or stepping back never silently resets it. The scope lives in the URL — every
+ * cross-page link threads it the same way the tab links do (`?date_from` / `?date_to` / `?q` / `?source`).
+ * The pull-request lens (`?run_scope`) is intentionally not carried: only workflow health honors it, so it
+ * stays on the Workflows tab rather than following a drill-down that can't apply it. */
+export function withScope(
+ url: string,
+ searchParams: Record<string, string | undefined>,
+ sourceId: string | null | undefined
+): string {
+ return combineUrl(url, {
+ ...(searchParams.date_from ? { date_from: searchParams.date_from } : {}),
+ ...(searchParams.date_to ? { date_to: searchParams.date_to } : {}),
+ ...(searchParams.q ? { q: searchParams.q } : {}),
+ ...(sourceId ? { source: sourceId } : {}),
+ }).url
+}
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
index 7700eea5576f..8faa7148f559 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { combineUrl } from 'kea-router'
-import { Link, Spinner } from '@posthog/lemon-ui'
+import { LemonSkeleton, Link } from '@posthog/lemon-ui'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
@@ -19,13 +19,11 @@ import { MetricTile } from '../components/MetricTile'
import { PullRequestTable } from '../components/PullRequestTable'
import { formatCost, formatMinutes } from '../components/runTables'
import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'
-import { Section, SectionNav } from '../components/Section'
+import { Section } from '../components/Section'
import { ShareRow } from '../components/ShareRow'
import { AuthorLogicProps, authorLogic } from './authorLogic'
import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
-const SHARE_COLORS = ['var(--brand-blue)', 'var(--success)', 'var(--warning)', 'var(--purple)', 'var(--danger)']
-
// date_from only (the list floors on it); "all time" / week+month snaps and Custom are out. Every option
// here stays within the list's 365d load window (max preset is 180d / YTD), so the client-side cost tiles
// are always a subset of the loaded PRs — a Custom range could reach past the load and desync the tiles
@@ -51,6 +49,7 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
windowedRows,
totalCostUsd,
totalBillableMinutes,
+ totalLoops,
openPrCount,
workflowCosts,
workflowCostsLoading,
@@ -61,7 +60,10 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
const hubUrl = combineUrl(urls.engineeringAnalytics(), sourceId ? { source: sourceId } : {}).url
const avatarUrl = prs[0]?.authorAvatarUrl
+ const costPerLoop = totalCostUsd != null && totalLoops > 0 ? totalCostUsd / totalLoops : null
const workflowCostsTotal = workflowCosts.reduce((sum, c) => sum + (c.estimated_cost_usd ?? 0), 0)
+ // Ranked, biggest spend first; the bar length is each workflow's share of the window's total.
+ const rankedCosts = [...workflowCosts].sort((a, b) => (b.estimated_cost_usd ?? 0) - (a.estimated_cost_usd ?? 0))
// A source can hold several repos, so the author's PRs may span repos. Only claim one repo (and link
// per-workflow into it) when they all agree; otherwise the page is genuinely cross-repo.
const repoSlugs = Array.from(new Set(prs.map((pr) => `${pr.repoOwner}/${pr.repoName}`)))
@@ -69,7 +71,7 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
return (
<SceneContent>
- <SceneTitleSection name={handle} resourceType={{ type: 'health' }} />
+ <SceneTitleSection name="Author" resourceType={{ type: 'health' }} />
<ScopeBar
repoSlot={
<RepoScopeChip
@@ -81,6 +83,15 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
}
lensFilter={{ label: `author: ${handle}`, to: hubUrl }}
showDate={false}
+ extra={
+ <DateFilter
+ dateFrom={dateFrom}
+ dateTo={dateTo}
+ onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
+ dateOptions={AUTHOR_DATE_OPTIONS}
+ size="small"
+ />
+ }
/>
<EntityHeader
icon={
@@ -104,101 +115,107 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
their CI cost. It carries no per-developer performance/ranking metric (no cycle time, no flaky
score): the cost figures are transparent spend, not a scoreboard (SPEC §2). */}
<div className="flex flex-col gap-4">
- {/* The picker scopes the cost tiles only — the PR list below stays the author's recent PRs. */}
- <div className="flex flex-col gap-2">
- <div className="flex flex-wrap items-center gap-2">
- <span className="text-xs font-semibold tracking-wide text-secondary uppercase">CI cost</span>
- <span className="text-xs text-tertiary">for PRs opened in</span>
- <DateFilter
- dateFrom={dateFrom}
- dateTo={dateTo}
- onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
- dateOptions={AUTHOR_DATE_OPTIONS}
- size="small"
- />
- </div>
- <div className="flex flex-wrap gap-2.5">
- <MetricTile
- label="Pull requests opened"
- value={windowedRows.length.toLocaleString()}
- sub="in the selected window"
- />
- <MetricTile
- label="CI cost"
- tooltip="Full CI cost of the PRs opened in the selected window, across each PR's whole history — not only runs inside the window. The 'Where their CI minutes go' breakdown below counts CI runs started in the window instead, so the two won't reconcile exactly."
- value={formatCost(totalCostUsd)}
- sub={
- totalCostUsd != null
- ? `${formatMinutes(totalBillableMinutes)} billable · ${formatCost(
- windowedRows.length ? totalCostUsd / windowedRows.length : null
- )} per PR`
- : 'no cost data yet'
- }
- />
- </div>
+ {/* The scope-bar date picker scopes everything below it: these tiles, the PR list, and the
+ breakdown. Tiles and list re-filter the already-loaded PRs client-side, so a date change
+ updates them instantly (no skeleton); the skeleton is only for the initial PR fetch, so
+ the tiles don't flash a zero before the list lands. */}
+ <div className="flex flex-wrap gap-2.5">
+ <MetricTile
+ label="Pull requests opened"
+ value={windowedRows.length.toLocaleString()}
+ sub="in the selected window"
+ loading={prsLoading}
+ />
+ <MetricTile
+ label="CI cost"
+ tooltip="Full CI cost of the PRs opened in the selected window, across each PR's whole history — not only runs inside the window. The 'Where their CI minutes go' breakdown below counts CI runs started in the window instead, so the two won't reconcile exactly."
+ value={formatCost(totalCostUsd)}
+ sub={
+ totalCostUsd != null
+ ? `${formatMinutes(totalBillableMinutes)} billable`
+ : 'no cost data yet'
+ }
+ loading={prsLoading}
+ />
+ <MetricTile
+ label="Cost per loop"
+ tooltip="A loop is one push and the CI it triggered. Cost per loop = total CI cost ÷ total pushes across the PRs opened in the window — the spend of one iteration, not a running total."
+ value={formatCost(costPerLoop)}
+ sub={
+ costPerLoop != null
+ ? `${totalLoops.toLocaleString()} loops in the window`
+ : 'no cost data yet'
+ }
+ loading={prsLoading}
+ />
</div>
- <SectionNav
- items={[
- { id: 'author-prs', label: 'Pull requests' },
- { id: 'author-cost', label: 'Cost' },
- ]}
- />
-
- <Section
- id="author-prs"
- title="Pull requests"
- note="the shared PR table, filtered to one author"
- right={
- !prsLoading ? <span className="text-secondary">{pluralize(prs.length, 'PR')}</span> : undefined
- }
- >
+ <Section id="author-prs" title="Pull requests">
<PullRequestTable
- rows={prs}
+ rows={windowedRows}
loading={prsLoading}
sourceId={sourceId}
- costLensEnabled
showAuthor={false}
+ showCreated
dataAttr="engineering-analytics-author-pr-table"
- emptyState={`No pull requests for ${handle} in the last year.`}
+ emptyState={`No pull requests for ${handle} in the selected window.`}
/>
</Section>
- <Section
- id="author-cost"
- title="Where their CI minutes go"
- note="CI runs started in the selected window, split by workflow (attributed via this author's PRs)"
- >
- {workflowCosts.length > 0 ? (
- <LemonCard hoverEffect={false} className="p-4 lg:max-w-xl">
- <h3 className="mb-1 flex items-center gap-1.5 text-xs font-semibold text-secondary">
- By workflow
- {workflowCostsLoading && <Spinner className="text-xs" />}
- </h3>
- {workflowCosts.slice(0, 8).map((cost, i) => (
- <ShareRow
- key={cost.workflow_name || '(unknown)'}
- label={cost.workflow_name || '(unknown workflow)'}
- sub={`${formatMinutes(cost.billable_minutes)} billable`}
- value={formatCost(cost.estimated_cost_usd)}
- share={
- workflowCostsTotal > 0 ? (cost.estimated_cost_usd ?? 0) / workflowCostsTotal : 0
- }
- color={SHARE_COLORS[i % SHARE_COLORS.length]}
- to={
- singleRepo
- ? combineUrl(
- urls.engineeringAnalyticsWorkflowRuns(
- singleRepo.repoOwner,
- singleRepo.repoName,
- cost.workflow_name
- ),
- sourceId ? { source: sourceId } : {}
- ).url
- : undefined
- }
- />
+ <Section id="author-cost" title="Where their CI minutes go">
+ {workflowCostsLoading ? (
+ <LemonCard hoverEffect={false} className="p-4">
+ <LemonSkeleton className="mb-3 h-4 w-24" />
+ {Array.from({ length: 6 }).map((_, i) => (
+ <div
+ key={i}
+ className="flex items-center gap-3 border-b border-primary px-1 py-2 last:border-b-0"
+ >
+ <div className="w-48 shrink-0">
+ <LemonSkeleton className="h-3.5 w-32" />
+ <LemonSkeleton className="mt-1.5 h-2.5 w-20" />
+ </div>
+ <LemonSkeleton className="h-2 flex-1" />
+ <LemonSkeleton className="h-3.5 w-12 shrink-0" />
+ </div>
))}
+ </LemonCard>
+ ) : workflowCosts.length > 0 ? (
+ <LemonCard hoverEffect={false} className="p-4">
+ <div className="mb-2 flex items-center justify-between gap-2">
+ <h3 className="m-0 text-xs font-semibold text-secondary">By workflow</h3>
+ <span className="text-xs tabular-nums text-tertiary">
+ {formatCost(workflowCostsTotal)} total
+ </span>
+ </div>
+ {rankedCosts.slice(0, 8).map((cost) => {
+ const usd = cost.estimated_cost_usd ?? 0
+ const share = workflowCostsTotal > 0 ? usd / workflowCostsTotal : 0
+ return (
+ <ShareRow
+ key={cost.workflow_name || '(unknown)'}
+ label={cost.workflow_name || '(unknown workflow)'}
+ sub={`${formatMinutes(cost.billable_minutes)} billable`}
+ value={formatCost(usd)}
+ valueSub={`${Math.round(share * 100)}%`}
+ share={share}
+ color="var(--data-color-1)"
+ fullWidthBar
+ to={
+ singleRepo
+ ? combineUrl(
+ urls.engineeringAnalyticsWorkflowRuns(
+ singleRepo.repoOwner,
+ singleRepo.repoName,
+ cost.workflow_name
+ ),
+ sourceId ? { source: sourceId } : {}
+ ).url
+ : undefined
+ }
+ />
+ )
+ })}
{workflowCosts.length > 8 && (
<div className="pt-2 text-xs text-tertiary">
+{workflowCosts.length - 8} more{' '}
@@ -208,9 +225,7 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
</LemonCard>
) : (
<span className="text-xs text-secondary">
- {workflowCostsLoading
- ? 'Loading…'
- : "No cost data — the job-level source isn't synced, or nothing ran in the window."}
+ No cost data yet. The job-level source isn't synced, or nothing ran in the window.
</span>
)}
</Section>
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
index 154a471b541b..e2c80abf84a1 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
@@ -1,21 +1,13 @@
import { useActions, useValues } from 'kea'
-import {
- LemonButton,
- LemonInput,
- LemonInputSelect,
- LemonSegmentedButton,
- LemonSelect,
- LemonSwitch,
-} from '@posthog/lemon-ui'
-
-import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { LemonButton, LemonInput, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
+import { RepoEntityHeader } from '../components/EntityHeader'
import { PullRequestTable } from '../components/PullRequestTable'
-import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'
-import { StatCard } from '../components/StatCard'
+import { SourceScopeChip } from '../components/ScopeBar'
+import { HeroStat } from '../components/StatCard'
import { CIStatusFilter, PRStateFilter, engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
export function EngineeringAnalyticsPullRequests(): JSX.Element {
@@ -26,30 +18,19 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
pullRequestsLoading,
tableTruncated,
stateFilter,
- author,
- repo,
ciStatusFilter,
search,
- authorOptions,
- repoOptions,
hasActiveFilters,
activeCard,
+ readyCount,
+ thrashCount,
sourceId,
+ activeSource,
notConnected,
pullRequestsLoadError,
- costLensEnabled,
} = useValues(engineeringAnalyticsLogic)
- const {
- setStateFilter,
- setAuthor,
- setRepo,
- setCiStatusFilter,
- setSearch,
- resetFilters,
- applyCardFilter,
- setCostLensEnabled,
- refresh,
- } = useActions(engineeringAnalyticsLogic)
+ const { setStateFilter, setCiStatusFilter, setSearch, resetFilters, applyCardFilter, refresh } =
+ useActions(engineeringAnalyticsLogic)
// A 400 means no GitHub source — prompt to connect. A non-400 failure of this scene's data (cards or
// the PR list) shows a retryable error, never the misleading "connect" state.
@@ -60,38 +41,60 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
return <CIAnalyticsLoadError onRetry={refresh} />
}
- const failingPct =
- cards && cards.openPrs > 0 ? `${Math.round((cards.failingCi / cards.openPrs) * 100)}% of open` : undefined
-
return (
<div className="flex flex-col gap-4">
- <ScopeBar repoSlot={<SourceScopeChip />} showDate={false} />
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
- <StatCard
+ <RepoEntityHeader repoFullName={activeSource?.repo || ''} right={<SourceScopeChip pickerOnly />} />
+
+ <div className="flex flex-wrap items-center gap-1">
+ <HeroStat
label="Open PRs"
- value={cards ? humanFriendlyNumber(cards.openPrs) : '—'}
+ value={cards?.openPrs ?? null}
+ align="start"
loading={cardsLoading}
onClick={() => applyCardFilter('open')}
active={activeCard === 'open'}
- filterHint="Filter the list to open PRs"
+ filterHint="Show all open PRs"
/>
- <StatCard
+ <span className="mx-1 h-8 w-px bg-border" />
+ <HeroStat
label="Failing CI"
- value={cards ? humanFriendlyNumber(cards.failingCi) : '—'}
- caption={failingPct}
+ value={cards?.failingCi ?? null}
+ tone="danger"
+ align="start"
loading={cardsLoading}
onClick={() => applyCardFilter('failing')}
active={activeCard === 'failing'}
- filterHint="Filter the list to open PRs with failing CI"
+ filterHint="Show open PRs with failing CI"
/>
- <StatCard
- label="Stuck > 7d"
- value={cards ? humanFriendlyNumber(cards.stuck) : '—'}
- caption="excludes drafts and bots"
+ <HeroStat
+ label="Stuck >7d"
+ value={cards?.stuck ?? null}
+ tone="warning"
+ align="start"
loading={cardsLoading}
onClick={() => applyCardFilter('stuck')}
active={activeCard === 'stuck'}
- filterHint="Filter the list to PRs stuck open for over 7 days"
+ filterHint="Show PRs stuck open over 7 days (excludes drafts and bots)"
+ />
+ <HeroStat
+ label="CI thrash"
+ value={thrashCount}
+ tone="warning"
+ align="start"
+ loading={pullRequestsLoading}
+ onClick={() => applyCardFilter('thrash')}
+ active={activeCard === 'thrash'}
+ filterHint="Show open PRs burning re-run cycles"
+ />
+ <HeroStat
+ label="Ready"
+ value={readyCount}
+ tone="success"
+ align="start"
+ loading={pullRequestsLoading}
+ onClick={() => applyCardFilter('ready')}
+ active={activeCard === 'ready'}
+ filterHint="Show open, non-draft PRs with green CI"
/>
</div>
@@ -101,7 +104,7 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
placeholder="Search title, repo, author, #id…"
value={search}
onChange={setSearch}
- className="w-64"
+ className="w-80"
/>
<LemonSegmentedButton
size="small"
@@ -127,40 +130,13 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
{ value: 'none', label: 'CI: none', labelInMenu: 'No CI' },
]}
/>
- <LemonSelect
- size="small"
- placeholder="Repo: all"
- value={repo}
- onChange={setRepo}
- allowClear
- options={repoOptions.map((r) => ({ value: r, label: r }))}
- />
- <div className="w-48">
- <LemonInputSelect
- mode="single"
- size="small"
- placeholder="Author: anyone"
- value={author ? [author] : []}
- onChange={(values) => setAuthor(values[0] ?? null)}
- options={authorOptions.map((a) => ({ key: a, label: a }))}
- data-attr="engineering-analytics-author-filter"
- />
- </div>
- <LemonSwitch
- label="Cost columns"
- checked={costLensEnabled}
- onChange={setCostLensEnabled}
- size="small"
- bordered
- data-attr="engineering-analytics-cost-lens"
- />
</div>
<PullRequestTable
rows={filteredPullRequests}
loading={pullRequestsLoading}
sourceId={sourceId}
- costLensEnabled={costLensEnabled}
+ showCreated
emptyState={
hasActiveFilters ? (
<div className="flex flex-col items-center gap-2">
@@ -175,12 +151,7 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
}
/>
- <div className="text-xs text-tertiary">
- CI status is workflow-level for each pull request's latest commit, not per-check. A run that hasn't
- completed shows as Running, not a pass or fail. "Open→merge" is created-to-merged time (merged PRs
- only), never review or cycle time.
- {tableTruncated && ' Showing the most recent 1000 PRs.'}
- </div>
+ {tableTruncated && <div className="text-xs text-tertiary">Showing the most recent 1000 pull requests.</div>}
</div>
)
}
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
index 30db695f05e3..380f92494ac4 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
@@ -218,7 +218,7 @@ function FlakyTestLeaderboard(): JSX.Element {
dataSource={flakyTests?.rows ?? []}
rowKey={(row) => row.nodeid}
loading={flakyTestsLoading}
- pagination={{ pageSize: 50 }}
+ pagination={{ pageSize: 25 }}
useURLForSorting={false}
emptyState="No flaky tests detected in this window."
nouns={['flaky test', 'flaky tests']}
@@ -620,7 +620,7 @@ function QuarantineRegister(): JSX.Element {
dataSource={filteredQuarantineEntries}
rowKey={(row) => `${row.runner}:${row.id}`}
loading={quarantineLoading}
- pagination={{ pageSize: 50 }}
+ pagination={{ pageSize: 25 }}
useURLForSorting={false}
emptyState={
hasActiveQuarantineFilters ? (
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
index de44d6f79c65..422420f0d14d 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
@@ -6,7 +6,8 @@ import { LemonButton, LemonInput, LemonSegmentedButton } from '@posthog/lemon-ui
import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
-import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'
+import { RepoEntityHeader } from '../components/EntityHeader'
+import { BranchScopeChip, ScopeDateFilter, SourceScopeChip } from '../components/ScopeBar'
import { WorkflowHealthTable } from '../components/WorkflowHealthTable'
import { WorkflowsHealthHeader } from '../components/WorkflowsHealthHeader'
import { WORKFLOW_HEALTH_LIMIT, WorkflowStatusFilter, engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
@@ -22,6 +23,7 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
hasActiveWorkflowFilters,
workflowCostAvailable,
sourceId,
+ activeSource,
notConnected,
workflowHealthLoadError,
} = useValues(engineeringAnalyticsLogic)
@@ -37,9 +39,15 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
return (
<div className="flex flex-col gap-4">
- <ScopeBar repoSlot={<SourceScopeChip />} showBranch />
+ <RepoEntityHeader repoFullName={activeSource?.repo || ''} right={<SourceScopeChip pickerOnly />} />
- <WorkflowsHealthHeader summary={fleetSummary} truncated={fleetTruncated} />
+ {/* Branch + window govern every surface below — the same scope the overview's date filter carries. */}
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <BranchScopeChip />
+ <ScopeDateFilter />
+ </div>
+
+ <WorkflowsHealthHeader summary={fleetSummary} truncated={fleetTruncated} loading={workflowHealthLoading} />
<div className="flex flex-wrap items-center gap-2">
<LemonInput
@@ -70,7 +78,7 @@ export function EngineeringAnalyticsWorkflows(): JSX.Element {
loading={workflowHealthLoading}
sourceId={sourceId}
showCost={workflowCostAvailable}
- defaultSorting={{ columnKey: 'runCount', order: -1 }}
+ pageSize={25}
emptyState={
hasActiveWorkflowFilters ? (
<div className="flex flex-col items-center gap-2">
diff --git a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
index 1921717f4ac5..807cf21f0f51 100644
--- a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
@@ -11,6 +11,7 @@ import {
LemonTableColumns,
LemonTag,
Link,
+ Tooltip,
} from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
@@ -32,11 +33,12 @@ import { MetricTile } from '../components/MetricTile'
import { PullRequestStateTag } from '../components/PullRequestStateTag'
import { RunConclusionTag } from '../components/runTables'
import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'
-import { Section, SectionNav } from '../components/Section'
+import { Section } from '../components/Section'
import type { WorkflowJobApi } from '../generated/api.schemas'
import { compactUsd } from '../lib/format'
import { githubCommitUrl, githubPrUrl } from '../lib/github'
import { LifecycleSummary, WorkflowRun, isPassingConclusion } from '../lib/lifecycle'
+import { PushRound, pushRoundColor, pushRoundOf, pushRoundVerdictLabel } from '../lib/pushRounds'
import {
PrCommitRuns,
PrRunRow,
@@ -70,12 +72,14 @@ interface TimelineNode {
dotClass: string
/** The connector leading into this node — dashed when the time span is still running. */
dashedIncoming?: boolean
- /** Small caption under the dot — relative time, "pushed", "now", … */
+ /** Small caption under the dot — relative time, the push's CI wall time, "now", … */
sublabel?: ReactNode
/** Round nodes render the sha in mono. */
mono?: boolean
/** Color the label red — a failed round / closed PR. */
danger?: boolean
+ /** Push nodes carry their CI round: a bar above the dot (height = wall time, color = verdict). */
+ round?: PushRound
}
interface LifecycleStripProps {
@@ -93,17 +97,26 @@ function roundStart(group: PrCommitRuns): string | null {
// Fixed row heights so dots and connectors line up across columns regardless of label/pill height.
const ROW_LABEL = 'flex h-5 items-center'
+const ROW_BAR = 'flex h-10 items-end justify-center'
const ROW_DOT = 'flex h-3 items-center'
const ROW_SUB = 'flex h-4 items-center'
+// Tallest push bar in px — must fit inside ROW_BAR's h-10 (40px) with a little headroom.
+const BAR_MAX_PX = 34
+
+/** Dot color matching the round's verdict, so the timeline and the bars tell one story. */
+function roundDotClass(round: PushRound): string {
+ return round.failed ? 'bg-danger' : round.pending ? 'bg-warning' : 'bg-success'
+}
// Cap push nodes so the strip fits on one line; older pushes collapse into a "+N earlier" node, and
// every round stays reachable in the list below.
const MAX_PUSH_NODES = 4
/**
- * Horizontal lifecycle timeline: dots are milestones, the pill above each connector is the gap between
- * them. Chronological — a PR's head-SHA runs can start (and finish) after the merge. Each push is its own
- * node, red when that round had a failure; clicking it jumps to that round's run table below.
+ * Horizontal lifecycle timeline crossed with a per-push bar chart: dots are milestones, the pill above
+ * each connector is the gap between them, and each push node grows a bar — height is that push's
+ * wall-clock CI time (shared scale), color its verdict. Chronological — a PR's head-SHA runs can start
+ * (and finish) after the merge.
*/
function LifecycleStrip({ summary, openedAt, commitGroups }: LifecycleStripProps): JSX.Element {
const nodes: TimelineNode[] = [
@@ -120,28 +133,32 @@ function LifecycleStrip({ summary, openedAt, commitGroups }: LifecycleStripProps
const collapseOlder = commitGroups.length > MAX_PUSH_NODES + 1
const shownRounds = collapseOlder ? commitGroups.slice(0, MAX_PUSH_NODES) : commitGroups
const hiddenRounds = collapseOlder ? commitGroups.slice(MAX_PUSH_NODES) : []
- shownRounds.forEach((group, index) => {
+ shownRounds.forEach((group) => {
const at = roundStart(group)
if (!at) {
return
}
- const hasFailure = group.runs.some((run) => run.conclusion != null && !isPassingConclusion(run.conclusion))
+ const round = pushRoundOf(group.headSha, group.runs)
nodes.push({
key: `round-${group.headSha}`,
label: group.headSha.slice(0, 7),
at,
- dotClass: hasFailure ? 'bg-danger' : 'bg-muted',
+ dotClass: roundDotClass(round),
mono: true,
- danger: hasFailure,
- // index 0 is the latest push (newest-first).
- sublabel: index === 0 ? 'latest push' : 'pushed',
+ danger: round.failed,
+ // The bar carries the verdict; the sublabel answers "how long did CI take on this push".
+ sublabel:
+ round.wallSeconds != null
+ ? humanFriendlyDuration(round.wallSeconds, { maxUnits: 1 })
+ : round.pending
+ ? 'running'
+ : undefined,
+ round,
})
})
if (hiddenRounds.length) {
const at = roundStart(hiddenRounds[0])
- const anyFailure = hiddenRounds.some((group) =>
- group.runs.some((run) => run.conclusion != null && !isPassingConclusion(run.conclusion))
- )
+ const anyFailure = hiddenRounds.some((group) => pushRoundOf(group.headSha, group.runs).failed)
if (at) {
nodes.push({
key: 'earlier-pushes',
@@ -195,6 +212,11 @@ function LifecycleStrip({ summary, openedAt, commitGroups }: LifecycleStripProps
const totalSeconds = Math.max(1, dayjs(nodes[nodes.length - 1].at).diff(dayjs(nodes[0].at), 'second'))
const minGrow = totalSeconds * 0.04
+ // Shared scale across the push bars, so their heights compare push-to-push.
+ const maxWall = Math.max(...nodes.map((node) => node.round?.wallSeconds ?? 0), 1)
+ const barPx = (round: PushRound): number =>
+ round.wallSeconds != null ? Math.max(6, Math.round((round.wallSeconds / maxWall) * BAR_MAX_PX)) : 6
+
return (
<LemonCard hoverEffect={false} className="px-5 py-4">
<div className="flex items-center gap-6">
@@ -216,6 +238,7 @@ function LifecycleStrip({ summary, openedAt, commitGroups }: LifecycleStripProps
{gapBetween(nodes[index - 1].at, node.at)}
</span>
</span>
+ <span className={ROW_BAR} />
<span className={ROW_DOT}>
<span className={connector(node.dashedIncoming)} />
</span>
@@ -234,6 +257,30 @@ function LifecycleStrip({ summary, openedAt, commitGroups }: LifecycleStripProps
{node.label}
</span>
</span>
+ <span className={cn(ROW_BAR, 'w-full')}>
+ {node.round && (
+ <Tooltip
+ title={`${node.round.headSha.slice(0, 7)} · ${
+ node.round.wallSeconds != null
+ ? humanFriendlyDuration(node.round.wallSeconds)
+ : 'no completed runs'
+ } · ${pushRoundVerdictLabel(node.round)}`}
+ >
+ <span
+ className={cn(
+ 'w-2.5 rounded-t-sm',
+ node.round.pending && 'animate-pulse'
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ height: barPx(node.round),
+ backgroundColor: pushRoundColor(node.round),
+ opacity: node.round.failed ? 1 : node.round.pending ? 0.9 : 0.65,
+ }}
+ />
+ </Tooltip>
+ )}
+ </span>
<span className={cn(ROW_DOT, 'w-full')}>
<span className={cn('flex-1', index > 0 && connector(node.dashedIncoming))} />
<span className={cn('h-2.5 w-2.5 shrink-0 rounded-full', node.dotClass)} />
@@ -461,6 +508,16 @@ function PrWorkflowsTable({
setRunExpanded: (rowKey: string, expanded: boolean, runId: number | null, runAttempt: number | null) => void
}): JSX.Element {
const latestByWorkflow = latestRunPerWorkflow(filteredRuns)
+ const isWorkflowFailing = (workflowName: string): boolean => {
+ const latest = latestByWorkflow.get(workflowName)
+ return latest?.conclusion != null && !isPassingConclusion(latest.conclusion)
+ }
+ // Failing workflows first — the order a reviewer triages in — then alphabetical.
+ const orderedRows = [...rows].sort(
+ (a, b) =>
+ Number(isWorkflowFailing(b.workflowName)) - Number(isWorkflowFailing(a.workflowName)) ||
+ a.workflowName.localeCompare(b.workflowName)
+ )
const columns: LemonTableColumns<PrWorkflowRow> = [
{
title: 'Workflow',
@@ -552,7 +609,7 @@ function PrWorkflowsTable({
]
return (
<LemonTable
- dataSource={rows}
+ dataSource={orderedRows}
columns={columns}
size="small"
loading={loading}
@@ -595,6 +652,7 @@ export function PullRequestDetailScene(): JSX.Element {
prRunsLoading,
prRunsFailed,
prCost,
+ prCostLoading,
pushes,
rerunCycles,
workflowFilter,
@@ -620,6 +678,9 @@ export function PullRequestDetailScene(): JSX.Element {
const passed = runs.filter((run) => run.conclusion !== null && isPassingConclusion(run.conclusion)).length
const failed = runs.filter((run) => run.conclusion !== null && !isPassingConclusion(run.conclusion)).length
const running = runs.filter((run) => run.conclusion === null).length
+ // The newest push's CI round — the wall-time tile and the lifecycle strip's last bar agree by construction.
+ const latestRound = commitGroups[0] ? pushRoundOf(commitGroups[0].headSha, commitGroups[0].runs) : null
+ const tilesLoading = prRunsLoading && commitGroups.length === 0
if (loadFailed) {
return (
@@ -640,7 +701,7 @@ export function PullRequestDetailScene(): JSX.Element {
return (
<SceneContent>
<SceneTitleSection
- name={pullRequest?.title ?? 'Pull request'}
+ name="Pull request"
resourceType={{ type: 'health' }}
actions={
githubUrl ? (
@@ -734,6 +795,18 @@ export function PullRequestDetailScene(): JSX.Element {
? 'passing'
: undefined
}
+ loading={tilesLoading}
+ />
+ <MetricTile
+ label="CI wall time"
+ tooltip="On the newest commit: earliest run start to latest completed run end."
+ value={
+ latestRound?.wallSeconds != null
+ ? humanFriendlyDuration(latestRound.wallSeconds, { maxUnits: 2 })
+ : '—'
+ }
+ sub={latestRound?.pending ? 'still running' : undefined}
+ loading={tilesLoading}
/>
<MetricTile
label="Pushes"
@@ -744,6 +817,7 @@ export function PullRequestDetailScene(): JSX.Element {
<span className="font-semibold text-warning-dark">+{rerunCycles} re-runs</span>
) : undefined
}
+ loading={tilesLoading}
/>
<MetricTile
label="CI cost"
@@ -756,15 +830,7 @@ export function PullRequestDetailScene(): JSX.Element {
}
value={prCost?.jobs_available ? compactUsd(prCost.estimated_cost_usd) : '—'}
sub={prCost?.jobs_available ? undefined : 'Job-level source not synced'}
- />
- <MetricTile
- label={
- summary?.mergedAt ? 'Open → merge' : summary?.closedAt ? 'Open → close' : 'Open so far'
- }
- value={gapBetween(
- summary?.openedAt ?? pullRequest.created_at,
- summary?.mergedAt ?? summary?.closedAt ?? dayjs().toISOString()
- )}
+ loading={prCostLoading && !prCost}
/>
</div>
</>
@@ -772,14 +838,6 @@ export function PullRequestDetailScene(): JSX.Element {
<LemonSkeleton className="h-24 w-full" />
)}
- <SectionNav
- items={[
- { id: 'pr-timeline', label: 'Lifecycle' },
- { id: 'pr-runs', label: 'CI runs' },
- { id: 'pr-failures', label: 'Failures' },
- ]}
- />
-
<Section id="pr-timeline" title="Lifecycle">
{summary && pullRequest ? (
<LifecycleStrip
@@ -801,7 +859,6 @@ export function PullRequestDetailScene(): JSX.Element {
Cumulative · {pluralize(passed, 'run')} passed
{failed > 0 && <> · {failed} failed</>}
{running > 0 && <> · {running} still running</>}
- {commitGroups.length > 1 && <> · {pluralize(commitGroups.length, 'commit')}</>}
</span>
) : undefined
}
diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx
index 60fa472c9dd5..71a6b5b74868 100644
--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx
+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx
@@ -16,8 +16,8 @@ import type {
const SOURCES: GitHubSourceApi[] = [{ id: 'src-1', repo: 'PostHog/posthog', prefix: '' }]
-// Deltas cover every pill state: pp up (good), % up (neutral), % up while good-is-down (bad), and
-// an hours drop (good) — the surface this scene's quill MetricCard migration changed.
+// One overview payload feeding the whole hub: the trend sparkline cards and the quill cost-per-merge
+// line chart. Each trend series carries a null bucket so the trim + carry-forward path is exercised.
const OVERVIEW: RepoOverviewApi = {
run_count: 1284,
run_count_prev: 1122,
@@ -40,6 +40,23 @@ const OVERVIEW: RepoOverviewApi = {
merges: 8,
cost_per_merge_usd: cost,
})),
+ time_to_green_series: [540, 600, null, 660, 720, 900, 780].map((p50_seconds, i) => ({
+ bucket_start: `2026-06-${25 + i}T00:00:00Z`,
+ p50_seconds,
+ })),
+ time_to_green_series_granularity: 'day',
+ success_rate_series: [0.82, 0.85, 0.8, null, 0.88, 0.79, 0.87].map((success_rate, i) => ({
+ bucket_start: `2026-06-${25 + i}T00:00:00Z`,
+ success_rate,
+ })),
+ success_rate_series_granularity: 'day',
+ open_to_merge_series: [14 * 3600, 16 * 3600, null, 12 * 3600, 15 * 3600, 18 * 3600, 13 * 3600].map(
+ (p50_seconds, i) => ({
+ bucket_start: `2026-06-${25 + i}T00:00:00Z`,
+ p50_seconds,
+ })
+ ),
+ open_to_merge_series_granularity: 'day',
}
const ACTIVITY: WorkflowRunActivityApi = {
@@ -50,6 +67,7 @@ const ACTIVITY: WorkflowRunActivityApi = {
duration_seconds: duration,
head_branch: 'master',
pr_number: 0,
+ head_sha: `deadbeef${String(i).padStart(2, '0')}`,
})),
truncated: false,
limit: 500,
@@ -98,6 +116,29 @@ const PULL_REQUESTS: PullRequestListApi = {
author: { handle: 'jane-dev', display_name: 'Jane Dev', avatar_url: '', is_bot: false },
repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },
ci: { runs: 6, passing: 4, failing: 2, pending: 0, failing_workflows: ['Backend CI', 'E2E - Playwright'] },
+ push_history: [
+ {
+ head_sha: 'aaa111',
+ started_at: '2026-06-24T11:00:00Z',
+ wall_seconds: 1320,
+ failed: false,
+ pending: false,
+ },
+ {
+ head_sha: 'bbb222',
+ started_at: '2026-06-25T09:30:00Z',
+ wall_seconds: 1500,
+ failed: false,
+ pending: false,
+ },
+ {
+ head_sha: 'ccc333',
+ started_at: '2026-06-26T14:00:00Z',
+ wall_seconds: 1680,
+ failed: true,
+ pending: false,
+ },
+ ],
number: 41231,
title: 'feat(insights): sticky breakdown legends',
state: 'open',
@@ -115,6 +156,29 @@ const PULL_REQUESTS: PullRequestListApi = {
author: { handle: 'sam-eng', display_name: 'Sam Eng', avatar_url: '', is_bot: false },
repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },
ci: { runs: 5, passing: 5, failing: 0, pending: 0 },
+ push_history: [
+ {
+ head_sha: 'ddd444',
+ started_at: '2026-06-30T09:15:00Z',
+ wall_seconds: 900,
+ failed: false,
+ pending: false,
+ },
+ {
+ head_sha: 'eee555',
+ started_at: '2026-06-30T15:00:00Z',
+ wall_seconds: 1020,
+ failed: false,
+ pending: false,
+ },
+ {
+ head_sha: 'fff666',
+ started_at: '2026-07-01T08:00:00Z',
+ wall_seconds: 960,
+ failed: false,
+ pending: false,
+ },
+ ],
number: 41250,
title: 'fix(cohorts): handle empty cohort in query builder',
state: 'merged',
@@ -142,8 +206,8 @@ const meta: Meta = {
mockDate: '2026-07-02',
featureFlags: [FEATURE_FLAGS.ENGINEERING_ANALYTICS],
testOptions: {
- // The change pill only renders once the overview payload (and its deltas) has landed.
- waitForSelector: '[data-attr="metric-card-change-pill"]',
+ // The hub is past its skeletons once the "needs attention" PR table has rendered.
+ waitForSelector: '[data-attr="engineering-analytics-attention-prs"]',
},
},
decorators: [
diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
index 0620b11e487c..9c54fd2ec6fe 100644
--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
@@ -4,8 +4,7 @@
import { useActions, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
-import { IconBox } from '@posthog/icons'
-import { LemonCard, LemonSkeleton, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonButton, LemonCard, LemonSkeleton, LemonTable, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
import { TimeSeriesLineChart, useChartTheme } from '@posthog/quill-charts'
import { TZLabel } from 'lib/components/TZLabel'
@@ -16,97 +15,83 @@ import { urls } from 'scenes/urls'
import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
-import { EntityHeader } from '../components/EntityHeader'
+import { RepoEntityHeader } from '../components/EntityHeader'
import { FailureLogGroups } from '../components/FailureLogs'
-import { MetricTile, percentChange, pointChange } from '../components/MetricTile'
import { PullRequestTable } from '../components/PullRequestTable'
-import { RunActivityChart, hasEnoughRunActivity } from '../components/RunActivityChart'
-import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'
-import { Section, SectionNav, scrollToSection } from '../components/Section'
-import { ShareRow } from '../components/ShareRow'
+import { formatAxisMinutes, hasEnoughRunActivity } from '../components/RunActivityChart'
+import { RunActivityMiniBars } from '../components/RunActivityMiniBars'
+import { ScopeDateFilter, SourceScopeChip } from '../components/ScopeBar'
+import { Section, scrollToSection } from '../components/Section'
+import { HeroStat } from '../components/StatCard'
+import { TrendCard } from '../components/TrendCard'
import { WorkflowHealthTable } from '../components/WorkflowHealthTable'
import type { MasterFailureGroupApi } from '../generated/api.schemas'
-import { compactCount, compactHoursLabel, compactMinutes, compactUsd, percent } from '../lib/format'
+import { compactHoursLabel, compactMinutes, compactUsd, percent } from '../lib/format'
+import { githubCommitUrl } from '../lib/github'
+import { HUB_PREVIEW_MAX } from '../lib/preview'
import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
import { repoOverviewLogic } from './repoOverviewLogic'
-const SHARE_COLORS = [
- 'var(--data-color-1)',
- 'var(--data-color-2)',
- 'var(--data-color-3)',
- 'var(--data-color-4)',
- 'var(--data-color-5)',
-]
-
-// The hub shows capped tables; the dedicated list pages keep the full 50-per-page tables.
-const HUB_TABLE_PAGE_SIZE = 8
-
function withSource(url: string, sourceId: string | null): string {
return combineUrl(url, sourceId ? { source: sourceId } : {}).url
}
-function RepoEntityHeader({ repoFullName }: { repoFullName: string }): JSX.Element {
- const name = repoFullName.split('/')[1] || repoFullName || 'GitHub repository'
- return (
- <EntityHeader
- icon={<IconBox />}
- title={name}
- // No slug line when the source hasn't reported a repo name yet.
- slug={
- repoFullName ? (
- <>
- {repoFullName}
- {' · '}
- <Link to={`https://github.com/${repoFullName}`} target="_blank" targetBlankIcon>
- View on GitHub
- </Link>
- </>
- ) : undefined
- }
- />
- )
-}
-
-/** Default-branch verdict tile: a calm dot when clean, a red "N failing" that jumps to the triage table. */
-function MasterStatusTile({
+/** The page's thesis: is the pipeline healthy right now? Default-branch verdict plus open-PR backlog
+ * pressure, both current-state, so it sits above the date filter that scopes everything below. */
+function PipelineVerdictHero({
failingCount,
+ failingWorkflows,
loading,
defaultBranch,
+ backlog,
}: {
failingCount: number
+ failingWorkflows: string[]
loading: boolean
defaultBranch: string
+ backlog: { open: number | null; failingCi: number | null; stuck: number | null }
}): JSX.Element {
const failing = failingCount > 0
const dotColor = loading ? 'var(--muted)' : failing ? 'var(--danger)' : 'var(--success)'
- const status = loading ? 'Checking…' : failing ? `${failingCount} failing` : 'Passing'
+ const status = loading ? 'Checking' : failing ? `${failingCount} failing` : 'Passing'
+ // Only the failing state earns a subline (which workflows broke). "Passing" already says the rest.
+ const failingNames = failingWorkflows.slice(0, 3).join(', ') + (failingCount > 3 ? ` +${failingCount - 3}` : '')
return (
<LemonCard
hoverEffect={failing}
onClick={failing ? () => scrollToSection('now') : undefined}
- className="flex min-w-44 flex-1 flex-col justify-center gap-1 px-5 py-4"
+ className={cn(
+ 'flex flex-wrap items-center justify-between gap-x-8 gap-y-4 px-6 py-5',
+ failing && 'bg-fill-error-tertiary'
+ )}
>
- <Tooltip title="Workflows failing on the default branch in the last 24 hours.">
- <span className="self-start cursor-default text-sm font-medium">
- {defaultBranch === 'main' ? 'Main' : 'Master'}
- </span>
- </Tooltip>
- {/* Typography mirrors quill MetricCard so the tile sits flush in the stat strip. */}
- <span className="mt-2 flex items-center gap-2">
- <span
- className="inline-block size-2.5 shrink-0 rounded-full"
- // eslint-disable-next-line react/forbid-dom-props
- style={{ backgroundColor: dotColor }}
- />
- <span
- className={cn(
- 'text-4xl font-bold leading-none tracking-tight',
- loading ? 'text-tertiary' : failing ? 'text-danger' : 'text-primary'
- )}
- >
- {status}
+ <div className="flex min-w-0 flex-col gap-1.5">
+ <Tooltip title="Default-branch workflow runs failing in the last 24 hours.">
+ <span className="w-fit cursor-default font-mono text-xs text-tertiary">{defaultBranch}</span>
+ </Tooltip>
+ <span className="flex items-baseline gap-2.5">
+ <span
+ className="inline-block size-2.5 shrink-0 translate-y-[-0.15em] rounded-full"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ backgroundColor: dotColor }}
+ />
+ <span
+ className={cn(
+ 'text-3xl font-bold leading-none tracking-tight',
+ loading ? 'text-tertiary' : failing ? 'text-danger' : 'text-primary'
+ )}
+ >
+ {status}
+ </span>
+ {failing && <span className="text-sm font-medium text-danger">View →</span>}
</span>
- </span>
+ {failing && <span className="truncate text-xs text-secondary">{failingNames}</span>}
+ </div>
+ <div className="flex items-center gap-6">
+ <HeroStat label="Open PRs" value={backlog.open} />
+ <HeroStat label="Failing CI" value={backlog.failingCi} tone="danger" />
+ <HeroStat label="Stuck >7d" value={backlog.stuck} tone="warning" />
+ </div>
</LemonCard>
)
}
@@ -240,32 +225,48 @@ export function RepoOverviewScene(): JSX.Element {
repoActivityLoading,
repoActivityFailed,
attentionPrs,
- draftCount,
- costByWorkflow,
- otherCostWorkflowCount,
costPerMergeSeries,
+ timeToGreenSeries,
+ passRateSeries,
+ openToMergeSeries,
jobsAvailable,
defaultBranch,
notConnected,
overviewFailed,
overviewLoading,
failingWorkflowCount,
+ masterFailures,
masterFailuresLoading,
+ prPreviewCount,
+ workflowPreviewCount,
} = useValues(repoOverviewLogic)
- const {
- cards,
- pullRequestsLoading,
- workflowHealth,
- workflowHealthLoading,
- sourceId,
- costLensEnabled,
- activeSource,
- } = useValues(engineeringAnalyticsLogic)
- const { loadOverview, loadMasterFailures, loadRepoActivity } = useActions(repoOverviewLogic)
+ const { cards, pullRequestsLoading, workflowHealth, workflowHealthLoading, sourceId, activeSource } =
+ useValues(engineeringAnalyticsLogic)
+ const { loadOverview, loadMasterFailures, loadRepoActivity, showMorePrs, showMoreWorkflows } =
+ useActions(repoOverviewLogic)
const { searchParams } = useValues(router)
const { timezone } = useValues(teamLogic)
const chartTheme = useChartTheme()
+ // Window/source changes reload the overview, activity, and workflow health (the date-scoped surfaces);
+ // the PR backlog is current-state, not windowed, so it stays put. Surface the reload so a window change
+ // doesn't silently swap stale numbers.
+ const hubReloading = overviewLoading || repoActivityLoading || workflowHealthLoading
+
+ // The hub previews each table: a short, sorted slice with "Show more" to grow in place, and "View all"
+ // to the dedicated full table. Workflows are ranked by cost (or run count) to pick the top few; the
+ // table then displays them failing-first-then-name. attentionPrs is already ordered failing-first.
+ // Distinct workflow names failing on the default branch — the hero's "what's broken" subline.
+ const failingWorkflows = Array.from(new Set(masterFailures.map((group) => group.workflow_name)))
+ const shownPrs = attentionPrs.slice(0, prPreviewCount)
+ const canShowMorePrs = shownPrs.length < attentionPrs.length && prPreviewCount < HUB_PREVIEW_MAX
+ // Rank the leaderboard by spend when cost is known (where the money goes), else by run volume.
+ const rankedWorkflows = jobsAvailable
+ ? [...workflowHealth].sort((a, b) => (b.estimatedCostUsd ?? -1) - (a.estimatedCostUsd ?? -1))
+ : [...workflowHealth].sort((a, b) => b.runCount - a.runCount)
+ const shownWorkflows = rankedWorkflows.slice(0, workflowPreviewCount)
+ const canShowMoreWorkflows = shownWorkflows.length < workflowHealth.length && workflowPreviewCount < HUB_PREVIEW_MAX
+
// jobsAvailable reads false until the overview payload lands, so "not synced" messaging
// during the initial fetch would misread as a broken setup — hold it back while loading.
const overviewPending = overviewLoading && !overview
@@ -287,98 +288,167 @@ export function RepoOverviewScene(): JSX.Element {
return (
<div className="flex flex-col gap-4">
- {/* The entity header below is the repo identity — the scope bar only adds the source
- picker (multi-source teams) so the repo name isn't stated twice on one screen. */}
- <ScopeBar repoSlot={<SourceScopeChip pickerOnly />} />
-
+ {/* Repo identity. The scope controls used to dock here; they now sit below the verdict hero, so
+ the date filter visibly governs only the windowed surfaces beneath it. */}
<RepoEntityHeader repoFullName={activeSource?.repo || ''} />
- <div className="flex flex-wrap gap-2.5">
- <MasterStatusTile
- failingCount={failingWorkflowCount}
- loading={masterFailuresLoading}
- defaultBranch={defaultBranch}
- />
- <MetricTile
- label="Pass rate"
- tooltip="Workflow-level, across all branches."
- value={percent(overview?.success_rate)}
- delta={{
- value: pointChange(overview?.success_rate, overview?.success_rate_prev),
- unit: 'pp',
- }}
- />
- <MetricTile
- label="Runs"
- value={compactCount(overview?.run_count)}
- delta={{ value: percentChange(overview?.run_count, overview?.run_count_prev) }}
- />
- <MetricTile
- label="CI cost"
- tooltip={
- jobsAvailable
- ? `Estimated: ${compactMinutes(overview?.billable_minutes)} billable × runner-tier rate.`
- : overviewPending
- ? undefined
- : 'Available once the job-level source is synced.'
- }
- value={jobsAvailable ? compactUsd(overview?.estimated_cost_usd) : '—'}
- delta={
- jobsAvailable
- ? {
- value: percentChange(overview?.estimated_cost_usd, overview?.estimated_cost_usd_prev),
- goodWhenDown: true,
- }
- : undefined
- }
- sub={jobsAvailable || overviewPending ? undefined : 'Job-level source not synced'}
- />
- <MetricTile
- label="Median PR open→merge"
- tooltip="Created to merged, over PRs merged in the window. Bots and drafts excluded."
- value={compactHoursLabel(overview?.median_open_to_merge_seconds)}
- delta={{
- value:
- overview?.median_open_to_merge_seconds != null &&
- overview?.median_open_to_merge_seconds_prev != null
- ? (overview.median_open_to_merge_seconds - overview.median_open_to_merge_seconds_prev) /
- 3600
- : null,
- unit: 'h',
- goodWhenDown: true,
- }}
- />
- <MetricTile
- label="Re-run cycles"
- tooltip="Runs with attempt > 1 in the window."
- value={compactCount(overview?.rerun_cycles)}
- delta={{
- value: percentChange(overview?.rerun_cycles, overview?.rerun_cycles_prev),
- goodWhenDown: true,
- }}
- />
+ {/* The thesis: is the pipeline healthy right now? Current-state, above the date filter. */}
+ <PipelineVerdictHero
+ failingCount={failingWorkflowCount}
+ failingWorkflows={failingWorkflows}
+ loading={masterFailuresLoading}
+ defaultBranch={defaultBranch}
+ backlog={{
+ open: cards?.openPrs ?? null,
+ failingCi: cards?.failingCi ?? null,
+ stuck: cards?.stuck ?? null,
+ }}
+ />
+
+ {/* Now zone: current-state surfaces above the filter. The hero owns the backlog summary, so this
+ section is just the triage table. */}
+ <MasterFailuresSection />
+
+ <Section id="prs" title="Pull requests needing attention">
+ <LemonCard hoverEffect={false} className="overflow-hidden p-0">
+ <PullRequestTable
+ rows={shownPrs}
+ loading={pullRequestsLoading}
+ sourceId={sourceId}
+ embedded
+ pageSize={HUB_PREVIEW_MAX}
+ emptyState="Nothing failing or stuck in the open backlog."
+ dataAttr="engineering-analytics-attention-prs"
+ />
+ <div className="flex flex-wrap items-center justify-between gap-2 border-t border-primary px-4 py-2 text-[11px] text-tertiary">
+ <span>
+ Showing {shownPrs.length} of {humanFriendlyNumber(attentionPrs.length)} needing attention
+ </span>
+ <div className="flex items-center gap-3">
+ {canShowMorePrs && (
+ <LemonButton size="xsmall" onClick={showMorePrs}>
+ Show more
+ </LemonButton>
+ )}
+ <Link to={withSource(urls.engineeringAnalyticsPullRequestList(), sourceId)}>
+ View all →
+ </Link>
+ </div>
+ </div>
+ </LemonCard>
+ </Section>
+
+ {/* The filter is the seam: everything above is current-state, everything below reflects its window. */}
+ <div className="mt-1 flex flex-wrap items-center justify-end gap-2 border-t border-primary pt-4">
+ {hubReloading && <Spinner className="text-secondary" />}
+ <SourceScopeChip pickerOnly />
+ <ScopeDateFilter />
</div>
- <SectionNav
- items={[
- { id: 'master', label: `${defaultBranch === 'main' ? 'Main' : 'Master'} health` },
- { id: 'now', label: `Failing on ${defaultBranch}` },
- { id: 'prs', label: 'Pull requests' },
- { id: 'workflows', label: 'Workflows' },
- { id: 'cost', label: 'Cost' },
- ]}
- />
+ {/* The windowed headline metrics, each a value + colored delta over a sentiment-colored sparkline.
+ CI cost is a window total, not a rate, so its number lives on the Workflows section below. */}
+ <Section id="trends" title="Trends" busy={overviewLoading}>
+ <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
+ {/* CI health: share of completed runs that passed, all branches. */}
+ <TrendCard
+ title="Pass rate"
+ series={passRateSeries}
+ formatValue={(value) => percent(value)}
+ renderTooltipValue={(value) => percent(value, 1)}
+ loading={overviewPending}
+ emptyText="Not enough completed CI runs in the window yet."
+ caption="Share of completed CI runs that passed, all branches."
+ />
+
+ {/* Median time-to-green on PR runs (success-only, PR-scoped; see #67398). */}
+ <TrendCard
+ title="PR time to green"
+ series={timeToGreenSeries}
+ formatValue={formatAxisMinutes}
+ renderTooltipValue={formatAxisMinutes}
+ goodWhenDown
+ loading={overviewPending}
+ emptyText="Not enough successful PR CI runs in the window yet."
+ caption="Median time-to-green on pull requests: successful runs only, default branch excluded."
+ />
+
+ {/* PR throughput: coarse created→merged time, bots and drafts excluded. */}
+ <TrendCard
+ title="Median PR open→merge"
+ series={openToMergeSeries}
+ formatValue={compactHoursLabel}
+ renderTooltipValue={compactHoursLabel}
+ goodWhenDown
+ loading={overviewPending}
+ emptyText="No PRs merged in the window yet."
+ caption="Median created-to-merged time, bots and drafts excluded. Coarse: draft and ready time are fused."
+ />
- <Section id="master" title={`${defaultBranch === 'main' ? 'Main' : 'Master'} health`}>
- {/* One dot per commit to the default branch: X = when its CI started, Y = wall-clock CI
- duration, color = the commit's overall verdict (red if any workflow failed). Replaces the
- old success-rate line + failed-runs bar — the scatter says time, outcome, and cost at once. */}
+ {/* CI cost per merged PR — the headline economic trend, so it earns a full quill line
+ chart (axes + tooltip) rather than a sparkline. costPerMergeSeries carries ISO labels
+ plus its interval; the chart owns tick/tooltip date formatting. Card chrome mirrors
+ TrendCard so it sits flush in the grid. */}
+ <LemonCard hoverEffect={false} className="flex flex-col p-4">
+ <h3 className="mb-1 text-xs font-semibold text-secondary">Cost per merged PR</h3>
+ {overviewPending ? (
+ <LemonSkeleton className="h-20 w-full" />
+ ) : jobsAvailable && costPerMergeSeries ? (
+ <div className="h-20 w-full">
+ <TimeSeriesLineChart
+ series={[
+ {
+ key: 'cost_per_merge',
+ label: 'Cost per merged PR',
+ data: costPerMergeSeries.values,
+ },
+ ]}
+ labels={costPerMergeSeries.labels}
+ theme={chartTheme}
+ config={{
+ xAxis: { timezone, interval: costPerMergeSeries.interval },
+ yAxis: { format: 'currency', currency: 'USD' },
+ tooltip: { valueFormatter: (value) => compactUsd(value) },
+ }}
+ />
+ </div>
+ ) : (
+ <div className="flex h-20 items-center text-xs text-secondary">
+ {jobsAvailable
+ ? 'No costable jobs in the window.'
+ : 'Cost appears once the job-level source is synced.'}
+ </div>
+ )}
+ <div className="mt-2 border-t border-primary pt-2 text-[11px] text-tertiary">
+ Estimated Depot CI cost per merged PR, trailing-window ratio. Per-workflow spend is in
+ Workflows below.
+ </div>
+ </LemonCard>
+ </div>
+ </Section>
+
+ <Section
+ id="master"
+ title={`${defaultBranch === 'main' ? 'Main' : 'Master'} health`}
+ busy={repoActivityLoading}
+ >
+ {/* Hub preview: one bar per default-branch commit, height = CI duration, color = verdict — the
+ at-a-glance "is master healthy and fast lately" read without the full chart's weight. The
+ full scatter (start-time axis, in-flight band, zoom) lives on the workflow page. */}
{hasEnoughRunActivity(activityRuns) ? (
- <RunActivityChart
+ <RunActivityMiniBars
runs={activityRuns}
truncated={activityTruncated}
- title={`Every ${defaultBranch} commit`}
+ title="CI duration per commit"
noun="commit"
+ onBarClick={(run) => {
+ // Each bar is a whole commit (its workflows collapsed), so open the commit on
+ // GitHub — all its checks — rather than one arbitrary workflow run.
+ const [owner, repoName] = (activeSource?.repo || '').split('/')
+ if (!run.headSha || !owner || !repoName) {
+ return
+ }
+ window.open(githubCommitUrl(owner, repoName, run.headSha), '_blank', 'noopener,noreferrer')
+ }}
/>
) : (
<LemonCard hoverEffect={false} className="p-4 text-xs text-secondary">
@@ -391,154 +461,59 @@ export function RepoOverviewScene(): JSX.Element {
)}
</Section>
- <MasterFailuresSection />
-
- <Section id="prs" title="Pull requests needing attention">
- <div className="mb-2 flex flex-wrap gap-2 text-xs text-secondary">
- <span>
- <strong className="text-primary">{cards ? humanFriendlyNumber(cards.openPrs) : '…'}</strong>{' '}
- open
- </span>
- <span>·</span>
- <span>
- <strong className="text-primary">{humanFriendlyNumber(draftCount)}</strong> drafts
- </span>
- <span>·</span>
- <span>
- <strong className="text-danger">{cards ? humanFriendlyNumber(cards.failingCi) : '…'}</strong>{' '}
- failing CI
- </span>
- <span>·</span>
- <span>
- <strong className="text-warning-dark">{cards ? humanFriendlyNumber(cards.stuck) : '…'}</strong>{' '}
- stuck &gt;7d
- </span>
- </div>
- <LemonCard hoverEffect={false} className="overflow-hidden p-0">
- <PullRequestTable
- rows={attentionPrs}
- loading={pullRequestsLoading}
- sourceId={sourceId}
- costLensEnabled={costLensEnabled}
- embedded
- pageSize={HUB_TABLE_PAGE_SIZE}
- emptyState="Nothing failing or stuck in the open backlog."
- dataAttr="engineering-analytics-attention-prs"
- />
- <div className="border-t border-primary px-4 py-2 text-[11px] text-tertiary">
- Showing {attentionPrs.length} of {cards ? humanFriendlyNumber(cards.openPrs) : '…'} open pull
- requests ·{' '}
- <Link to={withSource(urls.engineeringAnalyticsPullRequestList(), sourceId)}>View all</Link>
- </div>
- </LemonCard>
- </Section>
-
- <Section id="workflows" title="Workflows">
+ <Section
+ id="workflows"
+ title={jobsAvailable ? 'Top workflows by cost' : 'Busiest workflows'}
+ right={
+ jobsAvailable && overview?.estimated_cost_usd != null ? (
+ <Tooltip
+ title={`Estimated: ${compactMinutes(overview?.billable_minutes)} billable × runner-tier rate, across all workflows in the window.`}
+ >
+ <span className="cursor-default text-tertiary">
+ {compactUsd(overview.estimated_cost_usd)} total CI spend
+ </span>
+ </Tooltip>
+ ) : undefined
+ }
+ >
<LemonCard hoverEffect={false} className="overflow-hidden p-0">
<WorkflowHealthTable
- rows={workflowHealth}
+ rows={shownWorkflows}
loading={workflowHealthLoading}
sourceId={sourceId}
showCost={jobsAvailable}
embedded
- defaultSorting={{ columnKey: 'runCount', order: -1 }}
- pageSize={HUB_TABLE_PAGE_SIZE}
+ compact
+ pageSize={HUB_PREVIEW_MAX}
emptyState="No workflow runs in the window."
/>
- <div className="border-t border-primary px-4 py-2 text-[11px] text-tertiary">
- Showing top {Math.min(HUB_TABLE_PAGE_SIZE, workflowHealth.length)} of {workflowHealth.length}{' '}
- workflows ·{' '}
- <Link
- to={
- // A bare link would reset the shared window/branch scope (the filters logic
- // re-hydrates from the URL on every route) — carry it, plus the source.
- combineUrl(urls.engineeringAnalyticsWorkflows(), {
- ...(searchParams.date_from ? { date_from: searchParams.date_from } : {}),
- ...(searchParams.date_to ? { date_to: searchParams.date_to } : {}),
- ...(searchParams.q ? { q: searchParams.q } : {}),
- ...(sourceId ? { source: sourceId } : {}),
- }).url
- }
- >
- View all
- </Link>
- </div>
- </LemonCard>
- </Section>
-
- <Section id="cost" title="Cost">
- {overviewPending ? (
- <LemonCard hoverEffect={false} className="p-4">
- <LemonSkeleton className="mb-3 h-4 w-40" />
- <LemonSkeleton className="h-24 w-full" />
- </LemonCard>
- ) : jobsAvailable && costPerMergeSeries ? (
- <LemonCard hoverEffect={false} className="mb-2 p-4">
- <h3 className="mb-1 text-xs font-semibold text-secondary">Cost per merged PR</h3>
- {/* Charts fill their container, so the wrapper pins an explicit height. */}
- <div className="h-32 w-full">
- <TimeSeriesLineChart
- series={[
- {
- key: 'cost_per_merge',
- label: 'Cost per merged PR',
- data: costPerMergeSeries.values,
- },
- ]}
- labels={costPerMergeSeries.labels}
- theme={chartTheme}
- config={{
- xAxis: { timezone, interval: costPerMergeSeries.interval },
- yAxis: { format: 'currency', currency: 'USD' },
- tooltip: { valueFormatter: (value) => compactUsd(value) },
- }}
- />
- </div>
- <div className="mt-2 border-t border-primary pt-2 text-[11px] text-tertiary">
- Estimated Depot CI cost per PR merged. Each point divides a trailing window's CI cost by its
- merges (24 h, 7 d, or 4 w to match the grain), so quiet buckets don't punch holes in the
- trend. Cost counts by run start, merges by merge time — the same coarse split the daily
- depot tooling uses.
- </div>
- </LemonCard>
- ) : null}
- {overviewPending ? null : jobsAvailable && costByWorkflow.length > 0 ? (
- <LemonCard hoverEffect={false} className="p-4">
- <h3 className="mb-1 text-xs font-semibold text-secondary">By workflow</h3>
- {costByWorkflow.map((row, i) => (
- <ShareRow
- key={row.workflowName ?? 'other'}
- label={row.workflowName ?? `Other (${otherCostWorkflowCount} workflows)`}
- value={compactUsd(row.costUsd)}
- valueSub={`${Math.round(row.share * 100)}% of total`}
- share={row.share}
- color={row.workflowName ? SHARE_COLORS[i % SHARE_COLORS.length] : 'var(--muted)'}
+ <div className="flex flex-wrap items-center justify-between gap-2 border-t border-primary px-4 py-2 text-[11px] text-tertiary">
+ <span>
+ Showing top {shownWorkflows.length} of {workflowHealth.length} workflows
+ </span>
+ <div className="flex items-center gap-3">
+ {canShowMoreWorkflows && (
+ <LemonButton size="xsmall" onClick={showMoreWorkflows}>
+ Show more
+ </LemonButton>
+ )}
+ <Link
to={
- row.workflowName && workflowHealth.length
- ? withSource(
- urls.engineeringAnalyticsWorkflowRuns(
- workflowHealth[0].repoOwner,
- workflowHealth[0].repoName,
- row.workflowName
- ),
- sourceId
- )
- : undefined
+ // A bare link would reset the shared window/branch scope (the filters logic
+ // re-hydrates from the URL on every route) — carry it, plus the source.
+ combineUrl(urls.engineeringAnalyticsWorkflows(), {
+ ...(searchParams.date_from ? { date_from: searchParams.date_from } : {}),
+ ...(searchParams.date_to ? { date_to: searchParams.date_to } : {}),
+ ...(searchParams.q ? { q: searchParams.q } : {}),
+ ...(sourceId ? { source: sourceId } : {}),
+ }).url
}
- />
- ))}
- <div className="mt-2 border-t border-primary pt-2 text-[11px] text-tertiary">
- Estimated from billable job minutes × runner-tier rate. GitHub-hosted runners are free for
- open source.
+ >
+ View all →
+ </Link>
</div>
- </LemonCard>
- ) : (
- <LemonCard hoverEffect={false} className="p-4 text-xs text-secondary">
- {jobsAvailable
- ? 'No costable jobs in the window.'
- : 'Cost data will appear once the job-level source (github_workflow_jobs) is synced.'}
- </LemonCard>
- )}
+ </div>
+ </LemonCard>
</Section>
</div>
)
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
index bfde0ccb2b88..f00deab610fd 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { combineUrl } from 'kea-router'
+import { combineUrl, router } from 'kea-router'
import { IconCheckCircle, IconExternal, IconHourglass, IconPause, IconXCircle } from '@posthog/icons'
import { LemonButton, LemonSkeleton, Link } from '@posthog/lemon-ui'
@@ -23,6 +23,7 @@ import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'
import { githubCommitUrl, githubRunUrl } from '../lib/github'
import { isDecisiveFailure } from '../lib/lifecycle'
import { verdictTag } from '../lib/runStatus'
+import { withScope } from '../lib/scope'
import { WorkflowRunDetailLogicProps, workflowRunDetailLogic } from './workflowRunDetailLogic'
export const scene: SceneExport<WorkflowRunDetailLogicProps> = {
@@ -50,6 +51,7 @@ export function WorkflowRunDetailScene(): JSX.Element {
failureLogsLoading,
} = useValues(workflowRunDetailLogic)
const { loadRun } = useActions(workflowRunDetailLogic)
+ const { searchParams } = useValues(router)
if (!isValidRunId) {
return (
@@ -110,8 +112,9 @@ export function WorkflowRunDetailScene(): JSX.Element {
return (
<SceneContent>
+ {/* Scene chrome keeps the generic label; the EntityHeader below owns the title. */}
<SceneTitleSection
- name={run?.workflow_name ?? 'Workflow run'}
+ name="Workflow run"
resourceType={{ type: 'health' }}
actions={
githubUrl ? (
@@ -134,20 +137,22 @@ export function WorkflowRunDetailScene(): JSX.Element {
repoSlot={
<RepoScopeChip
label={`${run.repo.owner}/${run.repo.name}`}
- to={combineUrl(urls.engineeringAnalytics(), sourceId ? { source: sourceId } : {}).url}
+ to={withScope(urls.engineeringAnalytics(), searchParams, sourceId)}
/>
}
crumbs={[
{
label: run.workflow_name,
- to: combineUrl(
+ // Carries the window scope back so stepping up doesn't reset it.
+ to: withScope(
urls.engineeringAnalyticsWorkflowRuns(
run.repo.owner,
run.repo.name,
run.workflow_name
),
- sourceId ? { source: sourceId } : {}
- ).url,
+ searchParams,
+ sourceId
+ ),
},
{ label: `run #${run.id}` },
]}
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
index 72a8838fae46..00bfd0a8f6ef 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { combineUrl } from 'kea-router'
+import { combineUrl, router } from 'kea-router'
import { IconExternal, IconGear } from '@posthog/icons'
import { LemonButton, LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'
@@ -23,13 +23,14 @@ import { MetricTile } from '../components/MetricTile'
import { RunActivityChart } from '../components/RunActivityChart'
import { RunConclusionTag } from '../components/runTables'
import { RepoScopeChip, ScopeBar, WorkflowScopeChip } from '../components/ScopeBar'
-import { Section, SectionNav } from '../components/Section'
+import { Section } from '../components/Section'
import { ShareRow } from '../components/ShareRow'
import type { WorkflowRunnerCostApi } from '../generated/api.schemas'
import { compactCount, compactMinutes, compactUsd, percent } from '../lib/format'
import { githubCommitUrl, githubWorkflowUrl } from '../lib/github'
import { jobCacheKey } from '../lib/jobs'
import { isDecisiveFailure } from '../lib/lifecycle'
+import { withScope } from '../lib/scope'
import { WorkflowRunRow, WorkflowRunsLogicProps, workflowRunsLogic } from './workflowRunsLogic'
/** Spend by runner tier: tier, job count, cost (or 'free'), share bar scaled to billable spend. */
@@ -85,6 +86,8 @@ export function WorkflowRunsScene(): JSX.Element {
runRows,
runsLoading,
runnerCosts,
+ runnerCostsLoading,
+ runActivityLoading,
runJobs,
runJobsLoading,
expandedRunKeys,
@@ -104,6 +107,7 @@ export function WorkflowRunsScene(): JSX.Element {
queueP50Seconds,
} = useValues(workflowRunsLogic)
const { loadRuns, setRunExpanded } = useActions(workflowRunsLogic)
+ const { searchParams } = useValues(router)
const githubUrl = githubWorkflowUrl(repoOwner, repoName, workflowName)
// Master's own verdict when the window has master runs; the overall fleet state otherwise.
@@ -133,12 +137,11 @@ export function WorkflowRunsScene(): JSX.Element {
key: 'run',
render: (_, run) => (
<Link
- to={
- combineUrl(
- urls.engineeringAnalyticsWorkflowRun(run.repoOwner, run.repoName, run.id),
- sourceId ? { source: sourceId } : {}
- ).url
- }
+ to={withScope(
+ urls.engineeringAnalyticsWorkflowRun(run.repoOwner, run.repoName, run.id),
+ searchParams,
+ sourceId
+ )}
className="font-mono text-xs font-medium tabular-nums"
onClick={(e) => e.stopPropagation()}
>
@@ -270,8 +273,9 @@ export function WorkflowRunsScene(): JSX.Element {
return (
<SceneContent>
+ {/* Scene chrome keeps the generic label; the EntityHeader below owns the title. */}
<SceneTitleSection
- name={workflowName}
+ name="Workflow"
resourceType={{ type: 'health' }}
actions={
<LemonButton type="secondary" size="small" to={githubUrl} targetBlank sideIcon={<IconExternal />}>
@@ -284,7 +288,7 @@ export function WorkflowRunsScene(): JSX.Element {
repoSlot={
<RepoScopeChip
label={`${repoOwner}/${repoName}`}
- to={combineUrl(urls.engineeringAnalytics(), sourceId ? { source: sourceId } : {}).url}
+ to={withScope(urls.engineeringAnalytics(), searchParams, sourceId)}
/>
}
crumbs={[
@@ -305,12 +309,7 @@ export function WorkflowRunsScene(): JSX.Element {
<EntityHeader
icon={<IconGear />}
title={workflowName}
- slug={
- <>
- {repoOwner}/{repoName}
- {runsTruncated && <span> · run stats cover the most recent {runRows.length} runs</span>}
- </>
- }
+ slug={`${repoOwner}/${repoName}`}
right={verdictPill}
/>
<div className="flex flex-wrap gap-2.5">
@@ -320,6 +319,7 @@ export function WorkflowRunsScene(): JSX.Element {
healthSummary.completedRuns
)} completed runs passed.`}
value={percent(healthSummary.passRate)}
+ loading={runsLoading}
/>
<MetricTile
label="Runs"
@@ -329,6 +329,8 @@ export function WorkflowRunsScene(): JSX.Element {
: undefined
}
value={compactCount(healthSummary.totalRuns)}
+ sub={runsTruncated ? `stats cover the most recent ${runRows.length}` : undefined}
+ loading={runsLoading}
/>
<MetricTile
label="Duration p50"
@@ -341,11 +343,13 @@ export function WorkflowRunsScene(): JSX.Element {
? `→ ${humanFriendlyDuration(healthSummary.p95Seconds)} p95`
: undefined
}
+ loading={runsLoading}
/>
<MetricTile
label="Queue time p50"
tooltip="From job created to started, weighted across the workflow's jobs."
value={queueP50Seconds != null ? humanFriendlyDuration(queueP50Seconds) : '—'}
+ loading={jobAggregatesLoading}
/>
<MetricTile
label="Cost"
@@ -360,17 +364,10 @@ export function WorkflowRunsScene(): JSX.Element {
}
value={costSummary?.estimatedCostUsd != null ? compactUsd(costSummary.estimatedCostUsd) : '—'}
sub={costSummary?.estimatedCostUsd != null ? undefined : 'Job-level source not synced'}
+ loading={runnerCostsLoading}
/>
</div>
- <SectionNav
- items={[
- { id: 'health', label: 'Health' },
- { id: 'jobs', label: 'Jobs' },
- { id: 'cost', label: 'Cost' },
- { id: 'runs', label: 'Runs' },
- ]}
- />
- <Section id="health" title="Health">
+ <Section id="health" title="Health" busy={runActivityLoading && activityRuns.length > 0}>
<RunActivityChart runs={activityRuns} truncated={activityTruncated} />
</Section>
<Section id="jobs" title="Jobs">
@@ -380,7 +377,7 @@ export function WorkflowRunsScene(): JSX.Element {
totalCostUsd={costSummary?.estimatedCostUsd ?? null}
/>
</Section>
- <Section id="cost" title="Cost">
+ <Section id="cost" title="Cost" busy={runnerCostsLoading && runnerCosts.length > 0}>
{runnerCosts.length > 0 ? (
<RunnerTierCard costs={runnerCosts} />
) : (
@@ -400,6 +397,7 @@ export function WorkflowRunsScene(): JSX.Element {
rowKey={(run) => `${run.id}-${run.runAttempt}`}
useURLForSorting={false}
defaultSorting={{ columnKey: 'started', order: -1 }}
+ pagination={{ pageSize: 25 }}
onRow={(run) => ({
className: 'cursor-pointer',
onClick: () =>
diff --git a/products/engineering_analytics/frontend/scenes/authorLogic.ts b/products/engineering_analytics/frontend/scenes/authorLogic.ts
index 33413618d37a..f68372acf38b 100644
--- a/products/engineering_analytics/frontend/scenes/authorLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/authorLogic.ts
@@ -110,6 +110,11 @@ export const authorLogic = kea<authorLogicType>([
return minutes.length ? minutes.reduce((sum, m) => sum + m, 0) : null
},
],
+ // A loop is one push and the CI it triggered; total loops = pushes across the in-window PRs.
+ totalLoops: [
+ (s) => [s.windowedRows],
+ (rows: PullRequestRow[]): number => rows.reduce((sum, pr) => sum + pr.pushes, 0),
+ ],
openPrCount: [
(s) => [s.prs],
(prs: PullRequestRow[]): number => prs.filter((pr) => pr.state === 'open').length,
@@ -123,6 +128,12 @@ export const authorLogic = kea<authorLogicType>([
path: urls.engineeringAnalytics(),
iconType: 'health',
},
+ {
+ key: 'EngineeringAnalyticsPullRequests',
+ name: 'Pull requests',
+ path: urls.engineeringAnalyticsPullRequestList(),
+ iconType: 'health',
+ },
{ key: ['EngineeringAnalyticsAuthor', handle], name: handle, iconType: 'health' },
],
],
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts
index f45b0448d10d..d48269b7454a 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsFiltersLogic.ts
@@ -1,14 +1,27 @@
-import { actions, kea, listeners, path, reducers } from 'kea'
+import { actions, kea, listeners, path, reducers, selectors } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
+import { EngineeringAnalyticsWorkflowHealthRunScope } from '../generated/api.schemas'
import type { engineeringAnalyticsFiltersLogicType } from './engineeringAnalyticsFiltersLogicType'
// One window shared by every time-scoped CI-analytics surface, so a window picked on one page carries
// to the others. 7 days: long enough to read a week of spend, short enough that health reads as recent.
export const SHARED_DEFAULT_DATE_FROM = '-7d'
-// The branch scope is shared the same way. It's a server-side filter (head_branch): typing stages
-// branchInput; applyBranchFilter promotes it to appliedBranch, which the consuming logics send.
+// The "non-default branch" lens: PR-attributed runs with the default branch (master/main) excluded.
+const PR_SCOPE = EngineeringAnalyticsWorkflowHealthRunScope.PullRequest
+
+// The workflow-health request params the active branch scope resolves to. `run_scope` is workflow_health's
+// alone; every other surface reads `appliedBranch` (which the PR lens leaves empty, so they fall back to
+// all branches). Owning the scope→params mapping here means no consumer re-derives which param to send.
+export interface BranchHealthParams {
+ branch?: string
+ run_scope?: typeof PR_SCOPE
+}
+
+// The branch scope is shared like the window. An exact branch is a server-side head_branch filter; the PR
+// lens is a run_scope. The two are mutually exclusive — the reducers keep an invalid "branch + lens" state
+// from ever existing — so a page only ever sees one of them.
export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersLogicType>([
path(['products', 'engineering_analytics', 'frontend', 'scenes', 'engineeringAnalyticsFiltersLogic']),
@@ -17,15 +30,45 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
setBranchFilter: (branch: string) => ({ branch }),
applyBranchFilter: true,
setAppliedBranch: (branch: string) => ({ branch }),
+ // The "non-default branch" lens: PR-attributed runs, default branch (master/main) excluded.
+ scopeToPullRequests: true,
}),
reducers({
dateFrom: [SHARED_DEFAULT_DATE_FROM as string | null, { setDateRange: (_, { dateFrom }) => dateFrom }],
dateTo: [null as string | null, { setDateRange: (_, { dateTo }) => dateTo }],
- // branchInput is the staged text in the box; appliedBranch is what the consuming loaders send. '' means
- // all branches. appliedBranch persists across date reloads (e.g. "master on last 30d" → "last 90d").
- branchInput: ['', { setBranchFilter: (_, { branch }) => branch }],
- appliedBranch: ['', { setAppliedBranch: (_, { branch }) => branch }],
+ // branchInput is the staged text in the box; appliedBranch is what exact-branch consumers send. ''
+ // means all branches; the PR lens clears both, since it's mutually exclusive with an exact branch.
+ branchInput: [
+ '',
+ {
+ setBranchFilter: (_, { branch }) => branch,
+ scopeToPullRequests: () => '',
+ },
+ ],
+ appliedBranch: [
+ '',
+ {
+ setAppliedBranch: (_, { branch }) => branch,
+ scopeToPullRequests: () => '',
+ },
+ ],
+ // Applying any exact branch — including clearing to all — turns the PR lens off.
+ pullRequestScope: [
+ false,
+ {
+ scopeToPullRequests: () => true,
+ setAppliedBranch: () => false,
+ },
+ ],
+ }),
+
+ selectors({
+ branchHealthParams: [
+ (s) => [s.appliedBranch, s.pullRequestScope],
+ (appliedBranch, pullRequestScope): BranchHealthParams =>
+ pullRequestScope ? { run_scope: PR_SCOPE } : appliedBranch ? { branch: appliedBranch } : {},
+ ],
}),
listeners(({ actions, values }) => ({
@@ -37,8 +80,9 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
},
applyBranchFilter: () => {
const next = values.branchInput.trim()
- // Skip promoting (and the reload it triggers in consumers) when the box is unchanged.
- if (next === values.appliedBranch) {
+ // Skip promoting (and the reload it triggers) when nothing changes — unless the PR lens is on,
+ // which an exact branch must clear.
+ if (next === values.appliedBranch && !values.pullRequestScope) {
return
}
actions.setAppliedBranch(next)
@@ -46,7 +90,7 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
})),
actionToUrl(({ values }) => ({
- // Replace, not push — nudging a date shouldn't stack back-history. Defaults are omitted.
+ // Replace, not push — nudging a scope shouldn't stack back-history. Defaults are omitted.
setDateRange: () => {
const { pathname, searchParams, hashParams } = router.values.currentLocation
const next = { ...searchParams }
@@ -62,7 +106,8 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
}
return [pathname, next, hashParams, { replace: true }]
},
- // Mirror the applied branch into `?q=` so a branch-scoped view is shareable and survives reload.
+ // Mirror the exact branch into `?q=` so a branch-scoped view is shareable; drop the mutually
+ // exclusive PR lens.
setAppliedBranch: () => {
const { pathname, searchParams, hashParams } = router.values.currentLocation
const next = { ...searchParams }
@@ -71,6 +116,14 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
} else {
delete next.q
}
+ delete next.run_scope
+ return [pathname, next, hashParams, { replace: true }]
+ },
+ scopeToPullRequests: () => {
+ const { pathname, searchParams, hashParams } = router.values.currentLocation
+ const next = { ...searchParams }
+ next.run_scope = PR_SCOPE
+ delete next.q
return [pathname, next, hashParams, { replace: true }]
},
})),
@@ -84,8 +137,14 @@ export const engineeringAnalyticsFiltersLogic = kea<engineeringAnalyticsFiltersL
if (dateFrom !== values.dateFrom || dateTo !== values.dateTo) {
actions.setDateRange(dateFrom, dateTo)
}
+ if (searchParams.run_scope === PR_SCOPE) {
+ if (!values.pullRequestScope) {
+ actions.scopeToPullRequests()
+ }
+ return
+ }
const branch = (searchParams.q ?? '').trim()
- if (branch !== values.appliedBranch) {
+ if (branch !== values.appliedBranch || values.pullRequestScope) {
actions.setBranchFilter(branch)
// An empty value already applies via setBranchFilter's listener; a real branch needs the apply.
if (branch !== '') {
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
index 7a886c63ca08..bf3a3a2f1f5a 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
@@ -148,6 +148,7 @@ function makePr(overrides: Partial<PullRequestRow> = {}): PullRequestRow {
pending: 0,
failingWorkflows: [],
pushes: 0,
+ pushHistory: [],
rerunCycles: 0,
estimatedCostUsd: null,
billableMinutes: null,
@@ -169,6 +170,7 @@ function apiPr(overrides: Partial<PullRequestListItemApi> = {}): PullRequestList
open_to_merge_seconds: null,
labels: [],
pushes: 0,
+ push_history: [],
rerun_cycles: 0,
estimated_cost_usd: null,
...overrides,
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
index 0256ad74d735..bf771524897b 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
@@ -22,6 +22,7 @@ import {
import type {
GitHubSourceApi,
PullRequestListItemApi,
+ PushCISampleApi,
QuarantineRequestApi,
QuarantineRequestResultApi,
} from '../generated/api.schemas'
@@ -42,7 +43,7 @@ export type PRState = 'open' | 'closed' | 'merged'
/** 'draft' narrows open PRs; the other values mirror PRState. */
export type PRStateFilter = PRState | 'draft' | 'all'
export type CIStatusFilter = CIStatus | 'all'
-export type CardFilter = 'open' | 'failing' | 'stuck'
+export type CardFilter = 'open' | 'failing' | 'stuck' | 'ready' | 'thrash'
/** Mirrors the ci_cards "stuck" rule: open, non-draft, non-bot, older than 7 days. */
export const STUCK_AFTER_DAYS = 7
@@ -70,6 +71,8 @@ export interface PullRequestRow {
failingWorkflows: string[]
/** Distinct head SHAs across the PR's workflow runs. Fork PRs unattributed. */
pushes: number
+ /** Per-push CI rounds oldest first, capped server-side — drives the push-history sparkline. */
+ pushHistory: PushCISampleApi[]
/** Workflow runs attributed to this PR that were a 2nd+ attempt. */
rerunCycles: number
/** Estimated CI cost (USD) over the PR's billable jobs. Null when the job source isn't synced. */
@@ -206,6 +209,7 @@ export function toPullRequestRow(it: PullRequestListItemApi): PullRequestRow {
pending: it.ci.pending,
failingWorkflows: it.ci.failing_workflows ?? [],
pushes: it.pushes ?? 0,
+ pushHistory: it.push_history ?? [],
rerunCycles: it.rerun_cycles ?? 0,
estimatedCostUsd: it.estimated_cost_usd ?? null,
billableMinutes: it.billable_minutes ?? null,
@@ -219,6 +223,8 @@ export interface PullRequestFilters {
ciStatus: CIStatusFilter
search: string
stuckOnly: boolean
+ readyOnly: boolean
+ thrashOnly: boolean
}
export const DEFAULT_FILTERS: PullRequestFilters = {
@@ -228,12 +234,24 @@ export const DEFAULT_FILTERS: PullRequestFilters = {
ciStatus: 'all',
search: '',
stuckOnly: false,
+ readyOnly: false,
+ thrashOnly: false,
}
export function isStuck(row: PullRequestRow, stuckCutoffMs: number): boolean {
return row.state === 'open' && !row.isDraft && !row.isBot && Date.parse(row.createdAt) < stuckCutoffMs
}
+/** Open, ready-for-review, and green — the "unblocked, could merge" pile. */
+export function isReady(row: PullRequestRow): boolean {
+ return row.state === 'open' && !row.isDraft && ciStatusOf(row) === 'passing'
+}
+
+/** Open and burning re-run cycles — CI thrash worth a look. */
+export function isThrashing(row: PullRequestRow): boolean {
+ return row.state === 'open' && row.rerunCycles > 0
+}
+
function matchesStateFilter(row: PullRequestRow, state: PRStateFilter): boolean {
if (state === 'all') {
return true
@@ -259,6 +277,12 @@ export function filterPullRequests(
if (filters.stuckOnly && !isStuck(row, stuckCutoffMs)) {
return false
}
+ if (filters.readyOnly && !isReady(row)) {
+ return false
+ }
+ if (filters.thrashOnly && !isThrashing(row)) {
+ return false
+ }
if (filters.author && row.authorHandle !== filters.author) {
return false
}
@@ -521,7 +545,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
path(['products', 'engineering_analytics', 'frontend', 'scenes', 'engineeringAnalyticsLogic']),
connect(() => ({
- values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'appliedBranch']],
+ values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo', 'branchHealthParams']],
})),
actions({
@@ -534,9 +558,10 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
setWorkflowStatusFilter: (status: WorkflowStatusFilter) => ({ status }),
resetWorkflowFilters: true,
setStuckOnly: (stuckOnly: boolean) => ({ stuckOnly }),
+ setReadyOnly: (ready: boolean) => ({ ready }),
+ setThrashOnly: (thrash: boolean) => ({ thrash }),
applyCardFilter: (card: CardFilter) => ({ card }),
setSourceId: (sourceId: string | null) => ({ sourceId }),
- setCostLensEnabled: (enabled: boolean) => ({ enabled }),
resetFilters: true,
setQuarantineSearch: (search: string) => ({ search }),
setQuarantineLifecycleFilter: (lifecycle: QuarantineLifecycleFilter) => ({ lifecycle }),
@@ -585,7 +610,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
const items = await engineeringAnalyticsWorkflowHealth(projectId(), {
date_from: values.dateFrom ?? undefined,
date_to: values.dateTo ?? undefined,
- branch: values.appliedBranch || undefined,
+ ...values.branchHealthParams,
source_id: values.sourceId ?? undefined,
})
return items.map(
@@ -728,6 +753,22 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
resetFilters: () => DEFAULT_FILTERS.stuckOnly,
},
],
+ readyOnly: [
+ DEFAULT_FILTERS.readyOnly,
+ {
+ setReadyOnly: (_, { ready }) => ready,
+ setStateFilter: () => false,
+ resetFilters: () => DEFAULT_FILTERS.readyOnly,
+ },
+ ],
+ thrashOnly: [
+ DEFAULT_FILTERS.thrashOnly,
+ {
+ setThrashOnly: (_, { thrash }) => thrash,
+ setStateFilter: () => false,
+ resetFilters: () => DEFAULT_FILTERS.thrashOnly,
+ },
+ ],
workflowSearch: [
DEFAULT_WORKFLOW_FILTERS.search,
{
@@ -828,7 +869,6 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
loadWorkflowHealthFailure: (_, { errorObject }) => loaderStatusFromError(errorObject),
},
],
- costLensEnabled: [true, { setCostLensEnabled: (_, { enabled }) => enabled }],
}),
selectors({
@@ -864,25 +904,51 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
workflowHealth.some((row) => row.billableMinutes != null || row.estimatedCostUsd != null),
],
filters: [
- (s) => [s.stateFilter, s.author, s.repo, s.ciStatusFilter, s.search, s.stuckOnly],
- (stateFilter, author, repo, ciStatus, search, stuckOnly): PullRequestFilters => ({
+ (s) => [
+ s.stateFilter,
+ s.author,
+ s.repo,
+ s.ciStatusFilter,
+ s.search,
+ s.stuckOnly,
+ s.readyOnly,
+ s.thrashOnly,
+ ],
+ (
+ stateFilter,
+ author,
+ repo,
+ ciStatus,
+ search,
+ stuckOnly,
+ readyOnly,
+ thrashOnly
+ ): PullRequestFilters => ({
state: stateFilter,
author,
repo,
ciStatus,
search,
stuckOnly,
+ readyOnly,
+ thrashOnly,
}),
],
activeCard: [
- (s) => [s.stateFilter, s.ciStatusFilter, s.stuckOnly],
- (stateFilter, ciStatus, stuckOnly): CardFilter | null => {
+ (s) => [s.stateFilter, s.ciStatusFilter, s.stuckOnly, s.readyOnly, s.thrashOnly],
+ (stateFilter, ciStatus, stuckOnly, readyOnly, thrashOnly): CardFilter | null => {
if (stateFilter !== 'open') {
return null
}
if (stuckOnly) {
return 'stuck'
}
+ if (readyOnly) {
+ return 'ready'
+ }
+ if (thrashOnly) {
+ return 'thrash'
+ }
if (ciStatus === 'failing') {
return 'failing'
}
@@ -897,16 +963,10 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
(s) => [s.filters],
(filters): boolean => !objectsEqual({ ...filters, search: filters.search.trim() }, DEFAULT_FILTERS),
],
- authorOptions: [
- (s) => [s.pullRequests],
- (pullRequests): string[] =>
- Array.from(new Set(pullRequests.map((pr) => pr.authorHandle).filter(Boolean))).sort(),
- ],
- repoOptions: [
- (s) => [s.pullRequests],
- (pullRequests): string[] =>
- Array.from(new Set(pullRequests.map((pr) => `${pr.repoOwner}/${pr.repoName}`))).sort(),
- ],
+ // Counted over the loaded list (the "most recent 1000" cap applies), not a separate backend
+ // aggregate like the ci_cards counts — fine while a repo's open backlog fits in that window.
+ readyCount: [(s) => [s.pullRequests], (pullRequests): number => pullRequests.filter(isReady).length],
+ thrashCount: [(s) => [s.pullRequests], (pullRequests): number => pullRequests.filter(isThrashing).length],
anyLoading: [
(s) => [s.cardsLoading, s.pullRequestsLoading, s.workflowHealthLoading, s.quarantineLoading],
(cardsLoading, pullRequestsLoading, workflowHealthLoading, quarantineLoading): boolean =>
@@ -998,12 +1058,18 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
[engineeringAnalyticsFiltersLogic.actionTypes.setAppliedBranch]: () => {
actions.loadWorkflowHealth()
},
+ [engineeringAnalyticsFiltersLogic.actionTypes.scopeToPullRequests]: () => {
+ actions.loadWorkflowHealth()
+ },
applyCardFilter: ({ card }) => {
- // Clicking the already-active card toggles back to the plain open view.
+ // Clicking the already-active card toggles back to the plain open view. setStateFilter('open')
+ // runs first and clears every lens flag, so the explicit sets below leave exactly one active.
const target: CardFilter = values.activeCard === card ? 'open' : card
actions.setStateFilter('open')
actions.setCiStatusFilter(target === 'failing' ? 'failing' : 'all')
actions.setStuckOnly(target === 'stuck')
+ actions.setReadyOnly(target === 'ready')
+ actions.setThrashOnly(target === 'thrash')
},
applyQuarantineCard: ({ card }) => {
// Toggling a card off clears only the lifecycle/mode lens, leaving search and owner intact.
diff --git a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
index 95f0320aea7b..e0818aec6f35 100644
--- a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
@@ -434,6 +434,12 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
path: urls.engineeringAnalytics(),
iconType: 'health',
},
+ {
+ key: 'EngineeringAnalyticsPullRequests',
+ name: 'Pull requests',
+ path: urls.engineeringAnalyticsPullRequestList(),
+ iconType: 'health',
+ },
{
key: ['EngineeringAnalyticsPullRequest', `${repoOwner}/${repoName}#${number}`],
name: `${repoOwner}/${repoName} #${number}`,
diff --git a/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
index 8477fbb87e3a..82cf5f912351 100644
--- a/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
@@ -18,6 +18,7 @@ import type {
WorkflowRunActivityApi,
} from '../generated/api.schemas'
import { ciStatusOf } from '../lib/ci'
+import { HUB_PREVIEW_MAX, HUB_PREVIEW_ROWS, HUB_PREVIEW_STEP } from '../lib/preview'
import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import { PullRequestRow, STUCK_AFTER_DAYS, engineeringAnalyticsLogic, isStuck } from './engineeringAnalyticsLogic'
import type { repoOverviewLogicType } from './repoOverviewLogicType'
@@ -57,6 +58,8 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
actions({
loadLogsForRun: (runId: number) => ({ runId }),
+ showMorePrs: true,
+ showMoreWorkflows: true,
}),
loaders(({ values }) => ({
@@ -137,6 +140,18 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
loadRepoActivityFailure: () => true,
},
],
+ // How many rows the hub's preview tables show. Start short (HUB_PREVIEW_ROWS), grow by a fixed
+ // step on "Show more", capped so the hub stays a preview — the full tables live on the dedicated
+ // pages. No reset on reload: slicing tolerates any list length, and keeping the user's expansion
+ // across a window change is less surprising than snapping back.
+ prPreviewCount: [
+ HUB_PREVIEW_ROWS,
+ { showMorePrs: (count) => Math.min(HUB_PREVIEW_MAX, count + HUB_PREVIEW_STEP) },
+ ],
+ workflowPreviewCount: [
+ HUB_PREVIEW_ROWS,
+ { showMoreWorkflows: (count) => Math.min(HUB_PREVIEW_MAX, count + HUB_PREVIEW_STEP) },
+ ],
}),
selectors({
@@ -158,6 +173,7 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
durationSeconds: point.duration_seconds,
headBranch: point.head_branch,
prNumber: point.pr_number,
+ headSha: point.head_sha,
})),
],
activityTruncated: [(s) => [s.repoActivity], (repoActivity): boolean => repoActivity.truncated],
@@ -217,7 +233,8 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
(s) => [s.overview],
(overview): { values: number[]; labels: string[]; interval: 'hour' | 'day' | 'week' } | null => {
const series = overview?.cost_series ?? []
- if (!series.length) {
+ const firstData = series.findIndex((bucket) => bucket.cost_per_merge_usd != null)
+ if (firstData === -1) {
return null
}
const granularity = overview?.cost_series_granularity
@@ -228,6 +245,76 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
}
},
],
+ // Time-to-green trend (median success-only PR CI duration) in minutes. Empty buckets carry the last
+ // known value forward — a gap means "no new PR run to time", not 0 min, so zero-filling would draw a
+ // false dip. Trimmed to start at the first bucket with data so the line doesn't open on flat zeros.
+ // Null when no bucket has a successful PR run, so the card shows its own empty state.
+ timeToGreenSeries: [
+ (s) => [s.overview],
+ (overview): { values: number[]; labels: string[] } | null => {
+ const series = overview?.time_to_green_series ?? []
+ const firstData = series.findIndex((bucket) => bucket.p50_seconds != null)
+ if (firstData === -1) {
+ return null
+ }
+ const fmt = overview?.time_to_green_series_granularity === 'hour' ? 'MMM D HH:mm' : 'MMM D'
+ const trimmed = series.slice(firstData)
+ let last = 0
+ const values = trimmed.map((bucket) => {
+ if (bucket.p50_seconds != null) {
+ last = Math.round((bucket.p50_seconds / 60) * 10) / 10
+ }
+ return last
+ })
+ return { values, labels: trimmed.map((bucket) => dayjs(bucket.bucket_start).format(fmt)) }
+ },
+ ],
+ // Pass-rate trend (0-1). Empty buckets carry the last known value forward so a gap (no completed
+ // run) draws no false dip to zero; trimmed to start at the first bucket with data. Null when no
+ // bucket has a completed run, so the card shows its own empty state.
+ passRateSeries: [
+ (s) => [s.overview],
+ (overview): { values: number[]; labels: string[] } | null => {
+ const series = overview?.success_rate_series ?? []
+ const firstData = series.findIndex((bucket) => bucket.success_rate != null)
+ if (firstData === -1) {
+ return null
+ }
+ const fmt = overview?.success_rate_series_granularity === 'hour' ? 'MMM D HH:mm' : 'MMM D'
+ const trimmed = series.slice(firstData)
+ let last = 0
+ const values = trimmed.map((bucket) => {
+ if (bucket.success_rate != null) {
+ last = bucket.success_rate
+ }
+ return last
+ })
+ return { values, labels: trimmed.map((bucket) => dayjs(bucket.bucket_start).format(fmt)) }
+ },
+ ],
+ // Time-to-merge trend in seconds (median open→merge, bots/drafts excluded). Same carry-forward +
+ // trim as time-to-green: a gap means "nothing merged", not instant merges, so zero-filling would
+ // draw a false dip. Null when no bucket had a qualifying merge.
+ openToMergeSeries: [
+ (s) => [s.overview],
+ (overview): { values: number[]; labels: string[] } | null => {
+ const series = overview?.open_to_merge_series ?? []
+ const firstData = series.findIndex((bucket) => bucket.p50_seconds != null)
+ if (firstData === -1) {
+ return null
+ }
+ const fmt = overview?.open_to_merge_series_granularity === 'hour' ? 'MMM D HH:mm' : 'MMM D'
+ const trimmed = series.slice(firstData)
+ let last = 0
+ const values = trimmed.map((bucket) => {
+ if (bucket.p50_seconds != null) {
+ last = bucket.p50_seconds
+ }
+ return last
+ })
+ return { values, labels: trimmed.map((bucket) => dayjs(bucket.bucket_start).format(fmt)) }
+ },
+ ],
}),
listeners(({ actions, values }) => ({
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
index 03041d768806..681578985dc0 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
@@ -103,6 +103,12 @@ export const workflowRunDetailLogic = kea<workflowRunDetailLogicType>([
path: urls.engineeringAnalytics(),
iconType: 'health',
},
+ {
+ key: 'EngineeringAnalyticsWorkflows',
+ name: 'Workflows',
+ path: urls.engineeringAnalyticsWorkflows(),
+ iconType: 'health',
+ },
{
key: ['EngineeringAnalyticsWorkflowRun', `${repoOwner}/${repoName}/runs/${runId}`],
name: `${repoOwner}/${repoName} · run #${runId}`,
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
index da7ad8ce05e5..48d04c71206a 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
@@ -210,6 +210,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
durationSeconds: point.duration_seconds,
headBranch: point.head_branch,
prNumber: point.pr_number,
+ headSha: point.head_sha,
})),
],
// The chart's own cap, distinct from `runsTruncated` (the table's smaller cap).
@@ -284,6 +285,12 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
path: urls.engineeringAnalytics(),
iconType: 'health',
},
+ {
+ key: 'EngineeringAnalyticsWorkflows',
+ name: 'Workflows',
+ path: urls.engineeringAnalyticsWorkflows(),
+ iconType: 'health',
+ },
{
key: ['EngineeringAnalyticsWorkflowRuns', `${repoOwner}/${repoName}/${workflowName}`],
name: `${repoOwner}/${repoName} · ${workflowName}`,
diff --git a/products/engineering_analytics/manifest.tsx b/products/engineering_analytics/manifest.tsx
index 7f0a1a7c5db3..585184bb0bb3 100644
--- a/products/engineering_analytics/manifest.tsx
+++ b/products/engineering_analytics/manifest.tsx
@@ -50,47 +50,50 @@ export const manifest: ProductManifest = {
iconType: 'health',
},
},
- // Detail paths mirror GitHub 1:1 (owner/repo/pull/:n, owner/repo/actions/runs/:id); cross-repo
+ // Detail paths follow GitHub's REST-API shape (repos/:owner/:repo/pull-requests/:n, .../actions/runs/:id)
+ // — a repos/ prefix that keeps them clear of the tab routes and readable collection nouns. Cross-repo
// aggregates stay at the product root. Provider lives on the data (RepoRef.provider), so these url
// builders are the single place to branch verbs for a future provider (e.g. GitLab).
routes: {
- '/engineering-analytics': ['EngineeringAnalytics', 'engineeringAnalytics'],
- '/engineering-analytics/pulls': ['EngineeringAnalytics', 'engineeringAnalyticsPullRequestList'],
+ '/engineering-analytics/overview': ['EngineeringAnalytics', 'engineeringAnalytics'],
+ '/engineering-analytics/pull-requests': ['EngineeringAnalytics', 'engineeringAnalyticsPullRequestList'],
'/engineering-analytics/workflows': ['EngineeringAnalytics', 'engineeringAnalyticsWorkflows'],
'/engineering-analytics/test-health': ['EngineeringAnalytics', 'engineeringAnalyticsTestHealth'],
- '/engineering-analytics/:repoOwner/:repoName/pull/:number': [
+ '/engineering-analytics/repos/:repoOwner/:repoName/pull-requests/:number': [
'EngineeringAnalyticsPullRequest',
'engineeringAnalyticsPullRequest',
],
- '/engineering-analytics/:repoOwner/:repoName/actions/runs/:runId': [
+ '/engineering-analytics/repos/:repoOwner/:repoName/actions/runs/:runId': [
'EngineeringAnalyticsWorkflowRun',
'engineeringAnalyticsWorkflowRun',
],
- '/engineering-analytics/:repoOwner/:repoName/actions/workflows/:workflowName': [
+ '/engineering-analytics/repos/:repoOwner/:repoName/actions/workflows/:workflowName': [
'EngineeringAnalyticsWorkflowRuns',
'engineeringAnalyticsWorkflowRuns',
],
- '/engineering-analytics/author/:handle': ['EngineeringAnalyticsAuthor', 'engineeringAnalyticsAuthor'],
+ '/engineering-analytics/authors/:handle': ['EngineeringAnalyticsAuthor', 'engineeringAnalyticsAuthor'],
},
redirects: {
+ // Bare product root lands on the overview tab.
+ '/engineering-analytics': '/engineering-analytics/overview',
// The author *list* (leaderboards / rankings) stays removed — analytics aggregate at team/repo
// level only (see README locked decisions). The per-author page is a filtered PR view, reachable
// only via the author links on PR rows, so it keeps its route above.
- '/engineering-analytics/authors': '/engineering-analytics',
+ '/engineering-analytics/authors': '/engineering-analytics/overview',
},
urls: {
- engineeringAnalytics: (): string => '/engineering-analytics',
- engineeringAnalyticsPullRequestList: (): string => '/engineering-analytics/pulls',
+ engineeringAnalytics: (): string => '/engineering-analytics/overview',
+ engineeringAnalyticsPullRequestList: (): string => '/engineering-analytics/pull-requests',
engineeringAnalyticsWorkflows: (): string => '/engineering-analytics/workflows',
engineeringAnalyticsTestHealth: (): string => '/engineering-analytics/test-health',
engineeringAnalyticsPullRequest: (repoOwner: string, repoName: string, number: number | string): string =>
- `/engineering-analytics/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/pull/${number}`,
+ `/engineering-analytics/repos/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/pull-requests/${number}`,
engineeringAnalyticsWorkflowRun: (repoOwner: string, repoName: string, runId: number | string): string =>
- `/engineering-analytics/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/runs/${runId}`,
+ `/engineering-analytics/repos/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/runs/${runId}`,
engineeringAnalyticsWorkflowRuns: (repoOwner: string, repoName: string, workflowName: string): string =>
- `/engineering-analytics/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/workflows/${encodeURIComponent(workflowName)}`,
+ `/engineering-analytics/repos/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/actions/workflows/${encodeURIComponent(workflowName)}`,
engineeringAnalyticsAuthor: (handle: string): string =>
- `/engineering-analytics/author/${encodeURIComponent(handle)}`,
+ `/engineering-analytics/authors/${encodeURIComponent(handle)}`,
},
fileSystemTypes: {},
treeItemsNew: [],
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b6e74226be56..e7078100be22 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -32793,6 +32793,16 @@ export namespace Schemas {
NotRegex: 'not_regex',
} as const;
+ export interface OpenToMergeBucket {
+ /** Bucket start, aligned to open_to_merge_series_granularity (top of hour, midnight, or Monday). */
+ bucket_start: string;
+ /**
+ * Median merged_at - created_at seconds over PRs merged in this bucket, bots and drafts excluded. Null when nothing merged in the bucket (a gap, not instant merges).
+ * @nullable
+ */
+ p50_seconds: number | null;
+ }
+
/**
* * `quarantine` - QUARANTINE
* * `extend` - EXTEND
@@ -38311,6 +38321,16 @@ export namespace Schemas {
results: WizardSessionDTO[];
}
+ export interface PassRateBucket {
+ /** Bucket start, aligned to success_rate_series_granularity (top of hour, midnight, or Monday). */
+ bucket_start: string;
+ /**
+ * Fraction (0-1) of completed runs started in this bucket that succeeded. Null when the bucket had no completed run (a gap, not a 0% pass rate).
+ * @nullable
+ */
+ success_rate: number | null;
+ }
+
/**
* Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link). Defaults to an empty object. Unknown keys are rejected.
* @nullable
@@ -47354,6 +47374,22 @@ export namespace Schemas {
max_proxy_records: number;
}
+ export interface PushCISample {
+ /** Head commit SHA of this push (CI round). */
+ head_sha: string;
+ /** Earliest workflow-run start on this push. */
+ started_at: string;
+ /**
+ * Wall-clock CI seconds for this push: earliest run start to latest completed run end. Null while nothing has completed.
+ * @nullable
+ */
+ wall_seconds: number | null;
+ /** True when any latest-per-workflow run on this push concluded 'failure' or 'timed_out'. */
+ failed: boolean;
+ /** True when any latest-per-workflow run on this push hasn't completed yet. */
+ pending: boolean;
+ }
+
export interface PullRequestListItem {
/** The pull request author. */
author: Author;
@@ -47361,6 +47397,8 @@ export namespace Schemas {
repo: RepoRef;
/** CI status from the latest workflow runs on the head SHA. */
ci: CIStatusRollup;
+ /** This PR's CI rounds oldest-first, capped to the most recent pushes - one sample per push for the push-history sparkline. `pushes` stays the uncapped count. */
+ push_history: PushCISample[];
/** Pull request number within the repository. */
number: number;
/** Pull request title. */
@@ -50115,9 +50153,25 @@ export namespace Schemas {
recording_active_seconds?: number | null;
}
+ export interface TimeToGreenBucket {
+ /** Bucket start, aligned to time_to_green_series_granularity (top of hour, midnight, or Monday). */
+ bucket_start: string;
+ /**
+ * Median wall-clock seconds of successful PR-attributed CI runs started in this bucket. Null when the bucket had no successful PR run (a gap, not instant CI).
+ * @nullable
+ */
+ p50_seconds: number | null;
+ }
+
export interface RepoOverview {
/** CI cost per merged PR across the window, oldest first, zero-filled, bucketed by cost_series_granularity. Empty when the job-level source isn't synced. */
cost_series: CostPerMergeBucket[];
+ /** Median time-to-green (p50 successful PR-attributed CI run duration) per bucket across the window, oldest first, bucketed by time_to_green_series_granularity. Empty buckets carry null. */
+ time_to_green_series: TimeToGreenBucket[];
+ /** CI pass rate (completed runs that succeeded, all branches) per bucket across the window, oldest first, bucketed by success_rate_series_granularity. Empty buckets carry null. */
+ success_rate_series: PassRateBucket[];
+ /** Median time-to-merge (p50 open_to_merge_seconds, bots/drafts excluded) per bucket across the window, oldest first, bucketed by open_to_merge_series_granularity. Empty buckets carry null. */
+ open_to_merge_series: OpenToMergeBucket[];
/** Workflow runs started in the window, all branches and workflows. */
run_count: number;
/** Same count over the equal-length window immediately before date_from — the delta baseline. */
@@ -50172,6 +50226,12 @@ export namespace Schemas {
default_branch: string;
/** Bucket width of the cost_series trend, chosen to fit the window: 'hour', 'day', or 'week'. */
cost_series_granularity: string;
+ /** Bucket width of the time_to_green_series trend: 'hour', 'day', or 'week'. */
+ time_to_green_series_granularity: string;
+ /** Bucket width of the success_rate_series trend: 'hour', 'day', or 'week'. */
+ success_rate_series_granularity: string;
+ /** Bucket width of the open_to_merge_series trend: 'hour', 'day', or 'week'. */
+ open_to_merge_series_granularity: string;
}
export type ReportPriority = typeof ReportPriority[keyof typeof ReportPriority];
@@ -57831,6 +57891,8 @@ export namespace Schemas {
head_branch: string;
/** Attributed pull request number, or 0 when unattributed. */
pr_number: number;
+ /** Head commit SHA of the run/commit, or '' when unknown. */
+ head_sha: string;
}
export interface WorkflowRunActivity {