Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ trace-engine-cli report trace.json.gz --sections overview,tasks,network \

### `trace-engine-cli insights <file>`
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

Expand Down Expand Up @@ -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
Expand Down
47 changes: 46 additions & 1 deletion src/engine/extractors/insights.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -36,6 +38,42 @@ export interface ExtractInsightsOptions {
timeRange?: TimeRange;
}

type InsightModel = NonNullable<InsightModels[keyof InsightModels]>;

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).
*/
Expand Down Expand Up @@ -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;

Expand Down
2 changes: 2 additions & 0 deletions src/engine/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ export interface InsightEntryResult {
navigation: InsightSet['navigation'];
navigationId?: string;
model: InsightModels;
modelErrors: InsightSet['modelErrors'];
}

/**
Expand All @@ -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;
Expand Down
23 changes: 23 additions & 0 deletions src/engine/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[];
Expand Down
25 changes: 25 additions & 0 deletions src/formatters/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
DiffResult,
EventsResult,
FindResult,
InsightModelSummary,
InsightsResult,
InteractionsResult,
NavigationsResult,
Expand Down Expand Up @@ -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', ''];

Expand All @@ -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');
Expand Down
90 changes: 90 additions & 0 deletions test/extractors/insights.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) => 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<string, unknown>);
}
return events;
}

describe('Insights Extractor', () => {
let loaded: LoadedTrace;

Expand Down Expand Up @@ -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<string, unknown>),
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);
Expand Down
31 changes: 31 additions & 0 deletions test/formatters/markdown.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Loading