: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(engineering-analytics): add team delivery figures and a pr timeline (#101639)
Julian Bez3aaa11aafdcd
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 44e0c2192f2e..648097000b92 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7560,6 +7560,14 @@ snapshots:hash: v1.k794b7964.df91ee73eb9c7f851f7c987ff3d06f975e6187267e898a2a8b3a3a1f898dee7a.ieTfJEFpcuil3f4uqJ1jp_tg64ChsB81jLF3Rf9SeFMscenes-app-engineering-analytics-lead-time-box-plot--horizontal-log-scale--light:hash: v1.k794b7964.bc3a9455717626ef2f9541e03740bd0027c89139cd54ba4eb57a883d0e222667.OlAdmRvrHHSpGH8a2jHqV60Z957X8hIrNlcY9Duvv9A+ scenes-app-engineering-analytics-pull-request--merged--dark:+ hash: v1.k794b7964.80a2b728c5e0678bea85d723674691f871ef76948e3b6337b3483f14c883c139.eMeYeAcy8Hnc3_sf3F4zLyiktYufQrJL1CWlIr2HI-Y+ scenes-app-engineering-analytics-pull-request--merged--light:+ hash: v1.k794b7964.3defacb7f88f122971276608b2e5b6e3dc4e93a0d37d8a215fb790e9e9bb3694.S2THK6gGwY8V7wCKjc3xyQRz76khLRw7zXUwsybiaNQ+ scenes-app-engineering-analytics-pull-request--out-of-the-merge-queue--dark:+ hash: v1.k794b7964.b926894fba6585b7a88815232f7571095c49f7703c904c79aa772c98c500ed0e.PfbMVTD7emKKRe5TnvI1fvMqlmABOMZVCTqw-6j1hBA+ scenes-app-engineering-analytics-pull-request--out-of-the-merge-queue--light:+ hash: v1.k794b7964.344b2260c74f8fc6c56d783086a4864638fbaabd9f7173a0e223531ae1c573d6.PcDGFYzOXeeR91tJZQQDUBnivX-Tk8pXQ5_jhILqQ4Mscenes-app-engineering-analytics-repo-overview--repo-overview--dark:hash: v1.k794b7964.1a470083e7a94ff46652f4368277eae5d35c927d65b58685e43ce34881e1e728.SEm3E8XvqrTHtJNRhVGX-9aaaw6xdWyzTNb_mw6c380scenes-app-engineering-analytics-repo-overview--repo-overview--light:@@ -7572,6 +7580,14 @@ snapshots:hash: v1.k794b7964.7f17c5ac7c6862493f7c4d59e6e3c3146c42e3d7b08908ee1716d387c129ba64.lPsE9KrOSZee9wJq8zjqYnvk09numvEFWOn4mdCOgJEscenes-app-engineering-analytics-run-activity-chart--default--light:hash: v1.k794b7964.f63752ff3ebf3bbee3be4ddc83d1ff657d9cdd11ee71e7283c30ce5a1aefde72.yTb8kpRqcG51TbM2CqgRmC5YvgE7-6pV1Trc7y5wuto+ scenes-app-engineering-analytics-team--team--dark:+ hash: v1.k794b7964.8ab9a14d00c57a179d6ae23a4f318527a125e1a886eb5eec4739e83204ca91d6.nCHqHNwOO6d0m-LoBUv-3mlTDU45SqaZAvg_0XRWqF4+ scenes-app-engineering-analytics-team--team--light:+ hash: v1.k794b7964.ce702b43b3812be57a316311450f1f60264f12969ea5b89a1f229bb24c1f5ade.wQYkNs1KtELeBKDCbvAdMTIKf1gCKinpoO2DqlxtTjk+ scenes-app-engineering-analytics-team--team-without-membership--dark:+ hash: v1.k794b7964.3c3142b9a3a6bb141701854805597465f6f823106746e7b20c381f3d610eaddb.E0-u2Sj4HAj2xqSq6Z4Jh3fQz9gagK4K0Z-3hegKbkE+ scenes-app-engineering-analytics-team--team-without-membership--light:+ hash: v1.k794b7964.22b8a8a0e228d1af6ef2ee6ccd6790bdd39da67113cf04c9c4dccf349c280fa0.5ydsnSNLbc1Kym8S7J7u-e8YQS8iFYBHS-0g-1Q0VkUscenes-app-engineering-analytics-teams--team-ci-health-roster--dark:hash: v1.k794b7964.d2d7578360ba54b7fc61f23ee770a6874cf52b5a5cabd288bc1a28431e964263.YrKgeAKxWLMc3r7KjVvcYQ7QF9liZE7jBm9y_Z94k0Ascenes-app-engineering-analytics-teams--team-ci-health-roster--light:diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.mdindex 797fd78f6275..50520334d8ba 100644--- a/products/engineering_analytics/README.md+++ b/products/engineering_analytics/README.md@@ -124,7 +124,7 @@ Change one only in a separate PR with a written reason. Engineering-level decisi- Two first-class surfaces, one endpoint set: the in-app UI and MCP tools. Named typed endpoints run the curated read layer privately (no global HogQL views, core imports only the viewset); keep `mcp/tools.yaml` current whenever endpoints change.- One sanctioned write: the test-health sidecar (quarantine, as an issue plus PR through the team's GitHub App). The write now lives behind the API and MCP tool only; the test-health UI became the Trunk quarantine debt scoreboard because Trunk's auto-quarantine outran the file-based flow as the thing teams need to see. No saved views or stateful filters; persisted surfaces are a separate decision.- Data path: HogQL over the warehouse, plus reads from Logs and Traces. PR lifecycle event ingestion deferred. Product Postgres DB stays empty.-- No author leaderboards or per-developer performance rankings, ever. The author page (one author's PRs, CI cost, delivery timing and lead time against the repository, reached only from PR-row author links) is allowed; ranking people against each other is not.+- No author leaderboards or per-developer performance rankings, ever. The author page (one author's PRs, CI cost, delivery timing and lead time against the repository, reached only from PR-row author links) is allowed; ranking people against each other is not. The team page renders the same delivery figures for one GitHub team, as an aggregate and never a per-member figure. It leaves out the author page's per-pull-request day view, which is too long to read at team size.- Bots and drafts excluded by default in throughput / cycle-time reads; bot detection = `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`.- Author identity = `Author{handle, display_name, avatar_url, is_bot}`. No PostHog-user mapping.- Time to merge = `open_to_merge_seconds` = `merged_at - created_at`: coarse, and named so. `ready_to_merge_seconds` is the precise companion (last observed ready-for-review to merge, from `github_issue_events`); NULL means "not observed", never zero.diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex e9b428e55841..295007e9c43d 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -153,7 +153,7 @@ Engineering-specific decisions. Product-level decisions live in README → Locke- **CI Signals use immutable evidence.** Flaky checks require job rows from `github_workflow_jobs` showing a failed attempt followed by a successful later attempt for the same `(run_id, job)`. The run snapshot alone cannot prove this transition. Broken-default-branch detection reads GitHub's reported default branch from the PR snapshot's `base.repo`, the only full repository object in the tables this product reads (`query_default_branches` documents why the runs snapshot cannot answer it). A repo with no PR rows resolves nothing and is skipped: `repo_overview`'s master/main run-volume guess stays a display approximation, because a P1 needs GitHub's report, not inference. Detection gates on the canonical pass rate above. Duration comparisons require enough successful samples because the percentiles exclude failed and cancelled runs. All three conditions carry a week-stable `source_id`, and the coordinator records each emitted key in `SignalEmissionRecord` so an hourly sweep doesn't re-emit the same standing condition within its week. For broken-default-branch that means one signal per week per workflow, accepting that a distinct second breakage of the same workflow inside one week dedupes into the first rather than minting a signal (and a ledger row) per completed run.- **HogQL only for analytics data.** No raw ClickHouse.- **No product Postgres DB.** Analytics data lives in the warehouse / ClickHouse; any product-config model goes on the main DB as a team-scoped model (`TeamScopedRootMixin`), never a separate DB.-- **No author leaderboards or per-developer performance rankings; the author page is allowed.** The surveillance risk is ranking people against each other, not an engineer viewing their own friction. The delivery reads (`delivery_summary`, `pull_request_timelines`) take exactly one scope (one author, one GitHub team, or one pull request, defined once in `logic/delivery_scope.py`) and compare it with the repository, never with other authors or teams. A team scope matches authors through the `team_members` snapshot and matches nothing when it isn't synced. The author page is reachable only from PR-row author links; `author_workflow_costs` and the delivery reads stay UI-only (MCP `enabled: false`).+- **No author leaderboards or per-developer performance rankings; the author page is allowed.** The surveillance risk is ranking people against each other, not an engineer viewing their own friction. The delivery reads (`delivery_summary`, `pull_request_timelines`) take exactly one scope (one author, one GitHub team, or one pull request, defined once in `logic/delivery_scope.py`) and compare it with the repository, never with other authors or teams. A team scope matches authors through the `team_members` snapshot and matches nothing when it isn't synced. The team page passes its owning team straight through as that scope: an ownership file's team name is already the GitHub org team slug, which `hogli owners:lint --live` validates against the org on every ownership change, so no mapping sits between the two vocabularies. The author page is reachable only from PR-row author links; `author_workflow_costs` and the delivery reads stay UI-only (MCP `enabled: false`).- **A pull request timeline is replayed from immutable timestamps, defined once in `logic/pr_timeline.py`.** Run and job attempts, reviews and merge-queue gate runs become change points, and the state between two points follows one precedence: merge queue, out of the queue (open PRs, Trunk's current state), red checks, running checks, review state. A red stretch is labelled by what turned it green (a re-run of the same commit, the same job failing on the default branch within 12 hours, a later push), which is evidence about the cause, not proof of it. Every merge-queue state collapses into one span because the warehouse keeps no queue history. An author or team list reads CI from 30 days before the window at the earliest, so an older open pull request's timeline starts there; a single pull request is replayed whole.- **Bot detection, defined once:** `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist; per-team config deferred.- **Bots and drafts excluded by default** in throughput / cycle-time reads; first-class in bot-impact analysis, so never strip them at the substrate.diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex b4b98e9d8dc4..d3a82c2f2946 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -1713,6 +1713,13 @@ class PRTimelineSegment:ended_at: datetime+@dataclass(frozen=True)+class PRTimelinePush:+ head_sha: str+ # When the commit's first workflow run was created, which is when the commit arrived.+ pushed_at: datetime++@dataclass(frozen=True)class PRTimeline:"""One pull request's delivery timeline, from the moment it was ready for review (or opened,@@ -1728,8 +1735,8 @@ class PRTimeline:# Where the segments start: the last ready_for_review before the end, else created_at.started_at: datetimemerged_at: datetime | None- # Distinct head commits that triggered CI, merge-queue gate runs excluded.- pushes: int+ # Distinct head commits that triggered CI, oldest first, merge-queue gate runs excluded.+ pushes: list[PRTimelinePush]estimated_cost_usd: float | Nonebillable_minutes: float | Nonesegments: list[PRTimelineSegment]diff --git a/products/engineering_analytics/backend/logic/pr_timeline.py b/products/engineering_analytics/backend/logic/pr_timeline.pyindex 0cb1f9d66fbd..364e8ee91666 100644--- a/products/engineering_analytics/backend/logic/pr_timeline.py+++ b/products/engineering_analytics/backend/logic/pr_timeline.py@@ -28,7 +28,11 @@ from itertools import pairwisefrom posthog.dataclasses import frozen-from products.engineering_analytics.backend.facade.contracts import PRTimelineSegment, PRTimelineSegmentKind+from products.engineering_analytics.backend.facade.contracts import (+ PRTimelinePush,+ PRTimelineSegment,+ PRTimelineSegmentKind,+)from products.engineering_analytics.backend.logic.queries.master_failures import strip_shard_suffixfrom products.engineering_analytics.backend.logic.views.reviews import APPROVED_STATE, CHANGES_REQUESTED_STATE@@ -171,6 +175,9 @@ class PRTimelineBuilder:ended_at=max(gate.completed_at for gate in after_last_push if gate.completed_at is not None),)+ def pushes(self) -> list[PRTimelinePush]:+ return [PRTimelinePush(head_sha=push.head_sha, pushed_at=push.pushed_at) for push in self._pushes]+def build(self) -> list[PRTimelineSegment]:start, end = self._pr.started_at, self._pr.ended_atif end <= start:diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.pyindex 2fe2994c9936..5b82a00d0739 100644--- a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py+++ b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py@@ -264,7 +264,7 @@ class PullRequestTimelinesQuery:created_at=created_at,started_at=started_at,merged_at=merged_at,- pushes=len({attempt.head_sha for attempt in pr_attempts}),+ pushes=builder.pushes(),estimated_cost_usd=cost.estimated_cost_usd if cost else None,billable_minutes=cost.billable_seconds / 60 if cost else None,segments=builder.build(),diff --git a/products/engineering_analytics/backend/presentation/serializers/delivery.py b/products/engineering_analytics/backend/presentation/serializers/delivery.pyindex 6aab032e6249..44ea6a769866 100644--- a/products/engineering_analytics/backend/presentation/serializers/delivery.py+++ b/products/engineering_analytics/backend/presentation/serializers/delivery.py@@ -7,6 +7,7 @@ from products.engineering_analytics.backend.facade.contracts import (DeliverySummary,DurationDistribution,PRTimeline,+ PRTimelinePush,PRTimelineSegment,PullRequestTimelines,ScopeRepoDistribution,@@ -187,8 +188,24 @@ class PRTimelineSegmentSerializer(DataclassSerializer):}+class PRTimelinePushSerializer(DataclassSerializer):+ class Meta:+ dataclass = PRTimelinePush+ extra_kwargs = {+ "head_sha": {"help_text": "The pushed head commit."},+ "pushed_at": {+ "help_text": "When the commit's first workflow run was created, which is when the commit arrived."+ },+ }++class PRTimelineSerializer(DataclassSerializer):repo = RepoRefSerializer(help_text="The repository the pull request belongs to.")+ pushes = PRTimelinePushSerializer(+ many=True,+ help_text="Distinct head commits that triggered CI, oldest first, merge-queue gate runs excluded. A PR "+ "listed for an author or a team misses pushes from more than 30 days before the window.",+ )segments = PRTimelineSegmentSerializer(many=True, help_text="Consecutive segments from started_at to the merge, the close, or now, with no gaps.")@@ -209,7 +226,6 @@ class PRTimelineSerializer(DataclassSerializer):"help_text": "Where the timeline starts: the last ready_for_review before the end, else created_at. A PR listed for an author or a team starts no earlier than 30 days before the window, because older CI is not read."},"merged_at": {"help_text": "Merge time; null when not merged.", "allow_null": True},- "pushes": {"help_text": "Distinct head commits that triggered CI, merge-queue gate runs excluded."},"estimated_cost_usd": {"help_text": "Estimated CI cost over the PR's runs, in USD. Null when nothing was costable.","allow_null": True,diff --git a/products/engineering_analytics/backend/tests/test_delivery.py b/products/engineering_analytics/backend/tests/test_delivery.pyindex 53ce65ef5171..27694cfc71cd 100644--- a/products/engineering_analytics/backend/tests/test_delivery.py+++ b/products/engineering_analytics/backend/tests/test_delivery.py@@ -482,7 +482,10 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):assert kinds.get(24, [Kind.DRAFT]) == [Kind.DRAFT]merged = next(item for item in timelines.items if item.number == 21)assert merged.author.handle == "alice"- assert merged.pushes == 2+ assert [(push.head_sha, push.pushed_at) for push in merged.pushes] == [+ ("sha21a", _dt(_ago_offset_with_duration(2, 0, 3600)[0])),+ ("sha21b", _dt(_ago_offset_with_duration(2, 8 * 3600, 3600)[0])),+ ]assert merged.segments[-1].ended_at == merged.merged_atassert merged.started_at == _dt(_ago(2))old_open = next((item for item in timelines.items if item.number == 26), None)diff --git a/products/engineering_analytics/frontend/components/PullRequestDayView.tsx b/products/engineering_analytics/frontend/components/PullRequestDayView.tsxindex 8d67eaf94a1e..b14318674a4c 100644--- a/products/engineering_analytics/frontend/components/PullRequestDayView.tsx+++ b/products/engineering_analytics/frontend/components/PullRequestDayView.tsx@@ -10,14 +10,15 @@ import { urls } from 'scenes/urls'import type { PullRequestTimelinesApi } from '../generated/api.schemas'import { compactAgeLabel, compactUsd } from '../lib/format'+import { DayViewAlignment, DayViewGroup, DayViewRow, rowOrigin } from '../lib/pullRequestDayView'import {DAY_START_HOUR,- DayViewAlignment,- DayViewGroup,- DayViewRow,+ NIGHT_START_HOUR,SEGMENT_KIND_STYLES,+ TIMELINE_TIME_FORMAT,segmentBackground,-} from '../lib/pullRequestDayView'+ timeAxis,+} from '../lib/pullRequestTimeline'import { withCurrentScope } from '../lib/scope'import { PullRequestTimelineLegend } from './PullRequestTimelineLegend'import { PullRequestTimelineTrack } from './PullRequestTimelineTrack'@@ -30,24 +31,20 @@ function DayViewRowItem({row,alignment,days,- generatedAt,sourceId,- showAuthor,}: {row: DayViewRowalignment: DayViewAlignmentdays: number- generatedAt: stringsourceId: string | null- showAuthor: boolean}): JSX.Element {const { pr } = row+ const origin = rowOrigin(pr.started_at, alignment)const highlight = SEGMENT_KIND_STYLES[row.highlightKind]const hover = [pr.title,- showAuthor ? `by ${pr.author.handle}` : null,- `timeline from ${dayjs(pr.started_at).format('ddd D MMM HH:mm')}`,- pluralize(pr.pushes, 'push', 'pushes'),+ `timeline from ${dayjs(pr.started_at).format(TIMELINE_TIME_FORMAT)}`,+ pluralize(pr.pushes.length, 'push', 'pushes'),pr.estimated_cost_usd != null ? `CI cost ${compactUsd(pr.estimated_cost_usd)}` : null,].filter(Boolean)@@ -66,7 +63,11 @@ function DayViewRowItem({<span className="truncate text-[11px] text-secondary">{pr.title}</span></Link></Tooltip>- <PullRequestTimelineTrack pr={pr} alignment={alignment} days={days} generatedAt={generatedAt} />+ <PullRequestTimelineTrack+ pr={pr}+ axis={timeAxis(origin.valueOf(), origin.add(days, 'day').valueOf())}+ className="h-3.5"+ /><span className="text-right text-[11px] tabular-nums text-tertiary">{row.isOpen && <span className="mr-1 inline-block size-1.5 rounded-full bg-success align-middle" />}{compactAgeLabel(row.lengthSeconds)}@@ -91,7 +92,6 @@ export function PullRequestDayView({onAlignmentChange,loading,sourceId,- showAuthor = false,}: {timelines: PullRequestTimelinesApi | nullgroups: DayViewGroup[]@@ -100,8 +100,6 @@ export function PullRequestDayView({onAlignmentChange: (alignment: DayViewAlignment) => voidloading: booleansourceId: string | null- /** Name each pull request's author on hover, for scopes that list several authors (a team). */- showAuthor?: boolean}): JSX.Element {const step = days > 7 ? 2 : 1const ticks = Array.from({ length: Math.ceil(days / step) }).map((_, index) => index * step)@@ -116,7 +114,7 @@ export function PullRequestDayView({<PullRequestTimelineLegend /><div className="flex items-center gap-2"><Tooltip- title={`${alignmentNote} Shaded: nights 22:00 to 06:00 and weekends, in your time zone. The axis stretches to fit 90% of the pull requests; longer bars end in ›.`}+ title={`${alignmentNote} Shaded: nights ${NIGHT_START_HOUR}:00 to ${DAY_START_HOUR}:00 and weekends, in your time zone. The axis stretches to fit 90% of the pull requests; longer bars end in ›.`}><span className="cursor-default text-[11px] text-tertiary">axis fits {pluralize(days, 'day')}@@ -142,9 +140,7 @@ export function PullRequestDayView({</div>) : groups.length === 0 ? (<div className="py-6 text-center text-xs text-secondary">- {timelines?.scope_kind === 'github_team' && !timelines.has_membership_data- ? 'Team pull requests appear once the team members table on this GitHub source is synced.'- : 'No open pull requests, and nothing merged in the window.'}+ No open pull requests, and nothing merged in the window.</div>) : (<>@@ -176,9 +172,7 @@ export function PullRequestDayView({row={row}alignment={alignment}days={days}- generatedAt={timelines?.generated_at ?? ''}sourceId={sourceId}- showAuthor={showAuthor}/>))}</div>diff --git a/products/engineering_analytics/frontend/components/PullRequestDeliveryTimeline.tsx b/products/engineering_analytics/frontend/components/PullRequestDeliveryTimeline.tsxnew file mode 100644index 000000000000..1f9fc14cded0--- /dev/null+++ b/products/engineering_analytics/frontend/components/PullRequestDeliveryTimeline.tsx@@ -0,0 +1,176 @@+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 type { PRTimelineApi } from '../generated/api.schemas'+import { compactAgeLabel, percent } from '../lib/format'+import {+ MilestoneKind,+ SEGMENT_KIND_STYLES,+ TIMELINE_TIME_FORMAT,+ paddedAxis,+ secondsBetween,+ segmentBackground,+ timeInStates,+ timelineMilestones,+ timelineSpan,+ timelineStartLabel,+} from '../lib/pullRequestTimeline'+import { PullRequestTimelineLegend } from './PullRequestTimelineLegend'+import { PullRequestTimelineTrack } from './PullRequestTimelineTrack'++const MAX_DAY_LABELS = 8++const MILESTONE_STYLES: Record<MilestoneKind, { glyph: string; className: string }> = {+ start: { glyph: '○', className: 'text-secondary' },+ push: { glyph: '▲', className: 'text-[var(--data-color-12)]' },+ out_of_queue: { glyph: '✕', className: 'text-danger' },+ merged: { glyph: '●', className: 'text-success' },+ closed: { glyph: '●', className: 'text-danger' },+}++function endLabel(pr: PRTimelineApi): string {+ return pr.merged_at ? 'Merged' : pr.state === 'closed' ? 'Closed' : 'Now'+}++export function PullRequestDeliveryTimeline({ pr }: { pr: PRTimelineApi }): JSX.Element {+ const span = timelineSpan(pr)+ const axis = paddedAxis(span)+ const { wholeSeconds, groups, longest } = timeInStates(pr)+ const milestones = timelineMilestones(pr)+ const labelStep = Math.ceil(axis.dayStarts.length / MAX_DAY_LABELS)++ return (+ <LemonCard+ hoverEffect={false}+ className="@container p-4"+ data-attr="engineering-analytics-pr-delivery-timeline"+ >+ <div className="mb-3 flex flex-wrap items-baseline gap-x-3 gap-y-1">+ <span className="text-lg font-semibold tabular-nums">+ {humanFriendlyDuration(wholeSeconds, { maxUnits: 2 })}+ </span>+ <span className="text-xs text-secondary">+ {timelineStartLabel(pr).toLowerCase()} to {endLabel(pr).toLowerCase()}+ </span>+ {longest && (+ <span className="flex items-center gap-1.5 text-xs text-secondary">+ <span className="text-tertiary">·</span>+ longest state+ <span className="h-2.5 w-3 rounded-sm" style={segmentBackground(longest.kind)} />+ <span className="font-semibold text-primary">{SEGMENT_KIND_STYLES[longest.kind].short}</span>+ <span className="tabular-nums">{compactAgeLabel(longest.seconds)}</span>+ </span>+ )}+ </div>++ <div className="relative h-4">+ {milestones.map((milestone, index) => {+ const style = MILESTONE_STYLES[milestone.kind]+ const title = `${milestone.label} · ${dayjs(milestone.at).format(TIMELINE_TIME_FORMAT)}`+ return (+ <Tooltip key={`${milestone.kind}-${index}`} title={title}>+ <span+ role="img"+ aria-label={title}+ tabIndex={0}+ className={cn('absolute top-0 -translate-x-1/2 text-[11px] leading-4', style.className)}+ style={{ left: axis.position(dayjs(milestone.at).valueOf()) }}+ >+ {style.glyph}+ </span>+ </Tooltip>+ )+ })}+ </div>++ <PullRequestTimelineTrack pr={pr} axis={axis} className="h-6" />++ <div className="relative mt-1 h-4 overflow-hidden text-[10px] text-tertiary">+ {axis.dayStarts.map((day, index) =>+ day.valueOf() > axis.fromMs && index % labelStep === 0 ? (+ <span+ key={day.valueOf()}+ className="absolute pl-1 whitespace-nowrap"+ style={{ left: axis.position(day.valueOf()) }}+ >+ {day.format('ddd D MMM')}+ </span>+ ) : null+ )}+ </div>++ <div className="mt-4 grid grid-cols-1 gap-4 @min-[48rem]:grid-cols-[minmax(0,1fr)_16rem]">+ <div className="flex flex-col gap-3">+ <h3 className="m-0 text-xs font-semibold text-secondary">Where the time went</h3>+ {groups.map((group) => (+ <div key={group.label} className="flex flex-col gap-1">+ <div className="flex justify-between text-[11px] text-tertiary">+ <span>{group.label}</span>+ <span className="tabular-nums">{percent(group.share)}</span>+ </div>+ {group.states.map((state) => (+ <div+ key={state.kind}+ className="grid grid-cols-[minmax(0,11rem)_minmax(0,1fr)_3rem] items-center gap-2 text-xs"+ >+ <span className="flex min-w-0 items-center gap-1.5">+ <span+ className="h-2.5 w-3 shrink-0 rounded-sm"+ style={segmentBackground(state.kind)}+ />+ <span className="truncate">{SEGMENT_KIND_STYLES[state.kind].short}</span>+ </span>+ <span className="h-1.5 overflow-hidden rounded-sm bg-fill-secondary">+ <span+ className="block h-full rounded-sm"+ style={{+ width: `${100 * state.share}%`,+ ...segmentBackground(state.kind),+ }}+ />+ </span>+ <span className="text-right tabular-nums">{compactAgeLabel(state.seconds)}</span>+ </div>+ ))}+ </div>+ ))}+ </div>+ <div className="flex flex-col gap-1 text-xs @min-[48rem]:border-l @min-[48rem]:border-primary @min-[48rem]:pl-4">+ <h3 className="m-0 mb-1 text-xs font-semibold text-secondary">Milestones</h3>+ <div className="flex justify-between gap-2">+ <span className="text-secondary">{timelineStartLabel(pr)}</span>+ <span className="font-semibold tabular-nums">+ {dayjs(span.startedAt).format(TIMELINE_TIME_FORMAT)}+ </span>+ </div>+ <div className="flex justify-between gap-2">+ <span className="text-secondary">{endLabel(pr)}</span>+ <span className="font-semibold tabular-nums">+ {dayjs(span.endedAt).format(TIMELINE_TIME_FORMAT)}+ </span>+ </div>+ <div className="flex justify-between gap-2">+ <span className="text-secondary">Pushes</span>+ <span className="font-semibold tabular-nums">{pr.pushes.length}</span>+ </div>+ </div>+ </div>++ <ol className="sr-only">+ {pr.segments.map((segment) => (+ <li key={segment.started_at}>+ {`${SEGMENT_KIND_STYLES[segment.kind].label}, ${compactAgeLabel(secondsBetween(segment.started_at, segment.ended_at))}, from ${dayjs(segment.started_at).format(TIMELINE_TIME_FORMAT)}`}+ </li>+ ))}+ </ol>++ <div className="mt-4">+ <PullRequestTimelineLegend />+ </div>+ </LemonCard>+ )+}diff --git a/products/engineering_analytics/frontend/components/PullRequestTimelineLegend.tsx b/products/engineering_analytics/frontend/components/PullRequestTimelineLegend.tsxindex 2778bc0a7541..ea43784e3b3a 100644--- a/products/engineering_analytics/frontend/components/PullRequestTimelineLegend.tsx+++ b/products/engineering_analytics/frontend/components/PullRequestTimelineLegend.tsx@@ -1,6 +1,6 @@// The legend for pull request timeline tracks, grouped by who can move a pull request out of each state.-import { SEGMENT_KIND_STYLES, SEGMENT_LEGEND_GROUPS, segmentBackground } from '../lib/pullRequestDayView'+import { SEGMENT_KIND_STYLES, SEGMENT_LEGEND_GROUPS, segmentBackground } from '../lib/pullRequestTimeline'export function PullRequestTimelineLegend(): JSX.Element {return (diff --git a/products/engineering_analytics/frontend/components/PullRequestTimelineTrack.tsx b/products/engineering_analytics/frontend/components/PullRequestTimelineTrack.tsxindex d1a4db13d2d7..7716eb5fa0b1 100644--- a/products/engineering_analytics/frontend/components/PullRequestTimelineTrack.tsx+++ b/products/engineering_analytics/frontend/components/PullRequestTimelineTrack.tsx@@ -1,103 +1,97 @@-// One pull request's timeline as a track on a shared clock. The day view stacks one per row, and a-// single pull request page can draw one on its own with the same axis rules.-import { Tooltip } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'+import { cn } from 'lib/utils/css-classes'import type { PRTimelineApi } from '../generated/api.schemas'import { compactAgeLabel } from '../lib/format'import {- DayViewAlignment,- NIGHT_START_OFFSET_HOURS,+ NIGHT_START_HOUR,SEGMENT_KIND_STYLES,- hoursFromOrigin,- rowOrigin,+ TIMELINE_TIME_FORMAT,+ TimeAxis,+ secondsBetween,segmentBackground,-} from '../lib/pullRequestDayView'+ timelineSpan,+} from '../lib/pullRequestTimeline'++// Past this span a day is a few pixels wide, so shading only adds DOM nodes.+const MAX_SHADED_DAYS = 60export function PullRequestTimelineTrack({pr,- alignment,- days,- generatedAt,+ axis,+ className,}: {pr: PRTimelineApi- alignment: DayViewAlignment- /** Days the axis spans (see axisDays); a longer timeline ends in a clip marker. */- days: number- /** The "now" an open pull request's last segment ends at. */- generatedAt: string+ axis: TimeAxis+ className?: string}): JSX.Element {- const origin = rowOrigin(pr.started_at, alignment)- const hours = days * 24- const pct = (value: number): string => `${(100 * value) / hours}%`+ const { position, width } = axisconst segments = pr.segmentsconst isOpen = pr.state === 'open'- const end = segments.length ? hoursFromOrigin(origin, segments[segments.length - 1].ended_at) : 0+ const endMs = dayjs(timelineSpan(pr).endedAt).valueOf()return (- <div className="relative h-3.5 overflow-hidden rounded-sm">- {Array.from({ length: days }).map((_, day) => {- const weekday = origin.add(day, 'day').day()+ <div className={cn('relative overflow-hidden rounded-sm', className)}>+ {(axis.dayStarts.length <= MAX_SHADED_DAYS ? axis.dayStarts : []).map((day) => {+ const dayMs = day.valueOf()+ // Calendar times, not elapsed hours, so daylight saving days still shade 22:00 to 06:00.+ const nextDayMs = day.add(1, 'day').valueOf()+ const nightMs = day.hour(NIGHT_START_HOUR).valueOf()return (- <div key={day}>- {(weekday === 0 || weekday === 6) && (+ <div key={dayMs}>+ {(day.day() === 0 || day.day() === 6) && (<divclassName="absolute inset-y-0 bg-fill-secondary"- style={{ left: pct(day * 24), width: pct(24) }}+ style={{ left: position(dayMs), width: width(dayMs, nextDayMs) }}/>)}<divclassName="absolute inset-y-0 bg-fill-tertiary"- style={{- left: pct(day * 24 + NIGHT_START_OFFSET_HOURS),- width: pct(24 - NIGHT_START_OFFSET_HOURS),- }}+ style={{ left: position(nightMs), width: width(nightMs, nextDayMs) }}/>- {day > 0 && (+ {dayMs > axis.fromMs && (<divclassName="absolute inset-y-0 w-px bg-border-primary"- style={{ left: pct(day * 24) }}+ style={{ left: position(dayMs) }}/>)}</div>)})}{segments.map((segment, index) => {- const start = hoursFromOrigin(origin, segment.started_at)- if (start >= hours) {+ const startMs = dayjs(segment.started_at).valueOf()+ if (startMs >= axis.toMs) {return null}- const segmentEnd = Math.min(hoursFromOrigin(origin, segment.ended_at), hours)const live = isOpen && index === segments.length - 1- const duration = dayjs(segment.ended_at).diff(dayjs(segment.started_at), 'second')const style = SEGMENT_KIND_STYLES[segment.kind]return (<Tooltipkey={segment.started_at}- title={`${style.label} · ${compactAgeLabel(duration)}${live ? ' so far' : ''} · from ${dayjs(segment.started_at).format('ddd D MMM HH:mm')}`}+ title={`${style.label} · ${compactAgeLabel(secondsBetween(segment.started_at, segment.ended_at))}${live ? ' so far' : ''} · from ${dayjs(segment.started_at).format(TIMELINE_TIME_FORMAT)}`}><divclassName="absolute inset-y-px min-w-0.5 rounded-sm"style={{- left: pct(start),- width: pct(Math.max(segmentEnd - start, 0.05)),+ left: position(startMs),+ width: width(startMs, dayjs(segment.ended_at).valueOf()),...segmentBackground(segment.kind),}}/></Tooltip>)})}- {isOpen && segments.length > 0 && end <= hours && (- <Tooltip title={`Now, ${dayjs(generatedAt).format('ddd HH:mm')}`}>+ {isOpen && segments.length > 0 && endMs <= axis.toMs && (+ <Tooltip title={`Now, ${dayjs(endMs).format(TIMELINE_TIME_FORMAT)}`}><divclassName="absolute -inset-y-px w-[3px] -translate-x-px rounded-sm bg-[var(--text-3000)]"- style={{ left: pct(end) }}+ style={{ left: position(endMs) }}/></Tooltip>)}- {end > hours && (+ {endMs > axis.toMs && (<span className="absolute inset-y-0 right-0 flex w-3.5 items-center justify-center bg-surface-primary text-[11px] font-bold">›</span>diff --git a/products/engineering_analytics/frontend/components/RedTimeByCauseCard.tsx b/products/engineering_analytics/frontend/components/RedTimeByCauseCard.tsxindex b0c4da54c39c..ae60f0ac5c3d 100644--- a/products/engineering_analytics/frontend/components/RedTimeByCauseCard.tsx+++ b/products/engineering_analytics/frontend/components/RedTimeByCauseCard.tsx@@ -7,7 +7,8 @@ import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'import { pluralize } from 'lib/utils/strings'import { compactAgeLabel } from '../lib/format'-import { RedTimeByCause, SEGMENT_KIND_STYLES, segmentBackground } from '../lib/pullRequestDayView'+import { RedTimeByCause } from '../lib/pullRequestDayView'+import { SEGMENT_KIND_STYLES, segmentBackground } from '../lib/pullRequestTimeline'export function RedTimeByCauseCard({redTime,diff --git a/products/engineering_analytics/frontend/components/ScopeBar.tsx b/products/engineering_analytics/frontend/components/ScopeBar.tsxindex 6788e76bbffd..e5afcf41c07b 100644--- a/products/engineering_analytics/frontend/components/ScopeBar.tsx+++ b/products/engineering_analytics/frontend/components/ScopeBar.tsx@@ -22,6 +22,8 @@ import { cn } from 'lib/utils/css-classes'import { dateMapping } from 'lib/utils/dateFilters'import { urls } from 'scenes/urls'+import { DateMappingOption } from '~/types'+import { scopeFromValue, withScope } from '../lib/scope'import {RUN_SCOPE_OPTIONS,@@ -45,6 +47,11 @@ export const SCOPE_DATE_OPTIONS = dateMapping.filter(({ key }) =>].includes(key))+// The delivery reads cap a window at a year, so they offer only presets inside it and no custom range.+export const DELIVERY_DATE_OPTIONS = dateMapping.filter(({ key }) =>+ ['Last 7 days', 'Last 14 days', 'Last 30 days', 'Last 90 days', 'Last 180 days', 'This year'].includes(key)+)+export interface ScopeCrumb {label: stringto?: string@@ -231,15 +238,23 @@ export function RunScopeControl(): JSX.Element {/** 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 {+export function ScopeDateFilter({+ dateOptions = SCOPE_DATE_OPTIONS,+}: {+ /** Custom and rolling ranges show only when the options include Custom. */+ dateOptions?: DateMappingOption[]+}): JSX.Element {const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)+ const allowsCustomRange = dateOptions.some(({ key }) => key === 'Custom')return (<DateFilterdateFrom={dateFrom}dateTo={dateTo}onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}- dateOptions={SCOPE_DATE_OPTIONS}+ dateOptions={dateOptions}+ showCustomRangeOptions={allowsCustomRange}+ showRollingRangePicker={allowsCustomRange}size="small"/>)diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex 648c3b8ccd76..b6ff964e9e80 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -866,6 +866,13 @@ export interface WorkflowRunDetailApi {is_merge_queue: boolean}+export interface PRTimelinePushApi {+ /** The pushed head commit. */+ head_sha: string+ /** When the commit's first workflow run was created, which is when the commit arrived. */+ pushed_at: string+}+/*** * `draft` - DRAFT* * `waiting_for_review` - WAITING_FOR_REVIEW@@ -923,6 +930,8 @@ export interface PRTimelineSegmentApi {export interface PRTimelineApi {/** The repository the pull request belongs to. */repo: RepoRefApi+ /** Distinct head commits that triggered CI, oldest first, merge-queue gate runs excluded. A PR listed for an author or a team misses pushes from more than 30 days before the window. */+ pushes: PRTimelinePushApi[]/** Consecutive segments from started_at to the merge, the close, or now, with no gaps. */segments: PRTimelineSegmentApi[]/** Pull request number. */@@ -948,8 +957,6 @@ export interface PRTimelineApi {* @nullable*/merged_at: string | null- /** Distinct head commits that triggered CI, merge-queue gate runs excluded. */- pushes: number/*** Estimated CI cost over the PR's runs, in USD. Null when nothing was costable.* @nullablediff --git a/products/engineering_analytics/frontend/lib/lifecycle.ts b/products/engineering_analytics/frontend/lib/lifecycle.tsindex 25ba3984a4ce..d0205f73d9e0 100644--- a/products/engineering_analytics/frontend/lib/lifecycle.ts+++ b/products/engineering_analytics/frontend/lib/lifecycle.ts@@ -1,27 +1,5 @@-// Collapses a PR's raw lifecycle events (opened, ci_started, ci_finished, merged, closed — dozens per-// PR) into the facts the drill-in panel renders: milestones plus a verdict rollup.-import type { PRLifecycleEventApi } from '../generated/api.schemas'-export interface WorkflowVerdict {- workflow: string- conclusion: string- at: string-}--export interface LifecycleSummary {- openedAt: string | null- firstCiStartedAt: string | null- lastCiFinishedAt: string | null- mergedAt: string | null- closedAt: string | null- /** Completed runs whose conclusion was not a pass — the rows worth listing. */- notPassing: WorkflowVerdict[]- passed: number- /** Runs that started but never reported a finish — queued or in progress. */- unsettled: number-}-export interface WorkflowRun {workflow: string/** Null while the run hasn't reported a finish — queued or in progress. */@@ -115,54 +93,3 @@ export function workflowRuns(events: PRLifecycleEventApi[]): WorkflowRun[] {return runs}--export function summarizeLifecycle(events: PRLifecycleEventApi[]): LifecycleSummary {- const summary: LifecycleSummary = {- openedAt: null,- firstCiStartedAt: null,- lastCiFinishedAt: null,- mergedAt: null,- closedAt: null,- notPassing: [],- passed: 0,- unsettled: 0,- }- let started = 0- let finished = 0-- for (const event of events) {- switch (event.kind) {- case 'opened':- summary.openedAt = event.at- break- case 'merged':- summary.mergedAt = event.at- break- case 'closed':- summary.closedAt = event.at- break- case 'ci_started':- started += 1- if (!summary.firstCiStartedAt || event.at < summary.firstCiStartedAt) {- summary.firstCiStartedAt = event.at- }- break- case 'ci_finished': {- finished += 1- if (!summary.lastCiFinishedAt || event.at > summary.lastCiFinishedAt) {- summary.lastCiFinishedAt = event.at- }- const { workflow, conclusion } = parseFinishedDetail(event.detail)- if (conclusion === null || PASSING_CONCLUSIONS.has(conclusion)) {- summary.passed += 1- } else {- summary.notPassing.push({ workflow, conclusion, at: event.at })- }- break- }- }- }-- summary.unsettled = Math.max(0, started - finished)- return summary-}diff --git a/products/engineering_analytics/frontend/lib/pullRequestDayView.test.ts b/products/engineering_analytics/frontend/lib/pullRequestDayView.test.tsindex 6399af48669f..02479605a761 100644--- a/products/engineering_analytics/frontend/lib/pullRequestDayView.test.ts+++ b/products/engineering_analytics/frontend/lib/pullRequestDayView.test.ts@@ -24,7 +24,7 @@ function pr(created_at: at(segments[0][1]),started_at: at(segments[0][1]),merged_at: options.merged ? at(last[2]) : null,- pushes: 1,+ pushes: [],estimated_cost_usd: null,billable_minutes: null,segments: segments.map(([kind, start, end]) => ({ kind, started_at: at(start), ended_at: at(end) })),diff --git a/products/engineering_analytics/frontend/lib/pullRequestDayView.ts b/products/engineering_analytics/frontend/lib/pullRequestDayView.tsindex fed70905ebee..8ea4cddbda8a 100644--- a/products/engineering_analytics/frontend/lib/pullRequestDayView.ts+++ b/products/engineering_analytics/frontend/lib/pullRequestDayView.ts@@ -1,130 +1,19 @@// The author page's day view: every pull request on a shared clock, grouped by what is most useful// to look at first. Pure functions, so the grouping and the axis fit are testable without a render.-import type { CSSProperties } from 'react'-import { Dayjs, dayjs } from 'lib/dayjs'import { PRTimelineApi, PRTimelineSegmentKindEnumApi as Kind } from '../generated/api.schemas'+import { dayStartAtOrBefore, longestState, secondsBetween, stateSeconds, timelineSpan } from './pullRequestTimeline'export type DayViewAlignment = 'days' | 'weeks'/** The longest axis the day view draws; longer bars end in a clip marker. */export const MAX_AXIS_DAYS = 14-/** Rows start at this local hour, so a working day reads left to right without a split night. */-export const DAY_START_HOUR = 6-/** Night band, in hours after the row origin: 22:00 to 06:00. */-export const NIGHT_START_OFFSET_HOURS = 16const HOUR_SECONDS = 3600const DAY_HOURS = 24-export interface SegmentKindStyle {- label: string- short: string- color: string- pattern?: 'stripes' | 'dots' | 'dashes'-}--export const SEGMENT_KIND_STYLES: Record<Kind, SegmentKindStyle> = {- [Kind.WaitingForReview]: {- label: 'Waiting for approval',- short: 'review wait',- color: 'var(--data-color-3)',- },- [Kind.ChangesRequested]: {- label: 'Changes requested, no push yet',- short: 'changes requested',- color: 'var(--data-color-1)',- },- [Kind.ApprovedNotEnqueued]: {- label: 'Approved, nothing failing or running, not in the merge queue',- short: 'approved, not enqueued',- color: 'var(--data-color-1)',- pattern: 'stripes',- },- [Kind.RedFixedByPush]: {- label: 'Red until the next push',- short: 'red, fixed by a push',- color: 'var(--data-color-1)',- pattern: 'dots',- },- [Kind.CiRunning]: { label: 'CI running', short: 'CI running', color: 'var(--data-color-12)' },- [Kind.MergeQueue]: {- label: 'In the merge queue, restarts included',- short: 'merge queue',- color: 'var(--data-color-10)',- },- [Kind.OutOfMergeQueue]: {- label: 'Out of the merge queue, not added back',- short: 'out of the queue',- color: 'var(--data-color-10)',- pattern: 'stripes',- },- [Kind.RedPassedOnRerun]: {- label: 'Red, passed on a re-run of the same commit',- short: 'red, flake',- color: 'var(--data-color-13)',- },- [Kind.RedMasterBroken]: {- label: 'Red, the same job was failing on the default branch',- short: 'red, master broken',- color: 'var(--data-color-2)',- },- [Kind.RedNotProvable]: {- label: 'Red, cause not provable',- short: 'red, cause unknown',- color: 'var(--muted)',- pattern: 'dots',- },- [Kind.ReviewStateUnknown]: {- label: 'Review state unknown, reviews are not synced',- short: 'review state unknown',- color: 'var(--muted)',- pattern: 'stripes',- },- [Kind.Draft]: {- label: 'Draft, not ready for review yet',- short: 'draft',- color: 'var(--muted)',- pattern: 'dashes',- },-}--/** The fill for a segment kind. Patterns separate kinds that share a color, so the author's own states- * and the grey "unknown" states stay apart without extra hues. */-export function segmentBackground(kind: Kind): CSSProperties {- const { color, pattern } = SEGMENT_KIND_STYLES[kind]- switch (pattern) {- case 'stripes':- return {- backgroundColor: color,- backgroundImage: 'repeating-linear-gradient(135deg, rgb(255 255 255 / 45%) 0 2px, transparent 2px 5px)',- }- case 'dots':- return {- backgroundColor: color,- backgroundImage: 'radial-gradient(rgb(0 0 0 / 35%) 1px, transparent 1.2px)',- backgroundSize: '4px 4px',- }- case 'dashes':- return { backgroundImage: `repeating-linear-gradient(90deg, ${color} 0 4px, transparent 4px 7px)` }- default:- return { backgroundColor: color }- }-}--/** Legend order: who can move the pull request out of each state. */-export const SEGMENT_LEGEND_GROUPS: { label: string; kinds: Kind[] }[] = [- { label: 'Reviewers', kinds: [Kind.WaitingForReview] },- { label: 'Author', kinds: [Kind.ChangesRequested, Kind.ApprovedNotEnqueued, Kind.RedFixedByPush] },- {- label: 'CI and merge queue',- kinds: [Kind.CiRunning, Kind.MergeQueue, Kind.OutOfMergeQueue, Kind.RedPassedOnRerun, Kind.RedMasterBroken],- },- { label: 'Other', kinds: [Kind.RedNotProvable, Kind.ReviewStateUnknown, Kind.Draft] },-]-/** Current states an open pull request's author can clear without waiting on anyone else. */const AUTHOR_CAN_CLEAR: ReadonlySet<Kind> = new Set([Kind.OutOfMergeQueue,@@ -156,37 +45,23 @@ export interface DayViewGroup {rows: DayViewRow[]}-function secondsBetween(start: string, end: string): number {- return dayjs(end).diff(dayjs(start), 'second')-}-function toRow(pr: PRTimelineApi): DayViewRow | null {- const segments = pr.segments- if (segments.length === 0) {+ const current = pr.segments[pr.segments.length - 1]+ if (!current) {return null}const isOpen = pr.state === 'open'- const last = segments[segments.length - 1]- let highlightKind = last.kind- let highlightSeconds = secondsBetween(last.started_at, last.ended_at)- if (!isOpen) {- const totals = new Map<Kind, number>()- for (const segment of segments) {- totals.set(- segment.kind,- (totals.get(segment.kind) ?? 0) + secondsBetween(segment.started_at, segment.ended_at)- )- }- ;[highlightKind, highlightSeconds] = [...totals.entries()].reduce((best, entry) =>- entry[1] > best[1] ? entry : best- )- }+ const longest = longestState(stateSeconds(pr))+ const highlight =+ isOpen || !longest+ ? { kind: current.kind, seconds: secondsBetween(current.started_at, current.ended_at) }+ : longestreturn {pr,isOpen,- lengthSeconds: secondsBetween(segments[0].started_at, last.ended_at),- highlightKind,- highlightSeconds,+ lengthSeconds: timelineSpan(pr).seconds,+ highlightKind: highlight.kind,+ highlightSeconds: highlight.seconds,}}@@ -245,10 +120,8 @@ export function groupTimelines(items: PRTimelineApi[]): DayViewGroup[] {/** Where a row's clock starts: 06:00 local on the day it went ready (the day before when it went* ready in the small hours), or Monday 06:00 of that week so weekdays line up across rows. */export function rowOrigin(startedAt: string, alignment: DayViewAlignment): Dayjs {- const shifted = dayjs(startedAt).subtract(DAY_START_HOUR, 'hour')- const dayStart = shifted.startOf('day')- const origin = alignment === 'weeks' ? dayStart.subtract((dayStart.day() + 6) % 7, 'day') : dayStart- return origin.add(DAY_START_HOUR, 'hour')+ const dayStart = dayStartAtOrBefore(dayjs(startedAt).valueOf())+ return alignment === 'weeks' ? dayStart.subtract((dayStart.day() + 6) % 7, 'day') : dayStart}export function hoursFromOrigin(origin: Dayjs, at: string): number {@@ -260,7 +133,7 @@ export function hoursFromOrigin(origin: Dayjs, at: string): number {export function axisDays(items: PRTimelineApi[], alignment: DayViewAlignment): number {const ends = items.filter((pr) => pr.segments.length > 0)- .map((pr) => hoursFromOrigin(rowOrigin(pr.started_at, alignment), pr.segments[pr.segments.length - 1].ended_at))+ .map((pr) => hoursFromOrigin(rowOrigin(pr.started_at, alignment), timelineSpan(pr).endedAt)).sort((a, b) => a - b)if (ends.length === 0) {return 1@@ -282,12 +155,9 @@ export function redTimeByCause(items: PRTimelineApi[]): RedTimeByCause {const merged = items.filter((pr) => pr.merged_at != null)const totals = new Map<Kind, number>(RED_KINDS.map((kind) => [kind, 0]))for (const pr of merged) {- for (const segment of pr.segments) {- if (totals.has(segment.kind)) {- totals.set(- segment.kind,- (totals.get(segment.kind) ?? 0) + secondsBetween(segment.started_at, segment.ended_at)- )+ for (const { kind, seconds } of stateSeconds(pr)) {+ if (totals.has(kind)) {+ totals.set(kind, (totals.get(kind) ?? 0) + seconds)}}}diff --git a/products/engineering_analytics/frontend/lib/pullRequestTimeline.test.ts b/products/engineering_analytics/frontend/lib/pullRequestTimeline.test.tsnew file mode 100644index 000000000000..e0bd1613e3c1--- /dev/null+++ b/products/engineering_analytics/frontend/lib/pullRequestTimeline.test.ts@@ -0,0 +1,132 @@+import { PRTimelineApi, PRTimelineSegmentKindEnumApi as Kind } from '../generated/api.schemas'+import { paddedAxis, timeInStates, timelineMilestones, timelineSpan } from './pullRequestTimeline'++const HOUR = 3600 * 1000+// jest runs in UTC.+const T0 = Date.parse('2026-07-01T10:00:00Z')++function at(hours: number): string {+ return new Date(T0 + hours * HOUR).toISOString()+}++function pr(+ segments: [Kind, number, number][],+ options: {+ state?: PRTimelineApi['state']+ draft?: boolean+ openedAtStart?: boolean+ pushes?: [string, number][]+ } = {}+): PRTimelineApi {+ const state = options.state ?? 'open'+ return {+ number: 7,+ title: 'PR 7',+ author: { handle: 'alice', display_name: 'alice', avatar_url: '', is_bot: false },+ repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },+ state,+ is_draft: !!options.draft,+ created_at: at(segments[0][1] - (options.openedAtStart ? 0 : 1)),+ started_at: at(segments[0][1]),+ merged_at: state === 'merged' ? at(segments[segments.length - 1][2]) : null,+ pushes: (options.pushes ?? []).map(([headSha, hours]) => ({ head_sha: headSha, pushed_at: at(hours) })),+ estimated_cost_usd: null,+ billable_minutes: null,+ segments: segments.map(([kind, start, end]) => ({ kind, started_at: at(start), ended_at: at(end) })),+ }+}++describe('pullRequestTimeline', () => {+ it('groups time by who can move the pull request on, longest state first', () => {+ const { wholeSeconds, groups, longest } = timeInStates(+ pr(+ [+ [Kind.CiRunning, 0, 1],+ [Kind.WaitingForReview, 1, 5],+ [Kind.ApprovedNotEnqueued, 5, 6],+ [Kind.CiRunning, 6, 7],+ [Kind.RedFixedByPush, 7, 9],+ [Kind.MergeQueue, 9, 10],+ ],+ { state: 'merged' }+ )+ )++ expect(wholeSeconds).toBe(10 * 3600)+ expect(groups.map((group) => [group.label, group.share])).toEqual([+ ['Reviewers', 0.4],+ ['Author', 0.3],+ ['CI and merge queue', 0.3],+ ])+ expect(groups[1].states.map((state) => state.kind)).toEqual([Kind.RedFixedByPush, Kind.ApprovedNotEnqueued])+ expect(groups[2].states.map((state) => [state.kind, state.seconds])).toEqual([+ [Kind.CiRunning, 2 * 3600],+ [Kind.MergeQueue, 3600],+ ])+ expect(longest).toEqual({ kind: Kind.WaitingForReview, seconds: 4 * 3600, share: 0.4 })+ })++ it('marks pushes after the start, the queue dropping the pull request, and the merge, in time order', () => {+ const merged = pr(+ [+ [Kind.WaitingForReview, 0, 4],+ [Kind.MergeQueue, 4, 5],+ ],+ {+ state: 'merged',+ pushes: [+ ['aaaaaaaaaa', -2],+ ['bbbbbbbbbb', 0],+ ['cccccccccc', 2],+ ['dddddddddd', 6],+ ],+ }+ )++ expect(timelineMilestones(merged).map((milestone) => milestone.label)).toEqual([+ 'Ready for review',+ 'Push ccccccc',+ 'Merged',+ ])++ const kicked = pr(+ [+ [Kind.MergeQueue, 0, 2],+ [Kind.OutOfMergeQueue, 2, 3],+ ],+ { pushes: [['eeeeeeeeee', 1]] }+ )+ expect(timelineMilestones(kicked)).toEqual([+ { kind: 'start', at: at(0), label: 'Ready for review' },+ { kind: 'push', at: at(1), label: 'Push eeeeeee' },+ { kind: 'out_of_queue', at: at(2), label: 'Out of the merge queue' },+ ])+ })++ it.each([+ ['went ready after it opened', { state: 'closed' as const }, 'Ready for review', 'Closed'],+ [+ 'starts at opening with no ready event',+ { state: 'closed' as const, openedAtStart: true },+ 'Opened',+ 'Closed',+ ],+ ['is an open draft', { draft: true, openedAtStart: true }, 'Opened', undefined],+ ])('labels the ends of a pull request that %s', (_, options, startLabel, endLabel) => {+ const milestones = timelineMilestones(pr([[Kind.Draft, 0, 3]], options))++ expect(milestones[0].label).toBe(startLabel)+ expect(milestones.length > 1 ? milestones[milestones.length - 1].label : undefined).toBe(endLabel)+ })++ it('starts the axis at the day start before a small-hours start, so that night is shaded', () => {+ const axis = paddedAxis(timelineSpan(pr([[Kind.WaitingForReview, -7, 30]])))++ expect(axis.dayStarts.map((day) => day.toISOString())).toEqual([+ '2026-06-30T06:00:00.000Z',+ '2026-07-01T06:00:00.000Z',+ '2026-07-02T06:00:00.000Z',+ ])+ expect(axis.dayStarts[0].valueOf()).toBeLessThanOrEqual(axis.fromMs)+ })+})diff --git a/products/engineering_analytics/frontend/lib/pullRequestTimeline.ts b/products/engineering_analytics/frontend/lib/pullRequestTimeline.tsnew file mode 100644index 000000000000..de7c67a4267e--- /dev/null+++ b/products/engineering_analytics/frontend/lib/pullRequestTimeline.ts@@ -0,0 +1,268 @@+import type { CSSProperties } from 'react'++import { Dayjs, dayjs } from 'lib/dayjs'++import { PRTimelineApi, PRTimelineSegmentKindEnumApi as Kind } from '../generated/api.schemas'++export const TIMELINE_TIME_FORMAT = 'ddd D MMM HH:mm'+/** Rows start at this local hour, so a working day reads left to right without a split night. */+export const DAY_START_HOUR = 6+export const NIGHT_START_HOUR = 22++const MINUTE_MS = 60 * 1000++export interface SegmentKindStyle {+ label: string+ short: string+ color: string+ pattern?: 'stripes' | 'dots' | 'dashes'+}++export const SEGMENT_KIND_STYLES: Record<Kind, SegmentKindStyle> = {+ [Kind.WaitingForReview]: {+ label: 'Waiting for approval',+ short: 'review wait',+ color: 'var(--data-color-3)',+ },+ [Kind.ChangesRequested]: {+ label: 'Changes requested, no push yet',+ short: 'changes requested',+ color: 'var(--data-color-1)',+ },+ [Kind.ApprovedNotEnqueued]: {+ label: 'Approved, nothing failing or running, not in the merge queue',+ short: 'approved, not enqueued',+ color: 'var(--data-color-1)',+ pattern: 'stripes',+ },+ [Kind.RedFixedByPush]: {+ label: 'Red until the next push',+ short: 'red, fixed by a push',+ color: 'var(--data-color-1)',+ pattern: 'dots',+ },+ [Kind.CiRunning]: { label: 'CI running', short: 'CI running', color: 'var(--data-color-12)' },+ [Kind.MergeQueue]: {+ label: 'In the merge queue, restarts included',+ short: 'merge queue',+ color: 'var(--data-color-10)',+ },+ [Kind.OutOfMergeQueue]: {+ label: 'Out of the merge queue, not added back',+ short: 'out of the queue',+ color: 'var(--data-color-10)',+ pattern: 'stripes',+ },+ [Kind.RedPassedOnRerun]: {+ label: 'Red, passed on a re-run of the same commit',+ short: 'red, flake',+ color: 'var(--data-color-13)',+ },+ [Kind.RedMasterBroken]: {+ label: 'Red, the same job was failing on the default branch',+ short: 'red, master broken',+ color: 'var(--data-color-2)',+ },+ [Kind.RedNotProvable]: {+ label: 'Red, cause not provable',+ short: 'red, cause unknown',+ color: 'var(--muted)',+ pattern: 'dots',+ },+ [Kind.ReviewStateUnknown]: {+ label: 'Review state unknown, reviews are not synced',+ short: 'review state unknown',+ color: 'var(--muted)',+ pattern: 'stripes',+ },+ [Kind.Draft]: {+ label: 'Draft, not ready for review yet',+ short: 'draft',+ color: 'var(--muted)',+ pattern: 'dashes',+ },+}++/** The fill for a segment kind. Patterns separate kinds that share a color, so the author's own states+ * and the grey "unknown" states stay apart without extra hues. */+export function segmentBackground(kind: Kind): CSSProperties {+ const { color, pattern } = SEGMENT_KIND_STYLES[kind]+ switch (pattern) {+ case 'stripes':+ return {+ backgroundColor: color,+ backgroundImage: 'repeating-linear-gradient(135deg, rgb(255 255 255 / 45%) 0 2px, transparent 2px 5px)',+ }+ case 'dots':+ return {+ backgroundColor: color,+ backgroundImage: 'radial-gradient(rgb(0 0 0 / 35%) 1px, transparent 1.2px)',+ backgroundSize: '4px 4px',+ }+ case 'dashes':+ return { backgroundImage: `repeating-linear-gradient(90deg, ${color} 0 4px, transparent 4px 7px)` }+ default:+ return { backgroundColor: color }+ }+}++/** Legend order: who can move the pull request out of each state. */+export const SEGMENT_LEGEND_GROUPS: { label: string; kinds: Kind[] }[] = [+ { label: 'Reviewers', kinds: [Kind.WaitingForReview] },+ { label: 'Author', kinds: [Kind.ChangesRequested, Kind.ApprovedNotEnqueued, Kind.RedFixedByPush] },+ {+ label: 'CI and merge queue',+ kinds: [Kind.CiRunning, Kind.MergeQueue, Kind.OutOfMergeQueue, Kind.RedPassedOnRerun, Kind.RedMasterBroken],+ },+ { label: 'Other', kinds: [Kind.RedNotProvable, Kind.ReviewStateUnknown, Kind.Draft] },+]++export function secondsBetween(start: string, end: string): number {+ return dayjs(end).diff(dayjs(start), 'second')+}++export interface TimelineSpan {+ startedAt: string+ endedAt: string+ seconds: number+}++/** A timeline with no segments spans zero seconds at its start. */+export function timelineSpan(pr: PRTimelineApi): TimelineSpan {+ const segments = pr.segments+ const startedAt = segments.length ? segments[0].started_at : pr.started_at+ const endedAt = segments.length ? segments[segments.length - 1].ended_at : startedAt+ return { startedAt, endedAt, seconds: secondsBetween(startedAt, endedAt) }+}++export interface StateTime {+ kind: Kind+ seconds: number+}++export function stateSeconds(pr: PRTimelineApi): StateTime[] {+ const totals = new Map<Kind, number>()+ for (const segment of pr.segments) {+ totals.set(segment.kind, (totals.get(segment.kind) ?? 0) + secondsBetween(segment.started_at, segment.ended_at))+ }+ return [...totals].map(([kind, seconds]) => ({ kind, seconds }))+}++/** On a tie, the state that appeared first. */+export function longestState(states: StateTime[]): StateTime | null {+ return states.reduce<StateTime | null>(+ (best, state) => (!best || state.seconds > best.seconds ? state : best),+ null+ )+}++export interface StateShare extends StateTime {+ share: number+}++export interface StateTimeGroup {+ label: string+ seconds: number+ share: number+ states: StateShare[]+}++export interface TimeInStates {+ wholeSeconds: number+ groups: StateTimeGroup[]+ longest: StateShare | null+}++export function timeInStates(pr: PRTimelineApi): TimeInStates {+ const wholeSeconds = timelineSpan(pr).seconds+ const states = stateSeconds(pr)+ const totals = new Map(states.map((state) => [state.kind, state.seconds]))+ const share = (seconds: number): number => (wholeSeconds > 0 ? seconds / wholeSeconds : 0)+ const groups = SEGMENT_LEGEND_GROUPS.map((group) => {+ const groupStates = group.kinds+ .map((kind) => ({ kind, seconds: totals.get(kind) ?? 0 }))+ .filter((state) => state.seconds > 0)+ .map((state) => ({ ...state, share: share(state.seconds) }))+ .sort((a, b) => b.seconds - a.seconds)+ const seconds = groupStates.reduce((sum, state) => sum + state.seconds, 0)+ return { label: group.label, seconds, share: share(seconds), states: groupStates }+ }).filter((group) => group.states.length > 0)+ const longest = longestState(states)+ return { wholeSeconds, groups, longest: longest && { ...longest, share: share(longest.seconds) } }+}++export type MilestoneKind = 'start' | 'push' | 'out_of_queue' | 'merged' | 'closed'++export interface Milestone {+ kind: MilestoneKind+ at: string+ label: string+}++/** A start at creation means no ready event: opened ready, a draft, or issue events not synced. */+export function timelineStartLabel(pr: PRTimelineApi): string {+ return dayjs(pr.started_at).isSame(pr.created_at) ? 'Opened' : 'Ready for review'+}++export function timelineMilestones(pr: PRTimelineApi): Milestone[] {+ const { startedAt, endedAt } = timelineSpan(pr)+ const start = dayjs(startedAt)+ const end = dayjs(endedAt)+ const milestones: Milestone[] = [{ kind: 'start', at: startedAt, label: timelineStartLabel(pr) }]+ for (const push of pr.pushes) {+ const at = dayjs(push.pushed_at)+ if (at.isAfter(start) && !at.isAfter(end)) {+ milestones.push({ kind: 'push', at: push.pushed_at, label: `Push ${push.head_sha.slice(0, 7)}` })+ }+ }+ for (const segment of pr.segments) {+ if (segment.kind === Kind.OutOfMergeQueue) {+ milestones.push({ kind: 'out_of_queue', at: segment.started_at, label: 'Out of the merge queue' })+ }+ }+ if (pr.merged_at) {+ milestones.push({ kind: 'merged', at: pr.merged_at, label: 'Merged' })+ } else if (pr.state === 'closed') {+ milestones.push({ kind: 'closed', at: endedAt, label: 'Closed' })+ }+ return milestones.sort((a, b) => dayjs(a.at).valueOf() - dayjs(b.at).valueOf())+}++/** DAY_START_HOUR local on the day `ms` falls in, or on the day before when `ms` is in the small hours. */+export function dayStartAtOrBefore(ms: number): Dayjs {+ return dayjs(ms).subtract(DAY_START_HOUR, 'hour').startOf('day').add(DAY_START_HOUR, 'hour')+}++export interface TimeAxis {+ fromMs: number+ toMs: number+ /** The first day starts at or before fromMs, so a night that began before fromMs still shades its start. */+ dayStarts: Dayjs[]+ /** Percent of the axis from its start, clipped to the axis. */+ position: (ms: number) => string+ width: (startMs: number, endMs: number) => string+}++export function timeAxis(fromMs: number, toMs: number): TimeAxis {+ const span = toMs - fromMs+ const clip = (ms: number): number => Math.min(Math.max(ms, fromMs), toMs)+ const dayStarts: Dayjs[] = []+ for (let day = dayStartAtOrBefore(fromMs); day.valueOf() < toMs; day = day.add(1, 'day')) {+ dayStarts.push(day)+ }+ return {+ fromMs,+ toMs,+ dayStarts,+ position: (ms) => `${(100 * (clip(ms) - fromMs)) / span}%`,+ width: (startMs, endMs) => `${(100 * (clip(endMs) - clip(startMs))) / span}%`,+ }+}++/** The span padded on both sides, so its start and end markers stay inside the track. */+export function paddedAxis(span: TimelineSpan): TimeAxis {+ const start = dayjs(span.startedAt).valueOf()+ const end = dayjs(span.endedAt).valueOf()+ const pad = Math.max(0.02 * (end - start), 10 * MINUTE_MS)+ return timeAxis(start - pad, end + pad)+}diff --git a/products/engineering_analytics/frontend/scenes/DeliverySections.tsx b/products/engineering_analytics/frontend/scenes/DeliverySections.tsxindex 402635edb248..3c4d26f7b330 100644--- a/products/engineering_analytics/frontend/scenes/DeliverySections.tsx+++ b/products/engineering_analytics/frontend/scenes/DeliverySections.tsx@@ -1,7 +1,3 @@-// The delivery sections for one scope, meant to sit inside a page's ScopePanel: CI spend, getting merged,-// lead time to deploy, and the pull requests day view, each figure against the repository. The author-// page renders them for one author; a team page renders the same sections for one GitHub team.-import { useActions, useValues } from 'kea'import { pluralize } from 'lib/utils/strings'@@ -9,15 +5,12 @@ import { pluralize } from 'lib/utils/strings'import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'import { LeadTimeComparisonCard } from '../components/LeadTimeComparisonCard'import { PullRequestCountsCard } from '../components/PullRequestCountsCard'-import { PullRequestDayView } from '../components/PullRequestDayView'import { ReadyToMergeCard } from '../components/ReadyToMergeCard'-import { RedTimeByCauseCard } from '../components/RedTimeByCauseCard'import { ScopeComparisonCard } from '../components/ScopeComparisonCard'import { Section } from '../components/Section'import { DeliveryScope } from '../lib/deliveryScope'import { compactMinutes, compactUsd, percent } from '../lib/format'import { deliverySummaryLogic } from './deliverySummaryLogic'-import { pullRequestTimelinesLogic } from './pullRequestTimelinesLogic'const formatRatio = (value: number): string => value.toFixed(1)@@ -33,33 +26,18 @@ export function DeliverySections({sourceId: string | null}): JSX.Element {const summaryLogic = deliverySummaryLogic({ scope, sourceId })- const timelinesLogic = pullRequestTimelinesLogic({ scope, sourceId })const { summary, summaryLoading, summaryFailed } = useValues(summaryLogic)const { loadSummary } = useActions(summaryLogic)- const { timelines, timelinesLoading, timelinesFailed, dayViewAlignment, dayViewGroups, dayViewAxisDays, redTime } =- useValues(timelinesLogic)- const { loadTimelines, setDayViewAlignment } = useActions(timelinesLogic)- if (summaryFailed || timelinesFailed) {- return (- <CIAnalyticsLoadError- onRetry={() => {- loadSummary()- loadTimelines()- }}- />- )+ if (summaryFailed) {+ return <CIAnalyticsLoadError onRetry={loadSummary} />}const summaryPending = summaryLoading && !summary- const noMembers = summary?.scope_kind === 'github_team' && !summary.has_membership_data- const noMerges = noMembers- ? 'Team figures appear once the team members table on this GitHub source is synced.'- : 'Nothing merged in the window.'const costEmpty =summary && !summary.jobs_available? 'Cost appears once the workflow jobs table on this GitHub source is synced.'- : noMerges+ : 'Nothing merged in the window.'const reviewsEmpty =summary && !summary.review_data_available? 'Sync the reviews table on this GitHub source to see pushes after the first approval.'@@ -153,26 +131,6 @@ export function DeliverySections({loading={summaryPending}/></Section>-- <Section id="delivery-pull-requests" title="Pull requests">- <div className="flex flex-col gap-2">- <RedTimeByCauseCard- redTime={redTime}- loading={timelinesLoading && !timelines}- jobsAvailable={!!timelines?.jobs_available}- />- <PullRequestDayView- timelines={timelines}- groups={dayViewGroups}- days={dayViewAxisDays}- alignment={dayViewAlignment}- onAlignmentChange={setDayViewAlignment}- loading={timelinesLoading}- sourceId={sourceId}- showAuthor={scope.kind === 'github_team'}- />- </div>- </Section></>)}diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.stories.tsxindex 25ac8e754954..47065c6b9ab2 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.stories.tsx@@ -92,7 +92,9 @@ function timeline(created_at: startedAt,started_at: startedAt,merged_at: options.merged ? end : null,- pushes: steps.filter(([kind]) => kind === 'ci_running').length,+ pushes: segments+ .filter((segment) => segment.kind === 'ci_running')+ .map((segment, index) => ({ head_sha: `sha${number}${index}`, pushed_at: segment.started_at })),estimated_cost_usd: 4.2 * number,billable_minutes: 40 * number,segments,diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsxindex 68214c19e4de..e089d545968e 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx@@ -3,10 +3,8 @@ import { combineUrl } from 'kea-router'import { LemonSkeleton, Link } from '@posthog/lemon-ui'-import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { LemonCard } from 'lib/lemon-ui/LemonCard'import { Lettermark } from 'lib/lemon-ui/Lettermark'-import { dateMapping } from 'lib/utils/dateFilters'import { pluralize } from 'lib/utils/strings'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -14,23 +12,20 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'import { EntityHeader, VerdictPill } from '../components/EntityHeader'+import { PullRequestDayView } from '../components/PullRequestDayView'+import { RedTimeByCauseCard } from '../components/RedTimeByCauseCard'import { formatCost, formatMinutes } from '../components/runTables'-import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'+import { DELIVERY_DATE_OPTIONS, RepoScopeChip, ScopeBar, ScopeDateFilter } from '../components/ScopeBar'import { ScopePanel } from '../components/ScopePanel'import { Section } from '../components/Section'import { ShareRow } from '../components/ShareRow'import { AuthorLogicProps, authorLogic } from './authorLogic'import { DeliverySections } from './DeliverySections'import { deliverySummaryLogic } from './deliverySummaryLogic'-import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'import { pullRequestTimelinesLogic } from './pullRequestTimelinesLogic'-// Relative presets only: the backend caps a window at a year, and every preset here stays inside it.-const AUTHOR_DATE_OPTIONS = dateMapping.filter(({ key }) =>- ['Last 7 days', 'Last 14 days', 'Last 30 days', 'Last 90 days', 'Last 180 days', 'This year'].includes(key)-)-export const scene: SceneExport<AuthorLogicProps> = {component: EngineeringAnalyticsAuthorScene,logic: authorLogic,@@ -43,11 +38,18 @@ export const scene: SceneExport<AuthorLogicProps> = {export function EngineeringAnalyticsAuthorScene(): JSX.Element {const { handle, sourceId, deliveryScope, workflowCosts, workflowCostsLoading } = useValues(authorLogic)const { summary, summaryLoading } = useValues(deliverySummaryLogic({ scope: deliveryScope, sourceId }))- const { timelines, timelinesLoading, repoSlugs } = useValues(- pullRequestTimelinesLogic({ scope: deliveryScope, sourceId })- )- const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)- const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)+ const timelinesLogic = pullRequestTimelinesLogic({ scope: deliveryScope, sourceId })+ const {+ timelines,+ timelinesLoading,+ timelinesFailed,+ repoSlugs,+ dayViewAlignment,+ dayViewGroups,+ dayViewAxisDays,+ redTime,+ } = useValues(timelinesLogic)+ const { loadTimelines, setDayViewAlignment } = useActions(timelinesLogic)const hubUrl = combineUrl(urls.engineeringAnalytics(), sourceId ? { source: sourceId } : {}).urlconst avatarUrl = timelines?.items[0]?.author.avatar_url@@ -96,18 +98,33 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {authors with each other (SPEC §2). */}<ScopePanelbusy={summaryLoading || timelinesLoading || workflowCostsLoading}- controls={- <DateFilter- dateFrom={dateFrom}- dateTo={dateTo}- onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}- dateOptions={AUTHOR_DATE_OPTIONS}- size="small"- />- }+ controls={<ScopeDateFilter dateOptions={DELIVERY_DATE_OPTIONS} />}><DeliverySections scope={deliveryScope} scopeLabel="This author" sourceId={sourceId} />+ <Section id="delivery-pull-requests" title="Pull requests">+ {timelinesFailed ? (+ <CIAnalyticsLoadError onRetry={loadTimelines} />+ ) : (+ <div className="flex flex-col gap-2">+ <RedTimeByCauseCard+ redTime={redTime}+ loading={timelinesLoading && !timelines}+ jobsAvailable={!!timelines?.jobs_available}+ />+ <PullRequestDayView+ timelines={timelines}+ groups={dayViewGroups}+ days={dayViewAxisDays}+ alignment={dayViewAlignment}+ onAlignmentChange={setDayViewAlignment}+ loading={timelinesLoading}+ sourceId={sourceId}+ />+ </div>+ )}+ </Section>+<Section id="author-cost" title="Where their CI minutes go">{workflowCostsLoading ? (<LemonCard hoverEffect={false} className="p-4">diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.stories.tsxnew file mode 100644index 000000000000..efbc0f8685ea--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.stories.tsx@@ -0,0 +1,229 @@+import { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { App } from 'scenes/App'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'++import type { DeliverySummaryApi, DurationDistributionApi, TeamCIHealthListApi } from '../generated/api.schemas'++const HOUR = 3600+const TEAM = 'team-replay'++function distribution(p50Hours: number, count: number): DurationDistributionApi {+ return {+ pr_count: count,+ min_seconds: 0.2 * p50Hours * HOUR,+ p05_seconds: 0.3 * p50Hours * HOUR,+ p25_seconds: 0.6 * p50Hours * HOUR,+ p50_seconds: p50Hours * HOUR,+ mean_seconds: 1.8 * p50Hours * HOUR,+ p75_seconds: 2.2 * p50Hours * HOUR,+ p95_seconds: 6 * p50Hours * HOUR,+ max_seconds: 9 * p50Hours * HOUR,+ }+}++const SUMMARY: DeliverySummaryApi = {+ scope_kind: 'github_team',+ scope: TEAM,+ has_membership_data: true,+ jobs_available: true,+ review_data_available: true,+ ready_data_available: true,+ opened_pr_count: 41,+ merged_pr_count: 36,+ open_pr_count: 5,+ draft_pr_count: 2,+ cost_per_merged_pr_usd: { scope: 7.2, repo: 6.1 },+ billable_minutes_per_merged_pr: { scope: 96, repo: 84 },+ cost_per_push_usd: { scope: 1.1, repo: 1.2 },+ total_cost_usd: 302.4,+ total_billable_minutes: 4030,+ push_count: 274,+ median_ready_to_merge_seconds: { scope: 14 * HOUR, repo: 9 * HOUR },+ p90_ready_to_merge_seconds: { scope: 3.4 * 24 * HOUR, repo: 3.2 * 24 * HOUR },+ median_ready_to_first_approval_seconds: { scope: 3.2 * HOUR, repo: 2.6 * HOUR },+ median_first_approval_to_merge_seconds: { scope: 6.5 * HOUR, repo: 3.4 * HOUR },+ before_first_approval_share: { scope: 0.47, repo: 0.52 },+ pushes_after_approval_per_merged_pr: { scope: 1.1, repo: 0.9 },+ merge_queue_attempts_per_merged_pr: { scope: 1.35, repo: 1.3 },+ failed_merge_queue_share: { scope: 0.22, repo: 0.21 },+ lead_time: {+ deploy_data_available: true,+ environment_scope: 'prod-us, prod-eu',+ merged_pr_count: 36,+ deployed_merged_pr_count: 33,+ open_to_deploy: { scope: distribution(16, 33), repo: distribution(12, 640) },+ open_to_merge: { scope: distribution(15, 33), repo: distribution(10, 640) },+ merge_to_deploy: { scope: distribution(1.2, 33), repo: distribution(1.1, 640) },+ },+}++const TEAM_CI_HEALTH: TeamCIHealthListApi = {+ items: [+ {+ owner_team: TEAM,+ flaky_test_count: 8,+ flaky_test_count_prior: 11,+ regression_test_count: 3,+ regression_test_count_prior: 2,+ failed_run_count: 96,+ failed_run_count_prior: 120,+ same_commit_recovery_run_count: 14,+ same_commit_recovery_run_count_prior: 19,+ quarantined_failed_run_count: 2,+ quarantined_failed_run_count_prior: 1,+ last_seen_at: '2026-07-02T08:40:00Z',+ test_file_count: 204,+ test_file_count_prior: 201,+ merged_pr_count: 36,+ merged_pr_count_prior: 31,+ },+ ],+ truncated: false,+ limit: 100,+}++const TEAM_CI_ACTIVITY = {+ tests: [+ {+ runner: 'pytest',+ nodeid: 'products/replay/test_snapshots.py::test_resume_keeps_cursor',+ selector: 'products/replay/test_snapshots.py::test_resume_keeps_cursor',+ signal_count: 12,+ last_seen_at: '2026-07-02T07:10:00Z',+ },+ {+ runner: 'jest',+ nodeid: 'products/replay/frontend/scrubber.test.ts',+ selector: 'products/replay/frontend/scrubber.test.ts',+ signal_count: 4,+ last_seen_at: '2026-07-01T16:02:00Z',+ },+ ],+ truncated_tests: false,+}++const TEAM_MERGE_TREND = {+ has_membership_data: true,+ points: [+ { day: '2026-06-28', median_seconds: 11 * HOUR, average_seconds: 19 * HOUR },+ { day: '2026-06-29', median_seconds: 9 * HOUR, average_seconds: 14 * HOUR },+ { day: '2026-06-30', median_seconds: 13 * HOUR, average_seconds: 22 * HOUR },+ { day: '2026-07-01', median_seconds: 8 * HOUR, average_seconds: 12 * HOUR },+ ],+}++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Engineering Analytics/Team',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-07-02',+ featureFlags: [FEATURE_FLAGS.ENGINEERING_ANALYTICS],+ pageUrl: urls.engineeringAnalyticsTeam(TEAM),+ testOptions: {+ waitForSelector: '[data-attr="engineering-analytics-team-tests-table"]',+ },+ },+ decorators: [+ mswDecorator({+ get: {+ 'api/projects/:team_id/engineering_analytics/delivery_summary/': SUMMARY,+ 'api/projects/:team_id/engineering_analytics/team_ci_health/': TEAM_CI_HEALTH,+ 'api/projects/:team_id/engineering_analytics/team_ci_activity/': TEAM_CI_ACTIVITY,+ 'api/projects/:team_id/engineering_analytics/team_merge_trend/': TEAM_MERGE_TREND,+ 'api/projects/:team_id/engineering_analytics/sources/': [+ { id: 'src-1', repo: 'PostHog/posthog', prefix: '' },+ ],+ 'api/projects/:team_id/engineering_analytics/ci_cards/': {+ open_prs: 0,+ repos: 1,+ stuck: 0,+ failing_ci: 0,+ },+ 'api/projects/:team_id/engineering_analytics/pull_requests/': {+ items: [],+ truncated: false,+ limit: 1000,+ },+ 'api/projects/:team_id/engineering_analytics/workflow_health/': [],+ 'api/projects/:team_id/engineering_analytics/quarantine/': {+ available: false,+ entries: [],+ parse_errors: [],+ parse_warnings: [],+ repo: null,+ source_url: null,+ generated_at: null,+ },+ 'api/projects/:team_id/engineering_analytics/trunk_quarantine/': {+ available: false,+ ttl_days: 15,+ repository: null,+ trunk_url: null,+ teams: [],+ tests: [],+ },+ },+ }),+ ],+}+export default meta++type Story = StoryObj<typeof meta>++export const Team: Story = {+ render: () => <App />,+}++export const TeamWithoutMembership: Story = {+ render: () => <App />,+ decorators: [+ mswDecorator({+ get: {+ 'api/projects/:team_id/engineering_analytics/delivery_summary/': {+ ...SUMMARY,+ has_membership_data: false,+ merged_pr_count: 0,+ open_pr_count: 0,+ draft_pr_count: 0,+ opened_pr_count: 0,+ total_cost_usd: null,+ total_billable_minutes: null,+ push_count: 0,+ cost_per_merged_pr_usd: { scope: null, repo: 6.1 },+ billable_minutes_per_merged_pr: { scope: null, repo: 84 },+ cost_per_push_usd: { scope: null, repo: 1.2 },+ median_ready_to_merge_seconds: { scope: null, repo: 9 * HOUR },+ p90_ready_to_merge_seconds: { scope: null, repo: 3.2 * 24 * HOUR },+ median_ready_to_first_approval_seconds: { scope: null, repo: 2.6 * HOUR },+ median_first_approval_to_merge_seconds: { scope: null, repo: 3.4 * HOUR },+ before_first_approval_share: { scope: null, repo: 0.52 },+ pushes_after_approval_per_merged_pr: { scope: null, repo: 0.9 },+ merge_queue_attempts_per_merged_pr: { scope: null, repo: 1.3 },+ failed_merge_queue_share: { scope: null, repo: 0.21 },+ lead_time: {+ ...SUMMARY.lead_time,+ merged_pr_count: 0,+ deployed_merged_pr_count: 0,+ open_to_deploy: { scope: null, repo: distribution(12, 640) },+ open_to_merge: { scope: null, repo: distribution(10, 640) },+ merge_to_deploy: { scope: null, repo: distribution(1.1, 640) },+ },+ },+ 'api/projects/:team_id/engineering_analytics/team_merge_trend/': {+ has_membership_data: false,+ points: [],+ },+ 'api/projects/:team_id/engineering_analytics/team_ci_health/': {+ ...TEAM_CI_HEALTH,+ items: [{ ...TEAM_CI_HEALTH.items[0], merged_pr_count: null, merged_pr_count_prior: null }],+ },+ },+ }),+ ],+}diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.tsxindex 352f3c2c92ab..1e74f9d6eb5e 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.tsx@@ -24,6 +24,7 @@ import { WindowComparisonCard } from '../components/WindowComparisonCard'import { compactHoursLabel } from '../lib/format'import { githubFileUrl } from '../lib/github'import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'+import { TeamDeliveryPanel } from './TeamDeliveryPanel'import { TeamDetailLogicProps, TeamTestSignalRow, teamDetailLogic } from './teamDetailLogic'import {DEFAULT_TEAMS_WINDOW,@@ -54,6 +55,8 @@ export function EngineeringAnalyticsTeamScene(): JSX.Element {mergeTrendSeries,window,ownerTeam,+ deliveryScope,+ sourceId,} = useValues(teamDetailLogic)const { setWindow } = useActions(teamDetailLogic)const { activeSource } = useValues(engineeringAnalyticsLogic)@@ -110,7 +113,7 @@ export function EngineeringAnalyticsTeamScene(): JSX.Element {return (<SceneContent className="pb-16">- <SceneTitleSection name="Team CI health" resourceType={{ type: 'health' }} />+ <SceneTitleSection name="Team" resourceType={{ type: 'health' }} /><EntityHeadericon={<IconPeople />}title={isUnowned ? 'Unowned surfaces' : ownerTeam}@@ -132,6 +135,8 @@ export function EngineeringAnalyticsTeamScene(): JSX.Element {showDate={false}/>+ {deliveryScope && <TeamDeliveryPanel scope={deliveryScope} sourceId={sourceId} />}+<ScopePanelbusy={healthRowLoading || mergeTrendLoading}controls={diff --git a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.stories.tsx b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.stories.tsxnew file mode 100644index 000000000000..39cc2e032ab5--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.stories.tsx@@ -0,0 +1,265 @@+import { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { App } from 'scenes/App'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'++import type {+ CIFailureLogsApi,+ PRCostSummaryApi,+ PRLifecycleApi,+ PRTimelineApi,+ PullRequestTimelinesApi,+ WorkflowJobApi,+ WorkflowRunDetailApi,+} from '../generated/api.schemas'++const HOUR = 3600 * 1000+const REPO = { provider: 'github', owner: 'PostHog', name: 'posthog' } as const+const AUTHOR = { handle: 'jane-dev', display_name: 'jane-dev', avatar_url: '', is_bot: false }++function hoursAfter(start: string, hours: number): string {+ return new Date(Date.parse(start) + hours * HOUR).toISOString()+}++function timeline(+ number: number,+ title: string,+ startedAt: string,+ steps: [PRTimelineApi['segments'][number]['kind'], number][],+ pushes: [string, number][],+ merged: boolean+): PRTimelineApi {+ let cursor = 0+ const segments = steps.map(([kind, hours]) => {+ const segment = {+ kind,+ started_at: hoursAfter(startedAt, cursor),+ ended_at: hoursAfter(startedAt, cursor + hours),+ }+ cursor += hours+ return segment+ })+ return {+ number,+ title,+ author: AUTHOR,+ repo: REPO,+ state: merged ? 'merged' : 'open',+ is_draft: false,+ created_at: hoursAfter(startedAt, -0.5),+ started_at: startedAt,+ merged_at: merged ? hoursAfter(startedAt, cursor) : null,+ pushes: pushes.map(([headSha, hours]) => ({ head_sha: headSha, pushed_at: hoursAfter(startedAt, hours) })),+ estimated_cost_usd: 6.4,+ billable_minutes: 88,+ segments,+ }+}++function run(+ prNumber: number,+ id: number,+ workflow: string,+ headSha: string,+ startedAt: string,+ conclusion: string | null,+ options: { attempt?: number; mergeQueue?: boolean } = {}+): WorkflowRunDetailApi {+ return {+ repo: REPO,+ id,+ workflow_name: workflow,+ head_sha: headSha,+ head_branch: options.mergeQueue ? `trunk-merge/pr-${prNumber}/1` : `jane/pr-${prNumber}`,+ status: conclusion === null ? 'in_progress' : 'completed',+ conclusion,+ run_started_at: startedAt,+ updated_at: hoursAfter(startedAt, 0.4),+ duration_seconds: conclusion === null ? null : 24 * 60,+ run_attempt: options.attempt ?? 1,+ pr_number: prNumber,+ commit_pr_number: null,+ is_merge_queue: !!options.mergeQueue,+ }+}++function lifecycle(timelineItem: PRTimelineApi): PRLifecycleApi {+ return {+ pull_request: {+ author: AUTHOR,+ repo: REPO,+ id: 90000 + timelineItem.number,+ number: timelineItem.number,+ title: timelineItem.title,+ state: timelineItem.state,+ is_draft: false,+ created_at: timelineItem.created_at,+ merged_at: timelineItem.merged_at,+ closed_at: timelineItem.merged_at,+ },+ events: [{ kind: 'opened', at: timelineItem.created_at }],+ metric_quality: 'partial',+ }+}++function timelines(item: PRTimelineApi): PullRequestTimelinesApi {+ return {+ scope_kind: 'pull_request',+ scope: `PostHog/posthog#${item.number}`,+ has_membership_data: true,+ review_data_available: true,+ jobs_available: true,+ merge_queue_state_available: true,+ generated_at: '2026-07-02T12:00:00Z',+ truncated: false,+ limit: 200,+ items: [item],+ }+}++const READY = '2026-06-29T09:40:00Z'+const MERGED = timeline(+ 4721,+ 'feat(replay): keep the scrubber in place on resume',+ READY,+ [+ ['ci_running', 0.5],+ ['waiting_for_review', 21.5],+ ['changes_requested', 3],+ ['ci_running', 0.6],+ ['red_passed_on_rerun', 0.8],+ ['ci_running', 0.5],+ ['waiting_for_review', 2.1],+ ['approved_not_enqueued', 1.5],+ ['merge_queue', 0.9],+ ],+ [+ ['a1b2c3d4e5', -0.4],+ ['f6e5d4c3b2', 25],+ ],+ true+)+const SECOND_PUSH = hoursAfter(READY, 25)+const MERGED_RUNS: WorkflowRunDetailApi[] = [+ run(4721, 101, 'Backend CI', 'a1b2c3d4e5', hoursAfter(READY, -0.4), 'success'),+ run(4721, 102, 'Frontend CI', 'a1b2c3d4e5', hoursAfter(READY, -0.4), 'success'),+ run(4721, 103, 'Backend CI', 'f6e5d4c3b2', SECOND_PUSH, 'failure'),+ run(4721, 103, 'Backend CI', 'f6e5d4c3b2', hoursAfter(READY, 26.4), 'success', { attempt: 2 }),+ run(4721, 104, 'Frontend CI', 'f6e5d4c3b2', SECOND_PUSH, 'success'),+ run(4721, 105, 'Backend CI', '9a8b7c6d5e', hoursAfter(READY, 30.5), 'success', { mergeQueue: true }),+]++const KICKED_READY = '2026-07-01T08:00:00Z'+const KICKED = timeline(+ 4730,+ 'fix(replay): drop the stale snapshot cache',+ KICKED_READY,+ [+ ['ci_running', 0.6],+ ['waiting_for_review', 4.4],+ ['ci_running', 0.5],+ ['approved_not_enqueued', 0.5],+ ['merge_queue', 1.2],+ ['out_of_merge_queue', 20.8],+ ],+ [+ ['0c1d2e3f4a', -0.3],+ ['5b6c7d8e9f', 5],+ ],+ false+)+const KICKED_RUNS: WorkflowRunDetailApi[] = [+ run(4730, 201, 'Backend CI', '0c1d2e3f4a', hoursAfter(KICKED_READY, -0.3), 'success'),+ run(4730, 202, 'Backend CI', '5b6c7d8e9f', hoursAfter(KICKED_READY, 5), 'success'),+ run(4730, 203, 'Backend CI', '1f2e3d4c5b', hoursAfter(KICKED_READY, 6.2), 'failure', { mergeQueue: true }),+]++const FAILED_GATE_JOBS: WorkflowJobApi[] = [+ {+ id: 2031,+ run_id: 203,+ name: 'Django tests (Core, 3/8)',+ status: 'completed',+ conclusion: 'failure',+ started_at: hoursAfter(KICKED_READY, 6.3),+ completed_at: hoursAfter(KICKED_READY, 6.8),+ duration_seconds: 30 * 60,+ runner_provider: 'depot',+ runner_label: 'depot-ubuntu-latest-4',+ estimated_cost_usd: 0.4,+ },+]++const PR_COST: PRCostSummaryApi = {+ by_workflow: [],+ by_run: [],+ llm_spend: null,+ jobs_available: true,+ billable_minutes: 88,+ estimated_cost_usd: 6.4,+ costed_jobs: 41,+ unsettled_jobs: 0,+ excluded_jobs: 2,+}++const NO_FAILURE_LOGS: CIFailureLogsApi = {+ repo: REPO,+ jobs: [],+ pr_number: 4721,+ runs_attributed: 5,+ logs_available: false,+ truncated: false,+}++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Engineering Analytics/Pull Request',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-07-02',+ featureFlags: [FEATURE_FLAGS.ENGINEERING_ANALYTICS],+ pageUrl: urls.engineeringAnalyticsPullRequest('PostHog', 'posthog', MERGED.number),+ testOptions: {+ waitForSelector: '[data-attr="engineering-analytics-pr-delivery-timeline"]',+ },+ },+ decorators: [+ mswDecorator({+ get: {+ 'api/projects/:team_id/engineering_analytics/pr_lifecycle/': lifecycle(MERGED),+ 'api/projects/:team_id/engineering_analytics/pr_runs/': MERGED_RUNS,+ 'api/projects/:team_id/engineering_analytics/pr_cost/': PR_COST,+ 'api/projects/:team_id/engineering_analytics/ci_failure_logs/': NO_FAILURE_LOGS,+ 'api/projects/:team_id/engineering_analytics/pull_request_timelines/': timelines(MERGED),+ },+ }),+ ],+}+export default meta++type Story = StoryObj<typeof meta>++export const Merged: Story = {+ render: () => <App />,+}++export const OutOfTheMergeQueue: Story = {+ render: () => <App />,+ parameters: {+ pageUrl: urls.engineeringAnalyticsPullRequest('PostHog', 'posthog', KICKED.number),+ },+ decorators: [+ mswDecorator({+ get: {+ 'api/projects/:team_id/engineering_analytics/pr_lifecycle/': lifecycle(KICKED),+ 'api/projects/:team_id/engineering_analytics/pr_runs/': KICKED_RUNS,+ 'api/projects/:team_id/engineering_analytics/pull_request_timelines/': timelines(KICKED),+ 'api/projects/:team_id/engineering_analytics/workflow_jobs/': FAILED_GATE_JOBS,+ },+ }),+ ],+}diff --git a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsxindex efdc5c5833bb..b88dc66cdca0 100644--- a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx+++ b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx@@ -1,6 +1,5 @@import { useActions, useValues } from 'kea'import { combineUrl } from 'kea-router'-import { Fragment, ReactNode } from 'react'import { IconExternal, IconPullRequest } from '@posthog/icons'import {@@ -11,12 +10,9 @@ import {LemonTableColumns,LemonTag,Link,- Tooltip,} from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'-import { dayjs } from 'lib/dayjs'-import { LemonCard } from 'lib/lemon-ui/LemonCard'import { cn } from 'lib/utils/css-classes'import { humanFriendlyDuration } from 'lib/utils/durations'import { pluralize } from 'lib/utils/strings'@@ -30,6 +26,7 @@ import { EntityHeader, VerdictPill } from '../components/EntityHeader'import { FailureLogGroups } from '../components/FailureLogs'import { GroupedJobsTable } from '../components/GroupedJobsTable'import { MetricTile } from '../components/MetricTile'+import { PullRequestDeliveryTimeline } from '../components/PullRequestDeliveryTimeline'import { PullRequestStateTag } from '../components/PullRequestStateTag'import { RunConclusionTag } from '../components/runTables'import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'@@ -37,11 +34,10 @@ import { Section } from '../components/Section'import type { WorkflowJobApi } from '../generated/api.schemas'import { compactCount, 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 { WorkflowRun, isPassingConclusion } from '../lib/lifecycle'+import { pushRoundOf } from '../lib/pushRounds'import { withCurrentScope } from '../lib/scope'import {- PrCommitRuns,PrRunRow,PrWorkflowRow,PullRequestDetailLogicProps,@@ -61,254 +57,6 @@ export const scene: SceneExport<PullRequestDetailLogicProps> = {}),}-function gapBetween(from: string, to: string): string {- const seconds = dayjs(to).diff(dayjs(from), 'second')- return seconds <= 0 ? '<1s' : humanFriendlyDuration(seconds, { maxUnits: 2 })-}--interface TimelineNode {- key: string- label: string- at: string- 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, 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 {- summary: LifecycleSummary- openedAt: string- // One node per push (CI round); each scrolls to its run table below.- commitGroups: PrCommitRuns[]-}--/** The earliest run start in a round — where that push's CI begins on the timeline. */-function roundStart(group: PrCommitRuns): string | null {- const starts = group.runs.map((run) => run.startedAt).filter((at): at is string => !!at)- return starts.length ? starts.reduce((min, at) => (at < min ? at : min)) : group.latestStart-}--// 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 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[] = [- {- key: 'opened',- label: 'Opened',- at: openedAt,- dotClass: 'bg-muted',- sublabel: <TZLabel time={openedAt} />,- },- ]- // Only recent pushes get their own node; the rest collapse into one summary node so the strip never- // scrolls. commitGroups is newest-first. Don't collapse a single straggler — "+1 earlier" saves nothing.- 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) => {- const at = roundStart(group)- if (!at) {- return- }- const round = pushRoundOf(group.headSha, group.runs)- nodes.push({- key: `round-${group.headSha}`,- label: group.headSha.slice(0, 7),- at,- dotClass: roundDotClass(round),- mono: true,- 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) => pushRoundOf(group.headSha, group.runs).failed)- if (at) {- nodes.push({- key: 'earlier-pushes',- label: `+${hiddenRounds.length} earlier`,- at,- dotClass: anyFailure ? 'bg-danger' : 'bg-muted',- danger: anyFailure,- sublabel: 'pushes',- })- }- }- if (summary.mergedAt) {- nodes.push({- key: 'merged',- label: 'Merged',- at: summary.mergedAt,- dotClass: 'bg-success',- sublabel: <TZLabel time={summary.mergedAt} />,- })- } else if (summary.closedAt) {- nodes.push({- key: 'closed',- label: 'Closed',- at: summary.closedAt,- dotClass: 'bg-danger',- danger: true,- sublabel: <TZLabel time={summary.closedAt} />,- })- }- nodes.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0))-- const stillOpen = !summary.mergedAt && !summary.closedAt- if (stillOpen) {- nodes.push({- key: 'now',- label: 'Still open',- at: dayjs().toISOString(),- dotClass: 'animate-pulse border-2 border-warning bg-transparent',- dashedIncoming: true,- sublabel: 'now',- })- }-- // Not necessarily the last node's time: head-SHA runs can outlive the merge.- const totalTo = summary.mergedAt ?? summary.closedAt ?? nodes[nodes.length - 1].at- const connector = (dashed: boolean | undefined): string =>- dashed ? 'w-full border-t border-dashed border-border-bold' : 'h-px w-full bg-border-bold'-- // Connector widths are proportional to elapsed time, so the strip reads as a timeline. Floor each- // segment so a near-instant gap still draws a visible connector instead of collapsing to nothing.- 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">- <div className="flex min-w-0 flex-1 items-stretch">- {nodes.map((node, index) => (- <Fragment key={node.key}>- {index > 0 && (- <div- className="flex min-w-12 flex-col"- style={{- flexGrow: Math.max(- minGrow,- dayjs(node.at).diff(dayjs(nodes[index - 1].at), 'second')- ),- }}- >- <span className={cn(ROW_LABEL, 'justify-center')}>- <span className="rounded-full border bg-surface-secondary px-2 text-xs leading-4 whitespace-nowrap text-secondary tabular-nums">- {gapBetween(nodes[index - 1].at, node.at)}- </span>- </span>- <span className={ROW_BAR} />- <span className={ROW_DOT}>- <span className={connector(node.dashedIncoming)} />- </span>- <span className={ROW_SUB} />- </div>- )}- <div className="flex shrink-0 flex-col items-center px-1">- <span className={ROW_LABEL}>- <span- className={cn(- 'text-xs font-medium whitespace-nowrap',- node.mono && 'font-mono',- node.danger && 'text-danger'- )}- >- {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="w-2.5 rounded-t-sm"- // 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)} />- <span- className={cn(- 'flex-1',- index < nodes.length - 1 && connector(nodes[index + 1].dashedIncoming)- )}- />- </span>- <span className={cn(ROW_SUB, 'text-xs whitespace-nowrap text-tertiary')}>- {node.sublabel ?? <> </>}- </span>- </div>- </Fragment>- ))}- </div>- <div className="flex shrink-0 flex-col items-end self-center border-l border-primary pl-6">- <span className="text-lg font-semibold leading-6 tabular-nums">- {gapBetween(openedAt, totalTo)}- </span>- <span className="text-xs text-tertiary">- {summary.mergedAt ? 'open → merge' : summary.closedAt ? 'open → close' : 'open so far'}- </span>- </div>- </div>- </LemonCard>- )-}-// Stable per-row key — re-runs share a runId, so start time disambiguates attempts. Used for rowKey and// the expand-state set, so expanding one attempt doesn't open the others.function runRowKey(run: WorkflowRun): string {@@ -641,7 +389,6 @@ export function PullRequestDetailScene(): JSX.Element {lifecycle,lifecycleLoading,loadFailed,- summary,runs,commitGroups,filteredRuns,@@ -664,8 +411,13 @@ export function PullRequestDetailScene(): JSX.Element {runJobs,runJobsLoading,expandedRunKeys,+ timelines,+ timelinesLoading,+ timelinesFailed,+ timeline,} = useValues(pullRequestDetailLogic)- const { loadLifecycle, loadPrRuns, setWorkflowFilter, setRunExpanded } = useActions(pullRequestDetailLogic)+ const { loadLifecycle, loadPrRuns, loadTimelines, setWorkflowFilter, setRunExpanded } =+ useActions(pullRequestDetailLogic)const pullRequest = lifecycle?.pull_requestconst githubUrl = pullRequest@@ -675,7 +427,6 @@ export function PullRequestDetailScene(): JSX.Element {const passed = runs.filter((run) => run.conclusion !== null && isPassingConclusion(run.conclusion)).lengthconst failed = runs.filter((run) => run.conclusion !== null && !isPassingConclusion(run.conclusion)).lengthconst 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) : nullconst tilesLoading = prRunsLoading && commitGroups.length === 0@@ -846,14 +597,23 @@ export function PullRequestDetailScene(): JSX.Element {)}<Section id="pr-timeline" title="Lifecycle">- {summary && pullRequest ? (- <LifecycleStrip- summary={summary}- openedAt={summary.openedAt ?? pullRequest.created_at}- commitGroups={commitGroups}- />+ {timelinesFailed ? (+ <div className="flex items-center gap-3">+ <span className="text-sm text-secondary">+ Couldn't load the timeline for this pull request.+ </span>+ <LemonButton type="secondary" size="small" onClick={loadTimelines} loading={timelinesLoading}>+ Retry+ </LemonButton>+ </div>+ ) : !timelines ? (+ <LemonSkeleton className="h-40 w-full" />+ ) : timeline ? (+ <PullRequestDeliveryTimeline pr={timeline} />) : (- <LemonSkeleton className="h-12 w-full" />+ <div className="text-sm text-secondary">+ No timeline for this pull request yet. If it stays empty, check the GitHub source's sync status.+ </div>)}</Section>diff --git a/products/engineering_analytics/frontend/scenes/TeamDeliveryPanel.tsx b/products/engineering_analytics/frontend/scenes/TeamDeliveryPanel.tsxnew file mode 100644index 000000000000..84c14ec4ae0f--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/TeamDeliveryPanel.tsx@@ -0,0 +1,24 @@+import { useValues } from 'kea'++import { DELIVERY_DATE_OPTIONS, ScopeDateFilter } from '../components/ScopeBar'+import { ScopePanel } from '../components/ScopePanel'+import { DeliveryScope } from '../lib/deliveryScope'+import { DeliverySections } from './DeliverySections'+import { deliverySummaryLogic } from './deliverySummaryLogic'++export function TeamDeliveryPanel({ scope, sourceId }: { scope: DeliveryScope; sourceId: string | null }): JSX.Element {+ const { summary, summaryLoading } = useValues(deliverySummaryLogic({ scope, sourceId }))+ return (+ <ScopePanel busy={summaryLoading} controls={<ScopeDateFilter dateOptions={DELIVERY_DATE_OPTIONS} />}>+ {/* Without the members table a team matches no author, so every figure would be a false zero. */}+ {summary && !summary.has_membership_data ? (+ <div className="py-8 text-center text-sm text-secondary">+ No team membership data. Sync the team members table on this GitHub source to see this team's+ delivery figures.+ </div>+ ) : (+ <DeliverySections scope={scope} scopeLabel="This team" sourceId={sourceId} />+ )}+ </ScopePanel>+ )+}diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.tsindex 276792844b6c..10a37b1b0e0f 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts@@ -25,7 +25,7 @@ import type {WorkflowRunDetailApi,} from '../generated/api.schemas'import { ciStatusOf } from '../lib/ci'-import { summarizeLifecycle, workflowRuns } from '../lib/lifecycle'+import { workflowRuns } from '../lib/lifecycle'import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'import {DEFAULT_FILTERS,@@ -550,37 +550,6 @@ describe('engineeringAnalyticsLogic', () => {expect(series).toEqual({ completed: [completed], failures: [failures], labels: [label] })})- it('summarizeLifecycle rolls events up into milestones and verdicts', () => {- const summary = summarizeLifecycle([- { kind: 'opened', at: '2026-06-01T00:00:00Z' },- { kind: 'ci_started', at: '2026-06-01T00:01:00Z', detail: 'Backend CI' },- { kind: 'ci_started', at: '2026-06-01T00:02:00Z', detail: 'Frontend CI' },- { kind: 'ci_started', at: '2026-06-01T00:03:00Z', detail: 'E2E: smoke' },- { kind: 'ci_finished', at: '2026-06-01T00:30:00Z', detail: 'Backend CI: failure' },- { kind: 'ci_finished', at: '2026-06-01T00:20:00Z', detail: 'Frontend CI: success' },- { kind: 'merged', at: '2026-06-02T00:00:00Z' },- ])- expect(summary.openedAt).toBe('2026-06-01T00:00:00Z')- expect(summary.firstCiStartedAt).toBe('2026-06-01T00:01:00Z')- expect(summary.lastCiFinishedAt).toBe('2026-06-01T00:30:00Z')- expect(summary.mergedAt).toBe('2026-06-02T00:00:00Z')- expect(summary.closedAt).toBeNull()- expect(summary.notPassing).toEqual([- { workflow: 'Backend CI', conclusion: 'failure', at: '2026-06-01T00:30:00Z' },- ])- expect(summary.passed).toBe(1)- expect(summary.unsettled).toBe(1)- })-- it('summarizeLifecycle keeps workflow names that contain a colon', () => {- const summary = summarizeLifecycle([- { kind: 'ci_finished', at: '2026-06-01T00:30:00Z', detail: 'E2E: smoke: timed_out' },- ])- expect(summary.notPassing).toEqual([- { workflow: 'E2E: smoke', conclusion: 'timed_out', at: '2026-06-01T00:30:00Z' },- ])- })-it('workflowRuns pairs starts and finishes into per-workflow runs with durations', () => {const runs = workflowRuns([{ kind: 'opened', at: '2026-06-01T00:00:00Z' },diff --git a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.tsindex 4f1ff3080f85..54a3a6fdf9f4 100644--- a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts+++ b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts@@ -11,24 +11,21 @@ import {engineeringAnalyticsPrCost,engineeringAnalyticsPrLifecycle,engineeringAnalyticsPrRuns,+ engineeringAnalyticsPullRequestTimelines,engineeringAnalyticsWorkflowJobs,} from '../generated/api'import type {CIFailureLogsApi,PRCostSummaryApi,PRLifecycleApi,+ PRTimelineApi,+ PullRequestTimelinesApi,WorkflowJobApi,WorkflowRunDetailApi,} from '../generated/api.schemas'import { failedShardsLabel, groupJobs } from '../lib/jobGroups'import { jobCacheKey } from '../lib/jobs'-import {- LifecycleSummary,- WorkflowRun,- isDecisiveFailure,- isPassingConclusion,- summarizeLifecycle,-} from '../lib/lifecycle'+import { WorkflowRun, isDecisiveFailure, isPassingConclusion } from '../lib/lifecycle'const projectId = (): string => String(ApiConfig.getCurrentProjectId())@@ -199,7 +196,10 @@ export interface pullRequestDetailLogicValues {runJobsLoading: booleanruns: WorkflowRun[]sourceId: string | null- summary: LifecycleSummary | null+ timeline: PRTimelineApi | null+ timelines: PullRequestTimelinesApi | null+ timelinesFailed: boolean+ timelinesLoading: booleanworkflowFilter: string}@@ -289,6 +289,21 @@ export interface pullRequestDetailLogicActions {prRuns: WorkflowRunDetailApi[]payload?: any}+ loadTimelines: () => any+ loadTimelinesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadTimelinesSuccess: (+ timelines: PullRequestTimelinesApi,+ payload?: any+ ) => {+ timelines: PullRequestTimelinesApi+ payload?: any+ }setRunExpanded: (rowKey: string,expanded: boolean,@@ -312,7 +327,6 @@ export interface pullRequestDetailLogicMeta {sourceId: (arg: string | null) => string | nullrepoOwner: (arg: string) => stringrepoName: (arg: string) => string- summary: (lifecycle: PRLifecycleApi | null) => LifecycleSummary | nullruns: (prRuns: WorkflowRunDetailApi[]) => WorkflowRun[]commitGroups: (prRuns: WorkflowRunDetailApi[]) => PrCommitRuns[]filteredCommitGroups: (commitGroups: PrCommitRuns[], workflowFilter: string) => PrCommitRuns[]@@ -334,6 +348,7 @@ export interface pullRequestDetailLogicMeta {authoredRuns: (prRuns: WorkflowRunDetailApi[]) => WorkflowRunDetailApi[]pushes: (authoredRuns: WorkflowRunDetailApi[]) => numberrerunCycles: (authoredRuns: WorkflowRunDetailApi[]) => number+ timeline: (timelines: PullRequestTimelinesApi | null) => PRTimelineApi | nullbreadcrumbs: (repoOwner: string, repoName: string, number: number) => Breadcrumb[]}}@@ -385,6 +400,17 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([}),},],+ timelines: [+ null as PullRequestTimelinesApi | null,+ {+ loadTimelines: async (): Promise<PullRequestTimelinesApi> =>+ await engineeringAnalyticsPullRequestTimelines(projectId(), {+ pr_number: props.number,+ repo: `${props.repoOwner}/${props.repoName}`,+ source_id: props.sourceId ?? undefined,+ }),+ },+ ],prCost: [null as PRCostSummaryApi | null,{@@ -455,6 +481,7 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([loadPrRunsFailure: () => true,},],+ timelinesFailed: [false, { loadTimelines: () => false, loadTimelinesFailure: () => true }],expandedRunKeys: [[] as string[],{@@ -498,11 +525,6 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([(repoOwner: string): string => repoOwner,],repoName: [() => [(_, p: PullRequestDetailLogicProps) => p.repoName], (repoName: string): string => repoName],- summary: [- (s) => [s.lifecycle],- (lifecycle: PRLifecycleApi | null): LifecycleSummary | null =>- lifecycle ? summarizeLifecycle(lifecycle.events) : null,- ],runs: [(s) => [s.prRuns], (prRuns: WorkflowRunDetailApi[]): WorkflowRun[] => prRuns.map(toWorkflowRun)],commitGroups: [(s) => [s.prRuns],@@ -630,6 +652,11 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([(authoredRuns: WorkflowRunDetailApi[]): number =>authoredRuns.filter((run) => (run.run_attempt ?? 1) > 1).length,],+ timeline: [+ (s) => [s.timelines],+ (timelines: PullRequestTimelinesApi | null): PRTimelineApi | null =>+ timelines?.items.find((item) => item.segments.length > 0) ?? null,+ ],breadcrumbs: [(_, p) => [p.repoOwner, p.repoName, p.number],(repoOwner: string, repoName: string, number: number): Breadcrumb[] => [@@ -657,6 +684,7 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([afterMount(({ actions }) => {actions.loadLifecycle()actions.loadPrRuns()+ actions.loadTimelines()actions.loadPrCost()}),])diff --git a/products/engineering_analytics/frontend/scenes/pullRequestTimelinesLogic.ts b/products/engineering_analytics/frontend/scenes/pullRequestTimelinesLogic.tsindex 0360d36e25c3..c95ae835e56c 100644--- a/products/engineering_analytics/frontend/scenes/pullRequestTimelinesLogic.ts+++ b/products/engineering_analytics/frontend/scenes/pullRequestTimelinesLogic.ts@@ -108,13 +108,8 @@ export const pullRequestTimelinesLogic = kea<pullRequestTimelinesLogicType>([timelinesFailed: [false, { loadTimelines: () => false, loadTimelinesFailure: () => true }],}),- listeners(({ actions, props }) => ({- // A single pull request is shown whatever its age, so only list scopes follow the window.- [engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {- if (props.scope.kind !== 'pull_request') {- actions.loadTimelines()- }- },+ listeners(({ actions }) => ({+ [engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => actions.loadTimelines(),})),selectors({diff --git a/products/engineering_analytics/frontend/scenes/teamDetailLogic.ts b/products/engineering_analytics/frontend/scenes/teamDetailLogic.tsindex cc4e093c51d8..be84afd6540d 100644--- a/products/engineering_analytics/frontend/scenes/teamDetailLogic.ts+++ b/products/engineering_analytics/frontend/scenes/teamDetailLogic.ts@@ -10,6 +10,7 @@ import {engineeringAnalyticsTeamMergeTrend,} from '../generated/api'import type { TeamTestSignalApi } from '../generated/api.schemas'+import { DeliveryScope } from '../lib/deliveryScope'import { DEFAULT_TEAMS_WINDOW, TeamCIHealthRow, TeamsWindow, UNOWNED_TEAM, toTeamCIHealthRow } from './teamsLogic'const projectId = (): string => String(ApiConfig.getCurrentProjectId())@@ -48,6 +49,7 @@ export interface TeamMergeTrendData {export interface teamDetailLogicValues {activity: TeamActivityData | nullactivityLoading: boolean+ deliveryScope: DeliveryScope | nullhealthRow: TeamCIHealthRow | nullhealthRowLoading: booleanmergeTrend: TeamMergeTrendData | null@@ -58,6 +60,7 @@ export interface teamDetailLogicValues {median: number[]} | nullownerTeam: string+ sourceId: string | nullwindow: TeamsWindow}@@ -118,6 +121,8 @@ export interface teamDetailLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {ownerTeam: (ownerTeam: string) => string+ sourceId: (sourceId: string | null) => string | null+ deliveryScope: (ownerTeam: string) => DeliveryScope | nullmergeTrendSeries: (mergeTrend: TeamMergeTrendData | null) => {average: number[]labels: string[]@@ -210,6 +215,14 @@ export const teamDetailLogic = kea<teamDetailLogicType>([})),selectors({ownerTeam: [(_, p) => [p.ownerTeam], (ownerTeam: string) => ownerTeam],+ sourceId: [(_, p) => [p.sourceId], (sourceId: string | null) => sourceId],+ /** owners.yaml team names are GitHub team slugs (checked by `hogli owners:lint --live`). Null for+ * unowned surfaces, which have no GitHub team. */+ deliveryScope: [+ (s) => [s.ownerTeam],+ (ownerTeam: string): DeliveryScope | null =>+ ownerTeam === UNOWNED_TEAM ? null : { kind: 'github_team', githubTeam: ownerTeam },+ ],/** Quill-ready daily series on the backend's own day buckets. Gaps carry the last values* forward: a day without merges means "nothing merged", not instant merges, so* zero-filling would draw a false dip. Null when nothing merged in the window. */diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 49f6b831a31e..80b06df4cbbc 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -57478,6 +57478,13 @@ export namespace Schemas {metric_quality?: MetricQualityEnum;}+ export interface PRTimelinePush {+ /** The pushed head commit. */+ head_sha: string;+ /** When the commit's first workflow run was created, which is when the commit arrived. */+ pushed_at: string;+ }+/*** * `draft` - DRAFT* * `waiting_for_review` - WAITING_FOR_REVIEW@@ -57535,6 +57542,8 @@ export namespace Schemas {export interface PRTimeline {/** The repository the pull request belongs to. */repo: RepoRef;+ /** Distinct head commits that triggered CI, oldest first, merge-queue gate runs excluded. A PR listed for an author or a team misses pushes from more than 30 days before the window. */+ pushes: PRTimelinePush[];/** Consecutive segments from started_at to the merge, the close, or now, with no gaps. */segments: PRTimelineSegment[];/** Pull request number. */@@ -57560,8 +57569,6 @@ export namespace Schemas {* @nullable*/merged_at: string | null;- /** Distinct head commits that triggered CI, merge-queue gate runs excluded. */- pushes: number;/*** Estimated CI cost over the PR's runs, in USD. Null when nothing was costable.* @nullable