chrome-devtools-frontend 1.0.1575174 → 1.0.1575635

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 (89) hide show
  1. package/.stylelintrc.json +1 -1
  2. package/front_end/core/host/InspectorFrontendHostAPI.ts +2 -0
  3. package/front_end/core/sdk/CSSMatchedStyles.ts +27 -0
  4. package/front_end/entrypoints/main/MainImpl.ts +13 -7
  5. package/front_end/entrypoints/node_app/app/NodeConnectionsPanel.ts +3 -2
  6. package/front_end/generated/InspectorBackendCommands.ts +37 -0
  7. package/front_end/generated/protocol-mapping.d.ts +257 -0
  8. package/front_end/generated/protocol-proxy-api.d.ts +256 -0
  9. package/front_end/generated/protocol.ts +359 -0
  10. package/front_end/models/ai_assistance/AiConversation.ts +31 -10
  11. package/front_end/models/ai_assistance/AiHistoryStorage.ts +1 -0
  12. package/front_end/models/ai_assistance/agents/AiAgent.ts +29 -5
  13. package/front_end/models/ai_assistance/agents/ContextSelectionAgent.snapshot.txt +73 -0
  14. package/front_end/models/ai_assistance/agents/ContextSelectionAgent.ts +141 -0
  15. package/front_end/models/ai_assistance/ai_assistance.ts +2 -0
  16. package/front_end/models/javascript_metadata/NativeFunctions.js +5 -0
  17. package/front_end/models/live-metrics/LiveMetrics.ts +31 -51
  18. package/front_end/models/stack_trace/StackTrace.ts +2 -1
  19. package/front_end/panels/ai_assistance/AiAssistancePanel.ts +72 -6
  20. package/front_end/panels/ai_assistance/ai_assistance-meta.ts +1 -0
  21. package/front_end/panels/ai_assistance/components/ChatMessage.ts +6 -4
  22. package/front_end/panels/ai_assistance/components/ChatView.ts +5 -6
  23. package/front_end/panels/ai_assistance/components/chatView.css +10 -0
  24. package/front_end/panels/application/StorageView.ts +3 -3
  25. package/front_end/panels/application/preloading/components/preloadingDisabledInfobar.css +1 -1
  26. package/front_end/panels/common/aiCodeCompletionSummaryToolbar.css +1 -1
  27. package/front_end/panels/console/ConsoleContextSelector.ts +4 -3
  28. package/front_end/panels/elements/ElementsTreeElement.ts +2 -2
  29. package/front_end/panels/elements/StylePropertyTreeElement.ts +63 -0
  30. package/front_end/panels/elements/StylesSidebarPane.ts +17 -2
  31. package/front_end/panels/elements/stylePropertiesTreeOutline.css +4 -0
  32. package/front_end/panels/issues/AffectedMetadataAllowedSitesView.ts +3 -3
  33. package/front_end/panels/layer_viewer/Layers3DView.ts +2 -1
  34. package/front_end/panels/lighthouse/LighthouseStartView.ts +7 -6
  35. package/front_end/panels/linear_memory_inspector/LinearMemoryInspectorPane.ts +3 -2
  36. package/front_end/panels/network/RequestConditionsDrawer.ts +2 -3
  37. package/front_end/panels/network/SignedExchangeInfoView.ts +3 -4
  38. package/front_end/panels/network/components/HeaderSectionRow.css +1 -1
  39. package/front_end/panels/recorder/components/RecordingView.ts +2 -2
  40. package/front_end/panels/recorder/components/recordingView.css +5 -0
  41. package/front_end/panels/security/SecurityPanelSidebar.ts +10 -9
  42. package/front_end/panels/settings/AISettingsTab.ts +2 -1
  43. package/front_end/panels/settings/KeybindsSettingsTab.ts +3 -5
  44. package/front_end/panels/settings/SettingsScreen.ts +2 -3
  45. package/front_end/panels/sources/CallStackSidebarPane.ts +10 -0
  46. package/front_end/panels/sources/DebuggerPlugin.ts +18 -12
  47. package/front_end/panels/sources/ScopeChainSidebarPane.ts +4 -3
  48. package/front_end/panels/sources/SourcesNavigator.ts +2 -2
  49. package/front_end/panels/sources/SourcesPanel.ts +6 -3
  50. package/front_end/panels/sources/TabbedEditorContainer.ts +2 -2
  51. package/front_end/panels/sources/sources-meta.ts +2 -1
  52. package/front_end/panels/timeline/TimelinePanel.ts +2 -1
  53. package/front_end/panels/timeline/TimelineUIUtils.ts +2 -2
  54. package/front_end/panels/timeline/components/DetailsView.ts +7 -7
  55. package/front_end/panels/timeline/components/insights/BaseInsightComponent.ts +2 -2
  56. package/front_end/panels/timeline/overlays/components/EntryLabelOverlay.ts +4 -4
  57. package/front_end/panels/whats_new/releaseNoteView.css +1 -1
  58. package/front_end/third_party/chromium/README.chromium +1 -1
  59. package/front_end/third_party/puppeteer/README.chromium +2 -2
  60. package/front_end/third_party/puppeteer/package/lib/cjs/puppeteer/cdp/TargetManager.d.ts.map +1 -1
  61. package/front_end/third_party/puppeteer/package/lib/cjs/puppeteer/cdp/TargetManager.js +30 -25
  62. package/front_end/third_party/puppeteer/package/lib/cjs/puppeteer/cdp/TargetManager.js.map +1 -1
  63. package/front_end/third_party/puppeteer/package/lib/cjs/puppeteer/injected/injected.d.ts +1 -1
  64. package/front_end/third_party/puppeteer/package/lib/cjs/puppeteer/util/Mutex.d.ts +2 -2
  65. package/front_end/third_party/puppeteer/package/lib/cjs/puppeteer/util/version.d.ts +1 -1
  66. package/front_end/third_party/puppeteer/package/lib/cjs/puppeteer/util/version.js +1 -1
  67. package/front_end/third_party/puppeteer/package/lib/es5-iife/puppeteer-core-browser.js +30 -21
  68. package/front_end/third_party/puppeteer/package/lib/esm/puppeteer/cdp/TargetManager.d.ts.map +1 -1
  69. package/front_end/third_party/puppeteer/package/lib/esm/puppeteer/cdp/TargetManager.js +31 -26
  70. package/front_end/third_party/puppeteer/package/lib/esm/puppeteer/cdp/TargetManager.js.map +1 -1
  71. package/front_end/third_party/puppeteer/package/lib/esm/puppeteer/util/version.d.ts +1 -1
  72. package/front_end/third_party/puppeteer/package/lib/esm/puppeteer/util/version.js +1 -1
  73. package/front_end/third_party/puppeteer/package/package.json +3 -3
  74. package/front_end/third_party/puppeteer/package/src/cdp/TargetManager.ts +45 -44
  75. package/front_end/third_party/puppeteer/package/src/util/version.ts +1 -1
  76. package/front_end/ui/components/buttons/Button.ts +2 -2
  77. package/front_end/ui/components/panel_feedback/PreviewToggle.ts +1 -1
  78. package/front_end/ui/components/panel_feedback/panelFeedback.css +1 -1
  79. package/front_end/ui/kit/link/Link.ts +31 -0
  80. package/front_end/ui/legacy/LinkContextMenuProvider.ts +3 -5
  81. package/front_end/ui/legacy/components/object_ui/ObjectPopoverHelper.ts +2 -2
  82. package/front_end/ui/legacy/components/object_ui/ObjectPropertiesSection.ts +336 -250
  83. package/front_end/ui/legacy/inspectorCommon.css +0 -1
  84. package/front_end/ui/legacy/legacy.ts +0 -4
  85. package/front_end/ui/visual_logging/KnownContextValues.ts +4 -0
  86. package/front_end/ui/visual_logging/LoggingDriver.ts +10 -6
  87. package/package.json +1 -1
  88. package/front_end/ui/legacy/XElement.ts +0 -41
  89. package/front_end/ui/legacy/XLink.ts +0 -128
