: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
refactor(eng-analytics): share comparison bar rows (#102411)
Raúl Negrón-Otero8e7068c55aa7
diff --git a/products/engineering_analytics/frontend/components/ComparisonBarRow.tsx b/products/engineering_analytics/frontend/components/ComparisonBarRow.tsxindex b55f5542486c..aa4fc228a888 100644--- a/products/engineering_analytics/frontend/components/ComparisonBarRow.tsx+++ b/products/engineering_analytics/frontend/components/ComparisonBarRow.tsx@@ -1,16 +1,9 @@-// Every comparison card draws its bars with this row, so a comparison reads the same on every page.-import { ReactNode } from 'react'import { Tooltip } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'-export interface ComparisonBarMarker {- fraction: number- tooltip?: string-}-function fillClassName(muted: boolean, hasSegments: boolean): string {if (hasSegments) {return muted ? 'opacity-50' : ''@@ -22,7 +15,8 @@ export function ComparisonBarRow({label,labelTooltip,value,- fraction,+ max,+ formatValue,muted = false,marker,children,@@ -30,15 +24,18 @@ export function ComparisonBarRow({label: string/** Shown on hover over the label, e.g. the full name a narrow label truncates. */labelTooltip?: string- value: string- /** Bar length as a share of the track, 0–1. */- fraction: number+ value: number+ /** The largest figure on the card's shared scale. Omit it for a bar that fills the track, e.g. a share split. */+ max?: number+ formatValue: (value: number) => string/** The baseline row (previous window, repo), drawn quieter than the row it is compared with. */muted?: boolean- marker?: ComparisonBarMarker | null+ /** A companion figure pinned as a tick on the same scale, named in its tooltip (e.g. "90th percentile"). */+ marker?: { value: number; label: string } | null/** Segments that fill the bar instead of one color, e.g. a pass/fail or before/after split. */children?: ReactNode}): JSX.Element {+ const fraction = max == null ? 1 : max > 0 ? value / max : 0return (<div className="flex items-center gap-2"><Tooltip title={labelTooltip}>@@ -51,16 +48,16 @@ export function ComparisonBarRow({>{children}</div>- {marker && (- <Tooltip title={marker.tooltip}>+ {marker && max != null && max > 0 && (+ <Tooltip title={`${marker.label} ${formatValue(marker.value)}`}><divclassName="absolute -top-0.5 h-3.5 w-0.5 -translate-x-1/2 rounded-sm bg-[var(--text-3000)]"- style={{ left: `${marker.fraction * 100}%` }}+ style={{ left: `${(marker.value / max) * 100}%` }}/></Tooltip>)}</div>- <span className="w-14 shrink-0 text-right text-xs font-medium tabular-nums">{value}</span>+ <span className="w-14 shrink-0 text-right text-xs font-medium tabular-nums">{formatValue(value)}</span></div>)}diff --git a/products/engineering_analytics/frontend/components/LeadTimeComparisonCard.tsx b/products/engineering_analytics/frontend/components/LeadTimeComparisonCard.tsxindex bfa1f521adf9..1c6f5291e28d 100644--- a/products/engineering_analytics/frontend/components/LeadTimeComparisonCard.tsx+++ b/products/engineering_analytics/frontend/components/LeadTimeComparisonCard.tsx@@ -1,5 +1,4 @@-// Lead time to deploy for one scope (an author or a team) against the repository: one scope-vs-repo box-// plot per stage. No DORA band edge here: a band on one person's or one team's lead time reads as a grade.+// No DORA band edge: a band on one person's or one team's lead time reads as a grade.import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'@@ -30,7 +29,6 @@ export function LeadTimeComparisonCard({loading,}: {leadTime: DeliveryLeadTimeApi | null | undefined- /** The box label for the scope, e.g. "This author" or "This team". */scopeLabel: stringloading: boolean}): JSX.Element {diff --git a/products/engineering_analytics/frontend/components/MetricTile.tsx b/products/engineering_analytics/frontend/components/MetricTile.tsxindex 63ca3d95f7d0..725c92c8ead9 100644--- a/products/engineering_analytics/frontend/components/MetricTile.tsx+++ b/products/engineering_analytics/frontend/components/MetricTile.tsx@@ -91,28 +91,11 @@ function deltaToChange(delta: TileDelta | undefined): MetricChange | null {return { value: rounded, label: `${display}${delta.unit ?? '%'}` }}-export interface TileBenchmark {- /** The band name (e.g. 'Elite'), named in the label tooltip. */- label: string- band: 'elite' | 'high' | 'medium' | 'low'- /** The full benchmark ladder, shown in the label tooltip. */- tooltip: string-}--// Left accent per band: border-l-4 + a token class, the same accent recipe as WorkflowsHealthHeader.-const BENCHMARK_EDGE_CLASS: Record<TileBenchmark['band'], string> = {- elite: 'border-l-success',- high: 'border-l-purple',- medium: 'border-l-warning',- low: 'border-l-danger',-}-export function MetricTile({label,tooltip,value,delta,- benchmark,sub,loading = false,className,@@ -123,9 +106,6 @@ export function MetricTile({/** Pre-formatted headline value; '—' for no data. */value: stringdelta?: TileDelta- /** Where the value lands against a published benchmark ladder, shown as a coloured edge on the- * card plus the ladder detail in the label tooltip. */- benchmark?: TileBenchmark | null/** Visible caption — only for an answer worth a glance (what's failing, why there's no value). */sub?: ReactNode/** Backend load in flight: skeleton the value so it doesn't flash a stale/zero number. Only for a@@ -133,19 +113,8 @@ export function MetricTile({loading?: booleanclassName?: string}): JSX.Element {- const tooltipContent =- tooltip || benchmark ? (- <div className="flex flex-col gap-1">- {tooltip && <div>{tooltip}</div>}- {benchmark && (- <div>- DORA band: {benchmark.label.toLowerCase()}. {benchmark.tooltip}- </div>- )}- </div>- ) : undefined- const labelNode = tooltipContent ? (- <Tooltip title={tooltipContent}>+ const labelNode = tooltip ? (+ <Tooltip title={tooltip}><span className="cursor-default">{label}</span></Tooltip>) : (@@ -154,11 +123,7 @@ export function MetricTile({return (<LemonCardhoverEffect={false}- className={cn(- 'flex min-w-44 flex-1 flex-col justify-center px-5 py-4',- benchmark && `border-l-4 ${BENCHMARK_EDGE_CLASS[benchmark.band]}`,- className- )}+ className={cn('flex min-w-44 flex-1 flex-col justify-center px-5 py-4', className)}>{/* MetricCard has no loading prop; skeleton the whole tile on a genuine reload so it neverflashes a stale/zero headline (the loading-states rule). */}diff --git a/products/engineering_analytics/frontend/components/PullRequestCountsCard.tsx b/products/engineering_analytics/frontend/components/PullRequestCountsCard.tsxindex cf0a117ff39d..7989389cd4aa 100644--- a/products/engineering_analytics/frontend/components/PullRequestCountsCard.tsx+++ b/products/engineering_analytics/frontend/components/PullRequestCountsCard.tsx@@ -1,5 +1,4 @@-// Plain pull request counts for a delivery scope. No repo figure on purpose: comparing how much an author-// or a team ships ranks people, and these counts are only the denominators for the cards next to it.+// No repo figure: comparing how much an author or a team ships would rank people.import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'diff --git a/products/engineering_analytics/frontend/components/PullRequestDayView.tsx b/products/engineering_analytics/frontend/components/PullRequestDayView.tsxindex b14318674a4c..2c69f61a697e 100644--- a/products/engineering_analytics/frontend/components/PullRequestDayView.tsx+++ b/products/engineering_analytics/frontend/components/PullRequestDayView.tsx@@ -1,7 +1,3 @@-// Pull requests on a shared clock: each row starts at 06:00 on the day the pull request went ready (or-// Monday 06:00 of that week), so nights and weekends line up across rows and a long wait reads as the-// days it spanned. Groups put the work that needs attention first.-import { LemonCard, LemonSegmentedButton, LemonSkeleton, Link, Tooltip } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'diff --git a/products/engineering_analytics/frontend/components/PullRequestTimelineLegend.tsx b/products/engineering_analytics/frontend/components/PullRequestTimelineLegend.tsxindex ea43784e3b3a..a0da69923a0c 100644--- a/products/engineering_analytics/frontend/components/PullRequestTimelineLegend.tsx+++ b/products/engineering_analytics/frontend/components/PullRequestTimelineLegend.tsx@@ -1,5 +1,3 @@-// 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/pullRequestTimeline'export function PullRequestTimelineLegend(): JSX.Element {diff --git a/products/engineering_analytics/frontend/components/ReadyToMergeCard.tsx b/products/engineering_analytics/frontend/components/ReadyToMergeCard.tsxindex f4220e394599..cc004348d85c 100644--- a/products/engineering_analytics/frontend/components/ReadyToMergeCard.tsx+++ b/products/engineering_analytics/frontend/components/ReadyToMergeCard.tsx@@ -85,8 +85,8 @@ export function ReadyToMergeCard({dataAttr?: string}): JSX.Element {const [focus, ...baselines] = rows- const shown = rows.filter((row) => row.seconds != null)- const max = Math.max(...shown.flatMap((row) => [row.seconds ?? 0, row.p90Seconds ?? 0]))+ const shown = rows.filter((row): row is ReadyToMergeRow & { seconds: number } => row.seconds != null)+ const max = Math.max(...shown.flatMap((row) => [row.seconds, row.p90Seconds ?? 0]))return (<LemonCard hoverEffect={false} className="flex h-full flex-col p-4" data-attr={dataAttr}>@@ -114,16 +114,12 @@ export function ReadyToMergeCard({key={`${index}:${row.label}`}label={row.label}labelTooltip={row.labelTooltip}- value={compactAgeLabel(row.seconds)}- fraction={(row.seconds ?? 0) / max}+ value={row.seconds}+ max={max}+ formatValue={compactAgeLabel}muted={row !== focus}marker={- row.p90Seconds != null- ? {- fraction: row.p90Seconds / max,- tooltip: `90th percentile ${compactAgeLabel(row.p90Seconds)}`,- }- : null+ row.p90Seconds != null ? { value: row.p90Seconds, label: '90th percentile' } : null}><ApprovalSplit beforeShare={reviewsSynced ? row.beforeShare : null} />diff --git a/products/engineering_analytics/frontend/components/RedTimeByCauseCard.tsx b/products/engineering_analytics/frontend/components/RedTimeByCauseCard.tsxindex ae60f0ac5c3d..ddf5fd0d12da 100644--- a/products/engineering_analytics/frontend/components/RedTimeByCauseCard.tsx+++ b/products/engineering_analytics/frontend/components/RedTimeByCauseCard.tsx@@ -1,6 +1,5 @@-// Red check time on the listed merged pull requests, split by what turned the check green. No repo-// figure: the cause comes from replaying each pull request's timeline, which is too heavy to run over-// the whole repository per request.+// No repo figure: the cause comes from replaying each pull request's timeline, which is too heavy to run+// over the whole repository per request.import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'diff --git a/products/engineering_analytics/frontend/components/ScopeComparisonCard.tsx b/products/engineering_analytics/frontend/components/ScopeComparisonCard.tsxindex 8fd2c5da4e46..1426caecd82b 100644--- a/products/engineering_analytics/frontend/components/ScopeComparisonCard.tsx+++ b/products/engineering_analytics/frontend/components/ScopeComparisonCard.tsx@@ -1,6 +1,6 @@// A scope-against-repo card: one author's or one team's figure next to the same figure over the whole// repository. The question is "is this unusual here", so the graphic is two labeled bars on a shared-// zero-based scale. Window-over-window comparisons use WindowComparisonCard instead.+// zero-based scale. Use WindowComparisonCard when the question is this window against the previous one.import { ReactNode } from 'react'@@ -9,73 +9,33 @@ import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'import type { ScopeRepoFigureApi } from '../generated/api.schemas'import { ComparisonBarRow } from './ComparisonBarRow'-function ComparisonRow({- label,- value,- max,- formatValue,- isScope,- marker,- markerLabel,-}: {- label: string- value: number- max: number- formatValue: (value: number) => string- isScope: boolean- marker?: number | null- markerLabel?: string-}): JSX.Element {- return (- <ComparisonBarRow- label={label}- value={formatValue(value)}- fraction={max > 0 ? value / max : 0}- muted={!isScope}- marker={- marker != null && max > 0- ? { fraction: marker / max, tooltip: `${markerLabel} ${formatValue(marker)}` }- : null- }- />- )-}-export function ScopeComparisonCard({title,tooltip,scopeLabel,figure,formatValue,- marker,- markerLabel,caption,loading = false,emptyText,- dataAttr,}: {title: string/** Definition or methodology, shown on title hover. */tooltip?: ReactNode- /** The row label for the scope's bar, e.g. "This author" or "This team". */scopeLabel: stringfigure: ScopeRepoFigureApi | null | undefinedformatValue: (value: number) => string- /** A companion figure (e.g. p90) pinned as a tick on each bar, on the same scale. */- marker?: ScopeRepoFigureApi | null- markerLabel?: string/** The totals behind the figure, under the bars. */caption?: ReactNodeloading?: booleanemptyText: string- dataAttr?: string}): JSX.Element {const scope = figure?.scopeconst repo = figure?.repo- const max = Math.max(...[scope, repo, marker?.scope, marker?.repo].map((value) => value ?? 0))+ const max = Math.max(scope ?? 0, repo ?? 0)return (- <LemonCard hoverEffect={false} className="flex flex-col p-4" data-attr={dataAttr}>+ <LemonCard hoverEffect={false} className="flex flex-col p-4"><h3 className="mb-1 text-xs font-semibold text-secondary">{tooltip ? (<Tooltip title={tooltip}>@@ -96,25 +56,9 @@ export function ScopeComparisonCard({)}</div><div className="flex flex-col gap-1.5">- <ComparisonRow- label={scopeLabel}- value={scope}- max={max}- formatValue={formatValue}- isScope- marker={marker?.scope}- markerLabel={markerLabel}- />+ <ComparisonBarRow label={scopeLabel} value={scope} max={max} formatValue={formatValue} />{repo != null && (- <ComparisonRow- label="Repo"- value={repo}- max={max}- formatValue={formatValue}- isScope={false}- marker={marker?.repo}- markerLabel={markerLabel}- />+ <ComparisonBarRow label="Repo" value={repo} max={max} formatValue={formatValue} muted />)}</div>{caption && <div className="mt-2 text-[11px] tabular-nums text-tertiary">{caption}</div>}diff --git a/products/engineering_analytics/frontend/components/WindowComparisonCard.tsx b/products/engineering_analytics/frontend/components/WindowComparisonCard.tsxindex 7a3eb2728ccb..095ccf3e5c46 100644--- a/products/engineering_analytics/frontend/components/WindowComparisonCard.tsx+++ b/products/engineering_analytics/frontend/components/WindowComparisonCard.tsx@@ -2,8 +2,7 @@// window vs the previous window", a comparison of exactly two values, so the graphic is two labeled// horizontal bars on a shared zero-based scale rather than a time series: the daily buckets behind// these metrics are noise at this grain. Rates use a pass/fail split bar per window, where the-// status colors are the data; a duration card can pin a p90 tick on each bar to show the tail on-// the same scale as the median.+// status colors are the data.import { ReactNode } from 'react'@@ -11,11 +10,12 @@ import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'+import type { DoraBand, DoraBenchmark } from '../lib/doraBenchmark'import { percent } from '../lib/format'import { ComparisonBarRow } from './ComparisonBarRow'-import { DeltaBadge, percentChange, pointChange, type TileBenchmark } from './MetricTile'+import { DeltaBadge, percentChange, pointChange } from './MetricTile'-const BENCHMARK_EDGE_CLASS: Record<TileBenchmark['band'], string> = {+const BENCHMARK_EDGE_CLASS: Record<DoraBand, string> = {elite: 'border-l-success',high: 'border-l-purple',medium: 'border-l-warning',@@ -40,8 +40,6 @@ function ComparisonRow({formatValue,share,current,- marker,- markerLabel,}: {label: stringvalue: number@@ -50,32 +48,15 @@ function ComparisonRow({/** Render the value as a pass/fail split of the whole bar instead of a length. */share: booleancurrent: boolean- marker?: number | null- markerLabel?: string}): JSX.Element {if (share) {return (- <ComparisonBarRow label={label} value={formatValue(value)} fraction={1}>+ <ComparisonBarRow label={label} value={value} formatValue={formatValue}><PassFailSplit rate={value} /></ComparisonBarRow>)}- return (- <ComparisonBarRow- label={label}- value={formatValue(value)}- fraction={max > 0 ? value / max : 0}- muted={!current}- marker={- marker != null && max > 0- ? {- fraction: marker / max,- tooltip: markerLabel ? `${markerLabel} ${formatValue(marker)}` : undefined,- }- : null- }- />- )+ return <ComparisonBarRow label={label} value={value} max={max} formatValue={formatValue} muted={!current} />}export function WindowComparisonCard({@@ -89,9 +70,6 @@ export function WindowComparisonCard({deltaPrecision,tooltip,benchmark,- marker,- markerPrevious,- markerLabel,loading = false,emptyText,}: {@@ -110,16 +88,12 @@ export function WindowComparisonCard({deltaPrecision?: number/** Definition or methodology, shown on title hover. */tooltip?: ReactNode- benchmark?: TileBenchmark | null- /** A companion figure (e.g. p90) pinned as a tick on each magnitude bar, on the same scale as- * the value. Ignored in `share` mode, which has no scale to pin against. */- marker?: number | null- markerPrevious?: number | null- markerLabel?: string+ /** Where the value lands on its DORA ladder: a colored left edge plus the ladder in the title tooltip. */+ benchmark?: DoraBenchmark | nullloading?: booleanemptyText: string}): JSX.Element {- const max = Math.max(...[value, previousValue, marker, markerPrevious].map((number) => number ?? 0))+ const max = Math.max(value ?? 0, previousValue ?? 0)const delta = deltaUnit === 'pt' ? pointChange(value, previousValue) : percentChange(value, previousValue)const tooltipContent = benchmark ? (<div className="flex flex-col gap-1">@@ -167,8 +141,6 @@ export function WindowComparisonCard({formatValue={formatValue}share={share}current- marker={marker}- markerLabel={markerLabel}/>{previousValue != null && (<ComparisonRow@@ -178,8 +150,6 @@ export function WindowComparisonCard({formatValue={formatValue}share={share}current={false}- marker={markerPrevious}- markerLabel={markerLabel}/>)}</div>diff --git a/products/engineering_analytics/frontend/emptyState/EngineeringAnalyticsPreview.scss b/products/engineering_analytics/frontend/emptyState/EngineeringAnalyticsPreview.scssindex ae166dda160a..826d7e600ee1 100644--- a/products/engineering_analytics/frontend/emptyState/EngineeringAnalyticsPreview.scss+++ b/products/engineering_analytics/frontend/emptyState/EngineeringAnalyticsPreview.scss@@ -65,8 +65,6 @@color: var(--color-text-tertiary);}- // Pull request rows-&__rows {display: flex;flex-direction: column;@@ -149,8 +147,6 @@}}- // Bottom row: workflow runs and the stat card side by side.-&__bottom {display: grid;grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr);@@ -236,8 +232,6 @@}}- // Stat card-&__stat {padding: 0.625rem 0.75rem 0.75rem;}@@ -265,7 +259,6 @@stroke-width: 2;}- // The moving bit: a short bright segment cycling along the line.&__spark-trace {fill: none;stroke: var(--eng-preview-accent);@@ -285,8 +278,6 @@background: color-mix(in oklab, var(--eng-preview-accent) 8%, transparent);}-// Failing pull request selected-.EngAnalyticsPreview__radio--red:checked ~ .EngAnalyticsPreview__bottom .EngAnalyticsPreview__when-red {@include preview-swap-visible;}diff --git a/products/engineering_analytics/frontend/emptyState/EngineeringAnalyticsPreview.tsx b/products/engineering_analytics/frontend/emptyState/EngineeringAnalyticsPreview.tsxindex 91d55a74d140..078ad26e6000 100644--- a/products/engineering_analytics/frontend/emptyState/EngineeringAnalyticsPreview.tsx+++ b/products/engineering_analytics/frontend/emptyState/EngineeringAnalyticsPreview.tsx@@ -12,11 +12,10 @@ function areaPath(line: string): string {}/**- * Example-data preview for the engineering analytics empty state: the pull request list next- * to the CI runs of the selected pull request, plus the team's time-to-merge trend. A hidden- * radio pair drives the selection via `:checked ~` styles - no timers or state, per the- * preview rules in the `building-product-empty-states` skill. Both run lists share one grid- * cell and crossfade, so switching never moves the card.+ * Example-data preview for the engineering analytics empty state. A hidden radio pair drives the+ * selection through `:checked ~` styles, with no timers or state, per the+ * `building-product-empty-states` skill. Both run lists share one grid cell and crossfade, so+ * switching the selection never moves the card.*/export function EngineeringAnalyticsPreview(): JSX.Element {const isStatic = inStorybook() || inStorybookTestRunner()diff --git a/products/engineering_analytics/frontend/emptyState/engineeringAnalyticsSetupLogic.test.ts b/products/engineering_analytics/frontend/emptyState/engineeringAnalyticsSetupLogic.test.tsindex 65a8d0551360..3eedd0d4f598 100644--- a/products/engineering_analytics/frontend/emptyState/engineeringAnalyticsSetupLogic.test.ts+++ b/products/engineering_analytics/frontend/emptyState/engineeringAnalyticsSetupLogic.test.ts@@ -8,8 +8,6 @@ import { initKeaTests } from '~/test/init'import * as generatedApi from '../generated/api'import { engineeringAnalyticsSetupLogic } from './engineeringAnalyticsSetupLogic'-// Guards the mapping into the app-wide setup-status layer: if it breaks, the scene-// empty-state gate strands on its spinner or shows the wrong surface.describe('engineeringAnalyticsSetupLogic', () => {let sourcesSpy: jest.SpyInstance@@ -26,13 +24,6 @@ describe('engineeringAnalyticsSetupLogic', () => {it.each([[[], 'needs-setup'],[[{ id: 's1', repo: 'acme/web', prefix: '', synced: false }], 'has-data'],- [- [- { id: 's1', repo: 'acme/web', prefix: '', synced: true },- { id: 's2', repo: 'acme/api', prefix: '', synced: true },- ],- 'has-data',- ],])('pushes sources %j as status %s', async (sources, expected) => {sourcesSpy.mockResolvedValue(sources)const logic = engineeringAnalyticsSetupLogic()@@ -40,12 +31,4 @@ describe('engineeringAnalyticsSetupLogic', () => {await expectLogic(logic).toFinishAllListeners()expect(productSetupStatusLogic({ productKey: ProductKey.ENGINEERING_ANALYTICS }).values.status).toBe(expected)})-- it('fails open to unknown when the sources query fails before any answer', async () => {- sourcesSpy.mockRejectedValue(new Error('network down'))- const logic = engineeringAnalyticsSetupLogic()- logic.mount()- await expectLogic(logic).toFinishAllListeners()- expect(productSetupStatusLogic({ productKey: ProductKey.ENGINEERING_ANALYTICS }).values.status).toBe('unknown')- })})diff --git a/products/engineering_analytics/frontend/lib/deliveryScope.ts b/products/engineering_analytics/frontend/lib/deliveryScope.tsindex 6e097ddba097..134bf2de81a1 100644--- a/products/engineering_analytics/frontend/lib/deliveryScope.ts+++ b/products/engineering_analytics/frontend/lib/deliveryScope.ts@@ -1,6 +1,4 @@-// Which pull requests a delivery surface covers: one author's, one GitHub team's, or one pull request.-// Mirrors the backend's DeliveryScope, so a page picks its scope once and every delivery logic and-// request below it agrees on it.+// Mirrors the backend's DeliveryScope; keep the kinds and query params in sync.export type DeliveryScope =| { kind: 'author'; author: string }@@ -14,7 +12,6 @@ export interface DeliveryScopeParams {repo?: string}-/** The query params the delivery endpoints read the scope from. */export function deliveryScopeParams(scope: DeliveryScope): DeliveryScopeParams {switch (scope.kind) {case 'author':@@ -26,7 +23,6 @@ export function deliveryScopeParams(scope: DeliveryScope): DeliveryScopeParams {}}-/** A stable key for logics keyed by scope. */export function deliveryScopeKey(scope: DeliveryScope): string {switch (scope.kind) {case 'author':diff --git a/products/engineering_analytics/frontend/lib/pullRequestDayView.test.ts b/products/engineering_analytics/frontend/lib/pullRequestDayView.test.tsindex 02479605a761..66b3f10da780 100644--- a/products/engineering_analytics/frontend/lib/pullRequestDayView.test.ts+++ b/products/engineering_analytics/frontend/lib/pullRequestDayView.test.ts@@ -69,16 +69,21 @@ describe('pullRequestDayView', () => {expect(groups[3].rows[0].highlightKind).toBe(Kind.WaitingForReview)})+ // Without the p90 pick the 1000-hour row would push the axis to the 14-day cap. The bound is 2+ // rather than 1 because the row origin is the local 06:00 at or before the start, which sits up+ // to 23 hours earlier depending on the timezone Jest runs in.+ it('one outlier does not stretch the axis', () => {+ const lengths = [5, 6, 7, 8, 9, 10, 11, 12, 13, 1000]+ const items = lengths.map((length, index) => pr(index, [[Kind.CiRunning, 0, length]], { merged: true }))+ expect(axisDays(items, 'days')).toBeLessThanOrEqual(2)+ })+it.each([- ['one outlier does not stretch the axis', 'days', [5, 6, 7, 8, 9, 10, 11, 12, 13, 1000], [1, 2]],- ['weeks round up to a whole week', 'weeks', [5, 20, 30], [7, 7]],- ['long waits cap at two weeks', 'days', [400, 500, 600], [14, 14]],- ] as const)('%s', (_name, alignment, lengths, [atLeast, atMost]) => {+ ['weeks round up to a whole week', 'weeks', [5, 20, 30], 7],+ ['long waits cap at two weeks', 'days', [400, 500, 600], 14],+ ] as const)('%s', (_name, alignment, lengths, expectedDays) => {const items = lengths.map((length, index) => pr(index, [[Kind.CiRunning, 0, length]], { merged: true }))- const days = axisDays(items, alignment)- // The row origin follows the runner's time zone, so the fitted day count can shift by one.- expect(days).toBeGreaterThanOrEqual(atLeast)- expect(days).toBeLessThanOrEqual(atMost)+ expect(axisDays(items, alignment)).toBe(expectedDays)})it('averages red time by cause over merged pull requests only', () => {diff --git a/products/engineering_analytics/frontend/lib/pullRequestDayView.ts b/products/engineering_analytics/frontend/lib/pullRequestDayView.tsindex 8ea4cddbda8a..ef9269d6a1b8 100644--- a/products/engineering_analytics/frontend/lib/pullRequestDayView.ts+++ b/products/engineering_analytics/frontend/lib/pullRequestDayView.ts@@ -1,6 +1,3 @@-// 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 { Dayjs, dayjs } from 'lib/dayjs'import { PRTimelineApi, PRTimelineSegmentKindEnumApi as Kind } from '../generated/api.schemas'diff --git a/products/engineering_analytics/frontend/scenes/DeliverySections.tsx b/products/engineering_analytics/frontend/scenes/DeliverySections.tsxindex cd4b64dbca04..cfed12f2271d 100644--- a/products/engineering_analytics/frontend/scenes/DeliverySections.tsx+++ b/products/engineering_analytics/frontend/scenes/DeliverySections.tsx@@ -25,7 +25,6 @@ export function DeliverySections({}: {/** An author or a GitHub team; the summary endpoint rejects a single pull request. */scope: DeliveryScope- /** The row label for the scope's bars, e.g. "This author" or "This team". */scopeLabel: stringsourceId: string | null/** An author's comparison with their own team, which adds the team's row to the ready-to-merge card. */diff --git a/products/engineering_analytics/frontend/scenes/DoraLeadTimeSection.tsx b/products/engineering_analytics/frontend/scenes/DoraLeadTimeSection.tsxindex 5ebccae2923f..88b92052e5f8 100644--- a/products/engineering_analytics/frontend/scenes/DoraLeadTimeSection.tsx+++ b/products/engineering_analytics/frontend/scenes/DoraLeadTimeSection.tsx@@ -3,9 +3,10 @@ import { useActions, useValues } from 'kea'import { LemonBanner, LemonSelect } from '@posthog/lemon-ui'import { ScopePanel } from '../components/ScopePanel'+import { percent } from '../lib/format'import { DoraLeadTimeDistributions } from './DoraLeadTimeDistributions'import { DoraLeadTimeSummary } from './DoraLeadTimeSummary'-import { doraLogic } from './doraLogic'+import { UNATTRIBUTED_WARNING_SHARE, doraLogic } from './doraLogic'export function DoraLeadTimeSection(): JSX.Element {const { dora, doraLoading, githubTeam, githubTeamOptions, showUnattributedWarning } = useValues(doraLogic)@@ -30,9 +31,9 @@ export function DoraLeadTimeSection(): JSX.Element {{showUnattributedWarning && (<div data-attr="engineering-analytics-dora-unattributed"><LemonBanner type="warning">- More than 10% of PRs merged in this window have no successful deployment attributed in the- selected environments. Lead-time results exclude unmatched PRs. Check the source sync or allow- more time for deployments.+ More than {percent(UNATTRIBUTED_WARNING_SHARE)} of PRs merged in this window have no successful+ deployment attributed in the selected environments. Lead-time results exclude unmatched PRs.+ Check the source sync or allow more time for deployments.</LemonBanner></div>)}diff --git a/products/engineering_analytics/frontend/scenes/authorLogic.ts b/products/engineering_analytics/frontend/scenes/authorLogic.tsindex 0fc08b0802b2..75bdbeee5832 100644--- a/products/engineering_analytics/frontend/scenes/authorLogic.ts+++ b/products/engineering_analytics/frontend/scenes/authorLogic.ts@@ -62,8 +62,8 @@ export const authorLogic = kea<authorLogicType>([})),loaders(({ props, values }) => ({- // The author's CI spend split by workflow, for "where their CI minutes go". [] when the job-level- // source isn't synced.+ // The author's CI spend split by workflow, for "where their CI minutes go". [] when the+ // job-level source isn't synced.workflowCosts: [[] as WorkflowCostApi[],{diff --git a/products/engineering_analytics/frontend/scenes/doraLogic.test.ts b/products/engineering_analytics/frontend/scenes/doraLogic.test.tsindex 8b5de0d8d090..5db685f5de18 100644--- a/products/engineering_analytics/frontend/scenes/doraLogic.test.ts+++ b/products/engineering_analytics/frontend/scenes/doraLogic.test.ts@@ -70,27 +70,14 @@ describe('doraLogic', () => {const available = new Set(params.get('repo') === 'example/repo' ? ['staging'] : availableEnvironments)- const blankIndex = requested.indexOf('')- if (blankIndex >= 0) {+ if (requested.includes('invalid-item')) {return [400,{type: 'validation_error',- code: 'blank',- detail: 'This field may not be blank.',- attr: `environment__${blankIndex}`,- },- ]- }- const nullCharacterIndex = requested.findIndex((name) => name.includes('\0'))- if (nullCharacterIndex >= 0) {- return [- 400,- {- type: 'validation_error',- code: 'null_characters_not_allowed',- detail: 'Null characters are not allowed.',- attr: `environment__${nullCharacterIndex}`,+ code: 'invalid',+ detail: 'Invalid environment.',+ attr: 'environment__1',},]}@@ -174,20 +161,10 @@ describe('doraLogic', () => {logic.unmount()})- it('shows both resolved production regions as selected on first load', async () => {- await expectLogic(logic).toDispatchActions(['loadDoraSuccess'])- expect(requests[0].getAll('environment')).toEqual([])- expect(logic.values.selectedEnvironments).toEqual(['prod-us', 'prod-eu'])- expect(logic.values.environmentOptions.map(({ key }) => key)).toEqual(['dev', 'prod-us', 'prod-eu'])- })-it.each([[null, false],- [0, false],[0.1, false],[0.1001, true],- [0.25, true],- [1, true],])('warns only above 10%% unattributed merged PRs (%s)', async (share, showWarning) => {await expectLogic(logic).toDispatchActions(['loadDoraSuccess'])logic.actions.loadDoraSuccess({ ...DORA, unattributed_merged_pr_share: share })@@ -195,8 +172,12 @@ describe('doraLogic', () => {expect(logic.values.showUnattributedWarning).toBe(showWarning)})- it('sends the visible selections as repeated parameters and restores production when cleared', async () => {+ it('selects production on first load, sends the visible selections as repeated parameters, and restores production when cleared', async () => {await expectLogic(logic).toDispatchActions(['loadDoraSuccess'])+ expect(requests[0].getAll('environment')).toEqual([])+ expect(logic.values.selectedEnvironments).toEqual(['prod-us', 'prod-eu'])+ expect(logic.values.environmentOptions.map(({ key }) => key)).toEqual(['dev', 'prod-us', 'prod-eu'])+await expectLogic(logic, () => logic.actions.setEnvironments(['prod-eu', 'dev'])).toDispatchActions(['loadDoraSuccess',])@@ -224,7 +205,7 @@ describe('doraLogic', () => {])silenceKeaLoadersErrors()- for (const environments of [['missing'], ['prod-eu', ''], ['prod-eu', '\0']]) {+ for (const environments of [['missing'], ['prod-eu', 'invalid-item']]) {await expectLogic(logic, () => logic.actions.setEnvironments(environments)).toDispatchActions(['loadDoraFailure', 'restoreEnvironments']).toMatchValues({diff --git a/products/engineering_analytics/frontend/scenes/doraLogic.ts b/products/engineering_analytics/frontend/scenes/doraLogic.tsindex 7cbc59d548cc..94229a49d32e 100644--- a/products/engineering_analytics/frontend/scenes/doraLogic.ts+++ b/products/engineering_analytics/frontend/scenes/doraLogic.ts@@ -12,6 +12,8 @@ import { engineeringAnalyticsLogic, formatBucket, type WorkflowGranularity } froconst projectId = (): string => String(ApiConfig.getCurrentProjectId())+export const UNATTRIBUTED_WARNING_SHARE = 0.1+type LeadTimeSeriesApi = DoraOverviewApi['merge_to_deploy_series']function isEnvironmentValidationError(errorObject: unknown): errorObject is ApiError {@@ -248,7 +250,8 @@ export const doraLogic = kea<doraLogicType>([selectors({showUnattributedWarning: [(s) => [s.dora],- (dora: DoraOverviewApi | null): boolean => (dora?.unattributed_merged_pr_share ?? 0) > 0.1,+ (dora: DoraOverviewApi | null): boolean =>+ (dora?.unattributed_merged_pr_share ?? 0) > UNATTRIBUTED_WARNING_SHARE,],selectedEnvironments: [(s) => [s.dora, s.doraLoading, s.environments],diff --git a/products/engineering_analytics/frontend/scenes/pullRequestTimelinesLogic.ts b/products/engineering_analytics/frontend/scenes/pullRequestTimelinesLogic.tsindex c95ae835e56c..ad4ca622ce00 100644--- a/products/engineering_analytics/frontend/scenes/pullRequestTimelinesLogic.ts+++ b/products/engineering_analytics/frontend/scenes/pullRequestTimelinesLogic.ts@@ -126,7 +126,6 @@ export const pullRequestTimelinesLogic = kea<pullRequestTimelinesLogicType>([(s) => [s.timelines],(timelines: PullRequestTimelinesApi | null): RedTimeByCause => redTimeByCause(timelines?.items ?? []),],- // A source can hold several repos, so the listed pull requests may span repos.repoSlugs: [(s) => [s.timelines],(timelines: PullRequestTimelinesApi | null): string[] =>