chrome-devtools-mcp 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +10 -2
  2. package/build/node_modules/chrome-devtools-frontend/front_end/core/host/GdpClient.js +18 -3
  3. package/build/node_modules/chrome-devtools-frontend/front_end/core/host/UserMetrics.js +3 -2
  4. package/build/node_modules/chrome-devtools-frontend/front_end/core/i18n/i18n.js +24 -0
  5. package/build/node_modules/chrome-devtools-frontend/front_end/core/sdk/CSSMatchedStyles.js +5 -1
  6. package/build/node_modules/chrome-devtools-frontend/front_end/core/sdk/EnhancedTracesParser.js +4 -5
  7. package/build/node_modules/chrome-devtools-frontend/front_end/core/sdk/NetworkManager.js +1 -0
  8. package/build/node_modules/chrome-devtools-frontend/front_end/core/sdk/NetworkRequest.js +8 -0
  9. package/build/node_modules/chrome-devtools-frontend/front_end/core/sdk/TargetManager.js +4 -0
  10. package/build/node_modules/chrome-devtools-frontend/front_end/generated/InspectorBackendCommands.js +10 -7
  11. package/build/node_modules/chrome-devtools-frontend/front_end/generated/SupportedCSSProperties.js +40 -11
  12. package/build/node_modules/chrome-devtools-frontend/front_end/models/ai_assistance/data_formatters/PerformanceInsightFormatter.js +95 -283
  13. package/build/node_modules/chrome-devtools-frontend/front_end/models/ai_assistance/data_formatters/PerformanceTraceFormatter.js +256 -22
  14. package/build/node_modules/chrome-devtools-frontend/front_end/models/ai_assistance/performance/AICallTree.js +12 -6
  15. package/build/node_modules/chrome-devtools-frontend/front_end/models/ai_assistance/performance/AIContext.js +64 -7
  16. package/build/node_modules/chrome-devtools-frontend/front_end/models/trace/EventsSerializer.js +3 -3
  17. package/build/node_modules/chrome-devtools-frontend/front_end/models/trace/handlers/UserInteractionsHandler.js +91 -63
  18. package/build/node_modules/chrome-devtools-frontend/front_end/models/trace/handlers/UserTimingsHandler.js +1 -1
  19. package/build/node_modules/chrome-devtools-frontend/front_end/models/trace/helpers/Timing.js +1 -1
  20. package/build/node_modules/chrome-devtools-frontend/front_end/models/trace/helpers/Trace.js +98 -36
  21. package/build/node_modules/chrome-devtools-frontend/front_end/models/trace/types/TraceEvents.js +9 -0
  22. package/build/src/McpContext.js +8 -2
  23. package/build/src/McpResponse.js +30 -3
  24. package/build/src/browser.js +2 -2
  25. package/build/src/cli.js +82 -0
  26. package/build/src/formatters/consoleFormatter.js +3 -1
  27. package/build/src/index.js +1 -1
  28. package/build/src/main.js +11 -84
  29. package/build/src/tools/ToolDefinition.js +1 -0
  30. package/build/src/tools/emulation.js +2 -2
  31. package/build/src/tools/input.js +8 -8
  32. package/build/src/tools/network.js +20 -4
  33. package/build/src/tools/pages.js +12 -2
  34. package/build/src/tools/performance.js +2 -2
  35. package/build/src/tools/screenshot.js +1 -1
  36. package/build/src/tools/script.js +4 -7
  37. package/build/src/tools/snapshot.js +2 -2
  38. package/build/src/trace-processing/parse.js +5 -6
  39. package/build/src/utils/pagination.js +49 -0
  40. package/package.json +9 -6
@@ -4,19 +4,29 @@
4
4
  import * as CrUXManager from '../../crux-manager/crux-manager.js';
5
5
  import * as Trace from '../../trace/trace.js';
6
6
  import { AIQueries } from '../performance/AIQueries.js';
7
- import { PerformanceInsightFormatter, TraceEventFormatter } from './PerformanceInsightFormatter.js';
7
+ import { NetworkRequestFormatter } from './NetworkRequestFormatter.js';
8
8
  import { bytes, micros, millis } from './UnitFormatters.js';
