: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(eng-analytics): show ci jobs as a timeline (#117901)
Raúl Negrón-Oteroa7f1a82538b3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1da70423f088..d3df86247ed4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10563,13 +10563,13 @@ snapshots:scenes-app-engineering-analytics-workflow--workflow-detail-section-load-errors--light:hash: v1.k794b7964.54bd5d744f9ff16d43d5476daa93c4c8af0f2fdc466a00c49479421f1dbef642.2uK1j4cniblurwfUzmx3XF1wCcqHEbpSO9YncZXXmAwscenes-app-engineering-analytics-workflow-run--depot-run--dark:- hash: v1.k794b7964.5c5247ade6a51626e420c95ace81dfa0d92707dd77eda9dff82f72c4958a9ba3.21Y90ddqSJGLKmHOC70BrV8BhhYKMdIGsvR5iVGjk-s+ hash: v1.k794b7964.7ea4595766d44257b30d5d0761369a9b5d65fb550be19852a8ef4fa151189ed9.7X2-tDJWLvGhntaVuRxXKyAzkrXc7-sZxeThjhBbf-0scenes-app-engineering-analytics-workflow-run--depot-run--light:- hash: v1.k794b7964.4310d3874a46f749abe9a3c33499cb2b1eddf16f679397b7ecdc7fd016e449ee.67NkPxMSowlRW7ZO98l69xmdgHeDHUNcN7ky4baYFCE+ hash: v1.k794b7964.69d48207c7b7ef400f7f74a3d7d789a51a2aec0be06379c3a88597a474b617dc.So-Db6_GbyHGDa1n2UxwW0LzVESqpYs8_mmmD5E5eQoscenes-app-engineering-analytics-workflow-run--failed-run--dark:- hash: v1.k794b7964.57f0a4fa93b2ac0047988fcd1d21743e33c2d17a2c2976afec0978fd5250dbfd.sGvtBqyRxBWVbXP9YU1ZPhLX904HyMQr769HrYc4MBE+ hash: v1.k794b7964.126bb3411ae62853c6e90af9ebf7029da897c771a9175e3820f7bef7ec6a7be7.zRXsCdq5Kn3o5014RyokxnSy_ymx6neA4l6iNRYpt7wscenes-app-engineering-analytics-workflow-run--failed-run--light:- hash: v1.k794b7964.09457937484f13b9ebace240d32ca5bc8588813dd0dc10cb4c3f82c7881e5fbe.iBfzBOcMkH-74yq3tKjMFySd2Pjh5cXuufgQ2MM235Q+ hash: v1.k794b7964.fa48dd1b1ead01d71b716b639ea06b2832a72b4ec13db98a217d6008166475ce.Gmlgy0WoVFgr5i2AGja83ybmuyLQcuX8ol2_zUx6U-0scenes-app-engineering-analytics-workflow-run--jobs-and-logs-load-errors--dark:hash: v1.k794b7964.5b1a4847316c45be19eb0e63d58c896838e336d81f6882433d233fc8a0e7275d.DxIuUSHtA6_g2kYXEiKntxQMUlSdDZWmeBfpbacRkjQscenes-app-engineering-analytics-workflow-run--jobs-and-logs-load-errors--light:diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d5c27ca29251..0e4dce3e0d54 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3587,6 +3587,9 @@ importers:'@storybook/react':specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])+ '@tanstack/react-virtual':+ specifier: '*''@types/react':specifier: 18.3.27version: 18.3.27diff --git a/products/engineering_analytics/frontend/components/CITimeline.tsx b/products/engineering_analytics/frontend/components/CITimeline.tsxnew file mode 100644index 000000000000..08ff87aefe48--- /dev/null+++ b/products/engineering_analytics/frontend/components/CITimeline.tsx@@ -0,0 +1,127 @@+import { useVirtualizer } from '@tanstack/react-virtual'+import { useRef, useState } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import { cn } from 'lib/utils/css-classes'+import { humanFriendlyDuration } from 'lib/utils/durations'++import { TimelineData, TimelineNode, parentNodes, timelineTicks, visibleTimelineRows } from '../lib/ciTimeline'+import { timeAxis } from '../lib/pullRequestTimeline'+import { CITimelineRow, CI_TIMELINE_COLUMNS, CI_TIMELINE_ROW_HEIGHT_PX, CI_TIMELINE_SCALE } from './CITimelineRow'++const MAX_TICKS = 8++/** Failing rows start expanded so the first view shows what broke. */+export function CITimeline({ timeline }: { timeline: TimelineData }): JSX.Element {+ // Only what the person toggled is stored, so rows that arrive later still open by the failing rule.+ const [toggled, setToggled] = useState<ReadonlyMap<string, boolean>>(new Map())+ const isExpanded = (node: TimelineNode): boolean => toggled.get(node.id) ?? node.status === 'failure'+ const rows = visibleTimelineRows(timeline.nodes, isExpanded)+ // A job a re-run carried over from an earlier attempt starts before the axis, which clips it to the track.+ const axis = timeAxis(timeline.startMs, timeline.endMs)+ const ticks = timelineTicks((timeline.endMs - timeline.startMs) / 1000, MAX_TICKS)+ const tickPosition = (seconds: number): string => axis.position(timeline.startMs + seconds * 1000)++ // Expand all on a matrix-heavy push opens thousands of step rows, so only the rows in view mount.+ const scrollRef = useRef<HTMLDivElement>(null)+ const virtualizer = useVirtualizer({+ count: rows.length,+ getScrollElement: () => scrollRef.current,+ estimateSize: () => CI_TIMELINE_ROW_HEIGHT_PX,+ getItemKey: (index) => rows[index].node.id,+ overscan: 10,+ // The sticky tick header sits above the first row inside the scroll container.+ scrollMargin: CI_TIMELINE_ROW_HEIGHT_PX,+ })++ const setAll = (expanded: boolean): void =>+ setToggled(new Map(parentNodes(timeline.nodes).map((node) => [node.id, expanded])))+ const toggle = (node: TimelineNode): void =>+ setToggled((previous) => new Map(previous).set(node.id, !isExpanded(node)))++ return (+ <div className="overflow-hidden rounded border border-primary bg-surface-primary">+ <div className="flex items-center gap-2 border-b border-primary px-2 py-1.5">+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={() => setAll(true)}+ data-attr="engineering-analytics-ci-timeline-expand-all"+ >+ Expand all+ </LemonButton>+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={() => setAll(false)}+ data-attr="engineering-analytics-ci-timeline-collapse-all"+ >+ Collapse all+ </LemonButton>+ </div>+ <div ref={scrollRef} className="max-h-[70vh] overflow-y-auto">+ <div+ className={cn(+ 'sticky top-0 z-10 grid h-7 border-b border-primary bg-surface-secondary text-[11px] font-semibold text-tertiary',+ CI_TIMELINE_COLUMNS+ )}+ >+ <div className="flex items-center justify-between border-r border-primary px-2">+ <span>Name</span>+ <span>Duration</span>+ </div>+ <div className="relative">+ <div className={CI_TIMELINE_SCALE}>+ {ticks.map((seconds) => (+ <span+ key={seconds}+ className={cn(+ 'absolute top-1/2 -translate-y-1/2 font-normal tabular-nums whitespace-nowrap',+ seconds > 0 && '-translate-x-1/2'+ )}+ style={{ left: tickPosition(seconds) }}+ >+ {humanFriendlyDuration(seconds)}+ </span>+ ))}+ </div>+ </div>+ </div>+ <div className="relative" style={{ height: virtualizer.getTotalSize() }}>+ <div className={cn('pointer-events-none absolute inset-0 grid', CI_TIMELINE_COLUMNS)}>+ <div />+ <div className="relative">+ <div className={CI_TIMELINE_SCALE}>+ {ticks.map((seconds) => (+ <span+ key={seconds}+ className="absolute inset-y-0 border-l border-primary opacity-60"+ style={{ left: tickPosition(seconds) }}+ />+ ))}+ </div>+ </div>+ </div>+ {virtualizer.getVirtualItems().map((item) => {+ const row = rows[item.index]+ return (+ <div+ key={item.key}+ className="absolute inset-x-0 top-0"+ style={{ transform: `translateY(${item.start - CI_TIMELINE_ROW_HEIGHT_PX}px)` }}+ >+ <CITimelineRow+ row={row}+ axis={axis}+ expanded={isExpanded(row.node)}+ onToggle={() => toggle(row.node)}+ />+ </div>+ )+ })}+ </div>+ </div>+ </div>+ )+}diff --git a/products/engineering_analytics/frontend/components/CITimelineBar.tsx b/products/engineering_analytics/frontend/components/CITimelineBar.tsxnew file mode 100644index 000000000000..1d86300d92a8--- /dev/null+++ b/products/engineering_analytics/frontend/components/CITimelineBar.tsx@@ -0,0 +1,65 @@+import { Tooltip } from '@posthog/lemon-ui'++import { cn } from 'lib/utils/css-classes'+import { humanFriendlyDuration } from 'lib/utils/durations'++import { TimelineNode, TimelineStatus, timelineDuration } from '../lib/ciTimeline'+import { TimeAxis } from '../lib/pullRequestTimeline'+import { formatCost } from './runTables'++export const CI_TIMELINE_STATUS_FILL: Record<TimelineStatus, string> = {+ success: 'bg-success',+ failure: 'bg-danger',+ running: 'bg-warning',+ neutral: 'bg-muted',+ skipped: 'bg-muted',+}++const CENTERED = 'absolute top-1/2 -translate-y-1/2'++export function CITimelineBar({ node, axis }: { node: TimelineNode; axis: TimeAxis }): JSX.Element {+ if (node.startMs == null) {+ return (+ <span className={cn(CENTERED, 'left-0 text-xs text-tertiary')}>+ {node.status === 'skipped' ? 'Skipped' : 'Not started'}+ </span>+ )+ }+ if (node.endMs == null) {+ return (+ <span+ className={cn(CENTERED, 'text-xs whitespace-nowrap text-tertiary')}+ style={{ left: axis.position(node.startMs) }}+ >+ No update for over a day+ </span>+ )+ }+ const duration = timelineDuration(node)+ const offset = humanFriendlyDuration((node.startMs - axis.fromMs) / 1000)+ const isStep = node.kind === 'step'+ return (+ <>+ <Tooltip+ title={`${node.name}: ${node.status === 'running' ? 'running for' : 'ran'} ${duration}, starting ${offset} in${node.runner ? ` on ${node.runner}` : ''}${node.costUsd != null ? `, est. ${formatCost(node.costUsd)}` : ''}`}+ >+ <span+ className={cn(+ CENTERED,+ 'min-w-0.5 rounded-sm',+ isStep ? 'h-1.5' : 'h-2.5',+ isStep && node.status !== 'failure' && 'opacity-60',+ CI_TIMELINE_STATUS_FILL[node.status]+ )}+ style={{ left: axis.position(node.startMs), width: axis.width(node.startMs, node.endMs) }}+ />+ </Tooltip>+ <span+ className={cn(CENTERED, 'pl-1.5 text-[11px] tabular-nums whitespace-nowrap text-tertiary')}+ style={{ left: axis.position(node.endMs) }}+ >+ {duration}+ </span>+ </>+ )+}diff --git a/products/engineering_analytics/frontend/components/CITimelineRow.tsx b/products/engineering_analytics/frontend/components/CITimelineRow.tsxnew file mode 100644index 000000000000..1121ab683d41--- /dev/null+++ b/products/engineering_analytics/frontend/components/CITimelineRow.tsx@@ -0,0 +1,111 @@+import { IconChevronRight } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'++import { cn } from 'lib/utils/css-classes'+import { isExternalLink } from 'lib/utils/url'++import { TimelineRow, timelineDuration } from '../lib/ciTimeline'+import { TimeAxis } from '../lib/pullRequestTimeline'+import { CITimelineBar, CI_TIMELINE_STATUS_FILL } from './CITimelineBar'++/** The label column and the time track, shared by the header, the gridlines and every row so they line up. */+export const CI_TIMELINE_COLUMNS = 'grid-cols-[minmax(16rem,38%)_1fr]'+/** Insets of the time scale inside the track; the right one leaves room for the last bar's duration label. */+export const CI_TIMELINE_SCALE = 'absolute inset-y-0 left-2 right-14'+/** Every row and the header are `h-7`, so the virtualized list never measures one. */+export const CI_TIMELINE_ROW_HEIGHT_PX = 28++const GUIDE_LINE = 'before:absolute before:left-[7px] before:top-0 before:border-l before:border-primary'+const GUIDE_BRANCH = 'after:absolute after:left-[7px] after:right-0 after:top-1/2 after:border-t after:border-primary'++export function CITimelineRow({+ row,+ axis,+ expanded,+ onToggle,+}: {+ row: TimelineRow+ axis: TimeAxis+ expanded: boolean+ onToggle: () => void+}): JSX.Element {+ const { node } = row+ // Top-level rows have no parent row, so they get no guide column.+ const levels = row.lastAtLevel.slice(1)+ const isParent = node.children.length > 0+ const nameClass = cn(+ 'truncate',+ node.kind === 'step' ? 'text-secondary' : 'font-semibold',+ node.status === 'skipped' && 'text-tertiary'+ )++ return (+ <div className={cn('relative grid h-7 hover:bg-fill-highlight-50', CI_TIMELINE_COLUMNS)}>+ <div className="flex h-full min-w-0 items-center border-r border-primary pl-2 pr-2">+ {levels.map((isLast, level) => {+ const isOwn = level === levels.length - 1+ return (+ <span+ key={level}+ className={cn(+ 'relative h-full w-4 shrink-0',+ isOwn && GUIDE_BRANCH,+ (isOwn || !isLast) && GUIDE_LINE,+ isOwn && isLast ? 'before:h-1/2' : 'before:bottom-0'+ )}+ />+ )+ })}+ {isParent ? (+ <button+ type="button"+ className="flex h-full w-4 shrink-0 cursor-pointer items-center justify-center text-tertiary hover:text-primary"+ onClick={onToggle}+ aria-expanded={expanded}+ aria-label={`${expanded ? 'Collapse' : 'Expand'} ${node.name}`}+ data-attr="engineering-analytics-ci-timeline-toggle"+ >+ <IconChevronRight className={cn('size-3 transition-transform', expanded && 'rotate-90')} />+ </button>+ ) : (+ <span+ className={cn(+ 'relative h-full w-4 shrink-0',+ levels.length > 0 && GUIDE_BRANCH,+ 'after:left-0'+ )}+ />+ )}+ <span+ className={cn(+ 'mr-1.5 ml-0.5 size-2 shrink-0 rounded-sm',+ CI_TIMELINE_STATUS_FILL[node.status],+ node.status === 'skipped' && 'opacity-50'+ )}+ />+ {node.url ? (+ <Link+ to={node.url}+ target={isExternalLink(node.url) ? '_blank' : undefined}+ targetBlankIcon={false}+ subtle+ className={nameClass}+ data-attr="engineering-analytics-ci-timeline-open"+ >+ {node.name}+ </Link>+ ) : (+ <span className={nameClass}>{node.name}</span>+ )}+ <span className="ml-auto shrink-0 pl-2 text-xs tabular-nums text-secondary">+ {timelineDuration(node)}+ </span>+ </div>+ <div className="relative">+ <div className={CI_TIMELINE_SCALE}>+ <CITimelineBar node={node} axis={axis} />+ </div>+ </div>+ </div>+ )+}diff --git a/products/engineering_analytics/frontend/components/ciExplorer/CIExplorerTimeline.tsx b/products/engineering_analytics/frontend/components/ciExplorer/CIExplorerTimeline.tsxnew file mode 100644index 000000000000..d72b0767c490--- /dev/null+++ b/products/engineering_analytics/frontend/components/ciExplorer/CIExplorerTimeline.tsx@@ -0,0 +1,71 @@+import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { LemonBanner, Spinner } from '@posthog/lemon-ui'++import { pluralize } from 'lib/utils/strings'++import { workflowId } from '../../lib/ciExplorerGraph'+import { buildPushTimeline } from '../../lib/ciTimeline'+import { ciExplorerLogic } from '../../scenes/ciExplorerLogic'+import { CITimeline } from '../CITimeline'++export function CIExplorerTimeline(): JSX.Element {+ const {+ repoOwner,+ repoName,+ activePush,+ workflowRuns,+ jobsByRun,+ jobsByRunLoading,+ failedJobRuns,+ workflowRunUrl,+ } = useValues(ciExplorerLogic)+ const { retryFailedJobs } = useActions(ciExplorerLogic)+ const timeline = useMemo(+ () =>+ buildPushTimeline(+ { owner: repoOwner, name: repoName },+ workflowRuns.map((run) => ({+ id: workflowId(run),+ run,+ jobs: jobsByRun[workflowId(run)] ?? [],+ url: run.runId != null ? workflowRunUrl(run.runId, run.ciEngine ?? null) : undefined,+ })),+ Date.now()+ ),+ [repoOwner, repoName, workflowRuns, jobsByRun, workflowRunUrl]+ )++ if (!activePush) {+ return (+ <div className="py-16 text-center text-sm text-secondary">+ No CI runs are synced for this pull request yet. Runs appear here after the next sync.+ </div>+ )+ }+ return (+ <div className="flex flex-col gap-2">+ {failedJobRuns.length > 0 && (+ <LemonBanner+ type="warning"+ action={{+ children: 'Retry',+ onClick: retryFailedJobs,+ loading: jobsByRunLoading,+ disabledReason: jobsByRunLoading ? 'Loading' : undefined,+ 'data-attr': 'ci-explorer-timeline-retry-jobs',+ }}+ >+ Couldn't load jobs for {pluralize(failedJobRuns.length, 'workflow')}+ </LemonBanner>+ )}+ {jobsByRunLoading && (+ <span className="flex items-center gap-1.5 text-xs text-secondary">+ <Spinner /> Loading jobs+ </span>+ )}+ <CITimeline timeline={timeline} />+ </div>+ )+}diff --git a/products/engineering_analytics/frontend/lib/ciTimeline.test.ts b/products/engineering_analytics/frontend/lib/ciTimeline.test.tsnew file mode 100644index 000000000000..fc268c76356d--- /dev/null+++ b/products/engineering_analytics/frontend/lib/ciTimeline.test.ts@@ -0,0 +1,98 @@+import type { WorkflowJobApi } from '../generated/api.schemas'+import { buildPushTimeline, buildRunTimeline } from './ciTimeline'+import { WorkflowRun } from './lifecycle'++const NOW_MS = Date.parse('2026-06-10T00:00:00Z')+const REPO = { owner: 'PostHog', name: 'posthog' }++function job(id: number, name: string, startedAt: string, completedAt: string, conclusion = 'success'): WorkflowJobApi {+ return {+ id,+ run_id: 42,+ name,+ status: 'completed',+ conclusion,+ started_at: startedAt,+ completed_at: completedAt,+ duration_seconds: null,+ runner_provider: 'self_hosted',+ runner_label: 'depot-ubuntu-latest',+ estimated_cost_usd: null,+ ci_engine: 'github_actions',+ steps: [],+ }+}++function run(workflow: string, startedAt: string, finishedAt: string | null): WorkflowRun {+ return {+ workflow,+ conclusion: finishedAt ? 'success' : null,+ startedAt,+ finishedAt,+ durationSeconds: null,+ runId: workflow.length,+ runAttempt: 1,+ }+}++describe('ciTimeline', () => {+ test.each(['failure', 'startup_failure'])(+ 'nests matrix shards under a group that fails on a %s shard',+ (conclusion) => {+ const timeline = buildRunTimeline(+ REPO,+ '2026-06-09T00:00:00Z',+ [+ job(1, 'Jest (1/2)', '2026-06-09T00:01:00Z', '2026-06-09T00:03:00Z'),+ job(2, 'Jest (2/2)', '2026-06-09T00:02:00Z', '2026-06-09T00:05:00Z', conclusion),+ ],+ NOW_MS+ )++ expect(timeline.nodes).toHaveLength(1)+ expect(timeline.nodes[0]).toMatchObject({+ kind: 'group',+ name: 'Jest',+ status: 'failure',+ startMs: Date.parse('2026-06-09T00:01:00Z'),+ endMs: Date.parse('2026-06-09T00:05:00Z'),+ })+ expect(timeline.nodes[0].children.map((child) => [child.name, child.url])).toEqual([+ ['Jest (1/2)', 'https://github.com/PostHog/posthog/actions/runs/42/job/1'],+ ['Jest (2/2)', 'https://github.com/PostHog/posthog/actions/runs/42/job/2'],+ ])+ }+ )++ test.each([+ ['still running', '2026-06-09T23:50:00Z', null, [], NOW_MS, 'running'],+ ['silent for over a day', '2026-06-01T00:00:00Z', null, [], null, 'neutral'],+ ['days long but updated recently', '2026-06-01T00:00:00Z', '2026-06-09T23:00:00Z', [], NOW_MS, 'running'],+ [+ 'silent for over a day after a job finished',+ '2026-06-01T00:00:00Z',+ '2026-06-01T00:10:00Z',+ [job(1, 'Build', '2026-06-01T00:01:00Z', '2026-06-01T00:10:00Z')],+ null,+ 'neutral',+ ],+ ])(+ 'ends an unfinished run that is %s at the right time',+ (_, startedAt, updatedAt, jobs, expectedEndMs, expectedStatus) => {+ const timeline = buildPushTimeline(+ REPO,+ [+ { id: 'lint', run: run('Lint', '2026-06-09T23:50:00Z', '2026-06-09T23:55:00Z'), jobs: [] },+ { id: 'stuck', run: { ...run('Stuck', startedAt, null), updatedAt }, jobs },+ ],+ NOW_MS+ )++ expect(timeline.nodes.find((node) => node.name === 'Stuck')).toMatchObject({+ endMs: expectedEndMs,+ status: expectedStatus,+ })+ expect(timeline.endMs).toEqual(expectedEndMs ?? Date.parse('2026-06-09T23:55:00Z'))+ }+ )+})diff --git a/products/engineering_analytics/frontend/lib/ciTimeline.ts b/products/engineering_analytics/frontend/lib/ciTimeline.tsnew file mode 100644index 000000000000..3d94bc5e195e--- /dev/null+++ b/products/engineering_analytics/frontend/lib/ciTimeline.ts@@ -0,0 +1,251 @@+import { humanFriendlyDuration } from 'lib/utils/durations'++import type { WorkflowJobApi } from '../generated/api.schemas'+import { statusOf } from './ciExplorerGraph'+import { githubJobUrl } from './github'+import { groupJobs } from './jobGroups'+import { WorkflowRun } from './lifecycle'++export type TimelineStatus = 'success' | 'failure' | 'running' | 'neutral' | 'skipped'++export interface TimelineNode {+ id: string+ kind: 'workflow' | 'group' | 'job' | 'step'+ name: string+ /** A job's runner label. null on every other kind. */+ runner: string | null+ /** A job's estimated cost in USD. null when the runner tier is unknown or the job hasn't finished. */+ costUsd?: number | null+ /** The workflow's run page, or the GitHub log page of a job or step. */+ url?: string+ /** null when it never started, as for a skipped job. */+ startMs: number | null+ /** The build time while it runs. null when it never started or stopped reporting. */+ endMs: number | null+ status: TimelineStatus+ children: TimelineNode[]+}++export interface TimelineData {+ startMs: number+ endMs: number+ nodes: TimelineNode[]+}++export interface TimelineRow {+ node: TimelineNode+ /** Entry i is true when the row's ancestor at depth i + 1 is its parent's last child. The last entry is the row itself. */+ lastAtLevel: boolean[]+}++function timelineStatus(conclusion: string | null): TimelineStatus {+ return conclusion === 'skipped' ? 'skipped' : statusOf(conclusion)+}++function toMs(at: string | null): number | null {+ return at ? Date.parse(at) : null+}++// The webhook sync can miss a run's final event, so an unfinished item with no update for a day stopped reporting.+const STOPPED_REPORTING_MS = 24 * 60 * 60 * 1000++type Timing = Pick<TimelineNode, 'startMs' | 'endMs' | 'status'>++export interface TimelineRepo {+ owner: string+ name: string+}++/**+ * An unfinished item ends at `nowMs`. One that stopped reporting gets no end and no outcome.+ * Jobs and steps carry no update time, so their start stands in for it.+ */+function timing(+ startedAt: string | null,+ finishedAt: string | null,+ conclusion: string | null,+ nowMs: number,+ updatedAt: string | null = null+): Timing {+ const startMs = toMs(startedAt)+ const status = timelineStatus(conclusion)+ if (startMs == null) {+ return { startMs, endMs: null, status }+ }+ const endMs = toMs(finishedAt)+ if (endMs != null) {+ return { startMs, endMs, status }+ }+ return nowMs - (toMs(updatedAt) ?? startMs) < STOPPED_REPORTING_MS+ ? { startMs, endMs: nowMs, status }+ : { startMs, endMs: null, status: 'neutral' }+}++function combinedStatus(statuses: TimelineStatus[]): TimelineStatus {+ if (statuses.includes('failure')) {+ return 'failure'+ }+ if (statuses.includes('running')) {+ return 'running'+ }+ if (statuses.every((status) => status === 'skipped')) {+ return 'skipped'+ }+ return statuses.every((status) => status === 'success' || status === 'skipped') ? 'success' : 'neutral'+}++function minOf(values: (number | null)[]): number | null {+ const known = values.filter((v): v is number => v != null)+ return known.length ? Math.min(...known) : null+}++function maxOf(values: (number | null)[]): number | null {+ const known = values.filter((v): v is number => v != null)+ return known.length ? Math.max(...known) : null+}++const byStart = (a: TimelineNode, b: TimelineNode): number =>+ (a.startMs ?? Number.MAX_SAFE_INTEGER) - (b.startMs ?? Number.MAX_SAFE_INTEGER)++function jobId(job: WorkflowJobApi): string {+ return `job-${job.ci_engine ?? ''}-${job.id}`+}++function jobNode(job: WorkflowJobApi, repo: TimelineRepo, nowMs: number): TimelineNode {+ const id = jobId(job)+ // Depot CI jobs have no page on GitHub.+ const logUrl = (stepNumber?: number): string | undefined =>+ job.ci_engine === 'depot_ci' ? undefined : githubJobUrl(repo.owner, repo.name, job.run_id, job.id, stepNumber)+ return {+ id,+ kind: 'job',+ name: job.name,+ runner: job.runner_label || null,+ costUsd: job.estimated_cost_usd,+ url: logUrl(),+ ...timing(job.started_at, job.completed_at, job.conclusion, nowMs),+ children: job.steps.map(+ (step): TimelineNode => ({+ id: `${id}-step-${step.number}`,+ kind: 'step',+ name: step.name,+ runner: null,+ url: logUrl(step.number),+ ...timing(step.started_at, step.completed_at, step.conclusion, nowMs),+ children: [],+ })+ ),+ }+}++/** A run's jobs with matrix shards nested under their group, in start order. */+function jobNodes(jobs: WorkflowJobApi[], repo: TimelineRepo, nowMs: number): TimelineNode[] {+ return groupJobs(jobs)+ .map((group): TimelineNode => {+ if (group.jobs.length === 1) {+ return jobNode(group.jobs[0], repo, nowMs)+ }+ const shards = group.jobs.map((job) => jobNode(job, repo, nowMs)).sort(byStart)+ return {+ id: `${jobId(group.jobs[0])}-group`,+ kind: 'group',+ name: group.base,+ runner: null,+ startMs: minOf(shards.map((s) => s.startMs)),+ endMs: maxOf(shards.map((s) => s.endMs)),+ status: combinedStatus(shards.map((s) => s.status)),+ children: shards,+ }+ })+ .sort(byStart)+}++function flatten(nodes: TimelineNode[]): TimelineNode[] {+ return nodes.flatMap((node) => [node, ...flatten(node.children)])+}++/**+ * The end spans every descendant, since a child outlasts a parent whose finish the sync missed.+ * The start doesn't: a re-run lists jobs from an earlier attempt, and those started long before it.+ */+function withBounds(nodes: TimelineNode[], anchorMs: number | null, nowMs: number): TimelineData {+ const startMs = minOf([anchorMs, ...nodes.map((n) => n.startMs)]) ?? nowMs+ const endMs = maxOf(flatten(nodes).map((n) => n.endMs)) ?? startMs+ return { startMs, endMs: Math.max(endMs, startMs + 1000), nodes }+}++export function buildRunTimeline(+ repo: TimelineRepo,+ runStartedAt: string | null,+ jobs: WorkflowJobApi[],+ nowMs: number+): TimelineData {+ return withBounds(jobNodes(jobs, repo, nowMs), toMs(runStartedAt), nowMs)+}++export function buildPushTimeline(+ repo: TimelineRepo,+ runs: { id: string; run: WorkflowRun; jobs: WorkflowJobApi[]; url?: string }[],+ nowMs: number+): TimelineData {+ const nodes = runs+ .map(({ id, run, jobs, url }): TimelineNode => {+ const children = jobNodes(jobs, repo, nowMs)+ const own = timing(run.startedAt, run.finishedAt, run.conclusion, nowMs, run.updatedAt)+ // Only a run with no start of its own spans its jobs, so one that stopped reporting keeps its missing end.+ const span =+ own.startMs == null+ ? { startMs: minOf(children.map((c) => c.startMs)), endMs: maxOf(children.map((c) => c.endMs)) }+ : own+ return {+ id: `workflow-${id}`,+ kind: 'workflow',+ name: run.workflow,+ runner: null,+ url,+ startMs: span.startMs,+ endMs: span.endMs,+ status: own.status,+ children,+ }+ })+ .sort(byStart)+ return withBounds(nodes, null, nowMs)+}++export function visibleTimelineRows(nodes: TimelineNode[], isExpanded: (node: TimelineNode) => boolean): TimelineRow[] {+ const rows: TimelineRow[] = []+ const walk = (siblings: TimelineNode[], lastAtLevel: boolean[]): void => {+ siblings.forEach((node, index) => {+ const levels = [...lastAtLevel, index === siblings.length - 1]+ rows.push({ node, lastAtLevel: levels })+ if (isExpanded(node)) {+ walk(node.children, levels)+ }+ })+ }+ walk(nodes, [])+ return rows+}++export function timelineDuration(node: TimelineNode): string | null {+ return node.startMs != null && node.endMs != null ? humanFriendlyDuration((node.endMs - node.startMs) / 1000) : null+}++export function parentNodes(nodes: TimelineNode[]): TimelineNode[] {+ return nodes.flatMap((node) => (node.children.length ? [node, ...parentNodes(node.children)] : []))+}++const TICK_STEPS_SECONDS = [5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200]++/** Elapsed-second ticks from 0, at a round step that fits within maxTicks. */+export function timelineTicks(durationSeconds: number, maxTicks: number): number[] {+ const step =+ TICK_STEPS_SECONDS.find((s) => durationSeconds / s <= Math.max(1, maxTicks)) ??+ Math.ceil(durationSeconds / maxTicks / 3600) * 3600+ const ticks: number[] = []+ for (let t = 0; t <= durationSeconds; t += step) {+ ticks.push(t)+ }+ return ticks+}diff --git a/products/engineering_analytics/frontend/lib/lifecycle.ts b/products/engineering_analytics/frontend/lib/lifecycle.tsindex fab2eaa1ee1f..99867dce9d8d 100644--- a/products/engineering_analytics/frontend/lib/lifecycle.ts+++ b/products/engineering_analytics/frontend/lib/lifecycle.ts@@ -11,6 +11,8 @@ export interface WorkflowRun {conclusion: string | nullstartedAt: string | nullfinishedAt: string | null+ /** The sync's last update of the run. Absent where the source doesn't carry it. */+ updatedAt?: string | nulldurationSeconds: number | null/** GitHub Actions run id — links straight to the run page when present. */runId: number | nulldiff --git a/products/engineering_analytics/frontend/scenes/CIExplorerScene.tsx b/products/engineering_analytics/frontend/scenes/CIExplorerScene.tsxindex 9c408fdfcc92..de0e48015515 100644--- a/products/engineering_analytics/frontend/scenes/CIExplorerScene.tsx+++ b/products/engineering_analytics/frontend/scenes/CIExplorerScene.tsx@@ -16,6 +16,7 @@ import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'import { CIExplorerActivity } from '../components/ciExplorer/CIExplorerActivity'import { CIExplorerOverview } from '../components/ciExplorer/CIExplorerOverview'import { CIExplorerSummaryCounts } from '../components/ciExplorer/CIExplorerSummaryCounts'+import { CIExplorerTimeline } from '../components/ciExplorer/CIExplorerTimeline'import { EntityHeader } from '../components/EntityHeader'import { ProductNav } from '../components/ProductNav'import { PullRequestStateTag } from '../components/PullRequestStateTag'@@ -115,7 +116,7 @@ export function CIExplorerScene(): JSX.Element {</Link></>}- right={view === 'overview' && activePush ? <CIExplorerSummaryCounts /> : undefined}+ right={view !== 'activity' && activePush ? <CIExplorerSummaryCounts /> : undefined}/>)}@@ -126,6 +127,7 @@ export function CIExplorerScene(): JSX.Element {onChange={() => {}}tabs={[{ key: 'overview', label: 'Overview', link: viewUrl('overview') },+ { key: 'timeline', label: 'Timeline', link: viewUrl('timeline') },{ key: 'activity', label: 'Activity', link: viewUrl('activity') },]}barClassName="mb-0 border-b-0"@@ -169,6 +171,8 @@ export function CIExplorerScene(): JSX.Element {<LemonSkeleton className="h-96 w-full" />) : view === 'activity' ? (<CIExplorerActivity />+ ) : view === 'timeline' ? (+ <CIExplorerTimeline />) : (<CIExplorerOverview />)}diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsxindex c0188148656b..e792c9739667 100644--- a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx@@ -17,15 +17,16 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'+import { CITimeline } from '../components/CITimeline'import { EntityHeader, VerdictPill } from '../components/EntityHeader'import { FailureLogGroups } from '../components/FailureLogs'-import { GroupedJobsTable } from '../components/GroupedJobsTable'import { MetricTile } from '../components/MetricTile'import { ProductNav } from '../components/ProductNav'import { RepoSceneTitle } from '../components/RepoSceneTitle'import { formatCost, formatMinutes, runPrNumber } from '../components/runTables'import { ScopeBar } from '../components/ScopeBar'import { Section } from '../components/Section'+import { buildRunTimeline } from '../lib/ciTimeline'import { githubCommitUrl, githubRunUrl } from '../lib/github'import { isDecisiveFailure } from '../lib/lifecycle'import { verdictTag } from '../lib/runStatus'@@ -291,8 +292,21 @@ export function WorkflowRunDetailScene(): JSX.Element {onRetry={loadJobs}loading={jobsLoading}/>+ ) : jobs == null ? (+ <LemonSkeleton className="h-48 w-full" />+ ) : jobs.length === 0 ? (+ <div className="text-sm text-secondary">+ No job data yet. The job-level source isn't synced for this team.+ </div>) : (- <GroupedJobsTable jobs={jobs} loading={jobsLoading} />+ <CITimeline+ timeline={buildRunTimeline(+ { owner: repoOwner, name: repoName },+ run.run_started_at,+ jobs,+ Date.now()+ )}+ />)}</Section>diff --git a/products/engineering_analytics/frontend/scenes/ciExplorerContextLogic.ts b/products/engineering_analytics/frontend/scenes/ciExplorerContextLogic.tsindex 0e6ee2c48cc0..e6c4cb95401e 100644--- a/products/engineering_analytics/frontend/scenes/ciExplorerContextLogic.ts+++ b/products/engineering_analytics/frontend/scenes/ciExplorerContextLogic.ts@@ -87,8 +87,8 @@ export interface ciExplorerContextLogicActions {setLocation: (location: import('./ciExplorerLogic').CIExplorerLocation) => {location: import('./ciExplorerLogic').CIExplorerLocation} // ciExplorerLogic- setView: (view: CIExplorerView) => {- view: CIExplorerView+ setView: (view: 'activity' | 'overview' | 'timeline') => {+ view: 'activity' | 'overview' | 'timeline'} // ciExplorerLogichoverStep: (stepNumber: number | null) => {stepNumber: number | null@@ -123,7 +123,11 @@ export interface ciExplorerContextLogicActions {export interface ciExplorerContextLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {- active: (drawerOpen: boolean, drawerTab: CIExplorerDrawerTab, view: CIExplorerView) => boolean+ active: (+ drawerOpen: boolean,+ drawerTab: CIExplorerDrawerTab,+ view: 'activity' | 'overview' | 'timeline'+ ) => booleanselection: (workflows: CIExplorerWorkflow[],focusedNodeId: string | null,diff --git a/products/engineering_analytics/frontend/scenes/ciExplorerLogic.test.ts b/products/engineering_analytics/frontend/scenes/ciExplorerLogic.test.tsindex f930e401e81e..a1423d39cc0c 100644--- a/products/engineering_analytics/frontend/scenes/ciExplorerLogic.test.ts+++ b/products/engineering_analytics/frontend/scenes/ciExplorerLogic.test.ts@@ -110,6 +110,7 @@ describe('ciExplorerLogic', () => {test.each([['the plain page', '', { view: 'overview', older_commit: false }],['a link to a view', '?view=activity', { view: 'activity', older_commit: false }],+ ['a link to the timeline', '?view=timeline', { view: 'timeline', older_commit: false }],['a link to a commit', '?sha=def456', { view: 'overview', older_commit: true }],])('captures one viewed event when %s opens', (_, search, properties) => {open(search)@@ -117,6 +118,12 @@ describe('ciExplorerLogic', () => {expect(viewedEvents()).toEqual([properties])})+ test.each(['activity', 'timeline'] as const)('links to the %s view', (view) => {+ open('')++ expect(logic.values.locationUrl({ view, headSha: null, nodeId: null })).toContain(`view=${view}`)+ })+it('captures a viewed event when the view changes without a link', () => {open('')logic.actions.setView('activity')diff --git a/products/engineering_analytics/frontend/scenes/ciExplorerLogic.ts b/products/engineering_analytics/frontend/scenes/ciExplorerLogic.tsindex 0429d6bde56a..f049817e4231 100644--- a/products/engineering_analytics/frontend/scenes/ciExplorerLogic.ts+++ b/products/engineering_analytics/frontend/scenes/ciExplorerLogic.ts@@ -62,7 +62,8 @@ export interface CIExplorerLogicProps {sourceId: string | null}-export type CIExplorerView = 'overview' | 'activity'+const CI_EXPLORER_VIEWS = ['overview', 'activity', 'timeline'] as const+export type CIExplorerView = (typeof CI_EXPLORER_VIEWS)[number]export type CIExplorerDrawerTab = 'details' | 'context'/** Where the person is in the explorer. The URL holds the same three facts. */@@ -95,7 +96,7 @@ const CI_EXPLORER_ROUTE = `/engineering-analytics/repos/:repoOwner/:repoName/pulfunction locationSearchParams(current: Record<string, any>, location: CIExplorerLocation): Record<string, any> {const searchParams = { ...current }const own: [string, string | null][] = [- [VIEW_PARAM, location.view === 'activity' ? 'activity' : null],+ [VIEW_PARAM, location.view === 'overview' ? null : location.view],[SHA_PARAM, location.headSha],[NODE_PARAM, location.nodeId],]@@ -327,7 +328,7 @@ export interface ciExplorerLogicActions {location: CIExplorerLocation}setView: (view: CIExplorerView) => {- view: CIExplorerView+ view: 'activity' | 'overview' | 'timeline'}toggleJobTime: () => {value: true@@ -351,7 +352,7 @@ export interface ciExplorerLogicMeta {currentHeadSha: string | null) => PrCommitRuns | nullonOlderCommit: (selectedHeadSha: string | null, currentHeadSha: string | null) => boolean- currentView: (view: CIExplorerView, onOlderCommit: boolean) => CIExplorerView+ currentView: (view: 'activity' | 'overview' | 'timeline', onOlderCommit: boolean) => CIExplorerViewworkflowRunUrl: (repoOwner: string,repoName: string,@@ -947,7 +948,7 @@ export const ciExplorerLogic = kea<ciExplorerLogicType>([return}const location: CIExplorerLocation = {- view: searchParams[VIEW_PARAM] === 'activity' ? 'activity' : 'overview',+ view: CI_EXPLORER_VIEWS.find((view) => view === searchParams[VIEW_PARAM]) ?? 'overview',// The router reads an all-digit value as a number.headSha: searchParams[SHA_PARAM] == null ? null : String(searchParams[SHA_PARAM]),nodeId: searchParams[NODE_PARAM] == null ? null : String(searchParams[NODE_PARAM]),diff --git a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.tsindex 13eab6150cd1..d137c2a2f846 100644--- a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts+++ b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts@@ -136,6 +136,7 @@ function toWorkflowRun(run: WorkflowRunDetailApi): WorkflowRun {conclusion: run.conclusion,startedAt: run.run_started_at,finishedAt: run.status === 'completed' ? run.updated_at : null,+ updatedAt: run.updated_at,durationSeconds: run.duration_seconds,runId: run.id,ciEngine: run.ci_engine,diff --git a/products/engineering_analytics/package.json b/products/engineering_analytics/package.jsonindex 3747d233369f..c83c919fac2b 100644--- a/products/engineering_analytics/package.json+++ b/products/engineering_analytics/package.json@@ -20,6 +20,7 @@"@posthog/brand": "catalog:","@posthog/icons": "catalog:","@storybook/react": "catalog:",+ "@tanstack/react-virtual": "*","@types/react": "*","@xyflow/react": "*","elkjs": "*",