@@ -16,6 +16,7 @@ import {
16
16
  type ResponseData,
17
17
  ResponseType
18
18
  } from './agents/AiAgent.js';
19
+ import {ContextSelectionAgent} from './agents/ContextSelectionAgent.js';
19
20
  import {FileAgent} from './agents/FileAgent.js';
20
21
  import {NetworkAgent} from './agents/NetworkAgent.js';
21
22
  import {PerformanceAgent} from './agents/PerformanceAgent.js';
@@ -87,6 +88,7 @@ export class AiConversation {
87
88
  this.#isReadOnly = isReadOnly;
88
89
  this.#isExternal = isExternal;
89
90
  this.history = this.#reconstructHistory(data);
91
+ // Needs to be last
90
92
  this.#agent = this.#createAgent();
91
93
  }
92
94
 
@@ -226,16 +228,22 @@ export class AiConversation {
226
228
  serialize(): SerializedConversation {
227
229
  return {
228
230
  id: this.id,
229
- history: this.history.map(item => {
230
- if (item.type === ResponseType.USER_QUERY) {
231
- return {...item, imageInput: undefined};
232
- }
233
- // Remove the `confirm()`-function because `structuredClone()` throws on functions
234
- if (item.type === ResponseType.SIDE_EFFECT) {
235
- return {...item, confirm: undefined};
236
- }
237
- return item;
238
- }),
231
+ history: this.history
232
+ .map(item => {
233
+ if (item.type === ResponseType.CONTEXT_CHANGE) {
234
+ return null;
235
+ }
236
+
237
+ if (item.type === ResponseType.USER_QUERY) {
238
+ return {...item, imageInput: undefined};
239
+ }
240
+ // Remove the `confirm()`-function because `structuredClone()` throws on functions
241
+ if (item.type === ResponseType.SIDE_EFFECT) {
242
+ return {...item, confirm: undefined};
243
+ }
244
+ return item;
245
+ })
246
+ .filter(history => !!history),
239
247
  type: this.#type,
240
248
  isExternal: this.#isExternal,
241
249
  };
@@ -266,6 +274,10 @@ export class AiConversation {
266
274
  agent = new PerformanceAgent(options);
267
275
  break;
268
276
  }
277
+ case ConversationType.NONE: {
278
+ agent = new ContextSelectionAgent(options);
279
+ break;
280
+ }
269
281
  }
270
282
  return agent;
271
283
  }