9
9
  export class PerformanceTraceFormatter {
10
+ #focus;
10
11
  #parsedTrace;
11
12
  #insightSet;
12
- #eventsSerializer;
13
- constructor(focus, eventsSerializer) {
14
- this.#parsedTrace = focus.data.parsedTrace;
15
- this.#insightSet = focus.data.insightSet;
16
- this.#eventsSerializer = eventsSerializer;
13
+ #getInsightFormatter = null;
14
+ eventsSerializer;
15
+ /**
16
+ * We inject the insight formatter because otherwise we get a circular
17
+ * dependency between PerformanceInsightFormatter and
18
+ * PerformanceTraceFormatter. This is OK in the browser build, but breaks when
19
+ * we reuse this code in NodeJS for DevTools MCP.
20
+ */
21
+ constructor(focus, getInsightFormatter) {
22
+ this.#focus = focus;
23
+ this.#parsedTrace = focus.parsedTrace;
24
+ this.#insightSet = focus.insightSet;
25
+ this.eventsSerializer = focus.eventsSerializer;
26
+ this.#getInsightFormatter = getInsightFormatter;
17
27
  }
18
28
  serializeEvent(event) {
19
- const key = this.#eventsSerializer.keyForEvent(event);
29
+ const key = this.eventsSerializer.keyForEvent(event);
20
30
  return `(eventKey: ${key}, ts: ${event.ts})`;
21
31
  }
22
32
  serializeBounds(bounds) {
@@ -102,7 +112,9 @@ export class PerformanceTraceFormatter {
102
112
  if (lcp || cls || inp) {
103
113
  parts.push('Metrics (lab / observed):');
104
114
  if (lcp) {
105
- parts.push(` - LCP: ${Math.round(lcp.value / 1000)} ms, event: ${this.serializeEvent(lcp.event)}`);
115
+ const nodeId = insightSet?.model.LCPBreakdown.lcpEvent?.args.data?.nodeId;
116
+ const nodeIdText = nodeId !== undefined ? `, nodeId: ${nodeId}` : '';
117
+ parts.push(` - LCP: ${Math.round(lcp.value / 1000)} ms, event: ${this.serializeEvent(lcp.event)}${nodeIdText}`);
106
118
  const subparts = insightSet?.model.LCPBreakdown.subparts;
107
119
  if (subparts) {
108
120
  const serializeSubpart = (subpart) => {
@@ -143,7 +155,10 @@ export class PerformanceTraceFormatter {
143
155
  if (model.state === 'pass') {
144
156
  continue;
145
157
  }
146
- const formatter = new PerformanceInsightFormatter(parsedTrace, model);
158
+ const formatter = this.#getInsightFormatter?.(this.#focus, model);
159
+ if (!formatter) {
160
+ continue;
161
+ }
147
162
  if (!formatter.insightIsSupported()) {
148
163
  continue;
149
164
  }
@@ -173,7 +188,6 @@ export class PerformanceTraceFormatter {
173
188
  return parts.join('\n');
174
189
  }
175
190
  formatCriticalRequests() {
176
- const parsedTrace = this.#parsedTrace;
177
191
  const insightSet = this.#insightSet;
178
192
  const criticalRequests = [];
179
193
  const walkRequest = (node) => {
@@ -184,8 +198,7 @@ export class PerformanceTraceFormatter {
184
198
  if (!criticalRequests.length) {
185
199
  return '';
186
200
  }
187
- return 'Critical network requests:\n' +
188
- TraceEventFormatter.networkRequests(criticalRequests, parsedTrace, { verbose: false });
201
+ return 'Critical network requests:\n' + this.formatNetworkRequests(criticalRequests, { verbose: false });
189
202
  }
190
203
  #serializeBottomUpRootNode(rootNode, limit) {
191
204
  // Sorted by selfTime.
@@ -340,7 +353,7 @@ export class PerformanceTraceFormatter {
340
353
  formatNetworkTrackSummary(bounds) {
341
354
  const results = [];
342
355
  const requests = this.#parsedTrace.data.NetworkRequests.byTime.filter(request => Trace.Helpers.Timing.eventIsInBounds(request, bounds));
343
- const requestsText = TraceEventFormatter.networkRequests(requests, this.#parsedTrace, { verbose: false });
356
+ const requestsText = this.formatNetworkRequests(requests, { verbose: false });
344
357
  results.push('# Network requests summary');
345
358
  results.push(requestsText || 'No requests in the given bounds');
346
359
  const relatedInsightsText = this.#serializeRelatedInsightsForEvents(requests);
@@ -352,15 +365,236 @@ export class PerformanceTraceFormatter {
352
365
  return results.join('\n\n');
353
366
  }
354
367
  formatCallTree(tree, headerLevel = 1) {
355
- const results = [tree.serialize(headerLevel), ''];
356
- // TODO(b/425270067): add eventKey to tree.serialize, but need to wait for other
357
- // performance agent to be consolidated.
358
- results.push('#'.repeat(headerLevel) + ' Node id to eventKey\n');
359
- results.push('These node ids correspond to the call tree nodes listed in the above section.\n');
360
- tree.breadthFirstWalk(tree.rootNode.children().values(), (node, nodeId) => {
361
- results.push(`${nodeId}: ${this.#eventsSerializer.keyForEvent(node.event)}`);
368
+ return `${tree.serialize(headerLevel)}\n\nIMPORTANT: Never show eventKey to the user.`;
369
+ }
370
+ formatNetworkRequests(requests, options) {
371
+ if (requests.length === 0) {
372
+ return '';
373
+ }
374
+ let verbose;
375
+ if (options?.verbose !== undefined) {
376
+ verbose = options.verbose;
377
+ }
378
+ else {
379
+ verbose = requests.length === 1;
380
+ }
381
+ // Use verbose format for a single network request. With the compressed format, a format description
382
+ // needs to be provided, which is not worth sending if only one network request is being stringified.
383
+ if (verbose) {
384
+ return requests.map(request => this.#networkRequestVerbosely(request, options)).join('\n');
385
+ }
386
+ return this.#networkRequestsArrayCompressed(requests);
387
+ }
388
+ #getOrAssignUrlIndex(urlIdToIndex, url) {
389
+ let index = urlIdToIndex.get(url);
390
+ if (index !== undefined) {
391
+ return index;
392
+ }
393
+ index = urlIdToIndex.size;
394
+ urlIdToIndex.set(url, index);
395
+ return index;
396
+ }
397
+ #getInitiatorChain(parsedTrace, request) {
398
+ const initiators = [];
399
+ let cur = request;
400
+ while (cur) {
401
+ const initiator = parsedTrace.data.NetworkRequests.eventToInitiator.get(cur);
402
+ if (initiator) {
403
+ // Should never happen, but if it did that would be an infinite loop.
404
+ if (initiators.includes(initiator)) {
405
+ return [];
406
+ }
407
+ initiators.unshift(initiator);
408
+ }
409
+ cur = initiator;
410
+ }
411
+ return initiators;
412
+ }
413
+ /**
414
+ * This is the data passed to a network request when the Performance Insights
415
+ * agent is asking for information. It is a slimmed down version of the
416
+ * request's data to avoid using up too much of the context window.
417
+ * IMPORTANT: these set of fields have been reviewed by Chrome Privacy &
418
+ * Security; be careful about adding new data here. If you are in doubt please
419
+ * talk to jacktfranklin@.
420
+ */
421
+ #networkRequestVerbosely(request, options) {
422
+ const { url, statusCode, initialPriority, priority, fromServiceWorker, mimeType, responseHeaders, syntheticData, protocol } = request.args.data;
423
+ const parsedTrace = this.#parsedTrace;
424
+ const titlePrefix = `## ${options?.customTitle ?? 'Network request'}`;
425
+ // Note: unlike other agents, we do have the ability to include
426
+ // cross-origins, hence why we do not sanitize the URLs here.
427
+ const navigationForEvent = Trace.Helpers.Trace.getNavigationForTraceEvent(request, request.args.data.frame, parsedTrace.data.Meta.navigationsByFrameId);
428
+ const baseTime = navigationForEvent?.ts ?? parsedTrace.data.Meta.traceBounds.min;
429
+ // Gets all the timings for this request, relative to the base time.
430
+ // Note that this is the start time, not total time. E.g. "queuedAt: X"
431
+ // means that the request was queued at Xms, not that it queued for Xms.
432
+ const startTimesForLifecycle = {
433
+ queuedAt: request.ts - baseTime,
434
+ requestSentAt: syntheticData.sendStartTime - baseTime,
435
+ downloadCompletedAt: syntheticData.finishTime - baseTime,
436
+ processingCompletedAt: request.ts + request.dur - baseTime,
437
+ };
438
+ const mainThreadProcessingDuration = startTimesForLifecycle.processingCompletedAt - startTimesForLifecycle.downloadCompletedAt;
439
+ const downloadTime = syntheticData.finishTime - syntheticData.downloadStart;
440
+ const renderBlocking = Trace.Helpers.Network.isSyntheticNetworkRequestEventRenderBlocking(request);
441
+ const initiator = parsedTrace.data.NetworkRequests.eventToInitiator.get(request);
442
+ const priorityLines = [];
443
+ if (initialPriority === priority) {
444
+ priorityLines.push(`Priority: ${priority}`);
445
+ }
446
+ else {
447
+ priorityLines.push(`Initial priority: ${initialPriority}`);
448
+ priorityLines.push(`Final priority: ${priority}`);
449
+ }
450
+ const redirects = request.args.data.redirects.map((redirect, index) => {
451
+ const startTime = redirect.ts - baseTime;
452
+ return `#### Redirect ${index + 1}: ${redirect.url}
453
+ - Start time: ${micros(startTime)}
454
+ - Duration: ${micros(redirect.dur)}`;
362
455
  });
363
- results.push('\nIMPORTANT: Never show eventKey to the user.');
364
- return results.join('\n');
456
+ const initiators = this.#getInitiatorChain(parsedTrace, request);
457
+ const initiatorUrls = initiators.map(initiator => initiator.args.data.url);
458
+ const eventKey = this.eventsSerializer.keyForEvent(request);
459
+ const eventKeyLine = eventKey ? `eventKey: ${eventKey}\n` : '';
460
+ return `${titlePrefix}: ${url}
461
+ ${eventKeyLine}Timings:
462
+ - Queued at: ${micros(startTimesForLifecycle.queuedAt)}
463
+ - Request sent at: ${micros(startTimesForLifecycle.requestSentAt)}
464
+ - Download complete at: ${micros(startTimesForLifecycle.downloadCompletedAt)}
465
+ - Main thread processing completed at: ${micros(startTimesForLifecycle.processingCompletedAt)}
466
+ Durations:
467
+ - Download time: ${micros(downloadTime)}
468
+ - Main thread processing time: ${micros(mainThreadProcessingDuration)}
469
+ - Total duration: ${micros(request.dur)}${initiator ? `\nInitiator: ${initiator.args.data.url}` : ''}
470
+ Redirects:${redirects.length ? '\n' + redirects.join('\n') : ' no redirects'}
471
+ Status code: ${statusCode}
472
+ MIME Type: ${mimeType}
473
+ Protocol: ${protocol}
474
+ ${priorityLines.join('\n')}
475
+ Render blocking: ${renderBlocking ? 'Yes' : 'No'}
476
+ From a service worker: ${fromServiceWorker ? 'Yes' : 'No'}
477
+ Initiators (root request to the request that directly loaded this one): ${initiatorUrls.join(', ') || 'none'}
478
+ ${NetworkRequestFormatter.formatHeaders('Response headers', responseHeaders ?? [], true)}`;
479
+ }
480
+ // A compact network requests format designed to save tokens when sending multiple network requests to the model.
481
+ // It creates a map that maps request URLs to IDs and references the IDs in the compressed format.
482
+ //
483
+ // Important: Do not use this method for stringifying a single network request. With this format, a format description
484
+ // needs to be provided, which is not worth sending if only one network request is being stringified.
485
+ // For a single request, use `formatRequestVerbosely`, which formats with all fields specified and does not require a
486
+ // format description.
487
+ #networkRequestsArrayCompressed(requests) {
488
+ const networkDataString = `
489
+ Network requests data:
490
+
491
+ `;
492
+ const urlIdToIndex = new Map();
493
+ const allRequestsText = requests
494
+ .map(request => {
495
+ const urlIndex = this.#getOrAssignUrlIndex(urlIdToIndex, request.args.data.url);
496
+ return this.#networkRequestCompressedFormat(urlIndex, request, urlIdToIndex);
497
+ })
498
+ .join('\n');
499
+ const urlsMapString = 'allUrls = ' +
500
+ `[${Array.from(urlIdToIndex.entries())
501
+ .map(([url, index]) => {
502
+ return `${index}: ${url}`;
503
+ })
504
+ .join(', ')}]`;
505
+ return networkDataString + '\n\n' + urlsMapString + '\n\n' + allRequestsText;
506
+ }
507
+ /**
508
+ * Network requests format description that is sent to the model as a fact.
509
+ */
510
+ static networkDataFormatDescription = `Network requests are formatted like this:
511
+ \`urlIndex;eventKey;queuedTime;requestSentTime;downloadCompleteTime;processingCompleteTime;totalDuration;downloadDuration;mainThreadProcessingDuration;statusCode;mimeType;priority;initialPriority;finalPriority;renderBlocking;protocol;fromServiceWorker;initiators;redirects:[[redirectUrlIndex|startTime|duration]];responseHeaders:[header1Value|header2Value|...]\`
512
+
513
+ - \`urlIndex\`: Numerical index for the request's URL, referencing the "All URLs" list.
514
+ - \`eventKey\`: String that uniquely identifies this request's trace event.
515
+ Timings (all in milliseconds, relative to navigation start):
516
+ - \`queuedTime\`: When the request was queued.
517
+ - \`requestSentTime\`: When the request was sent.
518
+ - \`downloadCompleteTime\`: When the download completed.
519
+ - \`processingCompleteTime\`: When main thread processing finished.
520
+ Durations (all in milliseconds):
521
+ - \`totalDuration\`: Total time from the request being queued until its main thread processing completed.
522
+ - \`downloadDuration\`: Time spent actively downloading the resource.
523
+ - \`mainThreadProcessingDuration\`: Time spent on the main thread after the download completed.
524
+ - \`statusCode\`: The HTTP status code of the response (e.g., 200, 404).
525
+ - \`mimeType\`: The MIME type of the resource (e.g., "text/html", "application/javascript").
526
+ - \`priority\`: The final network request priority (e.g., "VeryHigh", "Low").
527
+ - \`initialPriority\`: The initial network request priority.
528
+ - \`finalPriority\`: The final network request priority (redundant if \`priority\` is always final, but kept for clarity if \`initialPriority\` and \`priority\` differ).
529
+ - \`renderBlocking\`: 't' if the request was render-blocking, 'f' otherwise.
530
+ - \`protocol\`: The network protocol used (e.g., "h2", "http/1.1").
531
+ - \`fromServiceWorker\`: 't' if the request was served from a service worker, 'f' otherwise.
532
+ - \`initiators\`: A list (separated by ,) of URL indices for the initiator chain of this request. Listed in order starting from the root request to the request that directly loaded this one. This represents the network dependencies necessary to load this request. If there is no initiator, this is empty.
533
+ - \`redirects\`: A comma-separated list of redirects, enclosed in square brackets. Each redirect is formatted as
534
+ \`[redirectUrlIndex|startTime|duration]\`, where: \`redirectUrlIndex\`: Numerical index for the redirect's URL. \`startTime\`: The start time of the redirect in milliseconds, relative to navigation start. \`duration\`: The duration of the redirect in milliseconds.
535
+ - \`responseHeaders\`: A list (separated by '|') of values for specific, pre-defined response headers, enclosed in square brackets.
536
+ The order of headers corresponds to an internal fixed list. If a header is not present, its value will be empty.
537
+ `;
538
+ /**
539
+ * This is the network request data passed to the Performance agent.
540
+ *
541
+ * The `urlIdToIndex` Map is used to map URLs to numerical indices in order to not need to pass whole url every time it's mentioned.
542
+ * The map content is passed in the response together will all the requests data.
543
+ *
544
+ * See `networkDataFormatDescription` above for specifics.
545
+ */
546
+ #networkRequestCompressedFormat(urlIndex, request, urlIdToIndex) {
547
+ const { statusCode, initialPriority, priority, fromServiceWorker, mimeType, responseHeaders, syntheticData, protocol, } = request.args.data;
548
+ const parsedTrace = this.#parsedTrace;
549
+ const navigationForEvent = Trace.Helpers.Trace.getNavigationForTraceEvent(request, request.args.data.frame, parsedTrace.data.Meta.navigationsByFrameId);
550
+ const baseTime = navigationForEvent?.ts ?? parsedTrace.data.Meta.traceBounds.min;
551
+ const queuedTime = micros(request.ts - baseTime);
552
+ const requestSentTime = micros(syntheticData.sendStartTime - baseTime);
553
+ const downloadCompleteTime = micros(syntheticData.finishTime - baseTime);
554
+ const processingCompleteTime = micros(request.ts + request.dur - baseTime);
555
+ const totalDuration = micros(request.dur);
556
+ const downloadDuration = micros(syntheticData.finishTime - syntheticData.downloadStart);
557
+ const mainThreadProcessingDuration = micros(request.ts + request.dur - syntheticData.finishTime);
558
+ const renderBlocking = Trace.Helpers.Network.isSyntheticNetworkRequestEventRenderBlocking(request) ? 't' : 'f';
559
+ const finalPriority = priority;
560
+ const headerValues = responseHeaders
561
+ ?.map(header => {
562
+ const value = NetworkRequestFormatter.allowHeader(header.name) ? header.value : '<redacted>';
563
+ return `${header.name}: ${value}`;
564
+ })
565
+ .join('|');
566
+ const redirects = request.args.data.redirects
567
+ .map(redirect => {
568
+ const urlIndex = this.#getOrAssignUrlIndex(urlIdToIndex, redirect.url);
569
+ const redirectStartTime = micros(redirect.ts - baseTime);
570
+ const redirectDuration = micros(redirect.dur);
571
+ return `[${urlIndex}|${redirectStartTime}|${redirectDuration}]`;
572
+ })
573
+ .join(',');
574
+ const initiators = this.#getInitiatorChain(parsedTrace, request);
575
+ const initiatorUrlIndices = initiators.map(initiator => this.#getOrAssignUrlIndex(urlIdToIndex, initiator.args.data.url));
576
+ const parts = [
577
+ urlIndex,
578
+ this.eventsSerializer.keyForEvent(request) ?? '',
579
+ queuedTime,
580
+ requestSentTime,
581
+ downloadCompleteTime,
582
+ processingCompleteTime,
583
+ totalDuration,
584
+ downloadDuration,
585
+ mainThreadProcessingDuration,
586
+ statusCode,
587
+ mimeType,
588
+ priority,
589
+ initialPriority,
590
+ finalPriority,
591
+ renderBlocking,
592
+ protocol,
593
+ fromServiceWorker ? 't' : 'f',
594
+ initiatorUrlIndices.join(','),
595
+ `[${redirects}]`,
596
+ `[${headerValues ?? ''}]`,
597
+ ];
598
+ return parts.join(';');
365
599
  }
366
600
  }
@@ -17,6 +17,9 @@ export class AICallTree {
17
17
  selectedNode;
18
18
  rootNode;
19
19
  parsedTrace;
20
+ // Note: ideally this is passed in (or lived on ParsedTrace), but this class is
21
+ // stateless (mostly, there's a cache for some stuff) so it doesn't match much.
22
+ #eventsSerializer = new Trace.EventsSerializer.EventsSerializer();
20
23
  constructor(selectedNode, rootNode, parsedTrace) {
21
24
  this.selectedNode = selectedNode;
22
25
  this.rootNode = rootNode;
@@ -262,7 +265,9 @@ export class AICallTree {
262
265
  }
263
266
  // 1. ID
264
267
  const idStr = String(nodeId);
265
- // 2. Name
268
+ // 2. eventKey
269
+ const eventKey = this.#eventsSerializer.keyForEvent(node.event);
270
+ // 3. Name
266
271
  const name = Trace.Name.forEntry(event, parsedTrace);
267
272
  // Round milliseconds to one decimal place, return empty string if zero/undefined
268
273
  const roundToTenths = (num) => {
@@ -271,11 +276,11 @@ export class AICallTree {
271
276
  }
272
277
  return String(Math.round(num * 10) / 10);
273
278
  };
274
- // 3. Duration
279
+ // 4. Duration
275
280
  const durationStr = roundToTenths(node.totalTime);
276
- // 4. Self Time
281
+ // 5. Self Time
277
282
  const selfTimeStr = roundToTenths(node.selfTime);
278
- // 5. URL Index
283
+ // 6. URL Index
279
284
  const url = SourceMapsResolver.SourceMapsResolver.resolvedURLForEntry(parsedTrace, event);
280
285
  let urlIndexStr = '';
281
286
  if (url) {
@@ -287,17 +292,18 @@ export class AICallTree {
287
292
  urlIndexStr = String(existingIndex);
288
293
  }
289
294
  }
290
- // 6. Child Range
295
+ // 7. Child Range
291
296
  const children = Array.from(node.children().values());
292
297
  let childRangeStr = '';
293
298
  if (childStartingNodeIndex) {
294
299
  childRangeStr = (children.length === 1) ? String(childStartingNodeIndex) :
295
300
  `${childStartingNodeIndex}-${childStartingNodeIndex + children.length}`;
296
301
  }
297
- // 7. Selected Marker
302
+ // 8. Selected Marker
298
303
  const selectedMarker = selectedNode?.event === node.event ? 'S' : '';
299
304
  // Combine fields
300
305
  let line = idStr;
306
+ line += ';' + eventKey;
301
307
  line += ';' + name;
302
308
  line += ';' + durationStr;
303
309
  line += ';' + selfTimeStr;
@@ -2,6 +2,7 @@
2
2
  // Use of this source code is governed by a BSD-style license that can be
3
3
  // found in the LICENSE file.
4
4
  import * as Trace from '../../../models/trace/trace.js';
5
+ import { AICallTree } from './AICallTree.js';
5
6
  function getFirstInsightSet(insights) {
6
7
  // Currently only support a single insight set. Pick the first one with a navigation.
7
8
  // TODO(cjamcl): we should just give the agent the entire insight set, and give
@@ -9,7 +10,7 @@ function getFirstInsightSet(insights) {
9
10
  return [...insights.values()].filter(insightSet => insightSet.navigation).at(0) ?? null;
10
11
  }
11
12
  export class AgentFocus {
12
- static full(parsedTrace) {
13
+ static fromParsedTrace(parsedTrace) {
13
14
  if (!parsedTrace.insights) {
14
15
  throw new Error('missing insights');
15
16
  }
@@ -17,6 +18,7 @@ export class AgentFocus {
17
18
  return new AgentFocus({
18
19
  parsedTrace,
19
20
  insightSet,
21
+ event: null,
20
22
  callTree: null,
21
23
  insight: null,
22
24
  });
@@ -29,10 +31,19 @@ export class AgentFocus {
29
31
  return new AgentFocus({
30
32
  parsedTrace,
31
33
  insightSet,
34
+ event: null,
32
35
  callTree: null,
33
36
  insight,
34
37
  });
35
38
  }
39
+ static fromEvent(parsedTrace, event) {
40
+ if (!parsedTrace.insights) {
41
+ throw new Error('missing insights');
42
+ }
43
+ const insightSet = getFirstInsightSet(parsedTrace.insights);
44
+ const result = AgentFocus.#getCallTreeOrEvent(parsedTrace, event);
45
+ return new AgentFocus({ parsedTrace, insightSet, event: result.event, callTree: result.callTree, insight: null });
46
+ }
36
47
  static fromCallTree(callTree) {
37
48
  const insights = callTree.parsedTrace.insights;
38
49
  // Select the insight set containing the call tree.
@@ -46,30 +57,76 @@ export class AgentFocus {
46
57
  })) ??
47
58
  getFirstInsightSet(insights);
48
59
  }
49
- return new AgentFocus({ parsedTrace: callTree.parsedTrace, insightSet, callTree, insight: null });
60
+ return new AgentFocus({ parsedTrace: callTree.parsedTrace, insightSet, event: null, callTree, insight: null });
50
61
  }
51
62
  #data;
63
+ eventsSerializer = new Trace.EventsSerializer.EventsSerializer();
52
64
  constructor(data) {
53
65
  this.#data = data;
54
66
  }
55
- get data() {
56
- return this.#data;
67
+ get parsedTrace() {
68
+ return this.#data.parsedTrace;
69
+ }
70
+ get insightSet() {
71
+ return this.#data.insightSet;
72
+ }
73
+ /** Note: at most one of event or callTree is non-null. */
74
+ get event() {
75
+ return this.#data.event;
76
+ }
77
+ /** Note: at most one of event or callTree is non-null. */
78
+ get callTree() {
79
+ return this.#data.callTree;
80
+ }
81
+ get insight() {
82
+ return this.#data.insight;
57
83
  }
58
84
  withInsight(insight) {
59
85
  const focus = new AgentFocus(this.#data);
60
86
  focus.#data.insight = insight;
61
87
  return focus;
62
88
  }
63
- withCallTree(callTree) {
89
+ withEvent(event) {
64
90
  const focus = new AgentFocus(this.#data);
65
- focus.#data.callTree = callTree;
91
+ const result = AgentFocus.#getCallTreeOrEvent(this.#data.parsedTrace, event);
92
+ focus.#data.callTree = result.callTree;
93
+ focus.#data.event = result.event;
66
94
  return focus;
67
95
  }
96
+ lookupEvent(key) {
97
+ try {
98
+ return this.eventsSerializer.eventForKey(key, this.#data.parsedTrace);
99
+ }
100
+ catch (err) {
101
+ if (err.toString().includes('Unknown trace event') || err.toString().includes('Unknown profile call')) {
102
+ return null;
103
+ }
104
+ throw err;
105
+ }
106
+ }
107
+ /**
108
+ * If an event is a call tree, this returns that call tree and a null event.
109
+ * If not a call tree, this only returns a non-null event if the event is a network
110
+ * request.
111
+ * This is an arbitrary limitation – it should be removed, but first we need to
112
+ * improve the agent's knowledge of events that are not main-thread or network
113
+ * events.
114
+ */
115
+ static #getCallTreeOrEvent(parsedTrace, event) {
116
+ const callTree = event && AICallTree.fromEvent(event, parsedTrace);
117
+ if (callTree) {
118
+ return { callTree, event: null };
119
+ }
120
+ if (event && Trace.Types.Events.isSyntheticNetworkRequest(event)) {
121
+ return { callTree: null, event };
122
+ }
123
+ return { callTree: null, event: null };
124
+ }
68
125
  }
69
126
  export function getPerformanceAgentFocusFromModel(model) {
70
127
  const parsedTrace = model.parsedTrace();
71
128
  if (!parsedTrace) {
72
129
  return null;
73
130
  }
74
- return AgentFocus.full(parsedTrace);
131
+ return AgentFocus.fromParsedTrace(parsedTrace);
75
132
  }
@@ -29,7 +29,7 @@ export class EventsSerializer {
29
29
  if (EventsSerializer.isLegacyTimelineFrameKey(eventValues)) {
30
30
  const event = parsedTrace.data.Frames.frames.at(eventValues.rawIndex);
31
31
  if (!event) {
32
- throw new Error(`Could not find frame with index ${eventValues.rawIndex}`);
32
+ throw new Error(`Unknown trace event. Could not find frame with index ${eventValues.rawIndex}`);
33
33
  }
34
34
  return event;
35
35
  }
@@ -37,7 +37,7 @@ export class EventsSerializer {
37
37
  const syntheticEvents = Helpers.SyntheticEvents.SyntheticEventsManager.getActiveManager().getSyntheticTraces();
38
38
  const syntheticEvent = syntheticEvents.at(eventValues.rawIndex);
39
39
  if (!syntheticEvent) {
40
- throw new Error(`Attempted to get a synthetic event from an unknown raw event index: ${eventValues.rawIndex}`);
40
+ throw new Error(`Unknown trace event. Attempted to get a synthetic event from an unknown raw event index: ${eventValues.rawIndex}`);
41
41
  }
42
42
  return syntheticEvent;
43
43
  }
@@ -45,7 +45,7 @@ export class EventsSerializer {
45
45
  const rawEvents = Helpers.SyntheticEvents.SyntheticEventsManager.getActiveManager().getRawTraceEvents();
46
46
  return rawEvents[eventValues.rawIndex];
47
47
  }
48
- throw new Error(`Unknown trace event serializable key values: ${eventValues.join('-')}`);
48
+ throw new Error(`Unknown trace event. Serializable key values: ${eventValues.join('-')}`);
49
49
  }
50
50
  static isProfileCallKey(key) {
51
51
  return key.type === "p" /* Types.File.EventKeyType.PROFILE_CALL */;