From 201f5fd271ffb59c5c45038cba2a59b467175ef1 Mon Sep 17 00:00:00 2001 From: Joan Leon Date: Thu, 26 Nov 2026 00:20:51 +0100 Subject: [PATCH] List the state and savings of every insight model Without --category, insights lists every DevTools insight model of the selected navigation in `models`, with its state, estimated metric savings and wasted bytes. Failing models come first so agents can prioritize. Savings use milliseconds (fcpMs, lcpMs, tbtMs, inpMs) and cls, and zero savings are left out. Models that the engine cannot compute are reported in warnings. --- README.md | 9 ++++ src/engine/extractors/insights.ts | 47 +++++++++++++++- src/engine/helpers.ts | 2 + src/engine/types.ts | 23 ++++++++ src/formatters/markdown.ts | 25 +++++++++ test/extractors/insights.test.ts | 90 +++++++++++++++++++++++++++++++ test/formatters/markdown.test.ts | 31 +++++++++++ 7 files changed, 226 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9a379b5..601c053 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,7 @@ trace-engine-cli report trace.json.gz --sections overview,tasks,network \ ### `trace-engine-cli insights ` Diagnostic insight cards for Core Web Vitals and performance bottlenecks. +Without `--category`, `models` lists the state and estimated savings of every DevTools insight model, failing models first. ```bash trace-engine-cli insights trace.json.gz @@ -391,6 +392,14 @@ The default is a main-frame navigation with a measured LCP when available. Use `--navigation` to select a trace navigation ID or InsightSet ID. With `--time-range`, insights select from navigation windows that overlap the range. +Without `--category`, the output starts with `models`. It lists every insight model of the selected navigation: + +- `state`: `fail`, `informative` or `pass`. Failing models come first. +- `metricSavings`: the estimated improvement in `fcpMs`, `lcpMs`, `tbtMs`, `inpMs` or `cls`, when the engine gives one. +- `wastedBytes`: the estimated transfer size that can be saved, when the engine gives one. + +If the engine cannot compute a model, `warnings` gives the model key and the error. + ```bash # All insights trace-engine-cli insights trace.json.gz diff --git a/src/engine/extractors/insights.ts b/src/engine/extractors/insights.ts index f1ccbbe..79a4e6b 100644 --- a/src/engine/extractors/insights.ts +++ b/src/engine/extractors/insights.ts @@ -14,10 +14,12 @@ import type { TimeRange } from '../../utils/filter.js'; import { microToMilli, round } from '../../utils/units.js'; -import { findInsightEntry } from '../helpers.js'; +import { findInsightEntry, type InsightEntryResult, type InsightModels } from '../helpers.js'; import type { LoadedTrace } from '../loader.js'; import type { InpBreakdownInsight, + InsightMetricSavings, + InsightModelSummary, InsightsResult, LcpBreakdownInsight, RenderBlockingInsight, @@ -36,6 +38,42 @@ export interface ExtractInsightsOptions { timeRange?: TimeRange; } +type InsightModel = NonNullable; + +const STATE_ORDER = { fail: 0, informative: 1, pass: 2 } as const; + +function summarizeMetricSavings( + savings: InsightModel['metricSavings'], +): InsightMetricSavings | undefined { + if (!savings) return undefined; + const summary: InsightMetricSavings = {}; + if (savings.FCP) summary.fcpMs = round(savings.FCP); + if (savings.LCP) summary.lcpMs = round(savings.LCP); + if (savings.TBT) summary.tbtMs = round(savings.TBT); + if (savings.INP) summary.inpMs = round(savings.INP); + if (savings.CLS) summary.cls = round(savings.CLS, 4); + return Object.keys(summary).length > 0 ? summary : undefined; +} + +function summarizeModels(entry: InsightEntryResult): InsightModelSummary[] { + const models: InsightModelSummary[] = []; + for (const model of Object.values(entry.model)) { + if (!model) continue; + const summary: InsightModelSummary = { + key: model.insightKey, + title: model.strings.title, + state: model.state, + }; + const metricSavings = summarizeMetricSavings(model.metricSavings); + if (metricSavings) summary.metricSavings = metricSavings; + if (model.wastedBytes && model.wastedBytes > 0) { + summary.wastedBytes = Math.round(model.wastedBytes); + } + models.push(summary); + } + return models.sort((a, b) => STATE_ORDER[a.state] - STATE_ORDER[b.state]); +} + /** * Extracts diagnostic insight cards for Web Vitals (LCP, INP, CLS, render blocking, 3rd party). */ @@ -65,6 +103,13 @@ export function extractInsights( } const category = options?.category; const shouldInclude = (cat: string) => !category || category === cat; + + if (!category && entry) { + result.models = summarizeModels(entry); + for (const [key, error] of Object.entries(entry.modelErrors)) { + if (error) warnings.push(`${key} insight could not be computed: ${error.message}`); + } + } const scopeToNavigation = Boolean(entry?.navigation || options?.navigationId); const allowGlobalFallback = !scopeToNavigation && !options?.timeRange; diff --git a/src/engine/helpers.ts b/src/engine/helpers.ts index b6efe41..26c01dc 100644 --- a/src/engine/helpers.ts +++ b/src/engine/helpers.ts @@ -112,6 +112,7 @@ export interface InsightEntryResult { navigation: InsightSet['navigation']; navigationId?: string; model: InsightModels; + modelErrors: InsightSet['modelErrors']; } /** @@ -136,6 +137,7 @@ export function findInsightEntry( navigation: set.navigation, navigationId: traceId, model: set.model, + modelErrors: set.modelErrors, }; if (navigationId) { if (key === navigationId || set.id === navigationId || traceId === navigationId) return entry; diff --git a/src/engine/types.ts b/src/engine/types.ts index aeb18ef..b3c393b 100644 --- a/src/engine/types.ts +++ b/src/engine/types.ts @@ -116,12 +116,35 @@ export interface ThirdPartyEntityInsight { mainThreadTimeMs: number; } +/** + * Estimated metric improvement if the issues found by an insight are fixed. + */ +export interface InsightMetricSavings { + fcpMs?: number; + lcpMs?: number; + tbtMs?: number; + inpMs?: number; + cls?: number; +} + +/** + * Result of one DevTools insight model for the selected navigation. + */ +export interface InsightModelSummary { + key: string; + title: string; + state: 'pass' | 'fail' | 'informative'; + metricSavings?: InsightMetricSavings; + wastedBytes?: number; +} + /** * Diagnostics and metric breakdowns for CWV bottlenecks. */ export interface InsightsResult { navigationId?: string; insightSetId?: string; + models?: InsightModelSummary[]; lcpBreakdown?: LcpBreakdownInsight | null; inpBreakdown?: InpBreakdownInsight | null; clsCulprits?: ClsCulpritInsight[]; diff --git a/src/formatters/markdown.ts b/src/formatters/markdown.ts index bfdbc31..d9159a7 100644 --- a/src/formatters/markdown.ts +++ b/src/formatters/markdown.ts @@ -16,6 +16,7 @@ import type { DiffResult, EventsResult, FindResult, + InsightModelSummary, InsightsResult, InteractionsResult, NavigationsResult, @@ -103,6 +104,17 @@ export function formatOverviewMarkdown(overview: OverviewResult): string { return lines.join('\n'); } +function formatInsightSavings({ metricSavings: s, wastedBytes }: InsightModelSummary): string { + const parts: string[] = []; + if (s?.fcpMs !== undefined) parts.push(`FCP ${formatMs(s.fcpMs)}`); + if (s?.lcpMs !== undefined) parts.push(`LCP ${formatMs(s.lcpMs)}`); + if (s?.tbtMs !== undefined) parts.push(`TBT ${formatMs(s.tbtMs)}`); + if (s?.inpMs !== undefined) parts.push(`INP ${formatMs(s.inpMs)}`); + if (s?.cls !== undefined) parts.push(`CLS ${formatScore(s.cls)}`); + if (wastedBytes !== undefined) parts.push(formatBytes(wastedBytes)); + return parts.join(', ') || '-'; +} + export function formatInsightsMarkdown(insights: InsightsResult): string { const lines: string[] = ['# Diagnostic Insights', '']; @@ -112,6 +124,19 @@ export function formatInsightsMarkdown(insights: InsightsResult): string { if (insights.insightSetId) lines.push(`- **Insight Set ID**: \`${insights.insightSetId}\``, ''); + if (insights.models && insights.models.length > 0) { + lines.push('## Insight Models'); + lines.push(''); + lines.push('| Insight | Key | State | Estimated Savings |'); + lines.push('|---|---|---|---|'); + for (const model of insights.models) { + lines.push( + `| ${model.title} | \`${model.key}\` | ${model.state} | ${formatInsightSavings(model)} |`, + ); + } + lines.push(''); + } + if (insights.lcpBreakdown) { const l = insights.lcpBreakdown; lines.push('## LCP Breakdown'); diff --git a/test/extractors/insights.test.ts b/test/extractors/insights.test.ts index c27981c..86acfc8 100644 --- a/test/extractors/insights.test.ts +++ b/test/extractors/insights.test.ts @@ -32,6 +32,21 @@ async function loadCwvVariant(t: TestContext, update: (events: unknown[]) => unk return loadTraceFromFile(file); } +function updateDocumentRequest( + events: unknown[], + eventName: string, + update: (data: Record) => void, +) { + for (const event of events) { + if (getPropertyByPath(event, 'name') !== eventName) continue; + if (getPropertyByPath(event, 'args.data.requestId') !== 'NAV_1') continue; + const data = getPropertyByPath(event, 'args.data'); + assert.ok(data && typeof data === 'object'); + update(data as Record); + } + return events; +} + describe('Insights Extractor', () => { let loaded: LoadedTrace; @@ -221,6 +236,81 @@ describe('Insights Extractor', () => { assert.equal(result.thirdParties[0].transferSizeBytes, 16384); }); + test('lists the state of every insight model, failing models first', async () => { + const fixturePath = path.resolve(import.meta.dirname, '../fixtures/navigation-cwv-trace.json'); + const result = extractInsights(await loadTraceFromFile(fixturePath)); + assert.ok(result.models); + + assert.deepEqual( + result.models.find((model) => model.key === 'LCPBreakdown'), + { key: 'LCPBreakdown', title: 'LCP breakdown', state: 'fail' }, + ); + assert.deepEqual( + result.models.find((model) => model.key === 'RenderBlocking'), + { key: 'RenderBlocking', title: 'Render-blocking requests', state: 'fail' }, + ); + + const rank = { fail: 0, informative: 1, pass: 2 }; + const ranks = result.models.map((model) => rank[model.state]); + assert.ok(ranks.includes(rank.pass)); + assert.deepEqual( + ranks, + [...ranks].sort((a, b) => a - b), + ); + }); + + test('reports metric savings in milliseconds and wasted bytes', async (t) => { + const trace = await loadCwvVariant(t, (events) => { + updateDocumentRequest(events, 'ResourceReceiveResponse', (data) => { + data.timing = { + ...(data.timing as Record), + receiveHeadersStart: 740, + receiveHeadersEnd: 745, + }; + }); + return updateDocumentRequest(events, 'ResourceFinish', (data) => { + data.decodedBodyLength = 30000; + }); + }); + const result = extractInsights(trace); + + assert.deepEqual( + result.models?.find((model) => model.key === 'DocumentLatency'), + { + key: 'DocumentLatency', + title: 'Document request latency', + state: 'fail', + metricSavings: { fcpMs: 600, lcpMs: 600 }, + wastedBytes: 20100, + }, + ); + }); + + test('reports insight models that failed to compute as warnings', async (t) => { + const trace = await loadCwvVariant(t, (events) => + updateDocumentRequest(events, 'ResourceReceiveResponse', (data) => { + delete data.timing; + }), + ); + const result = extractInsights(trace); + + assert.equal( + result.models?.find((model) => model.key === 'DocumentLatency'), + undefined, + ); + assert.ok( + result.warnings?.includes( + 'DocumentLatency insight could not be computed: missing document request timing', + ), + ); + }); + + test('omits the model list when a category is selected', async () => { + const fixturePath = path.resolve(import.meta.dirname, '../fixtures/navigation-cwv-trace.json'); + const result = extractInsights(await loadTraceFromFile(fixturePath), { category: 'lcp' }); + assert.equal(result.models, undefined); + }); + test('extractInsights parses CLS culprits for shifts-trace', async () => { const fixturePath = path.resolve(import.meta.dirname, '../fixtures/shifts-trace.json'); const shiftsLoaded = await loadTraceFromFile(fixturePath); diff --git a/test/formatters/markdown.test.ts b/test/formatters/markdown.test.ts index d84f733..2ef4889 100644 --- a/test/formatters/markdown.test.ts +++ b/test/formatters/markdown.test.ts @@ -138,6 +138,37 @@ describe('Markdown Formatter', () => { assert.ok(output.includes('## Third-Party Entities')); }); + test('formatInsightsMarkdown lists insight model states and savings', () => { + const output = formatInsightsMarkdown({ + models: [ + { + key: 'DocumentLatency', + title: 'Document request latency', + state: 'fail', + metricSavings: { fcpMs: 600, lcpMs: 600 }, + wastedBytes: 20100, + }, + { + key: 'CLSCulprits', + title: 'Layout shift culprits', + state: 'fail', + metricSavings: { cls: 0.12 }, + }, + { key: 'Viewport', title: 'Optimize viewport for mobile', state: 'pass' }, + ], + }); + + assert.ok(output.includes('## Insight Models')); + assert.ok(output.includes('| Insight | Key | State | Estimated Savings |')); + assert.ok( + output.includes( + '| Document request latency | `DocumentLatency` | fail | FCP 600ms, LCP 600ms, 19.63 KB |', + ), + ); + assert.ok(output.includes('| Layout shift culprits | `CLSCulprits` | fail | CLS 0.12 |')); + assert.ok(output.includes('| Optimize viewport for mobile | `Viewport` | pass | - |')); + }); + test('formatTasksMarkdown formats tasks list', () => { const tasks: TasksResult = { mode: 'list',