@@ -366,6 +378,10 @@ Time: ${micros(time)}`;
366
378
  }
367
379
 
368
380
  function shouldAddToHistory(data: ResponseData): boolean {
381
+ if (data.type === ResponseType.CONTEXT_CHANGE) {
382
+ return false;
383
+ }
384
+
369
385
  // We don't want to save partial responses to the conversation history.
370
386
  // TODO(crbug.com/463325400): We should save interleaved answers to the history as well.
371
387
  if (data.type === ResponseType.ANSWER && !data.complete) {
@@ -383,6 +399,11 @@ Time: ${micros(time)}`;
383
399
  },
384
400
  options.multimodalInput,
385
401
  )) {
402
+ if (data.type === ResponseType.CONTEXT_CHANGE) {
403
+ this.#type = ConversationType.NETWORK;
404
+ this.#agent = this.#createAgent();
405
+ }
406
+
386
407
  if (shouldAddToHistory(data)) {
387
408
  void this.addHistoryItem(data);
388
409
  }
@@ -8,6 +8,7 @@ import * as Common from '../../core/common/common.js';
8
8
  import {ResponseType, type SerializedResponseData} from './agents/AiAgent.js';
9
9
 
10
10
  export const enum ConversationType {
11
+ NONE = 'none',
11
12
  STYLING = 'freestyler',
12
13
  FILE = 'drjones-file',
13
14
  NETWORK = 'drjones-network-request',
@@ -17,6 +17,7 @@ export const enum ResponseType {
17
17
  ERROR = 'error',
18
18
  QUERYING = 'querying',
19
19
  USER_QUERY = 'user-query',
20
+ CONTEXT_CHANGE = 'context-change'
20
21
  }
21
22
 
22
23
  export const enum ErrorType {
@@ -84,6 +85,11 @@ export interface SideEffectResponse {
84
85
  code?: string;
85
86
  confirm: (confirm: boolean) => void;
86
87
  }
88
+ export interface ContextChangeResponse {
89
+ type: ResponseType.CONTEXT_CHANGE;
90
+ context: unknown;
91
+ }
92
+
87
93
  interface SerializedSideEffectResponse extends Omit<SideEffectResponse, 'confirm'> {}
88
94
 
89
95
  export interface ActionResponse {
@@ -105,13 +111,13 @@ export interface UserQuery {
105
111
  }
106
112
 
107
113
  export type ResponseData = AnswerResponse|SuggestionsResponse|ErrorResponse|ActionResponse|SideEffectResponse|
108
- ThoughtResponse|TitleResponse|QueryingResponse|ContextResponse|UserQuery;
114
+ ThoughtResponse|TitleResponse|QueryingResponse|ContextResponse|UserQuery|ContextChangeResponse;
109
115
 
110
116
  export type SerializedResponseData = AnswerResponse|SuggestionsResponse|ErrorResponse|ActionResponse|
111
117
  SerializedSideEffectResponse|ThoughtResponse|TitleResponse|QueryingResponse|ContextResponse|UserQuery;
112
118
 
113
119
  export type FunctionCallResponseData =
114
- TitleResponse|ThoughtResponse|ActionResponse|SideEffectResponse|SuggestionsResponse;
120
+ TitleResponse|ThoughtResponse|ActionResponse|SideEffectResponse|SuggestionsResponse|ContextChangeResponse;
115
121
 
116
122
  export interface BuildRequestOptions {
117
123
  text: string;
@@ -200,10 +206,14 @@ export abstract class ConversationContext<T> {
200
206
  }
201
207
 
202
208
  export type FunctionCallHandlerResult<Result> = {
209
+ requiresApproval: true,
210
+ }|{
203
211
  result: Result,
204
212
  }|{
205
- requiresApproval: true,
206
- }|{error: string};
213
+ context: unknown,
214
+ }|{
215
+ error: string,
216
+ };
207
217
 
208
218
  export interface FunctionHandlerOptions {
209
219
  /**
@@ -594,6 +604,15 @@ export abstract class AiAgent<T> {
594
604
  yield this.#createErrorResponse(ErrorType.ABORT);
595
605
  break;
596
606
  }
607
+
608
+ if ('context' in result) {
609
+ yield {
610
+ type: ResponseType.CONTEXT_CHANGE,
611
+ context: result.context,
612
+ };
613
+
614
+ return;
615
+ }
597
616
  query = {
598
617
  functionResponse: {
599
618
  name: functionCall.name,
@@ -615,6 +634,7 @@ export abstract class AiAgent<T> {
615
634
  if (isStructuredLogEnabled()) {
616
635
  window.dispatchEvent(new CustomEvent('aiassistancedone'));
617
636
  }
637
+ return;
618
638
  }
619
639
 
620
640
  async *
@@ -622,7 +642,7 @@ export abstract class AiAgent<T> {
622
642
  name: string,
623
643
  args: Record<string, unknown>,
624
644
  options?: FunctionHandlerOptions&{explanation?: string},
625
- ): AsyncGenerator<FunctionCallResponseData, {result: unknown}> {
645
+ ): AsyncGenerator<FunctionCallResponseData, {result: unknown}|{context: unknown}> {
626
646
  const call = this.#functionDeclarations.get(name);
627
647
  if (!call) {
628
648
  throw new Error(`Function ${name} is not found.`);
@@ -733,6 +753,10 @@ export abstract class AiAgent<T> {
733
753
  };
734
754
  }
735
755
 
756
+ if ('context' in result) {
757
+ return result as {context: unknown};
758
+ }
759
+
736
760
  return result as {result: unknown};
737
761
  }
738
762
 
@@ -0,0 +1,73 @@
1
+ Title: FileAgent buildRequest structure matches the snapshot
2
+ Content:
3
+ {
4
+ "client": "CHROME_DEVTOOLS",
5
+ "current_message": {
6
+ "parts": [
7
+ {
8
+ "text": "test input"
9
+ }
10
+ ],
11
+ "role": 1
12
+ },
13
+ "historical_contexts": [
14
+ {
15
+ "parts": [
16
+ {
17
+ "text": "question"
18
+ }
19
+ ],
20
+ "role": 1
21
+ },
22
+ {
23
+ "parts": [
24
+ {
25
+ "text": "answer"
26
+ }
27
+ ],
28
+ "role": 2
29
+ }
30
+ ],
31
+ "function_declarations": [
32
+ {
33
+ "name": "listNetworkRequests",
34
+ "description": "Gives a list of network requests",
35
+ "parameters": {
36
+ "type": 6,
37
+ "description": "",
38
+ "nullable": true,
39
+ "required": [],
40
+ "properties": {}
41
+ }
42
+ },
43
+ {
44
+ "name": "selectNetworkRequest",
45
+ "description": "From the list of selected request select one to debug",
46
+ "parameters": {
47
+ "type": 6,
48
+ "description": "",
49
+ "nullable": true,
50
+ "required": [
51
+ "url"
52
+ ],
53
+ "properties": {
54
+ "url": {
55
+ "type": 1,
56
+ "description": "The url of the requests",
57
+ "nullable": false
58
+ }
59
+ }
60
+ }
61
+ }
62
+ ],
63
+ "options": {},
64
+ "metadata": {
65
+ "disable_user_content_logging": false,
66
+ "string_session_id": "sessionId",
67
+ "user_tier": 3,
68
+ "client_version": "unit_test"
69
+ },
70
+ "functionality_type": 5,
71
+ "client_feature": 9
72
+ }
73
+ === end content
@@ -0,0 +1,141 @@
1
+ // Copyright 2026 The Chromium Authors
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ import * as Host from '../../../core/host/host.js';
6
+ import * as Platform from '../../../core/platform/platform.js';
7
+ import * as Root from '../../../core/root/root.js';
8
+ import * as Logs from '../../logs/logs.js';
9
+
10
+ import {
11
+ type AgentOptions,
12
+ AiAgent,
13
+ type ContextResponse,
14
+ type RequestOptions,
15
+ } from './AiAgent.js';
16
+
17
+ /**
18
+ * WARNING: preamble defined in code is only used when userTier is
19
+ * TESTERS. Otherwise, a server-side preamble is used (see
20
+ * chrome_preambles.gcl). Sync local changes with the server-side.
21
+ */
22
+ const preamble = `
23
+ You are a Web Development Assistant integrated into Chrome DevTools. Your tone is educational, supportive, and technically precise.
24
+ You aim to help developers of all levels, prioritizing teaching web concepts as the primary entry point for any solution.
25
+
26
+ # Considerations
27
+ * Determine what the question the domain of the question is - styling, network, sources, performance or other part of DevTools.
28
+ * When possible proactively try to gather additional data and select context that they user may find relevant to the question they are asking utilizing the function calls available to you.
29
+ * Avoid making assumptions without sufficient evidence, and always seek further clarification if needed.
30
+ * Always explore multiple possible explanations for the observed behavior before settling on a conclusion.
31
+ * When presenting solutions, clearly distinguish between the primary cause and contributing factors.
32
+ * Please answer only if you are sure about the answer. Otherwise, explain why you're not able to answer.
33
+ * When answering, always consider MULTIPLE possible solutions.
34
+ * If you are unable to gather more information provide a comprehensive guide to how to fix the issue using Chrome DevTools and explain how and why.
35
+ * You can suggest any panel or flow in Chrome DevTools that may help the user out
36
+
37
+ # Formatting Guidelines
38
+ * Use Markdown for all code snippets.
39
+ * Always specify the language for code blocks (e.g., \`\`\`css, \`\`\`javascript).
40
+ * Keep text responses concise and scannable.
41
+
42
+ * ALWAYS OUTPUT a list of follow-up queries at the end of your text response. The format is SUGGESTIONS: ["suggestion1", "suggestion2", "suggestion3"]. Make sure that the array and the \`SUGGESTIONS: \` text is in the same line. You're also capable of executing the fix for the issue user mentioned. Reflect this in your suggestions.
43
+ * **CRITICAL** NEVER write full Python programs - you should only write individual statements that invoke a single function from the provided library.
44
+ * **CRITICAL** NEVER output text before a function call. Always do a function call first.
45
+ * **CRITICAL** You are a debugging assistant in DevTools. NEVER provide answers to questions of unrelated topics such as legal advice, financial advice, personal opinions, medical advice, religion, race, politics, sexuality, gender, or any other non web-development topics. Answer "Sorry, I can't answer that. I'm best at questions about debugging web pages." to such questions.
46
+ `;
47
+
48
+ /**
49
+ * One agent instance handles one conversation. Create a new agent
50
+ * instance for a new conversation.
51
+ */
52
+ export class ContextSelectionAgent extends AiAgent<never> {
53
+ readonly preamble = preamble;
54
+ readonly clientFeature = Host.AidaClient.ClientFeature.CHROME_FILE_AGENT;
55
+ get userTier(): string|undefined {
56
+ // TODO: Make this depend on variable.
57
+ return Root.Runtime.hostConfig.devToolsFreestyler?.userTier;
58
+ }
59
+ get options(): RequestOptions {
60
+ const temperature = Root.Runtime.hostConfig.devToolsAiAssistanceFileAgent?.temperature;
61
+ const modelId = Root.Runtime.hostConfig.devToolsAiAssistanceFileAgent?.modelId;
62
+
63
+ return {
64
+ temperature,
65
+ modelId,
66
+ };
67
+ }
68
+
69
+ constructor(opts: AgentOptions) {
70
+ super(opts);
71
+
72
+ this.declareFunction<Record<string, never>>('listNetworkRequests', {
73
+ description: `Gives a list of network requests`,
74
+ parameters: {
75
+ type: Host.AidaClient.ParametersTypes.OBJECT,
76
+ description: '',
77
+ nullable: true,
78
+ required: [],
79
+ properties: {},
80
+ },
81
+ handler: async (_params, options) => {
82
+ if (!options?.approved) {
83
+ return {
84
+ requiresApproval: true,
85
+ };
86
+ }
87
+
88
+ const requestURls = [];
89
+ for (const request of Logs.NetworkLog.NetworkLog.instance().requests()) {
90
+ requestURls.push(request.url());
91
+ }
92
+
93
+ return {
94
+ result: requestURls,
95
+ };
96
+ },
97
+ });
98
+
99
+ this.declareFunction<{url: string}>('selectNetworkRequest', {
100
+ description: `From the list of selected request select one to debug`,
101
+ parameters: {
102
+ type: Host.AidaClient.ParametersTypes.OBJECT,
103
+ description: '',
104
+ nullable: true,
105
+ required: ['url'],
106
+ properties: {
107
+ url: {
108
+ type: Host.AidaClient.ParametersTypes.STRING,
109
+ description: 'The url of the requests',
110
+ nullable: false,
111
+ },
112
+ },
113
+ },
114
+ handler: async ({url}) => {
115
+ // TODO: Switch to using IDs to make is easier to link to as well.
116
+ const request = Logs.NetworkLog.NetworkLog.instance().requests().find(req => {
117
+ return req.url() === Platform.DevToolsPath.urlString`${url}` ||
118
+ req.url() === Platform.DevToolsPath.urlString`${url.slice(0, -1)}` ||
119
+ req.url() === Platform.DevToolsPath.urlString`${url}/`;
120
+ });
121
+
122
+ if (request) {
123
+ return {
124
+ context: request,
125
+ };
126
+ }
127
+
128
+ return {
129
+ error: 'No request found',
130
+ };
131
+ },
132
+ });
133
+ }
134
+
135
+ async * handleContextDetails(): AsyncGenerator<ContextResponse, void, void> {
136
+ }
137
+
138
+ override async enhanceQuery(query: string): Promise<string> {
139
+ return query;
140
+ }
141
+ }
@@ -4,6 +4,7 @@
4
4
 
5
5
  import * as AgentProject from './AgentProject.js';
6
6
  import * as AiAgent from './agents/AiAgent.js';
7
+ import * as ContextSelectionAgent from './agents/ContextSelectionAgent.js';
7
8
  import * as FileAgent from './agents/FileAgent.js';
8
9
  import * as NetworkAgent from './agents/NetworkAgent.js';
9
10
  import * as PatchAgent from './agents/PatchAgent.js';
@@ -40,6 +41,7 @@ export {
40
41
  AiUtils,
41
42
  BuiltInAi,
42
43
  ChangeManager,
44
+ ContextSelectionAgent,
43
45
  ConversationHandler,
44
46
  Debug,
45
47
  EvaluateAction,
@@ -6044,6 +6044,11 @@ export const NativeFunctions = [
6044
6044
  signatures: [["r"]],
6045
6045
  receivers: ["FetchEvent"]
6046
6046
  },
6047
+ {
6048
+ name: "respondWith",
6049
+ signatures: [["agentResponse"]],
6050
+ receivers: ["SubmitEvent"]
6051
+ },
6047
6052
  {
6048
6053
  name: "respondWith",
6049
6054
  signatures: [["paymentAbortedResponse"]],
@@ -62,7 +62,29 @@ export class LiveMetrics extends Common.ObjectWrapper.ObjectWrapper<EventTypes>
62
62
 
63
63
  private constructor() {
64
64
  super();
65
- SDK.TargetManager.TargetManager.instance().observeTargets(this);
65
+ const targetManager = SDK.TargetManager.TargetManager.instance();
66
+ targetManager.observeTargets(this, {scoped: true});
67
+ // Listen for target info changes to detect prerender activation.
68
+ // Scoped observers don't receive events when a prerendered target becomes
69
+ // primary because setScopeTarget() isn't called during that transition.
70
+ targetManager.addEventListener(
71
+ SDK.TargetManager.Events.AVAILABLE_TARGETS_CHANGED, this.#onAvailableTargetsChanged, this);
72
+ }
73
+
74
+ #onAvailableTargetsChanged(): void {
75
+ const primaryTarget = SDK.TargetManager.TargetManager.instance().primaryPageTarget();
76
+ if (primaryTarget && primaryTarget !== this.#target) {
77
+ // Primary target changed (e.g., prerender activation). Switch to it.
78
+ void this.#switchToTarget(primaryTarget);
79
+ }
80
+ }
81
+
82
+ async #switchToTarget(newTarget: SDK.Target.Target): Promise<void> {
83
+ if (this.#target) {
84
+ await this.disable();
85
+ }
86
+ this.#target = newTarget;
87
+ await this.enable();
66
88
  }
67
89
 
68
90
  static instance(opts: {forceNew?: boolean} = {forceNew: false}): LiveMetrics {
@@ -371,31 +393,6 @@ export class LiveMetrics extends Common.ObjectWrapper.ObjectWrapper<EventTypes>
371
393
  this.#sendStatusUpdate();
372
394
  }
373
395
 
374
- async #getFrameForExecutionContextId(executionContextId: Protocol.Runtime.ExecutionContextId):
375
- Promise<SDK.ResourceTreeModel.ResourceTreeFrame|null> {
376
- if (!this.#target) {
377
- return null;
378
- }
379
-
380
- const runtimeModel = this.#target.model(SDK.RuntimeModel.RuntimeModel);
381
- if (!runtimeModel) {
382
- return null;
383
- }
384
-
385
- const executionContext = runtimeModel.executionContext(executionContextId);
386
- if (!executionContext) {
387
- return null;
388
- }
389
-
390
- const frameId = executionContext.frameId;
391
- if (!frameId) {
392
- return null;
393
- }
394
-
395
- const frameManager = SDK.FrameManager.FrameManager.instance();
396
- return await frameManager.getOrWaitForFrame(frameId);
397
- }
398
-
399
396
  async #onBindingCalled(event: {data: Protocol.Runtime.BindingCalledEvent}): Promise<void> {
400
397
  const {data} = event;
401
398
  if (data.name !== Spec.EVENT_BINDING_NAME) {
@@ -407,22 +404,8 @@ export class LiveMetrics extends Common.ObjectWrapper.ObjectWrapper<EventTypes>
407
404
  await this.#mutex.run(async () => {
408
405
  const webVitalsEvent = JSON.parse(data.payload) as Spec.WebVitalsEvent;
409
406
 
410
- // This ensures that `#lastResetContextId` will always be an execution context on the
411
- // primary frame. If we receive events from this execution context then we automatically
412
- // know that they are for the primary frame.
413
- if (this.#lastResetContextId !== data.executionContextId) {
414
- if (webVitalsEvent.name !== 'reset') {
415
- return;
416
- }
417
-
418
- // We should avoid calling this function for every event.
419
- // If an interaction triggers a pre-rendered navigation then the old primary frame could
420
- // be removed before we reach this point, and then it will hang forever.
421
- const frame = await this.#getFrameForExecutionContextId(data.executionContextId);
422
- if (!frame?.isPrimaryFrame()) {
423
- return;
424
- }
425
-
407
+ // Track the execution context from 'reset' events for logInteractionScripts().
408
+ if (webVitalsEvent.name === 'reset') {
426
409
  this.#lastResetContextId = data.executionContextId;
427
410
  }
428
411
 
@@ -464,6 +447,7 @@ export class LiveMetrics extends Common.ObjectWrapper.ObjectWrapper<EventTypes>
464
447
  }
465
448
 
466
449
  async targetAdded(target: SDK.Target.Target): Promise<void> {
450
+ // Scoped observers can also receive events for OOPIFs and workers.
467
451
  if (target !== SDK.TargetManager.TargetManager.instance().primaryPageTarget()) {
468
452
  return;
469
453
  }
@@ -472,20 +456,12 @@ export class LiveMetrics extends Common.ObjectWrapper.ObjectWrapper<EventTypes>
472
456
  }
473
457
 
474
458
  async targetRemoved(target: SDK.Target.Target): Promise<void> {
459
+ // Scoped observers can also receive events for OOPIFs and workers.
475
460
  if (target !== this.#target) {
476
461
  return;
477
462
  }
478
463
  await this.disable();
479
464
  this.#target = undefined;
480
-
481
- // If the user navigates to a page that was pre-rendered then the primary page target
482
- // will be swapped and the old target will be removed. We should ensure live metrics
483
- // remain enabled on the new primary page target.
484
- const primaryPageTarget = SDK.TargetManager.TargetManager.instance().primaryPageTarget();
485
- if (primaryPageTarget) {
486
- this.#target = primaryPageTarget;
487
- await this.enable();
488
- }
489
465
  }
490
466
 
491
467
  async enable(): Promise<void> {
@@ -555,6 +531,10 @@ export class LiveMetrics extends Common.ObjectWrapper.ObjectWrapper<EventTypes>
555
531
  return;
556
532
  }
557
533
 
534
+ // Reset to ensure clean state when re-enabling on a new target.
535
+ // See crbug.com/478832430.
536
+ this.#lastResetContextId = undefined;
537
+
558
538
  await this.#killAllLiveMetricContexts();
559
539
 
560
540
  const runtimeModel = this.#target.model(SDK.RuntimeModel.RuntimeModel);
@@ -79,7 +79,8 @@ export class DebuggableFrameFlavor implements DebuggableFrame {
79
79
  readonly missingDebugInfo?: MissingDebugInfo;
80
80
  readonly sdkFrame: SDK.DebuggerModel.CallFrame;
81
81
 
82
- private constructor(frame: DebuggableFrame) {
82
+ /** Use the static {@link for}. Only public to satisfy the `setFlavor` Ctor type */
83
+ constructor(frame: DebuggableFrame) {
83
84
  this.url = frame.url;
84
85
  this.uiSourceCode = frame.uiSourceCode;
85
86
  this.name = frame.name;