-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathperformance.ts
More file actions
188 lines (174 loc) · 5.9 KB
/
performance.ts
File metadata and controls
188 lines (174 loc) · 5.9 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
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type {Page} from 'puppeteer-core';
import {logger} from '../logger.js';
import {zod} from '../third_party/modelcontextprotocol-sdk/index.js';
import type {InsightName} from '../trace-processing/parse.js';
import {
getInsightOutput,
getTraceSummary,
parseRawTraceBuffer,
traceResultIsSuccess,
} from '../trace-processing/parse.js';
import {ToolCategories} from './categories.js';
import type {Context, Response} from './ToolDefinition.js';
import {defineTool} from './ToolDefinition.js';
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: ToolCategories.PERFORMANCE,
readOnlyHint: true,
},
schema: {
reload: zod
.boolean()
.describe(
'Determines if, once tracing has started, the page should be automatically reloaded.',
),
autoStop: zod
.boolean()
.describe(
'Determines if the trace recording should be automatically stopped.',
),
},
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);
} 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: ToolCategories.PERFORMANCE,
readOnlyHint: true,
},
schema: {},
handler: async (_request, response, context) => {
if (!context.isRunningPerformanceTrace()) {
return;
}
const page = context.getSelectedPage();
await stopTracingAndAppendOutput(page, response, context);
},
});
export const analyzeInsight = defineTool({
name: 'performance_analyze_insight',
description:
'Provides more detailed information on a specific Performance Insight that was highlighted in the results of a trace recording.',
annotations: {
category: ToolCategories.PERFORMANCE,
readOnlyHint: true,
},
schema: {
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;
}
const insightOutput = getInsightOutput(
lastRecording,
request.params.insightName as InsightName,
);
if ('error' in insightOutput) {
response.appendResponseLine(insightOutput.error);
return;
}
response.appendResponseLine(insightOutput.output);
},
});
async function stopTracingAndAppendOutput(
page: Page,
response: Response,
context: Context,
): Promise<void> {
try {
const traceEventsBuffer = await page.tracing.stop();
const result = await parseRawTraceBuffer(traceEventsBuffer);
response.appendResponseLine('The performance trace has been stopped.');
if (traceResultIsSuccess(result)) {
context.storeTraceRecording(result);
const traceSummaryText = getTraceSummary(result);
response.appendResponseLine(traceSummaryText);
} else {
response.appendResponseLine(
'There was an unexpected error parsing the trace:',
);
response.appendResponseLine(result.error);
}
} catch (e) {
const errorText = e instanceof Error ? e.message : JSON.stringify(e);
logger(`Error stopping performance trace: ${errorText}`);
response.appendResponseLine(
'An error occurred generating the response for this trace:',
);
response.appendResponseLine(errorText);
} finally {
context.setIsRunningPerformanceTrace(false);
}
}