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): group pr timing on the pr tab (#90118)

Raúl Negrón-Oterocc05210a9256
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d3f040733887..cd81290ad7cb 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6496,6 +6496,18 @@ snapshots:
hash: v1.k794b7964.fadc2b2c0b5eedb49391586e0b3e5ea2aa845dd0b27c006cfad7389017158568.9Gke9ur_lx2xjtG29fVYUTYyUhDzjVg-dWWgpo5znTQ
scenes-app-discussions--threads--light:
hash: v1.k794b7964.28ac830bf83be5cbb6d7a397d67c9b9c61711904a822de38402b82220b0f7a49.7wENY7hvo1-qAJwq5fcsvKGJsfRAF_vDkpnM8iqFZcc
+ scenes-app-engineering-analytics-delivery-pipeline--all-stages--dark:
+ hash: v1.k794b7964.e6fc5778d62714ed6fd4174b65c767a850d116b902223aa6f2086ce967edcaed.HoZOw65AQI9tW_L6CG_9JN6y7lmyhzy_Q1PQL__zCsk
+ scenes-app-engineering-analytics-delivery-pipeline--all-stages--light:
+ hash: v1.k794b7964.b8d40ee2f5e774e572b6af6eb6f5f4e815218ebfe2898f30f1c5f9a19fae11e6.66m6qfAHgDF7eu8dEuvD0wyXon7JIjy7n681H3YeRf4
+ scenes-app-engineering-analytics-delivery-pipeline--nothing-merged--dark:
+ hash: v1.k794b7964.78b8c0e2d790301e64242aadc184ab0bb933a829620c882f16ece97a1ab38073.1inlX7qmhYPvWvPqalLkMgnLQXg2S4WLdYjeRAB3ykg
+ scenes-app-engineering-analytics-delivery-pipeline--nothing-merged--light:
+ hash: v1.k794b7964.52cbb38e2a3867f73dbc28e6f98e4ce75e2e019e375ce960c7dcffa6db68ece2.N_IycuxdbJjQKTVPTQ3RZ1zwW_Lkv8U3qCL5UhV8mL8
+ scenes-app-engineering-analytics-delivery-pipeline--without-deploys--dark:
+ hash: v1.k794b7964.ed77bebb55a2f4b82a6bd2c7c44532f84d9458f90cae160a9d213fdc0d08c86e.YbOszqMcIuSi1_wHeI8dVPXBs4AHAtL35W_MOvZLdu0
+ scenes-app-engineering-analytics-delivery-pipeline--without-deploys--light:
+ hash: v1.k794b7964.5eaee687a224ef9cd7d3707391948732cacb11769bdd619f315a101abcb85de1.ymQC-4XF77SeJ0AN5SrtlyYKs8Ve29MBfz4J8FGLWtg
scenes-app-engineering-analytics-health--health--dark:
hash: v1.k794b7964.0698630f83c06821e9d53560c494f1af19db540011811a1dcdc991ba671d17e1.wGW1HadqzVFD6pQY0t78xDUa_2cRYoVdw3TlTut2Msw
scenes-app-engineering-analytics-health--health--light:
@@ -6509,13 +6521,13 @@ snapshots:
scenes-app-engineering-analytics-lead-time-box-plot--default--light:
hash: v1.k794b7964.040d7b8b88503881e75c0e7d6c0bc8588c6096f1315f75b5071c2721d13f567a.jAkjFsaMTKwsbxZsBriJ6JoPzwYGQSXgG9ERQd0H06E
scenes-app-engineering-analytics-repo-overview--repo-overview--dark:
- hash: v1.k794b7964.93f0784927beb8f29f7060b98795fc4200dc169ef7f5da3fe255cf5e143c0ff3.-5znSrlummkvLSBLsYSKNzJ3Co4GxMNxsndYCtHeMms
+ hash: v1.k794b7964.09ef64d9006267921169bce24946a123da357220b073672855c5748cbfd70a8a.rmBqV1xBSmBbQ4ytQu1Wfbn8rU8G-_ygxdg4Iv2ZYa0
scenes-app-engineering-analytics-repo-overview--repo-overview--light:
- hash: v1.k794b7964.a7c7a2d6fefcf26234d5cacdbb217130930a6c25070affd05abe74d5bce3be76.20Bs4I2_GIprl6Dj7hDuA7yYpsl0aU8Z37Xv4brbh-4
+ hash: v1.k794b7964.9d8340734437cceaf8eafb5841d32cf348aba3984880deb43a087ca52a7c141e.i--Tf67fIXrujVAuex5BOv6a_g07DMjU4zt0M-wvE5s
scenes-app-engineering-analytics-repo-overview--repo-overview-with-trunk-queue-data--dark:
- hash: v1.k794b7964.4c6c1827581d663bfbb28276e2d73cf182f848f8f39444eba6455fae7f733bd5.OzZ6iginpNb78vCag84FYApu1nGgco-E28S3SxSObh4
+ hash: v1.k794b7964.09ef64d9006267921169bce24946a123da357220b073672855c5748cbfd70a8a.ZiDTQAtUGNSPIkKZAW9-A9Wg_gWA56jWWWnsyrEC73A
scenes-app-engineering-analytics-repo-overview--repo-overview-with-trunk-queue-data--light:
- hash: v1.k794b7964.f90a953f8439da15f49ebaec140a51e3fc77d27c271bdb39489155262f4c30e0.XBJrnoYWscrDRgpL9YwIWGHoNMse2ZeoaovXPXf4swA
+ hash: v1.k794b7964.9d8340734437cceaf8eafb5841d32cf348aba3984880deb43a087ca52a7c141e.a_ZXGTwAUt8Kl-DWfRAgHk82rJGHJ-xmR4V-kLHpsqo
scenes-app-engineering-analytics-run-activity-chart--default--dark:
hash: v1.k794b7964.7f17c5ac7c6862493f7c4d59e6e3c3146c42e3d7b08908ee1716d387c129ba64.lPsE9KrOSZee9wJq8zjqYnvk09numvEFWOn4mdCOgJE
scenes-app-engineering-analytics-run-activity-chart--default--light:
diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
index 8a793055161b..aacfefb9ac37 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -42,6 +42,7 @@ from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.logs.logs34 import TABLE_NAME as LOGS_LOCAL_TABLE
from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, TRACE_SPANS_TABLE_SQL
+from posthog.dataclasses import frozen
from posthog.models import Team
from posthog.models.scoping import team_scope
from posthog.storage import object_storage
@@ -49,6 +50,8 @@ from posthog.storage import object_storage
from products.engineering_analytics.backend.logic.job_logs.constants import CI_LOGS_SERVICE_NAME
from products.engineering_analytics.backend.logic.queries._test_spans import PYTEST_CI_SERVICE_NAME
from products.engineering_analytics.backend.logic.sources import (
+ DEPLOYMENT_STATUSES_SCHEMA,
+ DEPLOYMENTS_SCHEMA,
ISSUE_EVENTS_SCHEMA,
PULL_REQUESTS_SCHEMA,
TEAM_MEMBERS_SCHEMA,
@@ -58,6 +61,8 @@ from products.engineering_analytics.backend.logic.sources import (
)
from products.engineering_analytics.backend.logic.views.pull_requests import KNOWN_BOT_HANDLES
from products.engineering_analytics.backend.logic.views.source_schema import (
+ DEPLOYMENT_STATUSES_COLUMNS,
+ DEPLOYMENTS_COLUMNS,
ISSUE_EVENTS_COLUMNS,
PULL_REQUESTS_COLUMNS,
TEAM_MEMBERS_COLUMNS,
@@ -322,6 +327,53 @@ def _demo_master_commits(anchor: datetime, merged_prs: Sequence[dict[str, Any]])
return demo_runs
+# Merge-queue gate runs: the checked-in snapshot predates Trunk, so without these every queue
+# surface reads empty on a seeded stack. The `trunk-merge/pr-<n>/` branch name carries the PR
+# attribution; the bot actor corroborates it.
+_GATE_WORKFLOWS = ("Backend CI", "Frontend CI")
+_GATE_LEAD = timedelta(minutes=34)
+_GATE_RETRY_EVERY_N = 4
+
+
+def _gate_runs(prs: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ def iso(dt: datetime) -> str:
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+ runs: list[dict[str, Any]] = []
+ merged = [pr for pr in prs if pr.get("merged_at")]
+ for index, pr in enumerate(merged):
+ merged_at = datetime.fromisoformat(pr["merged_at"])
+ # Every fourth PR needs a second attempt, so multi-attempt share and the retry spread are real.
+ attempts = 2 if index % _GATE_RETRY_EVERY_N == 0 else 1
+ for attempt in range(attempts):
+ # The earlier attempt is the failed one, and it anchors the leg.
+ start = merged_at - _GATE_LEAD * (attempts - attempt)
+ failed = attempt < attempts - 1
+ for wf_index, workflow in enumerate(_GATE_WORKFLOWS):
+ runs.append(
+ {
+ "id": 9_900_000_000 + index * 100 + attempt * 10 + wf_index,
+ "name": workflow,
+ "head_sha": f"9a7e{index:05d}{attempt}{wf_index}" + "d" * 29,
+ "head_branch": f"trunk-merge/pr-{pr['number']}/{index:08d}-{attempt}",
+ "status": "completed",
+ "conclusion": "failure" if failed and wf_index == 0 else "success",
+ "created_at": iso(start),
+ "run_started_at": iso(start),
+ "updated_at": iso(start + timedelta(minutes=18 + wf_index * 5)),
+ "run_attempt": 1,
+ "repository": {"full_name": "PostHog/posthog"},
+ "pull_requests": [],
+ "actor": {"login": "trunk-io[bot]", "avatar_url": ""},
+ "head_commit": {
+ "message": f"{pr.get('title') or 'change'} (#{pr['number']})",
+ "author": {"name": "Trunk", "email": "[email protected]"},
+ },
+ }
+ )
+ return runs
+
+
def _spread_merges(prs: list[dict[str, Any]], anchor: datetime) -> None:
# The snapshot captured recently-updated PRs, so their merge times all cluster on the capture day
# and the cost-per-merge and time-to-merge trends collapse into a single bucket. Re-spread merged
@@ -348,6 +400,69 @@ def _spread_merges(prs: list[dict[str, Any]], anchor: datetime) -> None:
_ISSUE_EVENTS_WINDOW_DAYS = 10
+# Production ships in batches, so a merge waits for the next deploy instead of getting one of its own.
+# Every third merge triggers one, in both regions, succeeding minutes later.
+_DEPLOYS_EVERY_N_MERGES = 3
+_DEPLOY_LAG = timedelta(minutes=9)
+_DEPLOY_DURATION = timedelta(minutes=12)
+_PRODUCTION_ENVIRONMENTS = ("prod-us", "prod-eu")
+
+
+@frozen
+class _SeededDeployments:
+ """Deploy request rows and their status rows, written to the warehouse as a pair."""
+
+ deployments: list[dict[str, Any]]
+ statuses: list[dict[str, Any]]
+
+
+def _deployment_rows(prs: list[dict[str, Any]]) -> _SeededDeployments:
+ """Batched production deploys and the statuses that made them live, keyed off the merge stream."""
+ merged = sorted((pr for pr in prs if pr.get("merged_at")), key=lambda pr: pr["merged_at"])
+ deployments: list[dict[str, Any]] = []
+ statuses: list[dict[str, Any]] = []
+ for index, pr in enumerate(merged[::_DEPLOYS_EVERY_N_MERGES]):
+ requested = datetime.fromisoformat(pr["merged_at"]) + _DEPLOY_LAG
+ for offset, environment in enumerate(_PRODUCTION_ENVIRONMENTS):
+ deployment_id = 8_000_000_000 + index * 10 + offset
+ stagger = timedelta(minutes=offset)
+ deployments.append(
+ {
+ "id": deployment_id,
+ "sha": pr.get("merge_commit_sha") or "",
+ "ref": pr.get("merge_commit_sha") or "",
+ "task": "deploy",
+ "environment": environment,
+ "original_environment": environment,
+ "description": None,
+ "creator": None,
+ "payload": None,
+ # Left false like the real snapshot, so the seed exercises the unflagged fallback.
+ "production_environment": False,
+ "transient_environment": False,
+ "created_at": (requested + stagger).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "updated_at": (requested + stagger).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ }
+ )
+ live_at = (requested + _DEPLOY_DURATION + stagger).strftime("%Y-%m-%dT%H:%M:%SZ")
+ statuses.append(
+ {
+ "id": deployment_id + 5,
+ "deployment_id": deployment_id,
+ "state": "success",
+ "creator": None,
+ "description": None,
+ "environment": environment,
+ "target_url": None,
+ "log_url": None,
+ "environment_url": None,
+ "created_at": live_at,
+ "updated_at": live_at,
+ }
+ )
+ return _SeededDeployments(deployments=deployments, statuses=statuses)
+
+
def _issue_event_rows(prs: list[dict[str, Any]], anchor: datetime) -> list[dict[str, Any]]:
window_start = anchor - timedelta(days=_ISSUE_EVENTS_WINDOW_DAYS)
rows: list[dict[str, Any]] = []
@@ -1058,15 +1173,19 @@ class Command(BaseCommand):
# merge_commit_sha with the commit it landed, which is what the attribution join reads.
merged_prs = [pr for pr in prs if pr.get("merged_at")]
runs.extend(_demo_master_commits(_fixture_anchor(prs, runs), merged_prs))
+ runs.extend(_gate_runs(prs))
# Synthetic draft/ready transitions + merged events for ready_to_merge_seconds, windowed
# like a real capped issue-events sync (see _issue_event_rows).
issue_events = _issue_event_rows(prs, _fixture_anchor(prs, runs))
+ deploy_rows = _deployment_rows(prs)
# Always normalize timestamps to a ClickHouse-friendly format; rebasing is optional.
shift = timedelta(0) if options["keep_dates"] else self._rebase_delta(prs, runs)
prs = [self._shift_dates(pr, PR_DATE_FIELDS, shift) for pr in prs]
runs = [self._shift_dates(run, RUN_DATE_FIELDS, shift) for run in runs]
issue_events = [self._shift_dates(event, ("created_at",), shift) for event in issue_events]
+ deployments = [self._shift_dates(row, ("created_at",), shift) for row in deploy_rows.deployments]
+ deployment_statuses = [self._shift_dates(row, ("created_at",), shift) for row in deploy_rows.statuses]
if shift:
self.stdout.write(f"Rebased timestamps forward by {shift}.")
@@ -1119,6 +1238,19 @@ class Command(BaseCommand):
_trunk_quarantined_rows(),
source_kind="trunkio",
)
+ # Both halves or neither: a deployment without its statuses never says whether it shipped.
+ self._upsert_schema_table(
+ team, source, credential, prefix, DEPLOYMENTS_SCHEMA, DEPLOYMENTS_COLUMNS, deployments
+ )
+ self._upsert_schema_table(
+ team,
+ source,
+ credential,
+ prefix,
+ DEPLOYMENT_STATUSES_SCHEMA,
+ DEPLOYMENT_STATUSES_COLUMNS,
+ deployment_statuses,
+ )
# Per-test CI spans back the flaky-test leaderboard and the team CI health surfaces.
# Best-effort: a dev stack without the traces table still gets the warehouse seed.
diff --git a/products/engineering_analytics/frontend/components/DeliveryPipeline.stories.tsx b/products/engineering_analytics/frontend/components/DeliveryPipeline.stories.tsx
new file mode 100644
index 000000000000..fc3b72720709
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/DeliveryPipeline.stories.tsx
@@ -0,0 +1,50 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import type { DeliveryPipelineApi } from '../generated/api.schemas'
+import { DeliveryPipeline } from './DeliveryPipeline'
+
+const FULL: DeliveryPipelineApi = {
+ merged_pr_count: 52,
+ stages: [
+ { stage: 'open_to_gate', median_seconds: 16 * 3600 + 18 * 60, p90_seconds: 4 * 86400, pr_count: 39 },
+ { stage: 'gate_to_merge', median_seconds: 30 * 60 + 42, p90_seconds: 3 * 3600 + 8 * 60, pr_count: 39 },
+ ],
+}
+
+const meta: Meta<typeof DeliveryPipeline> = {
+ title: 'Scenes-App/Engineering Analytics/Delivery Pipeline',
+ component: DeliveryPipeline,
+ parameters: {
+ layout: 'fullscreen',
+ testOptions: { snapshotBrowsers: ['chromium'], viewport: { width: 900, height: 320 } },
+ },
+ decorators: [
+ (Story) => (
+ <div className="p-6">
+ <Story />
+ </div>
+ ),
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof DeliveryPipeline>
+
+export const AllStages: Story = {
+ args: { pipeline: FULL, mergeToDeploy: { medianSeconds: 29 * 60 + 42, prCount: 48, scopeLabel: 'production' } },
+}
+
+// Without the deployments source the deploy leg is absent, not zero.
+export const WithoutDeploys: Story = {
+ args: { pipeline: FULL, mergeToDeploy: null },
+}
+
+export const NothingMerged: Story = {
+ args: {
+ pipeline: {
+ merged_pr_count: 0,
+ stages: FULL.stages.map((stage) => ({ ...stage, median_seconds: null, p90_seconds: null, pr_count: 0 })),
+ },
+ mergeToDeploy: null,
+ },
+}
diff --git a/products/engineering_analytics/frontend/components/DeliveryPipeline.tsx b/products/engineering_analytics/frontend/components/DeliveryPipeline.tsx
new file mode 100644
index 000000000000..c34b146c7dd2
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/DeliveryPipeline.tsx
@@ -0,0 +1,124 @@
+// Where a change's time goes on the way to production, as bars sharing one scale.
+
+import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import type { DeliveryPipelineApi, DeliveryStageTimingApi } from '../generated/api.schemas'
+import { DeliveryStageTimingStageEnumApi } from '../generated/api.schemas'
+import { compactAgeLabel, compactCount } from '../lib/format'
+import { ShareRow } from './ShareRow'
+
+interface LegCopy {
+ label: string
+ sub: string
+ tooltip: string
+}
+
+const LEG_COPY: Record<DeliveryStageTimingApi['stage'], LegCopy> = {
+ [DeliveryStageTimingStageEnumApi.OpenToGate]: {
+ label: 'Open to merge queue',
+ sub: 'Review, changes, and waiting for a slot',
+ tooltip:
+ 'From the PR opening to its first merge queue gate run starting. Nothing records when a PR joined the queue, so this is the earliest queue activity we can see and everything before it is folded in.',
+ },
+ [DeliveryStageTimingStageEnumApi.GateToMerge]: {
+ label: 'In the merge queue',
+ sub: 'Gate runs until the PR merges',
+ tooltip: 'From the first gate run starting to the PR merging. Retried attempts are included.',
+ },
+}
+
+const MERGE_TO_DEPLOY_COPY: LegCopy = {
+ label: 'Merge to production',
+ sub: 'Waiting for the deploy that ships it',
+ tooltip:
+ 'From the merge to the first successful production deploy that contains it, resolved through the deploy head commit. The same measure as the Health tab.',
+}
+
+export interface MergeToDeployLeg {
+ medianSeconds: number | null
+ prCount: number
+ /** The Health tab's environment and team scope, shown beside the count because the legs above are repo-wide. */
+ scopeLabel: string
+}
+
+interface RenderedLeg {
+ key: string
+ copy: LegCopy
+ medianSeconds: number
+ p90Seconds: number | null
+ prCount: number
+ countSuffix?: string
+}
+
+export function DeliveryPipeline({
+ pipeline,
+ mergeToDeploy,
+ loading = false,
+}: {
+ pipeline: DeliveryPipelineApi | null | undefined
+ /** The post-merge leg, read from the DORA endpoint. Null while loading or when deploy data is not synced. */
+ mergeToDeploy: MergeToDeployLeg | null
+ loading?: boolean
+}): JSX.Element {
+ if (!pipeline) {
+ return (
+ <LemonCard hoverEffect={false} className="flex h-full flex-col gap-3 p-3">
+ {[0, 1, 2].map((row) => (
+ <LemonSkeleton key={row} className="h-8 w-full" active={loading} />
+ ))}
+ </LemonCard>
+ )
+ }
+ const legs: RenderedLeg[] = pipeline.stages
+ .filter((leg) => leg.median_seconds != null)
+ .map((leg) => ({
+ key: leg.stage,
+ copy: LEG_COPY[leg.stage],
+ medianSeconds: leg.median_seconds ?? 0,
+ p90Seconds: leg.p90_seconds ?? null,
+ prCount: leg.pr_count,
+ }))
+ if (mergeToDeploy?.medianSeconds != null) {
+ legs.push({
+ key: 'merge_to_deploy',
+ copy: MERGE_TO_DEPLOY_COPY,
+ medianSeconds: mergeToDeploy.medianSeconds,
+ p90Seconds: null,
+ prCount: mergeToDeploy.prCount,
+ countSuffix: mergeToDeploy.scopeLabel,
+ })
+ }
+ if (legs.length === 0) {
+ return (
+ <LemonCard hoverEffect={false} className="flex h-full items-center p-4 text-xs text-secondary">
+ {pipeline.merged_pr_count === 0
+ ? 'Nothing merged in the window.'
+ : 'No merged PR in the window has a measurable step yet.'}
+ </LemonCard>
+ )
+ }
+ // One scale across the legs, so a bar's length compares it against the slowest one.
+ const slowest = Math.max(...legs.map((leg) => leg.medianSeconds))
+ return (
+ <LemonCard hoverEffect={false} className="h-full p-2">
+ {legs.map((leg) => (
+ <ShareRow
+ key={leg.key}
+ fullWidthBar
+ label={<Tooltip title={leg.copy.tooltip}>{leg.copy.label}</Tooltip>}
+ sub={leg.copy.sub}
+ share={slowest > 0 ? leg.medianSeconds / slowest : 0}
+ color={leg.medianSeconds === slowest ? 'var(--data-color-1)' : 'var(--muted)'}
+ value={compactAgeLabel(leg.medianSeconds)}
+ valueSub={[
+ leg.p90Seconds != null ? `p90 ${compactAgeLabel(leg.p90Seconds)}` : null,
+ `${compactCount(leg.prCount)} PRs`,
+ leg.countSuffix ?? null,
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ />
+ ))}
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/ScopePanel.tsx b/products/engineering_analytics/frontend/components/ScopePanel.tsx
new file mode 100644
index 000000000000..3c74f41034ff
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/ScopePanel.tsx
@@ -0,0 +1,28 @@
+// The scope boundary: the source and window controls sit on the panel's rim, and everything inside
+// reflects them. Current-state surfaces belong outside it.
+
+import { ReactNode } from 'react'
+
+import { Spinner } from '@posthog/lemon-ui'
+
+import { ScopeDateFilter, SourceScopeChip } from './ScopeBar'
+
+export function ScopePanel({
+ busy = false,
+ children,
+}: {
+ /** Reloading with data already on screen, so a window change reads as "updating" rather than a silent swap. */
+ busy?: boolean
+ children: ReactNode
+}): JSX.Element {
+ return (
+ <div className="relative mt-4 rounded-lg border border-primary p-4">
+ <div className="absolute -top-4 right-3 flex flex-wrap items-center justify-end gap-2 bg-primary px-2">
+ {busy && <Spinner className="text-secondary" />}
+ <SourceScopeChip pickerOnly />
+ <ScopeDateFilter />
+ </div>
+ <div className="flex flex-col gap-4 pt-2">{children}</div>
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
index e2c80abf84a1..4029de216e82 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
@@ -1,14 +1,20 @@
import { useActions, useValues } from 'kea'
-import { LemonButton, LemonInput, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
+import { LemonButton, LemonCard, LemonInput, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
+import { DeliveryPipeline } from '../components/DeliveryPipeline'
import { RepoEntityHeader } from '../components/EntityHeader'
import { PullRequestTable } from '../components/PullRequestTable'
-import { SourceScopeChip } from '../components/ScopeBar'
+import { ScopePanel } from '../components/ScopePanel'
+import { Section } from '../components/Section'
import { HeroStat } from '../components/StatCard'
+import { WindowComparisonCard } from '../components/WindowComparisonCard'
+import { compactAgeLabel, compactHoursLabel, percent } from '../lib/format'
+import { doraLogic } from './doraLogic'
import { CIStatusFilter, PRStateFilter, engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
+import { timeToProductionLogic } from './timeToProductionLogic'
export function EngineeringAnalyticsPullRequests(): JSX.Element {
const {
@@ -31,6 +37,43 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
} = useValues(engineeringAnalyticsLogic)
const { setStateFilter, setCiStatusFilter, setSearch, resetFilters, applyCardFilter, refresh } =
useActions(engineeringAnalyticsLogic)
+ const { timing, timingLoading } = useValues(timeToProductionLogic)
+ const { dora, doraLoading, environmentScopeLabel, githubTeam } = useValues(doraLogic)
+
+ const pipeline = timing?.delivery_pipeline
+ const deploysSynced = !!dora?.deploy_data_available
+ // The deploy figures follow the Health tab's environment and team scope, so name that scope
+ // next to them instead of letting a narrowed number sit beside the repo-wide legs unlabeled.
+ const deployScopeLabel = githubTeam ? `${environmentScopeLabel}, ${githubTeam}` : environmentScopeLabel
+ const mergeToDeploy =
+ deploysSynced && dora
+ ? {
+ medianSeconds: dora.median_merge_to_deploy_seconds ?? null,
+ prCount: dora.deployed_pr_count,
+ scopeLabel: deployScopeLabel,
+ }
+ : null
+ // timingLoading with nothing on screen is the first fetch; the cards show a skeleton rather than
+ // an empty state, which would read as "nothing merged".
+ const timingPending = timingLoading && !timing
+ // Cycle time is ready->merge when the backend observed the draft/ready transitions; otherwise
+ // it falls back to the coarse created->merged span, labeled as such.
+ const cycleTime =
+ timing?.median_ready_to_merge_seconds != null
+ ? {
+ title: 'Median time from ready for review to merge',
+ value: timing.median_ready_to_merge_seconds,
+ previousValue: timing.median_ready_to_merge_seconds_prev,
+ tooltip:
+ 'Median ready-for-review to merged time, bots and drafts excluded. Time as a draft is not counted.',
+ }
+ : {
+ title: 'Median time from open to merge',
+ value: timing?.median_open_to_merge_seconds,
+ previousValue: timing?.median_open_to_merge_seconds_prev,
+ tooltip:
+ 'Median created-to-merged time, bots and drafts excluded. Coarse: draft and ready time are fused.',
+ }
// 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.
@@ -43,7 +86,89 @@ export function EngineeringAnalyticsPullRequests(): JSX.Element {
return (
<div className="flex flex-col gap-4">
- <RepoEntityHeader repoFullName={activeSource?.repo || ''} right={<SourceScopeChip pickerOnly />} />
+ <RepoEntityHeader repoFullName={activeSource?.repo || ''} />
+
+ {/* The panel is the scope. Everything below it is the current open backlog, not windowed. */}
+ <ScopePanel busy={timingLoading && !!timing}>
+ <Section id="delivery" title="Time to production" busy={timingLoading}>
+ <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
+ <WindowComparisonCard
+ title={cycleTime.title}
+ value={cycleTime.value}
+ previousValue={cycleTime.previousValue}
+ formatValue={compactHoursLabel}
+ goodWhenDown
+ loading={timingPending}
+ tooltip={cycleTime.tooltip}
+ emptyText="No PRs merged in the window yet."
+ />
+ <WindowComparisonCard
+ title={`Median time from merge to production (${deployScopeLabel})`}
+ value={dora?.median_merge_to_deploy_seconds}
+ previousValue={dora?.median_merge_to_deploy_seconds_prev}
+ formatValue={compactAgeLabel}
+ goodWhenDown
+ loading={doraLoading && !dora}
+ tooltip="Median wait from a PR's merge to the first successful deploy containing it, resolved through the deploy head commit. The same measure as the Health tab, in the environment and team scope selected there."
+ emptyText={
+ dora && !dora.deploy_data_available
+ ? 'Production timing appears once the deployments source is synced.'
+ : 'No PR merged in the window has reached production yet.'
+ }
+ />
+ </div>
+ <DeliveryPipeline pipeline={pipeline} mergeToDeploy={mergeToDeploy} loading={timingPending} />
+ </Section>
+
+ <Section id="merge-queue" title="Merge queue" busy={timingLoading}>
+ {timing &&
+ timing.merge_queue_merged_pr_count === 0 &&
+ timing.merge_queue_failed_or_cancelled_share == null ? (
+ <LemonCard hoverEffect={false} className="p-4 text-xs text-secondary">
+ No merge queue activity in the window.
+ </LemonCard>
+ ) : (
+ <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
+ <WindowComparisonCard
+ title="Merges retried in the queue"
+ tooltip="Share of queue-landed merges that needed more than one gate attempt. Bisection branches count toward the attempt they investigate."
+ value={timing?.merge_queue_multi_attempt_merge_share}
+ previousValue={timing?.merge_queue_multi_attempt_merge_share_prev}
+ formatValue={percent}
+ deltaUnit="pt"
+ goodWhenDown
+ loading={timingPending}
+ emptyText="No queue-landed merges in the window."
+ />
+ {timing?.merge_queue_trunk_available ? (
+ <WindowComparisonCard
+ title="Left the queue unmerged"
+ tooltip="Share of concluded merge queue entries that ended failed or cancelled, from the queue's own records."
+ value={timing?.merge_queue_failed_or_cancelled_share}
+ previousValue={timing?.merge_queue_failed_or_cancelled_share_prev}
+ formatValue={(v) => percent(v, 1)}
+ deltaUnit="pt"
+ goodWhenDown
+ loading={timingPending}
+ emptyText="No concluded queue entries in the window."
+ />
+ ) : (
+ <WindowComparisonCard
+ title="Merges with a failed queue run"
+ tooltip="Share of queue-landed merges where at least one gate run failed before the merge. Derived from CI run conclusions, not the queue's own eviction records."
+ value={timing?.merge_queue_failed_gate_merge_share}
+ previousValue={timing?.merge_queue_failed_gate_merge_share_prev}
+ formatValue={percent}
+ deltaUnit="pt"
+ goodWhenDown
+ loading={timingPending}
+ emptyText="No queue-landed merges in the window."
+ />
+ )}
+ </div>
+ )}
+ </Section>
+ </ScopePanel>
<div className="flex flex-wrap items-center gap-1">
<HeroStat
diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
index 034ebe1ff5bf..676a10a55415 100644
--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
@@ -5,7 +5,7 @@
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import { LemonButton, LemonCard, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
+import { LemonButton, LemonCard, Link, Tooltip } from '@posthog/lemon-ui'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
@@ -16,11 +16,11 @@ import { RepoEntityHeader } from '../components/EntityHeader'
import { PullRequestTable } from '../components/PullRequestTable'
import { formatAxisMinutes, hasEnoughRunActivity } from '../components/RunActivityChart'
import { RunActivityMiniBars } from '../components/RunActivityMiniBars'
-import { ScopeDateFilter, SourceScopeChip } from '../components/ScopeBar'
+import { ScopePanel } from '../components/ScopePanel'
import { Section } from '../components/Section'
import { WindowComparisonCard } from '../components/WindowComparisonCard'
import { WorkflowHealthTable } from '../components/WorkflowHealthTable'
-import { compactAgeLabel, compactHoursLabel, compactMinutes, compactUsd, percent } from '../lib/format'
+import { compactMinutes, compactUsd, percent } from '../lib/format'
import { githubCommitUrl } from '../lib/github'
import { HUB_PREVIEW_MAX } from '../lib/preview'
import { withCurrentScope, withScope } from '../lib/scope'
@@ -71,26 +71,6 @@ export function RepoOverviewScene(): JSX.Element {
const asMinutes = (seconds: number | null | undefined): number | null => (seconds != null ? seconds / 60 : null)
- // Cycle time is ready→merge wherever the backend can observe the draft/ready transitions. Without
- // them it falls back to the coarse created→merged span and says so, rather than labelling one
- // measure with the other's name.
- const cycleTime =
- overview?.median_ready_to_merge_seconds != null
- ? {
- title: 'Median time from ready for review to merge',
- value: overview.median_ready_to_merge_seconds,
- previousValue: overview.median_ready_to_merge_seconds_prev,
- tooltip:
- 'Median ready-for-review to merged time, bots and drafts excluded. Time as a draft is not counted.',
- }
- : {
- title: 'Median time from open to merge',
- value: overview?.median_open_to_merge_seconds,
- previousValue: overview?.median_open_to_merge_seconds_prev,
- tooltip:
- 'Median created-to-merged time, bots and drafts excluded. Coarse: draft and ready time are fused.',
- }
-
if (notConnected) {
return <ConnectGitHubSource />
}
@@ -109,226 +89,145 @@ export function RepoOverviewScene(): JSX.Element {
<div className="flex flex-col gap-4">
<RepoEntityHeader repoFullName={activeSource?.repo || ''} />
- {/* The panel is the scope: the controls sit on its rim, and everything inside reflects
- their window. The PR backlog below the panel is current-state, not windowed. */}
- <div className="relative mt-4 rounded-lg border border-primary p-4">
- <div className="absolute -top-4 right-3 flex flex-wrap items-center justify-end gap-2 bg-primary px-2">
- {hubReloading && <Spinner className="text-secondary" />}
- <SourceScopeChip pickerOnly />
- <ScopeDateFilter />
- </div>
- <div className="flex flex-col gap-4 pt-2">
- {/* The windowed headline metrics: each card compares this window against the previous
+ {/* The PR backlog below the panel is current-state, not windowed. */}
+ <ScopePanel busy={hubReloading}>
+ {/* The windowed headline metrics: each card compares this window against the previous
one directly (two values), not as a time series. CI cost is a window total, not a
rate, so its number lives on the Workflows section below. */}
- <Section id="ci-health" title="CI health" busy={overviewLoading}>
- <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
- <WindowComparisonCard
- title="CI pass rate"
- value={overview?.success_rate}
- previousValue={overview?.success_rate_prev}
- formatValue={(value) => percent(value, 1)}
- share
- deltaUnit="pt"
- deltaPrecision={1}
- loading={overviewPending}
- tooltip="Share of successful runs among runs that succeeded, failed, timed out, failed to start, or became stale. Skipped, canceled, neutral, and action-required runs are excluded."
- emptyText="No CI runs reached a pass-or-fail result in the window."
- />
+ <Section id="ci-health" title="CI health" busy={overviewLoading}>
+ <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
+ <WindowComparisonCard
+ title="CI pass rate"
+ value={overview?.success_rate}
+ previousValue={overview?.success_rate_prev}
+ formatValue={(value) => percent(value, 1)}
+ share
+ deltaUnit="pt"
+ deltaPrecision={1}
+ loading={overviewPending}
+ tooltip="Share of successful runs among runs that succeeded, failed, timed out, failed to start, or became stale. Skipped, canceled, neutral, and action-required runs are excluded."
+ emptyText="No CI runs reached a pass-or-fail result in the window."
+ />
- <WindowComparisonCard
- title="Median time from push to all checks green"
- value={asMinutes(overview?.median_time_to_green_seconds)}
- previousValue={asMinutes(overview?.median_time_to_green_seconds_prev)}
- formatValue={formatAxisMinutes}
- goodWhenDown
- loading={overviewPending}
- tooltip="Median time from a push until every workflow on it is green. Only fully green pushes count."
- emptyText="No fully green PR pushes in the window yet."
- />
+ <WindowComparisonCard
+ title="Median time from push to all checks green"
+ value={asMinutes(overview?.median_time_to_green_seconds)}
+ previousValue={asMinutes(overview?.median_time_to_green_seconds_prev)}
+ formatValue={formatAxisMinutes}
+ goodWhenDown
+ loading={overviewPending}
+ tooltip="Median time from a push until every workflow on it is green. Only fully green pushes count."
+ emptyText="No fully green PR pushes in the window yet."
+ />
- <WindowComparisonCard
- title={cycleTime.title}
- value={cycleTime.value}
- previousValue={cycleTime.previousValue}
- formatValue={compactHoursLabel}
- goodWhenDown
- loading={overviewPending}
- tooltip={cycleTime.tooltip}
- emptyText="No PRs merged in the window yet."
- />
+ <WindowComparisonCard
+ title="CI cost per merged PR"
+ value={overview?.cost_per_merge_usd}
+ previousValue={overview?.cost_per_merge_usd_prev}
+ formatValue={compactUsd}
+ goodWhenDown
+ loading={overviewPending}
+ emptyText={
+ !jobsAvailable
+ ? 'Cost appears once the job-level source is synced.'
+ : overview?.merged_pr_count === 0
+ ? 'Nothing merged in the window.'
+ : 'No costable jobs in the window.'
+ }
+ tooltip="Estimated Depot CI cost per merged PR. Per-workflow spend is in Workflows below."
+ />
+ </div>
+ </Section>
- <WindowComparisonCard
- title="CI cost per merged PR"
- value={overview?.cost_per_merge_usd}
- previousValue={overview?.cost_per_merge_usd_prev}
- formatValue={compactUsd}
- goodWhenDown
- loading={overviewPending}
- emptyText={
- !jobsAvailable
- ? 'Cost appears once the job-level source is synced.'
- : overview?.merged_pr_count === 0
- ? 'Nothing merged in the window.'
- : 'No costable jobs in the window.'
+ <Section
+ id="master"
+ title={`${overviewDefaultBranch === 'main' ? 'Main' : 'Master'} health`}
+ busy={repoActivityLoading}
+ >
+ {/* Hub preview: one bar per default-branch commit, height = CI duration, color = verdict, so
+ "is master healthy and fast lately" reads at a glance without the full chart's weight. The
+ full scatter (start-time axis, in-flight band, zoom) lives on the workflow page. */}
+ {hasEnoughRunActivity(activityRuns) ? (
+ <RunActivityMiniBars
+ runs={activityRuns}
+ truncated={activityTruncated}
+ title="CI duration per commit"
+ noun="commit"
+ onBarClick={(run) => {
+ // Each bar is a whole commit (its workflows collapsed), so open the commit on
+ // GitHub with all its checks rather than one arbitrary workflow run.
+ const [owner, repoName] = (activeSource?.repo || '').split('/')
+ if (!run.headSha || !owner || !repoName) {
+ return
}
- tooltip="Estimated Depot CI cost per merged PR. Per-workflow spend is in Workflows below."
- />
- </div>
- </Section>
+ window.open(
+ githubCommitUrl(owner, repoName, run.headSha),
+ '_blank',
+ 'noopener,noreferrer'
+ )
+ }}
+ />
+ ) : (
+ <LemonCard hoverEffect={false} className="p-4 text-xs text-secondary">
+ {repoActivityLoading
+ ? 'Loading…'
+ : repoActivityFailed
+ ? `Couldn't load ${overviewDefaultBranch} activity. Refresh to retry.`
+ : `Not enough completed runs on ${overviewDefaultBranch} in the window to chart yet.`}
+ </LemonCard>
+ )}
+ </Section>
- <Section id="merge-queue" title="Merge queue" busy={overviewLoading}>
- {overview &&
- overview.merge_queue_merged_pr_count === 0 &&
- overview.merge_queue_failed_or_cancelled_share == null ? (
- <LemonCard hoverEffect={false} className="p-4 text-xs text-secondary">
- No merge queue activity in the window.
- </LemonCard>
- ) : (
- <div className="grid grid-cols-1 gap-2 md:grid-cols-3">
- <WindowComparisonCard
- title="Median time in the merge queue"
- tooltip="From a PR's first merge queue gate run starting to the PR merging. Waiting before gate testing starts is not included. The tick marks the p90."
- value={overview?.merge_queue_median_first_gate_to_merge_seconds}
- previousValue={overview?.merge_queue_median_first_gate_to_merge_seconds_prev}
- formatValue={compactAgeLabel}
- goodWhenDown
- marker={overview?.merge_queue_p90_first_gate_to_merge_seconds}
- markerPrevious={overview?.merge_queue_p90_first_gate_to_merge_seconds_prev}
- markerLabel="p90"
- loading={overviewPending}
- emptyText="No queue-landed merges in the window."
- />
- <WindowComparisonCard
- title="Merges retried in the queue"
- tooltip="Share of queue-landed merges that needed more than one gate attempt. Bisection branches count toward the attempt they investigate."
- value={overview?.merge_queue_multi_attempt_merge_share}
- previousValue={overview?.merge_queue_multi_attempt_merge_share_prev}
- formatValue={percent}
- deltaUnit="pt"
- goodWhenDown
- loading={overviewPending}
- emptyText="No queue-landed merges in the window."
- />
- {overview?.merge_queue_trunk_available ? (
- <WindowComparisonCard
- title="Left the queue unmerged"
- tooltip="Share of concluded merge queue entries that ended failed or cancelled, from the queue's own records."
- value={overview?.merge_queue_failed_or_cancelled_share}
- previousValue={overview?.merge_queue_failed_or_cancelled_share_prev}
- formatValue={(v) => percent(v, 1)}
- deltaUnit="pt"
- goodWhenDown
- loading={overviewPending}
- emptyText="No concluded queue entries in the window."
- />
- ) : (
- <WindowComparisonCard
- title="Merges with a failed queue run"
- tooltip="Share of queue-landed merges where at least one gate run failed before the merge. Derived from CI run conclusions, not the queue's own eviction records."
- value={overview?.merge_queue_failed_gate_merge_share}
- previousValue={overview?.merge_queue_failed_gate_merge_share_prev}
- formatValue={percent}
- deltaUnit="pt"
- goodWhenDown
- loading={overviewPending}
- emptyText="No queue-landed merges in the window."
- />
+ <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={shownWorkflows}
+ loading={workflowHealthLoading}
+ sourceId={sourceId}
+ showCost={jobsAvailable}
+ embedded
+ compact
+ pageSize={HUB_PREVIEW_MAX}
+ emptyState="No workflow runs in the window."
+ />
+ <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>
)}
- </div>
- )}
- </Section>
-
- <Section
- id="master"
- title={`${overviewDefaultBranch === '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) ? (
- <RunActivityMiniBars
- runs={activityRuns}
- truncated={activityTruncated}
- 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
+ <Link
+ to={
+ // A bare link would reset the shared window / branch / repo scope (the filters
+ // logic re-hydrates from the URL on every route), so carry it, plus the source.
+ withScope(urls.engineeringAnalyticsWorkflows(), searchParams, sourceId)
}
- window.open(
- githubCommitUrl(owner, repoName, run.headSha),
- '_blank',
- 'noopener,noreferrer'
- )
- }}
- />
- ) : (
- <LemonCard hoverEffect={false} className="p-4 text-xs text-secondary">
- {repoActivityLoading
- ? 'Loading…'
- : repoActivityFailed
- ? `Couldn't load ${overviewDefaultBranch} activity. Refresh to retry.`
- : `Not enough completed runs on ${overviewDefaultBranch} in the window to chart yet.`}
- </LemonCard>
- )}
- </Section>
-
- <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={shownWorkflows}
- loading={workflowHealthLoading}
- sourceId={sourceId}
- showCost={jobsAvailable}
- embedded
- compact
- pageSize={HUB_PREVIEW_MAX}
- emptyState="No workflow runs in the window."
- />
- <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={
- // A bare link would reset the shared window / branch / repo scope (the filters
- // logic re-hydrates from the URL on every route) — carry it, plus the source.
- withScope(urls.engineeringAnalyticsWorkflows(), searchParams, sourceId)
- }
- >
- View all →
- </Link>
- </div>
+ View all →
+ </Link>
</div>
- </LemonCard>
- </Section>
- </div>
- </div>
+ </div>
+ </LemonCard>
+ </Section>
+ </ScopePanel>
<Section
id="prs"
diff --git a/products/engineering_analytics/frontend/scenes/timeToProductionLogic.ts b/products/engineering_analytics/frontend/scenes/timeToProductionLogic.ts
new file mode 100644
index 000000000000..84de6a38aaeb
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/timeToProductionLogic.ts
@@ -0,0 +1,85 @@
+import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiConfig } from 'lib/api'
+
+import { engineeringAnalyticsRepoOverview } from '../generated/api'
+import type { RepoOverviewApi } from '../generated/api.schemas'
+import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
+import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
+
+const projectId = (): string => String(ApiConfig.getCurrentProjectId())
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface timeToProductionLogicValues {
+ dateFrom: string | null // engineeringAnalyticsFiltersLogic
+ dateTo: string | null // engineeringAnalyticsFiltersLogic
+ scopeRepo: string | null // engineeringAnalyticsLogic
+ sourceId: string | null // engineeringAnalyticsLogic
+ timing: RepoOverviewApi | null
+ timingLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface timeToProductionLogicActions {
+ loadTiming: () => any
+ loadTimingFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadTimingSuccess: (
+ timing: RepoOverviewApi,
+ payload?: any
+ ) => {
+ timing: RepoOverviewApi
+ payload?: any
+ }
+}
+
+export type timeToProductionLogicType = MakeLogicType<timeToProductionLogicValues, timeToProductionLogicActions>
+
+// The windowed PR-lifecycle timings behind the pull-requests page: cycle time, the pre-merge
+// pipeline legs, and the merge queue's outcomes. The repo hub reads the same endpoint for its
+// CI-health numbers, so the two pages share a payload shape but never share state.
+export const timeToProductionLogic = kea<timeToProductionLogicType>([
+ path(['products', 'engineering_analytics', 'frontend', 'scenes', 'timeToProductionLogic']),
+
+ connect(() => ({
+ values: [
+ engineeringAnalyticsFiltersLogic,
+ ['dateFrom', 'dateTo'],
+ engineeringAnalyticsLogic,
+ ['sourceId', 'scopeRepo'],
+ ],
+ })),
+
+ loaders(({ values }) => ({
+ timing: [
+ null as RepoOverviewApi | null,
+ {
+ // The series are the expensive half of this endpoint and nothing here charts them.
+ loadTiming: async (): Promise<RepoOverviewApi> =>
+ await engineeringAnalyticsRepoOverview(projectId(), {
+ date_from: values.dateFrom ?? undefined,
+ date_to: values.dateTo ?? undefined,
+ include_series: false,
+ source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
+ }),
+ },
+ ],
+ })),
+
+ listeners(({ actions }) => ({
+ [engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => actions.loadTiming(),
+ [engineeringAnalyticsLogic.actionTypes.setSourceId]: () => actions.loadTiming(),
+ [engineeringAnalyticsLogic.actionTypes.refresh]: () => actions.loadTiming(),
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadTiming()
+ }),
+])