-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathperformance.ts
More file actions
259 lines (240 loc) · 8.13 KB
/
performance.ts
File metadata and controls
259 lines (240 loc) · 8.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import zlib from 'node:zlib';
import {logger} from '../logger.js';
import {zod, DevTools} from '../third_party/index.js';
import type {Page} from '../third_party/index.js';
import type {InsightName, TraceResult} from '../trace-processing/parse.js';
import {
parseRawTraceBuffer,
traceResultIsSuccess,
} from '../trace-processing/parse.js';
import {ToolCategory} from './categories.js';
import type {Context, Response} from './ToolDefinition.js';
import {defineTool} from './ToolDefinition.js';
const filePathSchema = zod
.string()
.optional()
.describe(
'The absolute file path, or a file path relative to the current working directory, to save the raw trace data. For example, trace.json.gz (compressed) or trace.json (uncompressed).',
);
export const startTrace = defineTool({
name: 'performance_start_trace',
description: `Starts a performance trace recording on the selected page. This can be used to look for performance problems and insights to improve the performance of the page. It will also report Core Web Vital (CWV) scores for the page.`,
annotations: {
category: ToolCategory.PERFORMANCE,
readOnlyHint: false,
},
schema: {
reload: zod
.boolean()
.describe(
'Determines if, once tracing has started, the current selected page should be automatically reloaded. Navigate the page to the right URL using the navigate_page tool BEFORE starting the trace if reload or autoStop is set to true.',
),
autoStop: zod
.boolean()
.describe(
'Determines if the trace recording should be automatically stopped.',
),
filePath: filePathSchema,
},
handler: async (request, response, context) => {
if (context.isRunningPerformanceTrace()) {
response.appendResponseLine(
'Error: a performance trace is already running. Use performance_stop_trace to stop it. Only one trace can be running at any given time.',
);
return;
}
context.setIsRunningPerformanceTrace(true);
const page = context.getSelectedPage();
const pageUrlForTracing = page.url();
if (request.params.reload) {
// Before starting the recording, navigate to about:blank to clear out any state.
await page.goto('about:blank', {
waitUntil: ['networkidle0'],
});
}
// Keep in sync with the categories arrays in:
// https://source.chromium.org/chromium/chromium/src/+/main:third_party/devtools-frontend/src/front_end/panels/timeline/TimelineController.ts
// https://github.com/GoogleChrome/lighthouse/blob/master/lighthouse-core/gather/gatherers/trace.js
const categories = [
'-*',
'blink.console',
'blink.user_timing',
'devtools.timeline',
'disabled-by-default-devtools.screenshot',
'disabled-by-default-devtools.timeline',
'disabled-by-default-devtools.timeline.invalidationTracking',
'disabled-by-default-devtools.timeline.frame',
'disabled-by-default-devtools.timeline.stack',
'disabled-by-default-v8.cpu_profiler',
'disabled-by-default-v8.cpu_profiler.hires',
'latencyInfo',
'loading',
'disabled-by-default-lighthouse',
'v8.execute',
'v8',
];
await page.tracing.start({
categories,
});
if (request.params.reload) {
await page.goto(pageUrlForTracing, {
waitUntil: ['load'],
});
}
if (request.params.autoStop) {
await new Promise(resolve => setTimeout(resolve, 5_000));
await stopTracingAndAppendOutput(
page,
response,
context,
request.params.filePath,
);
} else {
response.appendResponseLine(
`The performance trace is being recorded. Use performance_stop_trace to stop it.`,
);
}
},
});
export const stopTrace = defineTool({
name: 'performance_stop_trace',
description:
'Stops the active performance trace recording on the selected page.',
annotations: {
category: ToolCategory.PERFORMANCE,
readOnlyHint: false,
},
schema: {
filePath: filePathSchema,
},
handler: async (request, response, context) => {
if (!context.isRunningPerformanceTrace()) {
return;
}
const page = context.getSelectedPage();
await stopTracingAndAppendOutput(
page,
response,
context,
request.params.filePath,
);
},
});
export const analyzeInsight = defineTool({
name: 'performance_analyze_insight',
description:
'Provides more detailed information on a specific Performance Insight of an insight set that was highlighted in the results of a trace recording.',
annotations: {
category: ToolCategory.PERFORMANCE,
readOnlyHint: true,
},
schema: {
insightSetId: zod
.string()
.describe(
'The id for the specific insight set. Only use the ids given in the "Available insight sets" list.',
),
insightName: zod
.string()
.describe(
'The name of the Insight you want more information on. For example: "DocumentLatency" or "LCPBreakdown"',
),
},
handler: async (request, response, context) => {
const lastRecording = context.recordedTraces().at(-1);
if (!lastRecording) {
response.appendResponseLine(
'No recorded traces found. Record a performance trace so you have Insights to analyze.',
);
return;
}
response.attachTraceInsight(
lastRecording,
request.params.insightSetId,
request.params.insightName as InsightName,
);
},
});
async function stopTracingAndAppendOutput(
page: Page,
response: Response,
context: Context,
filePath?: string,
): Promise<void> {
try {
const traceEventsBuffer = await page.tracing.stop();
if (filePath && traceEventsBuffer) {
let dataToWrite: Uint8Array = traceEventsBuffer;
if (filePath.endsWith('.gz')) {
dataToWrite = await new Promise((resolve, reject) => {
zlib.gzip(traceEventsBuffer, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
const file = await context.saveFile(dataToWrite, filePath);
response.appendResponseLine(
`The raw trace data was saved to ${file.filename}.`,
);
}
const result = await parseRawTraceBuffer(traceEventsBuffer);
response.appendResponseLine('The performance trace has been stopped.');
if (traceResultIsSuccess(result)) {
if (context.isCruxEnabled()) {
await populateCruxData(result);
}
context.storeTraceRecording(result);
response.attachTraceSummary(result);
} else {
throw new Error(
`There was an unexpected error parsing the trace: ${result.error}`,
);
}
} finally {
context.setIsRunningPerformanceTrace(false);
}
}
/** We tell CrUXManager to fetch data so it's available when DevTools.PerformanceTraceFormatter is invoked */
async function populateCruxData(result: TraceResult): Promise<void> {
logger('populateCruxData called');
const cruxManager = DevTools.CrUXManager.instance();
// go/jtfbx. Yes, we're aware this API key is public. ;)
cruxManager.setEndpointForTesting(
'https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=AIzaSyBn5gimNjhiEyA_euicSKko6IlD3HdgUfk',
);
const cruxSetting =
DevTools.Common.Settings.Settings.instance().createSetting('field-data', {
enabled: true,
});
cruxSetting.set({enabled: true});
// Gather URLs to fetch CrUX data for
const urls = [...(result.parsedTrace.insights?.values() ?? [])].map(c =>
c.url.toString(),
);
urls.push(result.parsedTrace.data.Meta.mainFrameURL);
const urlSet = new Set(urls);
if (urlSet.size === 0) {
logger('No URLs found for CrUX data');
return;
}
logger(
`Fetching CrUX data for ${urlSet.size} URLs: ${Array.from(urlSet).join(', ')}`,
);
const cruxData = await Promise.all(
Array.from(urlSet).map(async url => {
const data = await cruxManager.getFieldDataForPage(url);
logger(`CrUX data for ${url}: ${data ? 'found' : 'not found'}`);
return data;
}),
);
result.parsedTrace.metadata.cruxFieldData = cruxData;
}