: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): add ci explorer graph model (#111946)
Raúl Negrón-Otero2d1632a621c5
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex fff383fa8bbb..9f323d3410a2 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3505,6 +3505,12 @@ importers:'@types/react':specifier: 18.3.27version: 18.3.27+ '@xyflow/react':+ specifier: '*'+ version: 12.6.0(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])+ elkjs:+ specifier: '*'+ version: 0.10.0kea:specifier: 'catalog:'version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])@@ -3514,6 +3520,9 @@ importers:kea-router:specifier: 'catalog:'version: 3.4.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ posthog-js:+ specifier: 'catalog:'+ version: 1.438.4(@types/[email protected])([email protected])react:specifier: 18.3.1version: 18.3.1diff --git a/products/engineering_analytics/frontend/lib/ciExplorerActivity.test.ts b/products/engineering_analytics/frontend/lib/ciExplorerActivity.test.tsnew file mode 100644index 000000000000..26a0c39fc21f--- /dev/null+++ b/products/engineering_analytics/frontend/lib/ciExplorerActivity.test.ts@@ -0,0 +1,63 @@+import type { PRLifecycleApi, WorkflowRunDetailApi } from '../generated/api.schemas'+import { activityDays, commitRows } from './ciExplorerActivity'++function run(overrides: Partial<WorkflowRunDetailApi>): WorkflowRunDetailApi {+ return {+ repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },+ id: 1,+ workflow_name: 'CI',+ head_sha: 'aaaaaaa1',+ head_branch: 'feature',+ status: 'completed',+ conclusion: 'success',+ run_started_at: '2026-06-01T10:00:00Z',+ updated_at: '2026-06-01T10:05:00Z',+ duration_seconds: 300,+ run_attempt: 1,+ pr_number: 10,+ commit_pr_number: null,+ is_merge_queue: false,+ ...overrides,+ }+}++const LIFECYCLE = {+ pull_request: { author: { handle: 'octocat' } },+ events: [+ { kind: 'opened', at: '2026-06-01T10:00:00Z' },+ { kind: 'ci_started', at: '2026-06-01T10:00:00Z', detail: 'CI' },+ { kind: 'ready_for_review', at: '2026-06-02T09:00:00Z', detail: 'hubot' },+ ],+} as unknown as PRLifecycleApi++describe('ciExplorerActivity', () => {+ it('orders people before the CI they started and leaves per-workflow CI events to the commit rows', () => {+ const days = activityDays(LIFECYCLE, commitRows([run({})]))++ expect(days.map((day) => day.rows.map((row) => (row.type === 'commit' ? 'commit' : row.kind)))).toEqual([+ ['opened', 'commit'],+ ['ready_for_review'],+ ])+ expect(days[0].rows[0]).toMatchObject({ actor: 'octocat' })+ expect(days[1].rows[0]).toMatchObject({ actor: 'hubot' })+ })++ it('counts failures as history and never marks a merge queue attempt as the current commit', () => {+ const runs = [+ run({ id: 1, conclusion: 'failure' }),+ run({ id: 2, run_started_at: '2026-06-01T10:20:00Z', updated_at: '2026-06-01T10:30:00Z' }),+ run({+ id: 3,+ head_sha: 'bbbbbbb2',+ is_merge_queue: true,+ run_started_at: '2026-06-01T12:00:00Z',+ updated_at: '2026-06-01T12:05:00Z',+ }),+ ]++ expect(commitRows(runs)).toMatchObject([+ { headSha: 'aaaaaaa1', runs: 2, failed: 1, elapsedSeconds: 1800, latest: true, mergeQueue: false },+ { headSha: 'bbbbbbb2', runs: 1, failed: 0, latest: false, mergeQueue: true },+ ])+ })+})diff --git a/products/engineering_analytics/frontend/lib/ciExplorerActivity.ts b/products/engineering_analytics/frontend/lib/ciExplorerActivity.tsnew file mode 100644index 000000000000..935765fcb2f9--- /dev/null+++ b/products/engineering_analytics/frontend/lib/ciExplorerActivity.ts@@ -0,0 +1,104 @@+// A pull request's activity in the order it happened: what people did to it, and the CI of each commit.++import { dayjs } from 'lib/dayjs'++import type { PRLifecycleApi, PRLifecycleEventApi, WorkflowRunDetailApi } from '../generated/api.schemas'+import { isDecisiveFailure } from './lifecycle'++// The commit rows carry the CI of the pull request, so the per-workflow start and finish events are left out.+export type CIActivityEventKind = Exclude<PRLifecycleEventApi['kind'], 'ci_started' | 'ci_finished'>++export interface CIActivityEvent {+ type: 'event'+ at: string+ kind: CIActivityEventKind+ /** Login of the person who did it, when the source says. */+ actor: string | null+}++export interface CIActivityCommit {+ type: 'commit'+ /** When the first run of the commit started. */+ at: string+ headSha: string+ /** A merge queue gate attempt, which tests a commit the queue made and not one the author pushed. */+ mergeQueue: boolean+ /** The newest commit the author pushed. */+ latest: boolean+ runs: number+ /** Runs that failed at any point, re-runs included. A count of history, not the commit's verdict. */+ failed: number+ /** First run start to last run update, re-runs and idle gaps included. Null while nothing has finished. */+ elapsedSeconds: number | null+}++export type CIActivityRow = CIActivityEvent | CIActivityCommit++export interface CIActivityDay {+ /** The calendar day, as YYYY-MM-DD. */+ date: string+ rows: CIActivityRow[]+}++function isActivityEvent(event: PRLifecycleEventApi): event is PRLifecycleEventApi & { kind: CIActivityEventKind } {+ return event.kind !== 'ci_started' && event.kind !== 'ci_finished'+}++/** One row per commit that has a started run. */+export function commitRows(prRuns: WorkflowRunDetailApi[]): CIActivityCommit[] {+ const bySha = new Map<string, WorkflowRunDetailApi[]>()+ for (const run of prRuns) {+ if (!run.run_started_at) {+ continue+ }+ const runs = bySha.get(run.head_sha)+ if (runs) {+ runs.push(run)+ } else {+ bySha.set(run.head_sha, [run])+ }+ }+ const rows = [...bySha.entries()].map(([headSha, runs]): CIActivityCommit => {+ const start = Math.min(...runs.map((run) => Date.parse(run.run_started_at as string)))+ const ends = runs+ .filter((run) => run.status === 'completed' && run.updated_at)+ .map((run) => Date.parse(run.updated_at as string))+ return {+ type: 'commit',+ at: new Date(start).toISOString(),+ headSha,+ mergeQueue: runs.every((run) => run.is_merge_queue),+ latest: false,+ runs: runs.length,+ failed: runs.filter((run) => isDecisiveFailure(run.conclusion)).length,+ elapsedSeconds: ends.length ? Math.max(0, Math.round((Math.max(...ends) - start) / 1000)) : null,+ }+ })+ const pushed = rows.filter((row) => !row.mergeQueue).sort((a, b) => b.at.localeCompare(a.at))[0]+ return rows.map((row) => ({ ...row, latest: row === pushed }))+}++/** The activity grouped by calendar day, oldest first. On a tie, what a person did comes before the CI it started. */+export function activityDays(lifecycle: PRLifecycleApi | null, commits: CIActivityCommit[]): CIActivityDay[] {+ const author = lifecycle?.pull_request.author.handle ?? null+ const events = (lifecycle?.events ?? []).filter(isActivityEvent).map(+ (event): CIActivityEvent => ({+ type: 'event',+ at: event.at,+ kind: event.kind,+ actor: event.kind === 'opened' ? author : (event.detail ?? null),+ })+ )+ const rows: CIActivityRow[] = [...events, ...commits].sort(+ (a, b) => Date.parse(a.at) - Date.parse(b.at) || Number(a.type === 'commit') - Number(b.type === 'commit')+ )+ const days: CIActivityDay[] = []+ for (const row of rows) {+ const date = dayjs(row.at).format('YYYY-MM-DD')+ if (days[days.length - 1]?.date !== date) {+ days.push({ date, rows: [] })+ }+ days[days.length - 1].rows.push(row)+ }+ return days+}diff --git a/products/engineering_analytics/frontend/lib/ciExplorerContext.test.ts b/products/engineering_analytics/frontend/lib/ciExplorerContext.test.tsnew file mode 100644index 000000000000..270cf3039ece--- /dev/null+++ b/products/engineering_analytics/frontend/lib/ciExplorerContext.test.ts@@ -0,0 +1,98 @@+import type { CITimingContextApi, WorkflowJobApi } from '../generated/api.schemas'+import { CIContextSelection, contextSelection, deltaPercent } from './ciExplorerContext'+import { buildWorkflows } from './ciExplorerGraph'+import type { WorkflowRun } from './lifecycle'++const RUN: WorkflowRun = {+ workflow: 'CI',+ workflowId: 7,+ ciEngine: 'github_actions',+ conclusion: 'failure',+ startedAt: '2026-06-01T00:00:00Z',+ finishedAt: '2026-06-01T00:10:00Z',+ durationSeconds: 600,+ runId: 42,+ runAttempt: 3,+}+const WORKFLOW = 'github_actions:42:3'++function job(id: number, name: string, conclusion: string): WorkflowJobApi {+ return {+ id,+ run_id: 42,+ name,+ status: 'completed',+ conclusion,+ started_at: '2026-06-01T00:00:00Z',+ completed_at: '2026-06-01T00:02:00Z',+ duration_seconds: 120,+ runner_provider: 'self_hosted',+ runner_label: 'depot-ubuntu-latest',+ estimated_cost_usd: null,+ ci_engine: 'github_actions',+ steps: [+ {+ number: 4,+ name: 'Run tests',+ status: 'completed',+ conclusion: 'success',+ started_at: null,+ completed_at: null,+ duration_seconds: 90,+ },+ ],+ }+}++const WORKFLOWS = buildWorkflows([RUN], {+ [WORKFLOW]: [+ job(1, 'Jest (1/2)', 'success'),+ job(2, 'Jest (2/2)', 'failure'),+ job(3, 'Lint', 'success'),+ job(4, 'Build (1/2)', 'cancelled'),+ job(5, 'Build (2/2)', 'cancelled'),+ ],+})++describe('ciExplorerContext', () => {+ test.each<[string, string, number | null, Partial<CIContextSelection>]>([+ ['a workflow', WORKFLOW, null, { kind: 'workflow', jobIds: [], runAttempt: 3, passed: false }],+ ['a matrix asks about every shard', `${WORKFLOW}/Jest`, null, { kind: 'matrix', passed: false }],+ [+ 'a matrix whose shards were all cancelled',+ `${WORKFLOW}/Build`,+ null,+ { kind: 'matrix', statusText: 'Cancelled', passed: false },+ ],+ ['a shard', `${WORKFLOW}/Jest/1`, null, { kind: 'job', jobIds: [1], passed: true }],+ [+ 'a step of the focused job',+ `${WORKFLOW}/Lint`,+ 4,+ { kind: 'step', jobIds: [3], stepNumber: 4, currentSeconds: 90 },+ ],+ ['a step the job does not have falls back to the job', `${WORKFLOW}/Lint`, 9, { kind: 'job', jobIds: [3] }],+ ])('contextSelection: %s', (_, nodeId, stepNumber, expected) => {+ expect(contextSelection(WORKFLOWS, nodeId, stepNumber)).toMatchObject(expected)+ })++ it('asks about every shard of a matrix', () => {+ expect(contextSelection(WORKFLOWS, `${WORKFLOW}/Jest`, null)?.jobIds.sort()).toEqual([1, 2])+ })++ test.each<[string, Partial<CIContextSelection>, number | null, number | null]>([+ ['a passed selection is compared', { passed: true, currentSeconds: 120 }, 100, 20],+ [+ 'a failed selection is not, because the average is of passed runs',+ { passed: false, currentSeconds: 120 },+ 100,+ null,+ ],+ ['a running selection is not', { passed: true, currentSeconds: null }, 100, null],+ ['no matching passed run means no comparison', { passed: true, currentSeconds: 120 }, null, null],+ ])('deltaPercent: %s', (_, selection, averageSeconds, expected) => {+ expect(+ deltaPercent(selection as CIContextSelection, { average_seconds: averageSeconds } as CITimingContextApi)+ ).toBe(expected)+ })+})diff --git a/products/engineering_analytics/frontend/lib/ciExplorerContext.ts b/products/engineering_analytics/frontend/lib/ciExplorerContext.tsnew file mode 100644index 000000000000..37c3af1eef7a--- /dev/null+++ b/products/engineering_analytics/frontend/lib/ciExplorerContext.ts@@ -0,0 +1,132 @@+// What the Context tab compares: the selected workflow, matrix, job, or step against its recent runs on the+// default branch.++import type { CITimingContextApi, CITimingSampleApi } from '../generated/api.schemas'+import { CIEngine, statusLabel } from './ciExplorerDetails'+import { CIExplorerWorkflow, elapsedSeconds, jobsOf, resolveNode, workflowJobs } from './ciExplorerGraph'+import { githubJobUrl, githubRunUrl } from './github'++export type CIContextKind = 'workflow' | 'matrix' | 'job' | 'step'++export const CONTEXT_KIND_NAME: Record<CIContextKind, string> = {+ workflow: 'Workflow',+ matrix: 'Matrix',+ job: 'Job',+ step: 'Step',+}++export interface CIContextSelection {+ /** Identifies the selection, so an answer for an earlier selection is never shown for this one. */+ key: string+ label: string+ kind: CIContextKind+ engine: NonNullable<CIEngine>+ statusText: string+ /** Only a passed selection is compared with the average, which is an average of passed runs. */+ passed: boolean+ currentSeconds: number | null+ runId: number+ runAttempt: number+ jobIds: number[]+ stepNumber: number | null+}++/** The selection the Context tab describes, or null when nothing comparable is focused. */+export function contextSelection(+ workflows: CIExplorerWorkflow[],+ nodeId: string | null,+ stepNumber: number | null+): CIContextSelection | null {+ const node = resolveNode(workflows, nodeId)+ const run = node?.workflow.run+ if (!node || !run || run.runId === null || !run.ciEngine) {+ return null+ }+ const base = { engine: run.ciEngine, runId: run.runId, runAttempt: run.runAttempt ?? 1 }+ const selection = (+ kind: CIContextKind,+ label: string,+ conclusion: string | null,+ currentSeconds: number | null,+ jobIds: number[],+ step: number | null = null+ ): CIContextSelection => ({+ ...base,+ key: [base.engine, base.runId, base.runAttempt, kind, jobIds.join(','), step ?? ''].join(':'),+ label,+ kind,+ statusText: statusLabel(conclusion),+ passed: conclusion === 'success',+ currentSeconds,+ jobIds,+ stepNumber: step,+ })+ const { workflow, item, shard } = node+ if (!item) {+ // The average is measured from the first job start to the last job finish, so the current value is too.+ // The run's own duration also counts the wait for a runner.+ const executed = workflowJobs(workflow).filter(+ (job) => job.conclusion !== 'skipped' && job.conclusion !== 'neutral'+ )+ return selection(+ 'workflow',+ run.workflow,+ run.conclusion,+ executed.length ? elapsedSeconds(executed) : null,+ []+ )+ }+ const job = shard?.job ?? (item.id === nodeId ? item.job : null)+ if (!job) {+ const shardJobs = jobsOf(item)+ // A matrix has a status and no conclusion of its own. Running maps to none, as it does for a job.+ // A matrix that did not run takes the conclusion all its shards share, so it reads "Cancelled" or "Skipped".+ const sharedConclusion = new Set(shardJobs.map((shardJob) => shardJob.conclusion)).size === 1+ return selection(+ 'matrix',+ item.name,+ item.status === 'running'+ ? null+ : item.status === 'neutral' && sharedConclusion+ ? shardJobs[0].conclusion+ : item.status,+ item.durationSeconds,+ shardJobs.map((shardJob) => shardJob.id)+ )+ }+ const step = stepNumber === null ? undefined : job.steps.find((s) => s.number === stepNumber)+ if (step) {+ return selection('step', step.name, step.conclusion, step.duration_seconds, [job.id], step.number)+ }+ return selection('job', job.name, job.conclusion, job.duration_seconds, [job.id])+}++/**+ * How far the selection is from the average, in percent. Null when the two do not compare: the selection did+ * not pass, has no duration yet, or no passed run matched.+ */+export function deltaPercent(selection: CIContextSelection, context: CITimingContextApi): number | null {+ if (!selection.passed || selection.currentSeconds === null || !context.average_seconds) {+ return null+ }+ return Math.round((selection.currentSeconds / context.average_seconds - 1) * 100)+}++/** Where a matched run can be read at its source. Depot CI has no public page for a run, so that one stays in PostHog. */+export function sampleUrl(+ repoOwner: string,+ repoName: string,+ sample: CITimingSampleApi,+ postHogRunUrl: string+): { url: string; external: boolean } {+ if (sample.ci_engine === 'depot_ci') {+ return { url: postHogRunUrl, external: false }+ }+ return {+ url:+ sample.job_id === null+ ? `${githubRunUrl(repoOwner, repoName, sample.run_id)}/attempts/${sample.run_attempt}`+ : githubJobUrl(repoOwner, repoName, sample.run_id, sample.job_id, sample.step_number),+ external: true,+ }+}diff --git a/products/engineering_analytics/frontend/lib/ciExplorerDetails.ts b/products/engineering_analytics/frontend/lib/ciExplorerDetails.tsnew file mode 100644index 000000000000..a3e0994ef71f--- /dev/null+++ b/products/engineering_analytics/frontend/lib/ciExplorerDetails.ts@@ -0,0 +1,252 @@+// What the CI explorer says about a node besides drawing it: its status word, its share of the push's job time,+// its tooltip, and the excerpt of a failed job's log.++import { dayjs } from 'lib/dayjs'+import { humanFriendlyDuration } from 'lib/utils/durations'++import type { CIFailureLogLineApi, WorkflowJobApi, WorkflowRunDetailApi } from '../generated/api.schemas'+import { CIExplorerItem, CIExplorerWorkflow, CIJobKind, jobsOf, resolveNode, workflowJobs } from './ciExplorerGraph'+import { compactUsd } from './format'++export type CIEngine = WorkflowRunDetailApi['ci_engine']++const KIND_NAME: Record<CIJobKind, string> = {+ test: 'Test',+ check: 'Check',+ build: 'Build',+ setup: 'Setup',+ report: 'Report',+ other: 'Job',+}++const STATUS_LABEL: Record<string, string> = {+ success: 'Passed',+ failure: 'Failed',+ startup_failure: 'Failed',+ timed_out: 'Timed out',+ cancelled: 'Cancelled',+ skipped: 'Skipped',+ neutral: 'Neutral',+ action_required: 'Action required',+ stale: 'Stale',+}++const LEVELS_SHOWN = 3+const EXCERPT_LINES = 12++// Raw statuses of a job or step that has not started.+const NOT_STARTED = new Set(['queued', 'waiting', 'pending', 'requested'])++/**+ * One word for how a run, job, or step ended. With no conclusion it has not ended, and the raw status tells+ * a queued one from a running one.+ */+export function statusLabel(conclusion: string | null | undefined, status?: string | null): string {+ if (conclusion) {+ return STATUS_LABEL[conclusion] ?? conclusion+ }+ return status && NOT_STARTED.has(status) ? 'Queued' : 'Running'+}++/** A duration, or the status word of what has no duration yet. */+export function elapsedLabel(seconds: number | null, status?: string | null): string {+ return seconds === null ? statusLabel(null, status) : humanFriendlyDuration(seconds, { maxUnits: 2 })+}++/** The CI provider that ran the workflow. The runner hardware is a separate fact. */+export function providerName(engine: CIEngine | undefined): string {+ return engine === 'depot_ci' ? 'Depot CI' : engine === 'github_actions' ? 'GitHub Actions' : 'Unknown provider'+}++function duration(seconds: number | null): string {+ return seconds === null ? 'Running' : humanFriendlyDuration(seconds, { maxUnits: 2 })+}++function jobSeconds(jobs: WorkflowJobApi[]): number {+ return jobs.reduce((sum, job) => sum + (job.duration_seconds ?? 0), 0)+}++// Null when no job has a cost, so an unknown runner tier never reads as free.+function costUsd(jobs: WorkflowJobApi[]): number | null {+ const costs = jobs.map((job) => job.estimated_cost_usd).filter((cost): cost is number => cost !== null)+ return costs.length ? costs.reduce((sum, cost) => sum + cost, 0) : null+}++function ran(job: WorkflowJobApi): boolean {+ return job.conclusion !== 'skipped'+}++/** The older of the sync times that are known, because everything on screen is at least that fresh. */+export function oldestSync(...times: (string | null | undefined)[]): string | null {+ const known = times.filter((time): time is string => !!time)+ return known.length ? known.reduce((oldest, time) => (time < oldest ? time : oldest)) : null+}++/** The summed duration of every job of the push. Jobs run in parallel, so this is more than the elapsed time. */+export function totalJobSeconds(workflows: CIExplorerWorkflow[]): number {+ return jobSeconds(workflows.flatMap(workflowJobs))+}++export interface CIExplorerShareLevel {+ id: string+ name: string+ elapsedSeconds: number | null+ jobSeconds: number+ /** Percent of the push's job time, 0 to 100. */+ share: number+}++/** The focused node and what contains it, outermost first, each as a share of the push's job time. */+export function shareLevels(workflows: CIExplorerWorkflow[], nodeId: string | null): CIExplorerShareLevel[] {+ const total = Math.max(1, totalJobSeconds(workflows))+ const node = resolveNode(workflows, nodeId)+ if (!node) {+ return []+ }+ const { workflow, item, shard } = node+ const level = (id: string, name: string, elapsed: number | null, jobs: WorkflowJobApi[]): CIExplorerShareLevel => {+ const seconds = jobSeconds(jobs)+ return { id, name, elapsedSeconds: elapsed, jobSeconds: seconds, share: (seconds / total) * 100 }+ }+ const levels = [level(workflow.id, workflow.run.workflow, workflow.run.durationSeconds, workflowJobs(workflow))]+ if (item) {+ levels.push(level(item.id, item.name, item.durationSeconds, jobsOf(item)))+ }+ if (shard) {+ levels.push(level(shard.id, shard.label, shard.job.duration_seconds, [shard.job]))+ }+ return levels.slice(0, LEVELS_SHOWN)+}++export interface CIExplorerTip {+ name: string+ rows: [string, string][]+}++function costRow(jobs: WorkflowJobApi[]): [string, string][] {+ const cost = costUsd(jobs)+ return cost === null ? [] : [['Estimated cost', compactUsd(cost)]]+}++function jobTip(name: string, job: WorkflowJobApi, kind: CIJobKind, containerSeconds: number | null): CIExplorerTip {+ const ofContainer =+ containerSeconds && job.duration_seconds !== null+ ? ` · ${Math.round((job.duration_seconds / containerSeconds) * 100)}% of elapsed`+ : ''+ const rows: [string, string][] = [+ ['Kind', KIND_NAME[kind]],+ ['Status', statusLabel(job.conclusion, job.status)],+ ['Elapsed', elapsedLabel(job.duration_seconds, job.status) + ofContainer],+ ['Provider', providerName(job.ci_engine)],+ ['Runner', job.runner_label || 'Unknown'],+ ...costRow([job]),+ ]+ if (job.started_at) {+ rows.push(['Started', dayjs(job.started_at).format('MMM D, HH:mm:ss')])+ }+ return { name, rows }+}++function matrixTip(item: CIExplorerItem): CIExplorerTip {+ const jobs = jobsOf(item)+ const durations = jobs.map((job) => job.duration_seconds).filter((d): d is number => d !== null)+ const failed = item.shards.filter((shard) => shard.status === 'failure').length+ const rows: [string, string][] = [+ ['Kind', `${KIND_NAME[item.kind]}, matrix`],+ ['Parallel jobs', String(item.shards.length)],+ ['Elapsed', duration(item.durationSeconds)],+ ['Job time', duration(jobSeconds(jobs))],+ ['Provider', providerName(jobs[0]?.ci_engine)],+ ...costRow(jobs),+ ]+ if (durations.length) {+ rows.push(['Slowest', duration(Math.max(...durations))], ['Fastest', duration(Math.min(...durations))])+ }+ if (failed) {+ rows.push(['Failed', String(failed)])+ }+ return { name: item.name, rows }+}++function workflowTip(workflow: CIExplorerWorkflow): CIExplorerTip {+ const jobs = workflowJobs(workflow)+ const executed = jobs.filter(ran)+ const rows: [string, string][] = [+ ['Provider', providerName(workflow.run.ciEngine)],+ ['Status', statusLabel(workflow.run.conclusion)],+ ['Attempt', String(workflow.run.runAttempt ?? 1)],+ ['Elapsed', duration(workflow.run.durationSeconds)],+ ['Job time', workflow.items === null ? 'Loading' : duration(jobSeconds(jobs))],+ [+ 'Jobs',+ workflow.items === null ? 'Loading' : `${executed.length} ran, ${jobs.length - executed.length} skipped`,+ ],+ ...costRow(jobs),+ ]+ if (workflow.run.event) {+ rows.push(['Trigger', workflow.run.event])+ }+ return { name: workflow.run.workflow, rows }+}++/** What a tooltip says about the node with this id, or null when no node has it. */+export function nodeTip(workflows: CIExplorerWorkflow[], nodeId: string): CIExplorerTip | null {+ for (const workflow of workflows) {+ if (workflow.id === nodeId) {+ return workflowTip(workflow)+ }+ for (const item of workflow.items ?? []) {+ if (item.id === nodeId) {+ return item.job ? jobTip(item.name, item.job, item.kind, workflow.run.durationSeconds) : matrixTip(item)+ }+ const shard = item.shards.find((s) => s.id === nodeId)+ if (shard) {+ return jobTip(shard.job.name, shard.job, item.kind, item.durationSeconds)+ }+ }+ }+ return null+}++export interface CIExplorerSummary {+ passed: number+ failed: number+ running: number+ /** Cancelled, skipped, and every other ending that is neither a pass nor a failure. */+ other: number+}++/** How the workflows of a push ended, as counts. It is not a merge verdict, because required checks are not synced. */+export function summarize(workflows: CIExplorerWorkflow[]): CIExplorerSummary {+ const summary: CIExplorerSummary = { passed: 0, failed: 0, running: 0, other: 0 }+ for (const workflow of workflows) {+ if (workflow.status === 'success') {+ summary.passed+++ } else if (workflow.status === 'failure') {+ summary.failed+++ } else if (workflow.status === 'running') {+ summary.running+++ } else {+ summary.other+++ }+ }+ return summary+}++export interface CIFailureExcerpt {+ /** The last lines of the failure region, where the error usually is. */+ tail: string+ /** The whole stored region, or null when the tail already shows all of it. */+ context: string | null+}++export function failureExcerpt(lines: CIFailureLogLineApi[]): CIFailureExcerpt | null {+ if (!lines.length) {+ return null+ }+ const text = lines.map((line) => line.text)+ return {+ tail: text.slice(-EXCERPT_LINES).join('\n'),+ context: text.length > EXCERPT_LINES ? text.join('\n') : null,+ }+}diff --git a/products/engineering_analytics/frontend/lib/ciExplorerGraph.test.ts b/products/engineering_analytics/frontend/lib/ciExplorerGraph.test.tsnew file mode 100644index 000000000000..580f560bedbc--- /dev/null+++ b/products/engineering_analytics/frontend/lib/ciExplorerGraph.test.ts@@ -0,0 +1,85 @@+import type { WorkflowJobApi } from '../generated/api.schemas'+import { buildWorkflows, latestRunPerWorkflow } from './ciExplorerGraph'+import type { WorkflowRun } from './lifecycle'++function run(overrides: Partial<WorkflowRun>): WorkflowRun {+ return {+ workflow: 'Backend CI',+ workflowId: 100,+ ciEngine: 'github_actions',+ conclusion: 'success',+ startedAt: '2026-06-01T00:00:00Z',+ finishedAt: '2026-06-01T00:10:00Z',+ durationSeconds: 600,+ runId: 1,+ runAttempt: 1,+ ...overrides,+ }+}++describe('ciExplorerGraph', () => {+ test.each<[string, WorkflowRun[], [number, number][]]>([+ [+ 'two providers that share a display name both stay',+ [run({ runId: 1 }), run({ runId: 2, ciEngine: 'depot_ci', workflowId: null })],+ [+ [1, 1],+ [2, 1],+ ],+ ],+ [+ 'a renamed workflow is still one workflow, and its newest run stands for it',+ [+ run({ runId: 1, workflow: 'Backend CI' }),+ run({ runId: 2, workflow: 'Backend', startedAt: '2026-06-01T01:00:00Z' }),+ ],+ [[2, 1]],+ ],+ [+ 'two workflows that share a display name both stay',+ [run({ runId: 1, workflowId: 100 }), run({ runId: 2, workflowId: 200 })],+ [+ [1, 1],+ [2, 1],+ ],+ ],+ [+ 'a re-run that reports the same start replaces the earlier attempt',+ [run({ runId: 1, runAttempt: 2, conclusion: 'success' }), run({ runId: 1, conclusion: 'failure' })],+ [[1, 2]],+ ],+ [+ 'a queued re-run has no start yet and still replaces the attempt before it',+ [+ run({ runId: 1, conclusion: 'failure' }),+ run({ runId: 1, runAttempt: 2, conclusion: null, startedAt: null }),+ ],+ [[1, 2]],+ ],+ ])('latestRunPerWorkflow: %s', (_, runs, expected) => {+ expect(latestRunPerWorkflow(runs).map((r) => [r.runId, r.runAttempt])).toEqual(expected)+ })++ test.each(['failure', 'timed_out', 'startup_failure', 'stale'])(+ 'a matrix with a %s shard beside a passed one is failed',+ (conclusion) => {+ const shard = (id: number, shardConclusion: string): WorkflowJobApi =>+ ({+ id,+ run_id: 1,+ name: `Jest (${id}/2)`,+ status: 'completed',+ conclusion: shardConclusion,+ started_at: '2026-06-01T00:00:00Z',+ completed_at: '2026-06-01T00:02:00Z',+ duration_seconds: 120,+ steps: [],+ }) as unknown as WorkflowJobApi+ const [workflow] = buildWorkflows([run({})], {+ 'github_actions:1:1': [shard(1, 'success'), shard(2, conclusion)],+ })++ expect(workflow.items?.map((item) => item.status)).toEqual(['failure'])+ }+ )+})diff --git a/products/engineering_analytics/frontend/lib/ciExplorerGraph.ts b/products/engineering_analytics/frontend/lib/ciExplorerGraph.tsnew file mode 100644index 000000000000..bdf2928531d1--- /dev/null+++ b/products/engineering_analytics/frontend/lib/ciExplorerGraph.ts@@ -0,0 +1,501 @@+// One push as a set of workflow graphs: a node per job or matrix, an edge per `needs` dependency.+// ELK places the nodes and routes the edges.++import type { ELK, ElkNode } from 'elkjs'++import type { WorkflowJobApi, WorkflowJobStepApi } from '../generated/api.schemas'+import { JobGroupConclusion, collapseTemplates, groupJobs } from './jobGroups'+import { jobCacheKey } from './jobs'+import { WorkflowRun, isDecisiveFailure } from './lifecycle'++export type CIStatus = 'success' | 'failure' | 'running' | 'neutral'+export type CIJobKind = 'test' | 'check' | 'build' | 'setup' | 'report' | 'other'++export interface CIExplorerShard {+ id: string+ label: string+ status: CIStatus+ job: WorkflowJobApi+ /** Duration relative to the slowest shard of the matrix, 0 to 1. */+ durationShare: number+}++/** A node of a workflow's graph: one job, or one matrix job with its shards. */+export interface CIExplorerItem {+ id: string+ name: string+ kind: CIJobKind+ status: CIStatus+ startedAt: number+ endedAt: number+ /** Elapsed time, from the first start to the last finish. Null while a job of the node has not finished. */+ durationSeconds: number | null+ /** Duration relative to the slowest item of the workflow, 0 to 1. */+ durationShare: number+ /** Set for a single job. */+ job: WorkflowJobApi | null+ /** Set for a matrix, failed first and then slowest first. */+ shards: CIExplorerShard[]+}++export interface CIExplorerWorkflow {+ id: string+ run: WorkflowRun+ status: CIStatus+ /** Duration relative to the slowest workflow of the push, 0 to 1. */+ durationShare: number+ /** Null while the workflow's jobs are loading. */+ items: CIExplorerItem[] | null+ edges: [string, string][]+ columnOf: Record<string, number>+}++export interface CIExplorerLayout {+ at: Record<string, { x: number; y: number }>+ width: number+ height: number+ /** SVG path data, one per edge. */+ wires: string[]+ /** Both ends of every edge. */+ ends: { x: number; y: number }[]+}++export const NODE_WIDTH = 264+const NODE_PADDING = 24+export const INNER_WIDTH = 744+/** A matrix lays its shards out INNER_WIDTH wide, then scales them down to fit the node. */+export const INNER_SCALE = (NODE_WIDTH - NODE_PADDING) / INNER_WIDTH+export const SHARDS_PER_ROW = 3+export const SHARD_HEIGHT = 40+export const SHARD_GAP = 8+const TITLE_CHARS_PER_LINE = 21+const SAME_COLUMN_MS = 5000++// A job's kind is guessed from its name. The first rule that matches wins.+const KIND_RULES: [CIJobKind, RegExp][] = [+ ['report', /\bpass(es)?$|tests pass|checks pass/i],+ [+ 'setup',+ /determine need|dynamic ci|discover|select|matrix|detect|get \w+ versions|hand off|wait for|prime|cancel|assign|token/i,+ ],+ ['report', /report|capture|calculate|coverage|summary|complete|snapshot changes|verdict|upload|comment/i],+ ['test', /test|jest|playwright|pytest|django|e2e|visual regression|flake verification/i],+ [+ 'check',+ /lint|format|typecheck|type ?checking|validate|semgrep|shellcheck|migration|openapi|check|guard|quality|audit|clippy/i,+ ],+ ['build', /build|image|compile|bundle|deploy/i],+]++export function jobKind(name: string): CIJobKind {+ return KIND_RULES.find(([, pattern]) => pattern.test(name))?.[0] ?? 'other'+}++export function statusOf(conclusion: string | null): CIStatus {+ if (conclusion === null) {+ return 'running'+ }+ if (isDecisiveFailure(conclusion)) {+ return 'failure'+ }+ return conclusion === 'success' ? 'success' : 'neutral'+}++const STATUS_RANK: Record<CIStatus, number> = { failure: 0, running: 1, success: 2, neutral: 3 }++const GROUP_STATUS: Record<JobGroupConclusion, CIStatus> = {+ failure: 'failure',+ running: 'running',+ success: 'success',+ cancelled: 'neutral',+ skipped: 'neutral',+}++function share(seconds: number | null, longest: number): number {+ return longest > 0 && seconds ? Math.min(1, seconds / longest) : 0+}++function startOf(job: WorkflowJobApi): number {+ return job.started_at ? Date.parse(job.started_at) : Infinity+}++function endOf(job: WorkflowJobApi): number {+ return job.completed_at ? Date.parse(job.completed_at) : Infinity+}++/** What a shard's name adds to its matrix name: "Django tests – Core (3/23)" becomes "Core (3/23)". */+function shardLabel(jobName: string, base: string): string {+ const name = collapseTemplates(jobName)+ const rest = name.startsWith(base) ? name.slice(base.length).replace(/^[\s–-]+/, '') : name+ return rest.replace(/^\((\d+\/\d+)\)$/, '$1') || name+}++/** First start to last finish. Null while a job is unfinished, because the last finish is not known yet. */+export function elapsedSeconds(jobs: WorkflowJobApi[]): number | null {+ const start = Math.min(...jobs.map(startOf))+ const end = Math.max(...jobs.map(endOf))+ return isFinite(start) && isFinite(end) ? Math.max(0, Math.round((end - start) / 1000)) : null+}++function itemsOf(workflowId: string, jobs: WorkflowJobApi[]): CIExplorerItem[] {+ const items = groupJobs(jobs).map((group): Omit<CIExplorerItem, 'durationShare'> => {+ const id = `${workflowId}/${group.base}`+ const slowest = Math.max(0, ...group.jobs.map((job) => job.duration_seconds ?? 0))+ const single = group.jobs.length === 1 ? group.jobs[0] : null+ return {+ id,+ name: single ? collapseTemplates(single.name) : group.base,+ kind: jobKind(group.base),+ // The group's own rollup does not count every failing conclusion, so a failed shard decides first.+ status: group.jobs.some((job) => statusOf(job.conclusion) === 'failure')+ ? 'failure'+ : GROUP_STATUS[group.conclusion],+ startedAt: Math.min(...group.jobs.map(startOf)),+ endedAt: Math.max(...group.jobs.map(endOf)),+ durationSeconds: single ? single.duration_seconds : elapsedSeconds(group.jobs),+ job: single,+ shards: single+ ? []+ : [...group.jobs]+ .sort(+ (a, b) =>+ STATUS_RANK[statusOf(a.conclusion)] - STATUS_RANK[statusOf(b.conclusion)] ||+ (b.duration_seconds ?? 0) - (a.duration_seconds ?? 0)+ )+ .map((job) => ({+ id: `${id}/${job.id}`,+ label: shardLabel(job.name, group.base),+ status: statusOf(job.conclusion),+ job,+ durationShare: share(job.duration_seconds, slowest),+ })),+ }+ })+ const longest = Math.max(0, ...items.map((item) => item.durationSeconds ?? 0))+ return items.map((item) => ({ ...item, durationShare: share(item.durationSeconds, longest) }))+}++// Jobs that started together share a column, and a job always sits to the right of a job it needs.+function columnsOf(items: CIExplorerItem[], edges: [string, string][]): Record<string, number> {+ const columnOf: Record<string, number> = {}+ const sorted = [...items].sort(+ (a, b) => a.startedAt - b.startedAt || (b.durationSeconds ?? 0) - (a.durationSeconds ?? 0)+ )+ if (!sorted.length) {+ return columnOf+ }+ const span = sorted[sorted.length - 1].startedAt - sorted[0].startedAt+ const tolerance = Math.max(SAME_COLUMN_MS, isFinite(span) ? span * 0.01 : 0)+ let column = 0+ sorted.forEach((item, index) => {+ if (index && item.startedAt - sorted[index - 1].startedAt > tolerance) {+ column+++ }+ const afterPrevious = edges+ .filter(([from, to]) => to === item.id && from in columnOf)+ .map(([from]) => columnOf[from] + 1)+ columnOf[item.id] = Math.max(column, ...afterPrevious)+ })+ return columnOf+}++export function workflowId(run: WorkflowRun): string {+ return run.runId === null ? run.workflow : jobCacheKey(run.runId, run.runAttempt, run.ciEngine)+}++/** What stays the same across the runs of one workflow. Two providers can run workflows with one display name. */+function workflowKey(run: WorkflowRun): string {+ return `${run.ciEngine ?? ''}:${run.workflowId ?? run.workflow}`+}++// A queued attempt has no start time yet, so two attempts of one run compare by attempt number. Two runs+// compare by start time, and a run that has not started is the newer one.+function isNewerRun(run: WorkflowRun, than: WorkflowRun): boolean {+ if (run.runId !== null && run.runId === than.runId) {+ return (run.runAttempt ?? 0) > (than.runAttempt ?? 0)+ }+ if (run.startedAt === null || than.startedAt === null) {+ return run.startedAt === null && than.startedAt !== null+ }+ return run.startedAt > than.startedAt+}++/** A re-run replaces the earlier attempt, as it does on GitHub's checks list. */+export function latestRunPerWorkflow(runs: WorkflowRun[]): WorkflowRun[] {+ const latest = new Map<string, WorkflowRun>()+ for (const run of runs) {+ const seen = latest.get(workflowKey(run))+ if (!seen || isNewerRun(run, seen)) {+ latest.set(workflowKey(run), run)+ }+ }+ return [...latest.values()]+}++/** The workflows of a push, failed first and then slowest first. */+export function buildWorkflows(runs: WorkflowRun[], jobsByRun: Record<string, WorkflowJobApi[]>): CIExplorerWorkflow[] {+ const longest = Math.max(0, ...runs.map((run) => run.durationSeconds ?? 0))+ return [...runs]+ .sort(+ (a, b) =>+ Number(statusOf(b.conclusion) === 'failure') - Number(statusOf(a.conclusion) === 'failure') ||+ (b.durationSeconds ?? 0) - (a.durationSeconds ?? 0)+ )+ .map((run): CIExplorerWorkflow => {+ const id = workflowId(run)+ const jobs = run.runId === null ? [] : jobsByRun[id]+ const items = jobs ? itemsOf(id, jobs) : null+ // An edge is a `needs` dependency from the workflow file, which is not synced yet.+ const edges: [string, string][] = []+ return {+ id,+ run,+ status: statusOf(run.conclusion),+ durationShare: share(run.durationSeconds, longest),+ items,+ edges,+ columnOf: items ? columnsOf(items, edges) : {},+ }+ })+}++const QUICK_STEP_SECONDS = 1+export const NO_STEPS: ReadonlySet<number> = new Set()+export const STEP_HEIGHT = 32+export const STEP_GAP = 4+/** Space above and below the step list inside a focused shard. */+export const SHARD_STEPS_PADDING = 14+const JOB_STEPS_MARGIN = 4++/** The steps worth a row. Quick steps that passed are left out, unless that leaves none. */+export function shownSteps(+ job: WorkflowJobApi,+ /** Numbers of the steps that the job's log has something to say about. Those are always shown. */+ badgedSteps: ReadonlySet<number> = NO_STEPS+): WorkflowJobStepApi[] {+ const notable = job.steps.filter(+ (step) =>+ (step.duration_seconds ?? 0) >= QUICK_STEP_SECONDS ||+ (step.conclusion ?? 'success') !== 'success' ||+ badgedSteps.has(step.number)+ )+ return notable.length ? notable : job.steps+}++function stepsHeight(job: WorkflowJobApi, badgedSteps: ReadonlySet<number>): number {+ const count = shownSteps(job, badgedSteps).length+ return count ? count * STEP_HEIGHT + (count - 1) * STEP_GAP : 0+}++/**+ * The space a node takes, known before it is drawn so the layout can run first.+ * A focused job shows its steps, so it is taller. A focused shard takes a grid row of its own.+ */+export function itemSize(+ item: CIExplorerItem,+ focusedNodeId: string | null = null,+ badgedSteps: ReadonlySet<number> = NO_STEPS+): { height: number; titleHeight: number; gridHeight: number; stepsHeight: number } {+ const titleHeight = 20 + Math.min(3, Math.ceil(item.name.length / TITLE_CHARS_PER_LINE)) * 17+ const jobSteps = item.job && focusedNodeId === item.id ? stepsHeight(item.job, badgedSteps) * INNER_SCALE : 0+ const focusedShard = item.shards.findIndex((shard) => shard.id === focusedNodeId)+ const rowHeights: number[] = []+ if (focusedShard === -1) {+ rowHeights.push(...Array(Math.ceil(item.shards.length / SHARDS_PER_ROW)).fill(SHARD_HEIGHT))+ } else {+ const shardSteps = stepsHeight(item.shards[focusedShard].job, badgedSteps)+ rowHeights.push(+ ...Array(Math.ceil(focusedShard / SHARDS_PER_ROW)).fill(SHARD_HEIGHT),+ SHARD_HEIGHT + (shardSteps ? shardSteps + SHARD_STEPS_PADDING : 0),+ ...Array(Math.ceil((item.shards.length - focusedShard - 1) / SHARDS_PER_ROW)).fill(SHARD_HEIGHT)+ )+ }+ const gridHeight =+ (rowHeights.reduce((sum, height) => sum + height, 0) + Math.max(0, rowHeights.length - 1) * SHARD_GAP) *+ INNER_SCALE+ return {+ gridHeight,+ titleHeight,+ stepsHeight: jobSteps,+ height:+ titleHeight ++ 2 ++ 10 ++ (rowHeights.length ? 12 + gridHeight : 0) ++ (jobSteps ? JOB_STEPS_MARGIN + jobSteps : 0),+ }+}++// Partitioning pins each node to the column `columnsOf` chose for it.+const ELK_OPTIONS = {+ 'elk.algorithm': 'layered',+ 'elk.direction': 'RIGHT',+ 'elk.edgeRouting': 'SPLINES',+ 'elk.partitioning.activate': 'true',+ 'elk.padding': '[top=0,left=0,bottom=0,right=0]',+ 'elk.spacing.nodeNode': '14',+ 'elk.spacing.edgeNode': '12',+ 'elk.spacing.edgeEdge': '8',+ 'elk.layered.spacing.nodeNodeBetweenLayers': '56',+ 'elk.layered.spacing.edgeNodeBetweenLayers': '14',+}++interface Point {+ x: number+ y: number+}++// ELK's spline route as SVG path data.+function wirePath(points: Point[]): string {+ let d = `M${points[0].x},${points[0].y}`+ for (let i = 1; i < points.length; ) {+ const left = points.length - i+ if (left >= 3) {+ d += ` C${points[i].x},${points[i].y} ${points[i + 1].x},${points[i + 1].y} ${points[i + 2].x},${points[i + 2].y}`+ } else if (left === 2) {+ d += ` Q${points[i].x},${points[i].y} ${points[i + 1].x},${points[i + 1].y}`+ } else {+ d += ` L${points[i].x},${points[i].y}`+ }+ i += Math.min(left, 3)+ }+ return d+}++export async function layoutWorkflow(+ elk: ELK,+ workflow: CIExplorerWorkflow,+ focusedNodeId: string | null = null,+ badgedSteps: ReadonlySet<number> = NO_STEPS+): Promise<CIExplorerLayout> {+ const items = workflow.items ?? []+ if (!items.length) {+ return { at: {}, width: NODE_WIDTH, height: 1, wires: [], ends: [] }+ }+ const graph: ElkNode = {+ id: 'root',+ layoutOptions: ELK_OPTIONS,+ children: items.map((item) => ({+ id: item.id,+ width: NODE_WIDTH,+ height: itemSize(item, focusedNodeId, badgedSteps).height,+ layoutOptions: { 'elk.partitioning.partition': String(workflow.columnOf[item.id]) },+ })),+ edges: workflow.edges.map(([from, to], index) => ({ id: `e${index}`, sources: [from], targets: [to] })),+ }+ const placed = await elk.layout(graph)+ const routes = (placed.edges ?? [])+ .flatMap((edge) => edge.sections ?? [])+ .map((section) => [section.startPoint, ...(section.bendPoints ?? []), section.endPoint])+ return {+ at: Object.fromEntries(+ (placed.children ?? []).map((child) => [child.id, { x: child.x ?? 0, y: child.y ?? 0 }])+ ),+ width: placed.width ?? NODE_WIDTH,+ height: placed.height ?? 1,+ wires: routes.map(wirePath),+ ends: routes.flatMap((points) => [points[0], points[points.length - 1]]),+ }+}++export const TILE_WIDTH = 300+// Tall enough for a workflow name that wraps to three lines.+export const TILE_HEIGHT = 134+/** The overview never shows smaller than this, so tile names stay readable. A long list pans instead. */+export const OVERVIEW_MIN_ZOOM = 0.8+export const TILE_GAP = 16+export const TILE_COLUMN_GAP = 56+/** The tiles hang off a rail that runs along the top and drops down the left of each column. */+export const RAIL_LEFT = 32+export const RAIL_TOP = 72++export function tileGridSize(columns: number, rows: number): { width: number; height: number } {+ return {+ width: RAIL_LEFT + columns * TILE_WIDTH + (columns - 1) * TILE_COLUMN_GAP,+ height: RAIL_TOP + rows * (TILE_HEIGHT + TILE_GAP) - TILE_GAP,+ }+}++/** How many rows of tiles show largest on a stage of this size. Tiles fill a column before the next starts. */+export function tileRows(count: number, stageWidth: number, stageHeight: number): number {+ let best = { rows: Math.max(1, count), scale: 0 }+ for (let columns = 1; columns <= count; columns++) {+ const rows = Math.ceil(count / columns)+ const size = tileGridSize(columns, rows)+ // More columns than fit at a readable zoom would push tiles off the side of the stage.+ if (columns > 1 && size.width * OVERVIEW_MIN_ZOOM > stageWidth) {+ break+ }+ const scale = Math.min(stageWidth / size.width, stageHeight / size.height)+ if (scale > best.scale + 1e-6) {+ best = { rows, scale }+ }+ }+ return best.rows+}++export interface CIExplorerFocusLevel {+ id: string+ name: string+ durationSeconds: number | null+}++/** What a node id names: a workflow, an item of it, or a shard of that item. */+export interface CIExplorerNode {+ workflow: CIExplorerWorkflow+ item: CIExplorerItem | null+ shard: CIExplorerShard | null+}++function contains(containerId: string, nodeId: string): boolean {+ return nodeId === containerId || nodeId.startsWith(`${containerId}/`)+}++/**+ * The node with this id and what contains it. A node id starts with the id of its container, so an id that+ * names nothing still resolves to the deepest container that exists.+ */+export function resolveNode(workflows: CIExplorerWorkflow[], nodeId: string | null): CIExplorerNode | null {+ const workflow = nodeId === null ? undefined : workflows.find((w) => contains(w.id, nodeId))+ if (!workflow || nodeId === null) {+ return null+ }+ const item = workflow.items?.find((i) => contains(i.id, nodeId)) ?? null+ return { workflow, item, shard: item?.shards.find((s) => s.id === nodeId) ?? null }+}++/** The jobs a node of the graph stands for: its one job, or every shard of a matrix. */+export function jobsOf(item: CIExplorerItem): WorkflowJobApi[] {+ return item.job ? [item.job] : item.shards.map((shard) => shard.job)+}++export function workflowJobs(workflow: CIExplorerWorkflow): WorkflowJobApi[] {+ return (workflow.items ?? []).flatMap(jobsOf)+}++/** The focused node and what contains it, outermost first. */+export function focusPath(workflows: CIExplorerWorkflow[], nodeId: string | null): CIExplorerFocusLevel[] {+ const node = resolveNode(workflows, nodeId)+ if (!node) {+ return []+ }+ const { workflow, item, shard } = node+ const path = [{ id: workflow.id, name: workflow.run.workflow, durationSeconds: workflow.run.durationSeconds }]+ if (item) {+ path.push({ id: item.id, name: item.name, durationSeconds: item.durationSeconds })+ }+ if (shard) {+ path.push({ id: shard.id, name: shard.label, durationSeconds: shard.job.duration_seconds })+ }+ return path+}++/** The job a focused node stands for: a single job, or one shard of a matrix. */+export function focusedJob(+ workflows: CIExplorerWorkflow[],+ nodeId: string | null+): { job: WorkflowJobApi; run: WorkflowRun } | null {+ const node = resolveNode(workflows, nodeId)+ const job = node?.shard?.job ?? (node?.item?.id === nodeId ? node.item.job : null)+ return node && job ? { job, run: node.workflow.run } : null+}diff --git a/products/engineering_analytics/frontend/lib/github.ts b/products/engineering_analytics/frontend/lib/github.tsindex 34a53f24614a..50ddbf282313 100644--- a/products/engineering_analytics/frontend/lib/github.ts+++ b/products/engineering_analytics/frontend/lib/github.ts@@ -11,6 +11,17 @@ export function githubRunUrl(repoOwner: string, repoName: string, runId: number)return `https://github.com/${repoOwner}/${repoName}/actions/runs/${runId}`}+/** A job's log page. With a step number, the page opens at the first line of that step. */+export function githubJobUrl(+ repoOwner: string,+ repoName: string,+ runId: number,+ jobId: number,+ stepNumber?: number | null+): string {+ return `${githubRunUrl(repoOwner, repoName, runId)}/job/${jobId}${stepNumber == null ? '' : `#step:${stepNumber}:1`}`+}+export function githubCommitUrl(repoOwner: string, repoName: string, sha: string): string {return `https://github.com/${repoOwner}/${repoName}/commit/${sha}`}diff --git a/products/engineering_analytics/frontend/lib/lifecycle.ts b/products/engineering_analytics/frontend/lib/lifecycle.tsindex 6b3d189af753..fab2eaa1ee1f 100644--- a/products/engineering_analytics/frontend/lib/lifecycle.ts+++ b/products/engineering_analytics/frontend/lib/lifecycle.ts@@ -3,6 +3,10 @@ import type { PRLifecycleEventApi, WorkflowRunDetailApi } from '../generated/apiexport interface WorkflowRun {ciEngine?: WorkflowRunDetailApi['ci_engine']workflow: string+ /** GitHub's id of the workflow, which survives a rename. Null for Depot CI and for rows synced without it. */+ workflowId?: number | null+ /** What started the run: 'push', 'pull_request', 'schedule'. Null when unknown. */+ event?: string | null/** Null while the run hasn't reported a finish — queued or in progress. */conclusion: string | nullstartedAt: string | nulldiff --git a/products/engineering_analytics/frontend/scenes/ciExplorerContextLogic.test.ts b/products/engineering_analytics/frontend/scenes/ciExplorerContextLogic.test.tsnew file mode 100644index 000000000000..e4fc5dc9a330--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/ciExplorerContextLogic.test.ts@@ -0,0 +1,184 @@+import { expectLogic } from 'kea-test-utils'++import { ApiConfig } from 'lib/api'++import { initKeaTests } from '~/test/init'++import {+ engineeringAnalyticsCiDataFreshness,+ engineeringAnalyticsCiTimingContext,+ engineeringAnalyticsPrLifecycle,+ engineeringAnalyticsPrRuns,+ engineeringAnalyticsWorkflowJobs,+} from '../generated/api'+import type { CITimingContextApi, WorkflowJobApi, WorkflowRunDetailApi } from '../generated/api.schemas'+import { ciExplorerContextLogic } from './ciExplorerContextLogic'+import { ciExplorerLogic } from './ciExplorerLogic'++jest.mock('../generated/api', () => ({+ engineeringAnalyticsCiDataFreshness: jest.fn(),+ engineeringAnalyticsCiFailureLogs: jest.fn(),+ engineeringAnalyticsCiTimingContext: jest.fn(),+ engineeringAnalyticsJobLogInsights: jest.fn(),+ engineeringAnalyticsPrLifecycle: jest.fn(),+ engineeringAnalyticsPrRuns: jest.fn(),+ engineeringAnalyticsWorkflowJobs: jest.fn(),+}))+jest.mock('lib/elk', () => ({+ getElk: async () => ({ layout: async (graph: unknown) => graph }),+}))++const mockContext = engineeringAnalyticsCiTimingContext as jest.MockedFunction<+ typeof engineeringAnalyticsCiTimingContext+>+const mockRuns = engineeringAnalyticsPrRuns as jest.MockedFunction<typeof engineeringAnalyticsPrRuns>+const mockJobs = engineeringAnalyticsWorkflowJobs as jest.MockedFunction<typeof engineeringAnalyticsWorkflowJobs>++const PROPS = { repoOwner: 'PostHog', repoName: 'posthog', number: 10, sourceId: null }+const WORKFLOW = 'github_actions:42:1'+const LINT = `${WORKFLOW}/Lint`+const BUILD = `${WORKFLOW}/Build`++const RUN: WorkflowRunDetailApi = {+ repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },+ id: 42,+ workflow_name: 'CI',+ workflow_id: 7,+ ci_engine: 'github_actions',+ head_sha: 'abc123',+ head_branch: 'feature',+ status: 'completed',+ conclusion: 'success',+ run_started_at: '2026-06-01T00:00:00Z',+ updated_at: '2026-06-01T00:05:00Z',+ duration_seconds: 300,+ run_attempt: 1,+ pr_number: 10,+ commit_pr_number: null,+ is_merge_queue: false,+}++function job(id: number, name: string): WorkflowJobApi {+ return {+ id,+ run_id: 42,+ name,+ status: 'completed',+ conclusion: 'success',+ started_at: '2026-06-01T00:00:00Z',+ completed_at: '2026-06-01T00:02:00Z',+ duration_seconds: 120,+ runner_provider: 'self_hosted',+ runner_label: 'depot-ubuntu-latest',+ estimated_cost_usd: null,+ ci_engine: 'github_actions',+ steps: [],+ }+}++function answer(averageSeconds: number): CITimingContextApi {+ return {+ default_branch: 'master',+ window_days: 7,+ identity: 'workflow_id',+ runs_scanned: 12,+ sampled: false,+ sample_count: 9,+ average_seconds: averageSeconds,+ recent: [],+ runs_synced_at: '2026-06-01T00:10:00Z',+ jobs_synced_at: '2026-06-01T00:10:00Z',+ unavailable_reason: null,+ }+}++function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolve: (value: T) => void = () => {}+ const promise = new Promise<T>((r) => (resolve = r))+ return { promise, resolve }+}++describe('ciExplorerContextLogic', () => {+ let explorer: ReturnType<typeof ciExplorerLogic.build>+ let logic: ReturnType<typeof ciExplorerContextLogic.build>++ beforeEach(async () => {+ localStorage.clear()+ initKeaTests()+ ApiConfig.setCurrentProjectId(1)+ jest.clearAllMocks()+ ;(engineeringAnalyticsPrLifecycle as jest.Mock).mockResolvedValue(null)+ ;(engineeringAnalyticsCiDataFreshness as jest.Mock).mockResolvedValue(null)+ mockRuns.mockResolvedValue([RUN])+ mockJobs.mockResolvedValue([job(1, 'Lint'), job(2, 'Build')])+ explorer = ciExplorerLogic(PROPS)+ explorer.mount()+ logic = ciExplorerContextLogic(PROPS)+ logic.mount()+ await expectLogic(explorer).toDispatchActions(['loadLayoutsSuccess'])+ })++ afterEach(() => {+ logic?.unmount()+ explorer?.unmount()+ })++ it('asks for nothing until the Context tab is open', async () => {+ explorer.actions.setFocus(LINT)+ explorer.actions.openDrawer('details')+ explorer.actions.setFocus(BUILD)+ await expectLogic(logic).toFinishAllListeners()++ expect(mockContext).not.toHaveBeenCalled()++ mockContext.mockResolvedValue(answer(100))+ explorer.actions.openDrawer('context')+ await expectLogic(logic).toDispatchActions(['loadAnswerSuccess'])++ expect(mockContext).toHaveBeenCalledTimes(1)+ expect(mockContext.mock.calls[0][1]).toMatchObject({ kind: 'job', job_ids: '2', run_id: 42, run_attempt: 1 })+ })++ it('cancels the request for a selection the person left, and never shows its late answer', async () => {+ const first = deferred<CITimingContextApi>()+ const second = deferred<CITimingContextApi>()+ mockContext.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)++ // The logic waits for the selection to settle before it asks, so the test owns that clock.+ jest.useFakeTimers()+ try {+ explorer.actions.setFocus(LINT)+ explorer.actions.openDrawer('context')+ await jest.advanceTimersByTimeAsync(1000)+ explorer.actions.setFocus(BUILD)+ await jest.advanceTimersByTimeAsync(1000)++ expect(mockContext).toHaveBeenCalledTimes(2)+ expect((mockContext.mock.calls[0][2] as RequestInit).signal?.aborted).toBe(true)+ expect((mockContext.mock.calls[1][2] as RequestInit).signal?.aborted).toBe(false)++ first.resolve(answer(1))+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.context).toBeNull()++ second.resolve(answer(100))+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.context).toMatchObject({ average_seconds: 100 })+ } finally {+ jest.useRealTimers()+ }+ })++ it('reports a failed request and asks again on retry', async () => {+ mockContext.mockRejectedValueOnce(new Error('boom')).mockResolvedValueOnce(answer(100))++ explorer.actions.setFocus(LINT)+ explorer.actions.openDrawer('context')+ await expectLogic(logic).toDispatchActions(['loadAnswerFailure'])+ expect(logic.values).toMatchObject({ failed: true, context: null })++ logic.actions.retry()+ await expectLogic(logic).toDispatchActions(['loadAnswerSuccess'])+ expect(logic.values).toMatchObject({ failed: false, context: { average_seconds: 100 } })+ })+})diff --git a/products/engineering_analytics/frontend/scenes/ciExplorerContextLogic.ts b/products/engineering_analytics/frontend/scenes/ciExplorerContextLogic.tsnew file mode 100644index 000000000000..0e6ee2c48cc0--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/ciExplorerContextLogic.ts@@ -0,0 +1,310 @@+import {+ MakeLogicType,+ actions,+ afterMount,+ beforeUnmount,+ connect,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { ApiConfig } from 'lib/api'++import { engineeringAnalyticsCiTimingContext } from '../generated/api'+import type { CITimingContextApi } from '../generated/api.schemas'+import { CIContextSelection, contextSelection } from '../lib/ciExplorerContext'+import type { CIExplorerWorkflow } from '../lib/ciExplorerGraph'+import { CIExplorerDrawerTab, CIExplorerLogicProps, CIExplorerView, ciExplorerLogic } from './ciExplorerLogic'++const projectId = (): string => String(ApiConfig.getCurrentProjectId())++// The server keeps an answer for the same time, so asking again sooner returns the same numbers.+const ANSWER_TTL_MS = 5 * 60 * 1000+const ANSWERS_KEPT = 24+// A pass over several nodes on the way to one asks for the last node only.+const SETTLE_MS = 150+const STEP_HOVER_MS = 600+// pinned: analytics event names. Renaming one breaks the insights built on it.+const EVENT_LOADED = 'ci explorer timing context loaded'+const EVENT_FAILED = 'ci explorer timing context failed'++/** An answer and the selection it describes. The pair is what keeps a late answer off a newer selection. */+export interface CIContextAnswer {+ key: string+ context: CITimingContextApi+}++interface KeptAnswer {+ expires: number+ context: CITimingContextApi+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface ciExplorerContextLogicValues {+ drawerOpen: boolean // ciExplorerLogic+ drawerTab: CIExplorerDrawerTab // ciExplorerLogic+ focusedNodeId: string | null // ciExplorerLogic+ view: CIExplorerView // ciExplorerLogic+ workflows: CIExplorerWorkflow[] // ciExplorerLogic+ active: boolean+ answer: CIContextAnswer | null+ answerLoading: boolean+ context: CITimingContextApi | null+ failed: boolean+ selection: CIContextSelection | null+ stepNumber: number | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface ciExplorerContextLogicActions {+ closeDrawer: () => {+ value: true+ } // ciExplorerLogic+ loadJobsSuccess: (+ jobsByRun: Record<string, import('../generated/api.schemas').WorkflowJobApi[]>,+ payload?: import('../lib/lifecycle').WorkflowRun[] | undefined+ ) => {+ jobsByRun: Record<string, import('../generated/api.schemas').WorkflowJobApi[]>+ payload?: import('../lib/lifecycle').WorkflowRun[]+ } // ciExplorerLogic+ openDrawer: (tab: CIExplorerDrawerTab) => {+ tab: CIExplorerDrawerTab+ } // ciExplorerLogic+ setFocus: (+ nodeId: string | null,+ moveCamera?: boolean | undefined+ ) => {+ moveCamera: boolean+ nodeId: string | null+ } // ciExplorerLogic+ setLocation: (location: import('./ciExplorerLogic').CIExplorerLocation) => {+ location: import('./ciExplorerLogic').CIExplorerLocation+ } // ciExplorerLogic+ setView: (view: CIExplorerView) => {+ view: CIExplorerView+ } // ciExplorerLogic+ hoverStep: (stepNumber: number | null) => {+ stepNumber: number | null+ }+ loadAnswer: (selection: CIContextSelection) => CIContextSelection+ loadAnswerFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAnswerSuccess: (+ answer: CIContextAnswer | null,+ payload?: CIContextSelection+ ) => {+ answer: CIContextAnswer | null+ payload?: CIContextSelection+ }+ retry: () => {+ value: true+ }+ selectStep: (stepNumber: number | null) => {+ stepNumber: number | null+ }+ sync: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface ciExplorerContextLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ active: (drawerOpen: boolean, drawerTab: CIExplorerDrawerTab, view: CIExplorerView) => boolean+ selection: (+ workflows: CIExplorerWorkflow[],+ focusedNodeId: string | null,+ stepNumber: number | null+ ) => CIContextSelection | null+ context: (answer: CIContextAnswer | null, selection: CIContextSelection | null) => CITimingContextApi | null+ }+}++export type ciExplorerContextLogicType = MakeLogicType<+ ciExplorerContextLogicValues,+ ciExplorerContextLogicActions,+ CIExplorerLogicProps,+ ciExplorerContextLogicMeta+>++/** The Context tab's data. It asks for nothing until the tab is open, and one request at a time after that. */+export const ciExplorerContextLogic = kea<ciExplorerContextLogicType>([+ path(['products', 'engineering_analytics', 'frontend', 'scenes', 'ciExplorerContextLogic']),+ props({} as CIExplorerLogicProps),+ key((props) => `${props.repoOwner}/${props.repoName}#${props.number}@${props.sourceId ?? ''}`),+ connect((props: CIExplorerLogicProps) => ({+ values: [ciExplorerLogic(props), ['workflows', 'focusedNodeId', 'drawerOpen', 'drawerTab', 'view']],+ actions: [+ ciExplorerLogic(props),+ ['setFocus', 'setLocation', 'setView', 'openDrawer', 'closeDrawer', 'loadJobsSuccess'],+ ],+ })),++ actions({+ selectStep: (stepNumber: number | null) => ({ stepNumber }),+ // Null when the pointer leaves the step it was on.+ hoverStep: (stepNumber: number | null) => ({ stepNumber }),+ retry: true,+ sync: true,+ }),++ loaders(({ props, values, cache }) => ({+ answer: [+ null as CIContextAnswer | null,+ {+ loadAnswer: async (selection: CIContextSelection, breakpoint): Promise<CIContextAnswer | null> => {+ const answers: Map<string, KeptAnswer> = (cache.answers ??= new Map())+ const kept = answers.get(selection.key)+ if (kept && kept.expires > Date.now()) {+ return { key: selection.key, context: kept.context }+ }+ await breakpoint(SETTLE_MS)+ const controller = new AbortController()+ cache.controller = controller+ try {+ const context = await engineeringAnalyticsCiTimingContext(+ projectId(),+ {+ repo: `${props.repoOwner}/${props.repoName}`,+ source_id: props.sourceId ?? undefined,+ ci_engine: selection.engine,+ run_id: selection.runId,+ run_attempt: selection.runAttempt,+ kind: selection.kind,+ job_ids: selection.jobIds.length ? selection.jobIds.join(',') : undefined,+ step_number: selection.stepNumber ?? undefined,+ },+ { signal: controller.signal }+ )+ breakpoint()+ if (answers.size >= ANSWERS_KEPT) {+ answers.delete(answers.keys().next().value as string)+ }+ answers.set(selection.key, { expires: Date.now() + ANSWER_TTL_MS, context })+ return { key: selection.key, context }+ } catch (error) {+ // A cancelled request is not a failure. The tab was closed, or a newer selection replaced it.+ if (controller.signal.aborted) {+ breakpoint()+ return values.answer+ }+ throw error+ }+ },+ },+ ],+ })),++ reducers({+ stepNumber: [+ null as number | null,+ {+ selectStep: (_, { stepNumber }) => stepNumber,+ setFocus: () => null,+ setLocation: () => null,+ },+ ],+ failed: [+ false,+ {+ loadAnswer: () => false,+ loadAnswerFailure: () => true,+ },+ ],+ }),++ selectors({+ active: [+ (s) => [s.drawerOpen, s.drawerTab, s.view],+ (drawerOpen: boolean, drawerTab: CIExplorerDrawerTab, view: CIExplorerView): boolean =>+ drawerOpen && drawerTab === 'context' && view === 'overview',+ ],+ selection: [+ (s) => [s.workflows, s.focusedNodeId, s.stepNumber],+ (+ workflows: CIExplorerWorkflow[],+ focusedNodeId: string | null,+ stepNumber: number | null+ ): CIContextSelection | null => contextSelection(workflows, focusedNodeId, stepNumber),+ ],+ // Null while the answer on hand describes another selection.+ context: [+ (s) => [s.answer, s.selection],+ (answer: CIContextAnswer | null, selection: CIContextSelection | null): CITimingContextApi | null =>+ answer && selection && answer.key === selection.key ? answer.context : null,+ ],+ }),++ listeners(({ actions, values, cache }) => {+ const ask = (): void => {+ cache.controller?.abort()+ if (values.active && values.selection) {+ actions.loadAnswer(values.selection)+ }+ }+ return {+ sync: ask,+ openDrawer: ask,+ closeDrawer: ask,+ setView: ask,+ setFocus: ask,+ setLocation: ask,+ selectStep: ask,+ // A selection restored from a link has nothing to compare until its jobs arrive.+ loadJobsSuccess: () => {+ if (values.active && values.selection && values.context === null && !values.answerLoading) {+ ask()+ }+ },+ hoverStep: async ({ stepNumber }, breakpoint) => {+ // The wait ends early when the pointer moves to another step or leaves, so only a rest selects.+ await breakpoint(STEP_HOVER_MS)+ if (stepNumber !== null && values.active && values.stepNumber !== stepNumber) {+ actions.selectStep(stepNumber)+ }+ },+ loadAnswerSuccess: ({ answer, payload }) => {+ // A cancelled request hands back the earlier answer, which was counted when it arrived.+ if (answer && payload && answer.key === payload.key) {+ posthog.capture(EVENT_LOADED, {+ kind: payload.kind,+ engine: payload.engine,+ sample_count: answer.context.sample_count,+ unavailable_reason: answer.context.unavailable_reason,+ })+ }+ },+ loadAnswerFailure: () => {+ posthog.capture(EVENT_FAILED, { kind: values.selection?.kind })+ },+ retry: () => {+ if (values.selection) {+ cache.answers?.delete(values.selection.key)+ }+ ask()+ },+ }+ }),++ // The drawer can mount with the tab already open and a selection already made.+ afterMount(({ actions }) => {+ actions.sync()+ }),++ beforeUnmount(({ cache }) => {+ cache.controller?.abort()+ }),+])diff --git a/products/engineering_analytics/frontend/scenes/ciExplorerLogic.test.ts b/products/engineering_analytics/frontend/scenes/ciExplorerLogic.test.tsnew file mode 100644index 000000000000..f930e401e81e--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/ciExplorerLogic.test.ts@@ -0,0 +1,137 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { ApiConfig } from 'lib/api'++import { initKeaTests } from '~/test/init'++import {+ engineeringAnalyticsCiDataFreshness,+ engineeringAnalyticsJobLogInsights,+ engineeringAnalyticsPrLifecycle,+ engineeringAnalyticsPrRuns,+ engineeringAnalyticsWorkflowJobs,+} from '../generated/api'+import type { WorkflowJobApi, WorkflowRunDetailApi } from '../generated/api.schemas'+import { ciExplorerLogic } from './ciExplorerLogic'++jest.mock('../generated/api', () => ({+ engineeringAnalyticsCiDataFreshness: jest.fn(),+ engineeringAnalyticsCiFailureLogs: jest.fn(),+ engineeringAnalyticsJobLogInsights: jest.fn(),+ engineeringAnalyticsPrLifecycle: jest.fn(),+ engineeringAnalyticsPrRuns: jest.fn(),+ engineeringAnalyticsWorkflowJobs: jest.fn(),+}))+jest.mock('lib/elk', () => ({+ getElk: async () => ({ layout: async (graph: unknown) => graph }),+}))++const mockInsights = engineeringAnalyticsJobLogInsights as jest.MockedFunction<+ typeof engineeringAnalyticsJobLogInsights+>++const PROPS = { repoOwner: 'PostHog', repoName: 'posthog', number: 10, sourceId: null }+const PAGE = '/engineering-analytics/repos/PostHog/posthog/pull-requests/10/ci-explorer'+const LINT = 'github_actions:42:1/Lint'++const RUN: WorkflowRunDetailApi = {+ repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },+ id: 42,+ workflow_name: 'CI',+ workflow_id: 7,+ ci_engine: 'github_actions',+ head_sha: 'abc123',+ head_branch: 'feature',+ status: 'completed',+ conclusion: 'success',+ run_started_at: '2026-06-01T00:00:00Z',+ updated_at: '2026-06-01T00:05:00Z',+ duration_seconds: 300,+ run_attempt: 1,+ pr_number: 10,+ commit_pr_number: null,+ is_merge_queue: false,+}++const LINT_JOB: WorkflowJobApi = {+ id: 1,+ run_id: 42,+ name: 'Lint',+ status: 'completed',+ conclusion: 'success',+ started_at: '2026-06-01T00:00:00Z',+ completed_at: '2026-06-01T00:02:00Z',+ duration_seconds: 120,+ runner_provider: 'self_hosted',+ runner_label: 'depot-ubuntu-latest',+ estimated_cost_usd: null,+ ci_engine: 'github_actions',+ steps: [],+}++describe('ciExplorerLogic', () => {+ let logic: ReturnType<typeof ciExplorerLogic.build>+ let capture: jest.SpyInstance++ const open = (search: string): void => {+ router.actions.push(`${PAGE}${search}`)+ logic = ciExplorerLogic(PROPS)+ logic.mount()+ }+ const viewedEvents = (): unknown[] =>+ capture.mock.calls.filter(([event]) => event === 'ci explorer viewed').map(([, properties]) => properties)++ beforeEach(() => {+ localStorage.clear()+ initKeaTests()+ ApiConfig.setCurrentProjectId(1)+ jest.clearAllMocks()+ capture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)+ ;(engineeringAnalyticsPrLifecycle as jest.Mock).mockResolvedValue(null)+ ;(engineeringAnalyticsCiDataFreshness as jest.Mock).mockResolvedValue(null)+ ;(engineeringAnalyticsPrRuns as jest.Mock).mockResolvedValue([RUN])+ ;(engineeringAnalyticsWorkflowJobs as jest.Mock).mockResolvedValue([LINT_JOB])+ mockInsights.mockResolvedValue({+ log_read: true,+ attributed_to_steps: true,+ job: [],+ steps: [],+ log_truncated: false,+ })+ })++ afterEach(() => {+ logic?.unmount()+ capture.mockRestore()+ })++ 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 a commit', '?sha=def456', { view: 'overview', older_commit: true }],+ ])('captures one viewed event when %s opens', (_, search, properties) => {+ open(search)++ expect(viewedEvents()).toEqual([properties])+ })++ it('captures a viewed event when the view changes without a link', () => {+ open('')+ logic.actions.setView('activity')++ expect(viewedEvents()).toEqual([+ { view: 'overview', older_commit: false },+ { view: 'activity', older_commit: false },+ ])+ })++ it('reads the log of a job that a link focused before the jobs arrived', async () => {+ open(`?node=${encodeURIComponent(LINT)}`)+ await expectLogic(logic).toDispatchActions(['loadJobInsightsSuccess'])++ expect(mockInsights).toHaveBeenCalledTimes(1)+ expect(mockInsights.mock.calls[0][1]).toMatchObject({ run_id: 42, job_id: 1 })+ })+})diff --git a/products/engineering_analytics/frontend/scenes/ciExplorerLogic.ts b/products/engineering_analytics/frontend/scenes/ciExplorerLogic.tsnew file mode 100644index 000000000000..3b027548e2cf--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/ciExplorerLogic.ts@@ -0,0 +1,1021 @@+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'+import posthog from 'posthog-js'++import { ApiConfig } from 'lib/api'+import { getElk } from 'lib/elk'+import { urls } from 'scenes/urls'++import { Breadcrumb } from '~/types'++import {+ engineeringAnalyticsCiDataFreshness,+ engineeringAnalyticsCiFailureLogs,+ engineeringAnalyticsJobLogInsights,+ engineeringAnalyticsPrLifecycle,+ engineeringAnalyticsPrRuns,+ engineeringAnalyticsWorkflowJobs,+} from '../generated/api'+import type {+ CIDataFreshnessApi,+ CIFailureLogsApi,+ CIJobFailureLogApi,+ JobLogInsightsApi,+ PRLifecycleApi,+ WorkflowJobApi,+ WorkflowRunDetailApi,+} from '../generated/api.schemas'+import type { CIEngineEnumApi } from '../generated/api.schemas'+import { CIActivityCommit, CIActivityDay, activityDays, commitRows } from '../lib/ciExplorerActivity'+import {+ CIExplorerShareLevel,+ CIExplorerSummary,+ oldestSync,+ shareLevels,+ summarize,+ totalJobSeconds,+} from '../lib/ciExplorerDetails'+import {+ CIExplorerFocusLevel,+ CIExplorerLayout,+ CIExplorerWorkflow,+ buildWorkflows,+ focusPath,+ focusedJob,+ latestRunPerWorkflow,+ layoutWorkflow,+} from '../lib/ciExplorerGraph'+import { jobCacheKey } from '../lib/jobs'+import { WorkflowRun, isDecisiveFailure } from '../lib/lifecycle'+import { pushRoundOf } from '../lib/pushRounds'+import { withScope } from '../lib/scope'+import { PrCommitRuns, groupRunsByCommit } from './pullRequestDetailLogic'++const projectId = (): string => String(ApiConfig.getCurrentProjectId())++export interface CIExplorerLogicProps {+ repoOwner: string+ repoName: string+ number: number+ sourceId: string | null+}++export type CIExplorerView = 'overview' | 'activity'+export type CIExplorerDrawerTab = 'details' | 'context'++/** Where the person is in the explorer. The URL holds the same three facts. */+export interface CIExplorerLocation {+ view: CIExplorerView+ /** Null follows the newest push. */+ headSha: string | null+ nodeId: string | null+}++/** A request to move the camera. A focus change that follows the camera, such as a zoom out, makes none. */+export interface CIExplorerCameraRequest {+ sequence: number+ /** Fit shows the whole selection, however small that makes its text. */+ fit: boolean+}++// pinned: URL search params. Renaming one breaks shared links.+const VIEW_PARAM = 'view'+const SHA_PARAM = 'sha'+const NODE_PARAM = 'node'+// pinned: analytics event names. Renaming one breaks the insights built on it.+const EVENT_VIEWED = 'ci explorer viewed'+const EVENT_DRAWER_OPENED = 'ci explorer drawer opened'+const EVENT_REFRESHED = 'ci explorer refreshed'+const CI_EXPLORER_PATH_END = '/ci-explorer'+const CI_EXPLORER_ROUTE = `/engineering-analytics/repos/:repoOwner/:repoName/pull-requests/:number${CI_EXPLORER_PATH_END}`++/** The search params that put the explorer at `location`, keeping every param that is not the explorer's own. */+function 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],+ [SHA_PARAM, location.headSha],+ [NODE_PARAM, location.nodeId],+ ]+ for (const [param, value] of own) {+ if (value === null) {+ delete searchParams[param]+ } else {+ searchParams[param] = value+ }+ }+ return searchParams+}++function jobInsightsKey(job: WorkflowJobApi): string {+ return `${job.ci_engine ?? ''}:${job.run_id}:${job.id}`+}++function viewedProperties(view: CIExplorerView, selectedHeadSha: string | null): Record<string, unknown> {+ return { view, older_commit: selectedHeadSha !== null }+}++function runJobsKey(run: WorkflowRun): string | null {+ return run.runId === null ? null : jobCacheKey(run.runId, run.runAttempt, run.ciEngine)+}++function workflowsOfNodes(workflows: CIExplorerWorkflow[], nodeIds: (string | null)[]): CIExplorerWorkflow[] {+ return workflows.filter(+ (workflow) =>+ workflow.items !== null && nodeIds.some((id) => id !== null && `${id}/`.startsWith(`${workflow.id}/`))+ )+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface ciExplorerLogicValues {+ activePush: PrCommitRuns | null+ activity: CIActivityDay[]+ breadcrumbs: Breadcrumb[]+ cameraRequest: CIExplorerCameraRequest+ commits: CIActivityCommit[]+ currentHeadSha: string | null+ currentView: CIExplorerView+ drawerOpen: boolean+ drawerTab: CIExplorerDrawerTab+ failedJobRuns: WorkflowRun[]+ failureLogs: CIFailureLogsApi | null+ failureLogsFailed: boolean+ failureLogsLoading: boolean+ focusLevels: CIExplorerFocusLevel[]+ focusedBadgedSteps: ReadonlySet<number>+ focusedJob: {+ job: WorkflowJobApi+ run: WorkflowRun+ } | null+ focusedJobFailure: CIJobFailureLogApi | null+ focusedJobInsights: JobLogInsightsApi | null+ focusedNodeId: string | null+ freshness: CIDataFreshnessApi | null+ freshnessLoading: boolean+ jobInsights: Record<string, JobLogInsightsApi>+ jobInsightsLoading: boolean+ jobTimeOpen: boolean+ jobsByRun: Record<string, WorkflowJobApi[]>+ jobsByRunLoading: boolean+ layouts: Record<string, CIExplorerLayout>+ layoutsLoading: boolean+ lifecycle: PRLifecycleApi | null+ lifecycleLoading: boolean+ loadFailed: boolean+ locationUrl: (target: CIExplorerLocation) => string+ logicProps: CIExplorerLogicProps+ onOlderCommit: boolean+ prRuns: WorkflowRunDetailApi[] | null+ prRunsLoading: boolean+ pullRequestUrl: string+ pushDurationSeconds: number | null+ pushes: PrCommitRuns[]+ refreshing: boolean+ repoName: string+ repoOwner: string+ selectedHeadSha: string | null+ shareLevels: CIExplorerShareLevel[]+ sourceId: string | null+ summary: CIExplorerSummary+ syncedAt: string | null+ totalJobSeconds: number+ view: CIExplorerView+ workflowRunUrl: (runId: number, ciEngine: CIEngineEnumApi | null | undefined) => string+ workflowRuns: WorkflowRun[]+ workflows: CIExplorerWorkflow[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface ciExplorerLogicActions {+ closeDrawer: () => {+ value: true+ }+ fitView: () => {+ value: true+ }+ loadFailureLogs: () => any+ loadFailureLogsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadFailureLogsSuccess: (+ failureLogs: CIFailureLogsApi | null,+ payload?: any+ ) => {+ failureLogs: CIFailureLogsApi | null+ payload?: any+ }+ loadFreshness: () => any+ loadFreshnessFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadFreshnessSuccess: (+ freshness: CIDataFreshnessApi | null,+ payload?: any+ ) => {+ freshness: CIDataFreshnessApi | null+ payload?: any+ }+ loadJobInsights: (job: WorkflowJobApi) => WorkflowJobApi+ loadJobInsightsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadJobInsightsSuccess: (+ jobInsights: Record<string, JobLogInsightsApi>,+ payload?: WorkflowJobApi+ ) => {+ jobInsights: Record<string, JobLogInsightsApi>+ payload?: WorkflowJobApi+ }+ loadJobs: (runs: WorkflowRun[]) => WorkflowRun[]+ loadJobsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadJobsSuccess: (+ jobsByRun: Record<string, WorkflowJobApi[]>,+ payload?: WorkflowRun[]+ ) => {+ jobsByRun: Record<string, WorkflowJobApi[]>+ payload?: WorkflowRun[]+ }+ loadLayouts: (workflows: CIExplorerWorkflow[]) => CIExplorerWorkflow[]+ loadLayoutsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadLayoutsSuccess: (+ layouts: Record<string, CIExplorerLayout>,+ payload?: CIExplorerWorkflow[]+ ) => {+ layouts: Record<string, CIExplorerLayout>+ payload?: CIExplorerWorkflow[]+ }+ loadLifecycle: () => any+ loadLifecycleFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadLifecycleSuccess: (+ lifecycle: PRLifecycleApi | null,+ payload?: any+ ) => {+ lifecycle: PRLifecycleApi | null+ payload?: any+ }+ loadPrRuns: () => any+ loadPrRunsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadPrRunsSuccess: (+ prRuns: WorkflowRunDetailApi[],+ payload?: any+ ) => {+ prRuns: WorkflowRunDetailApi[]+ payload?: any+ }+ openDrawer: (tab: CIExplorerDrawerTab) => {+ tab: CIExplorerDrawerTab+ }+ refresh: () => {+ value: true+ }+ retryFailedJobs: () => {+ value: true+ }+ setFailedJobRuns: (+ asked: WorkflowRun[],+ failed: WorkflowRun[]+ ) => {+ asked: WorkflowRun[]+ failed: WorkflowRun[]+ }+ setFocus: (+ nodeId: string | null,+ moveCamera?: boolean+ ) => {+ moveCamera: boolean+ nodeId: string | null+ }+ setLocation: (location: CIExplorerLocation) => {+ location: CIExplorerLocation+ }+ setView: (view: CIExplorerView) => {+ view: CIExplorerView+ }+ toggleJobTime: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface ciExplorerLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ logicProps: (arg: CIExplorerLogicProps) => CIExplorerLogicProps+ repoOwner: (arg: string) => string+ repoName: (arg: string) => string+ sourceId: (arg: string | null) => string | null+ pushes: (prRuns: WorkflowRunDetailApi[] | null) => PrCommitRuns[]+ commits: (prRuns: WorkflowRunDetailApi[] | null) => CIActivityCommit[]+ currentHeadSha: (commits: CIActivityCommit[]) => string | null+ activePush: (+ pushes: PrCommitRuns[],+ selectedHeadSha: string | null,+ currentHeadSha: string | null+ ) => PrCommitRuns | null+ onOlderCommit: (selectedHeadSha: string | null, currentHeadSha: string | null) => boolean+ currentView: (view: CIExplorerView, onOlderCommit: boolean) => CIExplorerView+ workflowRunUrl: (+ repoOwner: string,+ repoName: string,+ sourceId: string | null,+ searchParams: Record<string, any>+ ) => (runId: number, ciEngine: CIEngineEnumApi | null | undefined) => string+ locationUrl: (+ location: {+ hash: string+ pathname: string+ search: string+ },+ searchParams: Record<string, any>+ ) => (target: CIExplorerLocation) => string+ workflowRuns: (activePush: PrCommitRuns | null) => WorkflowRun[]+ workflows: (workflowRuns: WorkflowRun[], jobsByRun: Record<string, WorkflowJobApi[]>) => CIExplorerWorkflow[]+ summary: (workflows: CIExplorerWorkflow[]) => CIExplorerSummary+ activity: (lifecycle: PRLifecycleApi | null, commits: CIActivityCommit[]) => CIActivityDay[]+ syncedAt: (freshness: CIDataFreshnessApi | null) => string | null+ totalJobSeconds: (workflows: CIExplorerWorkflow[]) => number+ shareLevels: (workflows: CIExplorerWorkflow[], focusedNodeId: string | null) => CIExplorerShareLevel[]+ focusLevels: (workflows: CIExplorerWorkflow[], focusedNodeId: string | null) => CIExplorerFocusLevel[]+ focusedJob: (+ workflows: CIExplorerWorkflow[],+ focusedNodeId: string | null+ ) => {+ job: WorkflowJobApi+ run: WorkflowRun+ } | null+ focusedJobInsights: (+ focusedJob: {+ job: WorkflowJobApi+ run: WorkflowRun+ } | null,+ jobInsights: Record<string, JobLogInsightsApi>+ ) => JobLogInsightsApi | null+ focusedBadgedSteps: (focusedJobInsights: JobLogInsightsApi | null) => ReadonlySet<number>+ focusedJobFailure: (+ focusedJob: {+ job: WorkflowJobApi+ run: WorkflowRun+ } | null,+ failureLogs: CIFailureLogsApi | null+ ) => CIJobFailureLogApi | null+ pushDurationSeconds: (activePush: PrCommitRuns | null) => number | null+ pullRequestUrl: (+ repoOwner: string,+ repoName: string,+ number: number,+ sourceId: string | null,+ searchParams: Record<string, any>+ ) => string+ breadcrumbs: (+ repoOwner: string,+ repoName: string,+ number: number,+ sourceId: string | null,+ pullRequestUrl: string,+ searchParams: Record<string, any>+ ) => Breadcrumb[]+ }+}++export type ciExplorerLogicType = MakeLogicType<+ ciExplorerLogicValues,+ ciExplorerLogicActions,+ CIExplorerLogicProps,+ ciExplorerLogicMeta+>++export const ciExplorerLogic = kea<ciExplorerLogicType>([+ path(['products', 'engineering_analytics', 'frontend', 'scenes', 'ciExplorerLogic']),+ props({} as CIExplorerLogicProps),+ key((props) => `${props.repoOwner}/${props.repoName}#${props.number}@${props.sourceId ?? ''}`),++ actions({+ setView: (view: CIExplorerView) => ({ view }),+ setFocus: (nodeId: string | null, moveCamera: boolean = true) => ({ nodeId, moveCamera }),+ setLocation: (location: CIExplorerLocation) => ({ location }),+ fitView: true,+ openDrawer: (tab: CIExplorerDrawerTab) => ({ tab }),+ closeDrawer: true,+ toggleJobTime: true,+ setFailedJobRuns: (asked: WorkflowRun[], failed: WorkflowRun[]) => ({ asked, failed }),+ retryFailedJobs: true,+ refresh: true,+ }),++ loaders(({ props, values, actions }) => ({+ lifecycle: [+ null as PRLifecycleApi | null,+ {+ loadLifecycle: async (): Promise<PRLifecycleApi | null> =>+ await engineeringAnalyticsPrLifecycle(projectId(), {+ pr_number: props.number,+ repo: `${props.repoOwner}/${props.repoName}`,+ source_id: props.sourceId ?? undefined,+ }),+ },+ ],+ prRuns: [+ null as WorkflowRunDetailApi[] | null,+ {+ loadPrRuns: async (): Promise<WorkflowRunDetailApi[]> =>+ await engineeringAnalyticsPrRuns(projectId(), {+ pr_number: props.number,+ repo: `${props.repoOwner}/${props.repoName}`,+ source_id: props.sourceId ?? undefined,+ }),+ },+ ],+ // When the stored runs and jobs were last synced from their source. Null until asked, or when the answer failed.+ freshness: [+ null as CIDataFreshnessApi | null,+ {+ loadFreshness: async (): Promise<CIDataFreshnessApi | null> =>+ await engineeringAnalyticsCiDataFreshness(projectId(), {+ repo: `${props.repoOwner}/${props.repoName}`,+ source_id: props.sourceId ?? undefined,+ }),+ },+ ],+ jobsByRun: [+ {} as Record<string, WorkflowJobApi[]>,+ {+ loadJobs: async (runs: WorkflowRun[]): Promise<Record<string, WorkflowJobApi[]>> => {+ const failed: WorkflowRun[] = []+ const loaded = await Promise.all(+ runs.map(async (run): Promise<[string, WorkflowJobApi[]] | null> => {+ const cacheKey = runJobsKey(run)+ if (cacheKey === null || run.runId === null) {+ return null+ }+ // One run that cannot be read must not hide the jobs of the others.+ try {+ const jobs = await engineeringAnalyticsWorkflowJobs(projectId(), {+ run_id: run.runId,+ ci_engine: run.ciEngine ?? undefined,+ run_attempt: run.runAttempt ?? undefined,+ source_id: props.sourceId ?? undefined,+ repo: `${props.repoOwner}/${props.repoName}`,+ })+ return [cacheKey, jobs]+ } catch {+ failed.push(run)+ return null+ }+ })+ )+ actions.setFailedJobRuns(runs, failed)+ // Read after the await, so two pushes loading at once do not overwrite each other.+ return { ...values.jobsByRun, ...Object.fromEntries(loaded.filter((entry) => entry !== null)) }+ },+ },+ ],+ // Null until asked for, which happens once a workflow of the pull request has failed.+ failureLogs: [+ null as CIFailureLogsApi | null,+ {+ loadFailureLogs: async (): Promise<CIFailureLogsApi | null> =>+ await engineeringAnalyticsCiFailureLogs(projectId(), {+ pr_number: props.number,+ repo: `${props.repoOwner}/${props.repoName}`,+ source_id: props.sourceId ?? undefined,+ }),+ },+ ],+ // Keyed by job. What a finished job's log says it did, read when the job is first focused.+ jobInsights: [+ {} as Record<string, JobLogInsightsApi>,+ {+ loadJobInsights: async (job: WorkflowJobApi): Promise<Record<string, JobLogInsightsApi>> => {+ const insights = await engineeringAnalyticsJobLogInsights(projectId(), {+ repo: `${props.repoOwner}/${props.repoName}`,+ run_id: job.run_id,+ job_id: job.id,+ ci_engine: job.ci_engine ?? undefined,+ source_id: props.sourceId ?? undefined,+ })+ return { ...values.jobInsights, [jobInsightsKey(job)]: insights }+ },+ },+ ],+ // Keyed by workflow id. A workflow has no entry until its graph is placed.+ layouts: [+ {} as Record<string, CIExplorerLayout>,+ {+ loadLayouts: async (workflows: CIExplorerWorkflow[]): Promise<Record<string, CIExplorerLayout>> => {+ const elk = await getElk()+ const focus = values.focusedNodeId+ const placed = await Promise.all(+ workflows.map(async (workflow): Promise<[string, CIExplorerLayout] | null> => {+ // One graph that cannot be placed must not hide the others.+ try {+ return [+ workflow.id,+ await layoutWorkflow(elk, workflow, focus, values.focusedBadgedSteps),+ ]+ } catch {+ return null+ }+ })+ )+ // A layout is sized for the focus it started with. When the focus moved meanwhile, the+ // workflows that held either focus are placed again by the newer request, and this result+ // must not overwrite that one.+ const moved = values.focusedNodeId+ const stale = (id: string): boolean =>+ moved !== focus &&+ [focus, moved].some((node) => node !== null && `${node}/`.startsWith(`${id}/`))+ return {+ ...values.layouts,+ ...Object.fromEntries(+ placed.filter((entry) => entry !== null && !stale(entry[0])) as [string, CIExplorerLayout][]+ ),+ }+ },+ },+ ],+ })),++ reducers({+ view: [+ 'overview' as CIExplorerView,+ {+ setView: (_, { view }) => view,+ setLocation: (_, { location }) => location.view,+ },+ ],+ // Null follows the newest push.+ selectedHeadSha: [+ null as string | null,+ {+ setLocation: (_, { location }) => location.headSha,+ },+ ],+ focusedNodeId: [+ null as string | null,+ {+ setFocus: (_, { nodeId }) => nodeId,+ setLocation: (_, { location }) => location.nodeId,+ },+ ],+ cameraRequest: [+ { sequence: 0, fit: false } as CIExplorerCameraRequest,+ {+ setFocus: (state, { moveCamera }) =>+ moveCamera ? { sequence: state.sequence + 1, fit: false } : state,+ setLocation: (state) => ({ sequence: state.sequence + 1, fit: false }),+ fitView: (state) => ({ sequence: state.sequence + 1, fit: true }),+ },+ ],+ drawerOpen: [+ false,+ { persist: true },+ {+ openDrawer: () => true,+ closeDrawer: () => false,+ },+ ],+ drawerTab: ['details' as CIExplorerDrawerTab, { persist: true }, { openDrawer: (_, { tab }) => tab }],+ // The share of job time is shown on request, so the page opens on the canvas.+ jobTimeOpen: [false, { persist: true }, { toggleJobTime: (open) => !open }],+ // The runs whose jobs could not be read. A run leaves the list when a later request for it succeeds.+ failedJobRuns: [+ [] as WorkflowRun[],+ {+ setFailedJobRuns: (state, { asked, failed }) => {+ const askedKeys = new Set(asked.map(runJobsKey))+ return [...state.filter((run) => !askedKeys.has(runJobsKey(run))), ...failed]+ },+ },+ ],+ loadFailed: [+ false,+ {+ loadPrRuns: () => false,+ loadPrRunsFailure: () => true,+ },+ ],+ failureLogsFailed: [+ false,+ {+ loadFailureLogs: () => false,+ loadFailureLogsFailure: () => true,+ },+ ],+ refreshing: [+ false,+ {+ refresh: () => true,+ loadPrRunsSuccess: () => false,+ loadPrRunsFailure: () => false,+ },+ ],+ }),++ selectors({+ // What a logic that works beside this one for the same pull request is keyed with.+ logicProps: [+ () => [(_, p: CIExplorerLogicProps) => p],+ (logicProps: CIExplorerLogicProps): CIExplorerLogicProps => logicProps,+ ],+ repoOwner: [() => [(_, p: CIExplorerLogicProps) => p.repoOwner], (repoOwner: string): string => repoOwner],+ repoName: [() => [(_, p: CIExplorerLogicProps) => p.repoName], (repoName: string): string => repoName],+ sourceId: [+ () => [(_, p: CIExplorerLogicProps) => p.sourceId],+ (sourceId: string | null): string | null => sourceId,+ ],+ // Newest push first.+ pushes: [+ (s) => [s.prRuns],+ (prRuns: WorkflowRunDetailApi[] | null): PrCommitRuns[] => groupRunsByCommit(prRuns ?? []),+ ],+ commits: [+ (s) => [s.prRuns],+ (prRuns: WorkflowRunDetailApi[] | null): CIActivityCommit[] => commitRows(prRuns ?? []),+ ],+ // The newest commit the author pushed. The activity marks it, and the overview opens it, from this one rule.+ currentHeadSha: [+ (s) => [s.commits],+ (commits: CIActivityCommit[]): string | null => commits.find((commit) => commit.latest)?.headSha ?? null,+ ],+ activePush: [+ (s) => [s.pushes, s.selectedHeadSha, s.currentHeadSha],+ (+ pushes: PrCommitRuns[],+ selectedHeadSha: string | null,+ currentHeadSha: string | null+ ): PrCommitRuns | null => {+ const headSha = selectedHeadSha ?? currentHeadSha+ return (+ pushes.find((push) => push.headSha === headSha) ??+ (selectedHeadSha === null ? pushes[0] : null) ??+ null+ )+ },+ ],+ onOlderCommit: [+ (s) => [s.selectedHeadSha, s.currentHeadSha],+ (selectedHeadSha: string | null, currentHeadSha: string | null): boolean =>+ selectedHeadSha !== null && selectedHeadSha !== currentHeadSha,+ ],+ // An older commit is reached from the activity, so Activity stays the current view there.+ currentView: [+ (s) => [s.view, s.onOlderCommit],+ (view: CIExplorerView, onOlderCommit: boolean): CIExplorerView => (onOlderCommit ? 'activity' : view),+ ],+ workflowRunUrl: [+ (s, p) => [p.repoOwner, p.repoName, s.sourceId, router.selectors.searchParams],+ (+ repoOwner: string,+ repoName: string,+ sourceId: string | null,+ searchParams: Record<string, string | undefined>+ ) =>+ (runId: number, ciEngine: WorkflowRunDetailApi['ci_engine']): string =>+ withScope(+ urls.engineeringAnalyticsWorkflowRun(repoOwner, repoName, runId, ciEngine),+ searchParams,+ sourceId+ ),+ ],+ locationUrl: [+ () => [router.selectors.location, router.selectors.searchParams],+ (location: { pathname: string }, searchParams: Record<string, any>) =>+ (target: CIExplorerLocation): string =>+ combineUrl(location.pathname, locationSearchParams(searchParams, target)).url,+ ],+ workflowRuns: [+ (s) => [s.activePush],+ (activePush: PrCommitRuns | null): WorkflowRun[] => latestRunPerWorkflow(activePush?.runs ?? []),+ ],+ workflows: [+ (s) => [s.workflowRuns, s.jobsByRun],+ (workflowRuns: WorkflowRun[], jobsByRun: Record<string, WorkflowJobApi[]>): CIExplorerWorkflow[] =>+ buildWorkflows(workflowRuns, jobsByRun),+ ],+ summary: [(s) => [s.workflows], (workflows: CIExplorerWorkflow[]): CIExplorerSummary => summarize(workflows)],+ activity: [+ (s) => [s.lifecycle, s.commits],+ (lifecycle: PRLifecycleApi | null, commits: CIActivityCommit[]): CIActivityDay[] =>+ activityDays(lifecycle, commits),+ ],+ syncedAt: [+ (s) => [s.freshness],+ (freshness: CIDataFreshnessApi | null): string | null =>+ oldestSync(freshness?.runs_synced_at, freshness?.jobs_synced_at),+ ],+ totalJobSeconds: [+ (s) => [s.workflows],+ (workflows: CIExplorerWorkflow[]): number => totalJobSeconds(workflows),+ ],+ shareLevels: [+ (s) => [s.workflows, s.focusedNodeId],+ (workflows: CIExplorerWorkflow[], focusedNodeId: string | null): CIExplorerShareLevel[] =>+ shareLevels(workflows, focusedNodeId),+ ],+ focusLevels: [+ (s) => [s.workflows, s.focusedNodeId],+ (workflows: CIExplorerWorkflow[], focusedNodeId: string | null): CIExplorerFocusLevel[] =>+ focusPath(workflows, focusedNodeId),+ ],+ focusedJob: [+ (s) => [s.workflows, s.focusedNodeId],+ (+ workflows: CIExplorerWorkflow[],+ focusedNodeId: string | null+ ): { job: WorkflowJobApi; run: WorkflowRun } | null => focusedJob(workflows, focusedNodeId),+ ],+ focusedJobInsights: [+ (s) => [s.focusedJob, s.jobInsights],+ (+ focusedJob: { job: WorkflowJobApi; run: WorkflowRun } | null,+ jobInsights: Record<string, JobLogInsightsApi>+ ): JobLogInsightsApi | null => (focusedJob ? (jobInsights[jobInsightsKey(focusedJob.job)] ?? null) : null),+ ],+ // The steps of the focused job that its log has something to say about. Those always get a row.+ focusedBadgedSteps: [+ (s) => [s.focusedJobInsights],+ (insights: JobLogInsightsApi | null): ReadonlySet<number> =>+ new Set((insights?.steps ?? []).filter((step) => step.badges.length).map((step) => step.number)),+ ],+ focusedJobFailure: [+ (s) => [s.focusedJob, s.failureLogs],+ (+ focusedJob: { job: WorkflowJobApi; run: WorkflowRun } | null,+ failureLogs: CIFailureLogsApi | null+ ): CIJobFailureLogApi | null =>+ failureLogs?.jobs.find(+ (log) =>+ log.job_id === focusedJob?.job.id &&+ log.run_id === focusedJob?.job.run_id &&+ // Two CI engines can reuse a run id and a job id.+ (log.ci_engine ?? null) === (focusedJob?.job.ci_engine ?? null)+ ) ?? null,+ ],+ pushDurationSeconds: [+ (s) => [s.activePush],+ (activePush: PrCommitRuns | null): number | null =>+ activePush ? pushRoundOf(activePush.headSha, activePush.runs).wallSeconds : null,+ ],+ pullRequestUrl: [+ (s, p) => [p.repoOwner, p.repoName, p.number, s.sourceId, router.selectors.searchParams],+ (+ repoOwner: string,+ repoName: string,+ number: number,+ sourceId: string | null,+ searchParams: Record<string, string | undefined>+ ): string =>+ withScope(urls.engineeringAnalyticsPullRequest(repoOwner, repoName, number), searchParams, sourceId),+ ],+ breadcrumbs: [+ (s, p) => [p.repoOwner, p.repoName, p.number, s.sourceId, s.pullRequestUrl, router.selectors.searchParams],+ (+ repoOwner: string,+ repoName: string,+ number: number,+ sourceId: string | null,+ pullRequestUrl: string,+ searchParams: Record<string, string | undefined>+ ): Breadcrumb[] => [+ {+ key: 'EngineeringAnalytics',+ name: 'Engineering analytics',+ path: withScope(urls.engineeringAnalytics(), searchParams, sourceId),+ iconType: 'health',+ },+ {+ key: ['EngineeringAnalyticsPullRequest', `${repoOwner}/${repoName}#${number}`],+ name: `${repoOwner}/${repoName} #${number}`,+ path: pullRequestUrl,+ iconType: 'health',+ },+ {+ key: ['EngineeringAnalyticsCIExplorer', `${repoOwner}/${repoName}#${number}`],+ name: 'CI explorer',+ iconType: 'health',+ },+ ],+ ],+ }),++ listeners(({ actions, values, selectors, cache }) => {+ const captureViewed = (): void => {+ cache.viewCaptured = true+ posthog.capture(EVENT_VIEWED, viewedProperties(values.view, values.selectedHeadSha))+ }+ const loadMissingJobs = (): void => {+ const missing = values.workflowRuns.filter((run) => {+ const cacheKey = runJobsKey(run)+ return cacheKey !== null && !(cacheKey in values.jobsByRun)+ })+ if (missing.length) {+ actions.loadJobs(missing)+ }+ }+ const loadMissingLayouts = (): void => {+ const missing = values.workflows.filter(+ (workflow) => workflow.items !== null && !(workflow.id in values.layouts)+ )+ if (missing.length) {+ actions.loadLayouts(missing)+ }+ }+ const loadFocusedJobInsights = (): void => {+ const job = values.focusedJob?.job+ if (+ job &&+ job.status === 'completed' &&+ job.ci_engine !== 'depot_ci' &&+ !(jobInsightsKey(job) in values.jobInsights)+ ) {+ actions.loadJobInsights(job)+ }+ }+ // A focused job shows its steps, so it is taller. Its workflow is placed again when it gains or loses the focus.+ const onFocusChange = (previous: string | null): void => {+ const resized = workflowsOfNodes(values.workflows, [previous, values.focusedNodeId])+ if (resized.length && previous !== values.focusedNodeId) {+ actions.loadLayouts(resized)+ }+ loadFocusedJobInsights()+ }+ return {+ setLocation: ({ location }, __, ___, previousState) => {+ if (+ location.view !== selectors.view(previousState) ||+ location.headSha !== selectors.selectedHeadSha(previousState)+ ) {+ captureViewed()+ }+ loadMissingJobs()+ loadMissingLayouts()+ onFocusChange(selectors.focusedNodeId(previousState))+ },+ setView: ({ view }, __, ___, previousState) => {+ if (view !== selectors.view(previousState)) {+ captureViewed()+ }+ },+ setFocus: (_, __, ___, previousState) => onFocusChange(selectors.focusedNodeId(previousState)),+ // A refresh can change the jobs of a run, so every placed workflow that got jobs is placed again.+ loadJobsSuccess: ({ payload }) => {+ const reloaded = new Set((payload ?? []).map(runJobsKey))+ const stale = values.workflows.filter(+ (workflow) =>+ workflow.items !== null && (reloaded.has(workflow.id) || !(workflow.id in values.layouts))+ )+ if (stale.length) {+ actions.loadLayouts(stale)+ }+ // A link can focus a job before its run's jobs arrive.+ loadFocusedJobInsights()+ },+ // A node from a link that no longer exists gives way to the nearest level that does.+ loadLayoutsSuccess: () => {+ const focused = values.focusedNodeId+ if (focused === null || values.workflows.some((workflow) => workflow.items === null)) {+ return+ }+ const deepest = values.focusLevels[values.focusLevels.length - 1]?.id ?? null+ if (deepest !== focused) {+ actions.setFocus(deepest)+ }+ },+ // A step with a chip always gets a row, so the focused job can grow once its log is read.+ loadJobInsightsSuccess: () => {+ if (values.focusedBadgedSteps.size) {+ const resized = workflowsOfNodes(values.workflows, [values.focusedNodeId])+ if (resized.length) {+ actions.loadLayouts(resized)+ }+ }+ },+ loadPrRunsSuccess: (_, __, ___, previousState) => {+ if (selectors.refreshing(previousState)) {+ actions.loadJobs(values.workflowRuns)+ } else {+ loadMissingJobs()+ }+ // A workflow whose jobs need no request gets no loadJobsSuccess to place it.+ loadMissingLayouts()+ const failed = values.pushes.some((push) => push.runs.some((run) => isDecisiveFailure(run.conclusion)))+ if (failed && (values.failureLogs === null || selectors.refreshing(previousState))) {+ actions.loadFailureLogs()+ }+ },+ retryFailedJobs: () => {+ if (values.failedJobRuns.length) {+ actions.loadJobs(values.failedJobRuns)+ }+ },+ refresh: () => {+ posthog.capture(EVENT_REFRESHED)+ actions.loadLifecycle()+ actions.loadPrRuns()+ actions.loadFreshness()+ },+ openDrawer: ({ tab }) => {+ posthog.capture(EVENT_DRAWER_OPENED, { tab })+ },+ }+ }),++ urlToAction(({ actions, values, props }) => ({+ [CI_EXPLORER_ROUTE]: ({ repoOwner, repoName, number }, searchParams) => {+ // Another pull request's URL belongs to another instance of this logic.+ if (+ decodeURIComponent(repoOwner ?? '') !== props.repoOwner ||+ decodeURIComponent(repoName ?? '') !== props.repoName ||+ Number(number) !== props.number+ ) {+ return+ }+ const location: CIExplorerLocation = {+ view: searchParams[VIEW_PARAM] === 'activity' ? 'activity' : '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]),+ }+ if (+ location.view !== values.view ||+ location.headSha !== values.selectedHeadSha ||+ location.nodeId !== values.focusedNodeId+ ) {+ actions.setLocation(location)+ }+ },+ })),++ actionToUrl(({ values }) => {+ const url = (+ replace: boolean+ ): [string, Record<string, any>, Record<string, any>, { replace: boolean }] | undefined => {+ // A focus change can arrive after the person left for another page. That page's URL is not ours to write.+ if (!router.values.location.pathname.endsWith(CI_EXPLORER_PATH_END)) {+ return undefined+ }+ return [+ router.values.location.pathname,+ locationSearchParams(router.values.searchParams, {+ view: values.view,+ headSha: values.selectedHeadSha,+ nodeId: values.focusedNodeId,+ }),+ router.values.hashParams,+ { replace },+ ]+ }+ return {+ setView: () => url(false),+ // Zooming moves the focus many times, and Back must leave the view, not replay the zoom.+ setFocus: () => url(true),+ }+ }),++ afterMount(({ actions, values, cache }) => {+ // The router has already read the URL. A link that opens on a view or a commit was captured then.+ if (!cache.viewCaptured) {+ posthog.capture(EVENT_VIEWED, viewedProperties(values.view, values.selectedHeadSha))+ }+ actions.loadLifecycle()+ actions.loadPrRuns()+ actions.loadFreshness()+ }),+])diff --git a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.tsindex b7e2982f1f21..fe709b811068 100644--- a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts+++ b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts@@ -132,6 +132,8 @@ function percentile(values: number[], q: number): number | null {function toWorkflowRun(run: WorkflowRunDetailApi): WorkflowRun {return {workflow: run.workflow_name,+ workflowId: run.workflow_id ?? null,+ event: run.event ?? null,conclusion: run.conclusion,startedAt: run.run_started_at,finishedAt: run.status === 'completed' ? run.updated_at : null,diff --git a/products/engineering_analytics/package.json b/products/engineering_analytics/package.jsonindex d6d567ff1f6e..b0cb7cc8caf6 100644--- a/products/engineering_analytics/package.json+++ b/products/engineering_analytics/package.json@@ -9,7 +9,8 @@"@posthog/quill-charts": "workspace:*","kea": "catalog:","kea-loaders": "catalog:",- "kea-router": "catalog:"+ "kea-router": "catalog:",+ "posthog-js": "catalog:"},"devDependencies": {"kea-test-utils": "catalog:"@@ -19,6 +20,8 @@"@posthog/icons": "catalog:","@storybook/react": "catalog:","@types/react": "*",+ "@xyflow/react": "*",+ "elkjs": "*","react": "*"}}