chrome-devtools-frontend 1.0.1735750 → 1.0.1736236

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 (112) hide show
  1. package/.agents/skills/code-review/SKILL.md +1 -0
  2. package/.agents/skills/devtools-uistrings/SKILL.md +147 -0
  3. package/DIR_METADATA +6 -0
  4. package/docs/cookbook/localization.md +1 -1
  5. package/eslint.config.mjs +0 -1
  6. package/front_end/application_tokens.css +1 -1
  7. package/front_end/core/host/AidaClient.ts +147 -202
  8. package/front_end/core/host/AidaClientTypes.ts +9 -0
  9. package/front_end/core/host/AidaErrors.ts +416 -0
  10. package/front_end/core/host/AidaGcaTranslation.ts +11 -0
  11. package/front_end/core/host/InspectorFrontendHostAPI.ts +9 -2
  12. package/front_end/core/host/UserMetrics.ts +25 -0
  13. package/front_end/core/host/UserMetricsEnums.ts +25 -0
  14. package/front_end/core/host/host.ts +3 -1
  15. package/front_end/core/i18n/collect-ui-strings.js +20 -0
  16. package/front_end/core/root/Runtime.ts +12 -0
  17. package/front_end/core/sdk/NetworkManager.ts +0 -6
  18. package/front_end/core/sdk/OverlayModel.ts +0 -6
  19. package/front_end/core/sdk/PrivateVerificationTokensModel.ts +0 -18
  20. package/front_end/core/sdk/RehydratingConnection.ts +5 -2
  21. package/front_end/core/sdk/ResourceTreeModel.ts +0 -42
  22. package/front_end/core/sdk/ScreenCaptureModel.ts +0 -84
  23. package/front_end/core/sdk/ServiceWorkerCacheModel.ts +0 -15
  24. package/front_end/core/sdk/StorageBucketsModel.ts +0 -15
  25. package/front_end/devtools_compatibility.js +57 -2
  26. package/front_end/entrypoints/inspector_main/RenderingOptions.ts +203 -127
  27. package/front_end/entrypoints/inspector_main/renderingOptions.css +5 -0
  28. package/front_end/entrypoints/node_app/app/NodeMain.ts +0 -9
  29. package/front_end/entrypoints/node_app/app/nodeConnectionsPanel.css +0 -22
  30. package/front_end/generated/SupportedCSSProperties.ts +0 -136
  31. package/front_end/generated/protocol-proxy-api.d.ts +231 -231
  32. package/front_end/models/ai_assistance/DOMHelpers.ts +18 -15
  33. package/front_end/models/ai_assistance/ExtensionScope.ts +9 -0
  34. package/front_end/models/ai_assistance/agents/PerformanceAgent.snapshot.txt +13 -13
  35. package/front_end/models/ai_assistance/agents/PerformanceAgent.ts +1 -1
  36. package/front_end/models/ai_assistance/ai_assistance.ts +2 -0
  37. package/front_end/models/ai_assistance/data_formatters/PerformanceInsightFormatter.snapshot.txt +18 -8
  38. package/front_end/models/ai_assistance/data_formatters/PerformanceInsightFormatter.ts +2 -2
  39. package/front_end/models/ai_assistance/data_formatters/PerformanceTraceFormatter.snapshot.txt +103 -81
  40. package/front_end/models/ai_assistance/data_formatters/PerformanceTraceFormatter.ts +15 -203
  41. package/front_end/models/ai_assistance/injected.ts +6 -1
  42. package/front_end/models/ai_assistance/skills/styling.md +8 -10
  43. package/front_end/models/ai_assistance/tools/GetTraceEventByKey.ts +1 -1
  44. package/front_end/models/ai_assistance/tools/SetElementStyles.ts +288 -0
  45. package/front_end/models/ai_assistance/tools/Tool.ts +1 -0
  46. package/front_end/models/ai_assistance/tools/ToolRegistry.ts +3 -0
  47. package/front_end/models/bindings/ResourceScriptMapping.ts +64 -16
  48. package/front_end/models/javascript_metadata/NativeFunctions.ts +1 -1
  49. package/front_end/models/trace/handlers/FlowsHandler.ts +10 -0
  50. package/front_end/models/trace/handlers/SamplesHandler.ts +3 -2
  51. package/front_end/models/trace/handlers/ScriptsHandler.ts +25 -26
  52. package/front_end/models/trace/helpers/TreeHelpers.ts +4 -0
  53. package/front_end/panels/ai_assistance/components/chatInput.css +4 -4
  54. package/front_end/panels/animation/AnimationTimeline.ts +3 -3
  55. package/front_end/panels/animation/animationTimeline.css +6 -4
  56. package/front_end/panels/application/IndexedDBModel.ts +0 -15
  57. package/front_end/panels/application/appManifestView.css +2 -5
  58. package/front_end/panels/application/components/backForwardCacheView.css +1 -5
  59. package/front_end/panels/application/components/serviceWorkerRouterView.css +2 -2
  60. package/front_end/panels/common/CommentsOverlayWidget.ts +2 -1
  61. package/front_end/panels/console/consolePrompt.css +0 -12
  62. package/front_end/panels/console/consoleView.css +2 -2
  63. package/front_end/panels/developer_resources/developerResourcesView.css +4 -3
  64. package/front_end/panels/elements/DOMTreeWidget.ts +1 -0
  65. package/front_end/panels/elements/StylePropertyTreeElement.ts +2 -1
  66. package/front_end/panels/elements/components/CSSHintDetailsView.ts +12 -5
  67. package/front_end/panels/elements/components/cssVariableValueView.css +1 -1
  68. package/front_end/panels/elements/elementsPanel.css +0 -6
  69. package/front_end/panels/emulation/deviceModeView.css +5 -6
  70. package/front_end/panels/explain/components/consoleInsight.css +1 -1
  71. package/front_end/panels/issues/issuesTree.css +1 -1
  72. package/front_end/panels/lighthouse/lighthouseStartView.css +2 -2
  73. package/front_end/panels/linear_memory_inspector/components/linearMemoryInspector.css +1 -1
  74. package/front_end/panels/media/playerMessagesView.css +1 -1
  75. package/front_end/panels/mobile_throttling/throttlingSettingsTab.css +1 -6
  76. package/front_end/panels/network/networkLogView.css +2 -2
  77. package/front_end/panels/performance_monitor/performanceMonitor.css +0 -4
  78. package/front_end/panels/protocol_monitor/JSONEditor.ts +4 -2
  79. package/front_end/panels/recorder/recordingListView.css +1 -1
  80. package/front_end/panels/screencast/screencastView.css +1 -1
  81. package/front_end/panels/search/searchResultsPane.css +1 -1
  82. package/front_end/panels/security/SecurityModel.ts +0 -6
  83. package/front_end/panels/security/SecurityPanel.ts +120 -108
  84. package/front_end/panels/security/originView.css +1 -1
  85. package/front_end/panels/sensors/locationsSettingsTab.css +2 -2
  86. package/front_end/panels/settings/emulation/devicesSettingsTab.css +0 -52
  87. package/front_end/panels/settings/settingsScreen.css +0 -7
  88. package/front_end/panels/sources/breakpointsView.css +0 -2
  89. package/front_end/panels/sources/components/HeadersView.ts +15 -2
  90. package/front_end/panels/sources/watchExpressionsSidebarPane.css +0 -1
  91. package/front_end/panels/timeline/TimelineLoader.ts +16 -6
  92. package/front_end/panels/timeline/TimelinePanel.ts +7 -2
  93. package/front_end/panels/timeline/components/cwvMetrics.css +1 -1
  94. package/front_end/panels/timeline/components/sidebarAnnotationsTab.css +4 -4
  95. package/front_end/third_party/chromium/README.chromium +1 -1
  96. package/front_end/ui/components/input/textInput.css +1 -1
  97. package/front_end/ui/legacy/DockController.ts +1 -1
  98. package/front_end/ui/legacy/UIUtils.ts +148 -10
  99. package/front_end/ui/legacy/components/perf_ui/pieChart.css +1 -1
  100. package/front_end/ui/legacy/components/utils/TargetDetachedDialog.ts +0 -3
  101. package/front_end/ui/legacy/components/utils/imagePreview.css +1 -1
  102. package/front_end/ui/legacy/inspectorCommon.css +1 -14
  103. package/front_end/ui/legacy/inspectorDrawerTabbedPane.css +3 -2
  104. package/front_end/ui/legacy/theme_support/ThemeSupport.ts +44 -9
  105. package/front_end/ui/lit/strip-whitespace.ts +1 -1
  106. package/package.json +3 -3
  107. package/front_end/generated/Deprecation.ts +0 -471
  108. package/front_end/panels/accessibility/axBreadcrumbs.css +0 -155
  109. package/front_end/panels/network/requestHeadersTree.css +0 -226
  110. package/front_end/panels/recorder/startView.css +0 -38
  111. package/front_end/panels/security/ipProtectionView.css +0 -141
  112. package/front_end/ui/legacy/components/inline_editor/animationNameSwatch.css +0 -27
@@ -42,6 +42,7 @@ Load the skill or `.agents/rules/` files that match what the diff touches, and a
42
42
  | Ported Chromium web tests (`web_tests/http/tests/devtools`) | `migrate-chromium-test` |
43
43
  | Flaky or disabled tests, or `it.skip` / `it.skipOnPlatforms` | `fix-tests` |
44
44
  | Rendering user-controlled strings (URLs, names, console text) | `devtools-unicode-escaping` |
45
+ | Adding or modifying `UIStrings` or `@description` / `@example` L10n comments | `devtools-uistrings` |
45
46
  | `front_end/models/*`, `BUILD.gn`, `devtools_grd_files.gni`, entrypoints | `devtools-model-management` |
46
47
  | Reviewing foundation, models, and build configs (`front_end/(core|models|entrypoints|generated)/**`, `BUILD.gn`, `*.gni`) | `.agents/rules/models-and-core/*.md` |
47
48
  | Merging modules or consolidating `BUILD.gn` | `merging-devtools-module` |
@@ -0,0 +1,147 @@
1
+ ---
2
+ name: devtools-uistrings
3
+ description: >-
4
+ Reviews added or modified UIStrings and localization (@description / @example)
5
+ comments in Chrome DevTools for UX writing style, inline backtick locking,
6
+ sentence case, UI glossary terminology, translator context, and sibling string
7
+ consistency beyond what ESLint and check-strings.js enforce. Use when a CL or
8
+ local diff adds or edits UIStrings or i18n calls in front_end/. Don't use for
9
+ syntax rules already enforced by l10n ESLint rules or for unlocalized locked
10
+ strings.
11
+ ---
12
+
13
+ # Reviewing DevTools `UIStrings` and Localization Comments
14
+
15
+ Apply these checks when a diff adds or modifies `const UIStrings = { ... }`
16
+ entries or their JSDoc comments in `front_end/`.
17
+
18
+ ## 1. Do Not Flag
19
+
20
+ - **Already enforced by ESLint (`scripts/eslint_rules/lib/l10n-*.ts`):** Do not
21
+ comment on curly apostrophes (`’`) vs. straight quotes (`"`) inside
22
+ `UIStrings` values, Unicode ellipses (`…`) vs. `...`, uppercase `URL`,
23
+ negative contractions (`don’t`, `can’t`, `isn’t`, etc.), single- vs.
24
+ multi-sentence trailing periods, whole-phrase backtick locking, or unused keys
25
+ in regular `*.ts` files.
26
+ - **Already enforced by `third_party/i18n/check-strings.js`:** Do not comment
27
+ on missing/empty `@description` tags, missing `@example` tags for `{PH1}`
28
+ placeholders, unclosed backticks, malformed Markdown links, or `\n` literals.
29
+ - **Exempt strings:** Do not flag `UIStringsNotTranslate`,
30
+ `i18n.i18n.lockedString(...)`, or pre-existing `UIStrings` entries that were
31
+ not modified (including verbatim moves during a refactor).
32
+ - **Non-issues:** Do not nitpick minor `@description` lead-in wording variations
33
+ that are equally clear to translators (e.g., `Tooltip text for…` vs. `Tooltip
34
+ for…`), and do not force synonym swaps where grammar or spec precision breaks
35
+ (e.g., `a suitable Cross-Origin Resource Policy` where `a fit …` is
36
+ ungrammatical, or RFC terms like `additional parameters`).
37
+
38
+ ## 2. Shared Capitalization & DevTools UI Terminology
39
+
40
+ Apply these rules consistently in both `UIStrings` values and `@description`
41
+ comments:
42
+
43
+ - **Sentence case:** Capitalize only the first word, proper nouns, product
44
+ names (`Chrome DevTools`), acronyms, backtick-locked spec terms (e.g.,
45
+ `` '`Trusted Type` violations' ``), and web platform APIs / worker types
46
+ (`Background Fetch API`, `Service Worker` / `Service Workers`, `Web Worker` /
47
+ `Web Workers`).
48
+ - **Panels vs. features/concepts:**
49
+ - Capitalize user-facing panel names (`Console`, `Network`, `Elements`,
50
+ `Sources`, `Performance`, `Memory`, `Application`, `Security`,
51
+ `Lighthouse`, `Recorder`, `Issues`). For multi-word panel or tab names,
52
+ capitalize only the first word (`Developer resources panel`, `Memory
53
+ inspector panel`, `Remote devices tab`). When paired with a noun, keep the
54
+ second word lowercase (`Console panel`, `Console sidebar`, `Memory panel`).
55
+ - Map internal folder or class names to user-facing panel names (`profiler` ->
56
+ `Memory panel`, `Timeline UIUtils` -> `Performance panel`,
57
+ `linear_memory_inspector` -> `Memory inspector panel`).
58
+ - Keep feature, view, tool, and concept names **lowercase** unless starting a
59
+ sentence (`conditional breakpoint`, `command menu`, `quick open`, `heap
60
+ profiler`, `heap snapshot view`, `allocation sampling`, `isolate selector`,
61
+ `summary view`, `console message`, `network log`).
62
+ - **UI glossary & platform terms:** Use `panel`, `tab`, `drawer`, `sidebar`,
63
+ `table` (or `datagrid`), `action bar`, and `status bar`; never call a tab,
64
+ sidebar, or section a `pane`. Prefer `JavaScript modules` over `ES modules`,
65
+ and write `top level` with a space when used as a noun (`The top level of
66
+ JavaScript modules`).
67
+
68
+ ## 3. User-Facing String Values
69
+
70
+ - **Prefer short, everyday synonyms (when grammatical and spec-accurate):**
71
+ - `preserve` -> `keep` | `additional` -> `more` | `prevent` -> `stop`
72
+ - `submit` -> `send` | `modification` -> `change` | `create` -> `add` |
73
+ `suitable` -> `fit`
74
+ - `receive` -> `get` in general prose (e.g., `get the reports`), **except**
75
+ keep `receive` / `received` for network or worker data/message reception
76
+ (e.g., `receive data while cached`, `received a message from a
77
+ SharedWorker`).
78
+ - **Cut filler, politeness & banned branding:** Remove `please`, `sorry`,
79
+ `very`, `strongly`, `there is` / `there are`, marketing adjectives
80
+ (`seamless`, `awesome`, `fast`, `quick`), and `"Powered by AI"` (use neutral
81
+ action labels such as `'Understand this message'`).
82
+ - **Inline backtick-locking (`\`...\``):** Wrap embedded technical tokens (CSS
83
+ properties, values, and media features like `` `print` ``, `` `screen` ``,
84
+ `` `prefers-color-scheme` ``; HTTP headers like `` `Alt-Svc` ``; HTML
85
+ attributes; and JS APIs like `` `console.clear()` ``) in backticks so
86
+ translators do not translate them. Keep spec capitalization inside backticks
87
+ while using sentence case outside (`` '`Trusted Type` violations' ``).
88
+ - **Articles, positive contractions, symbols & actionability:** Avoid fragile
89
+ `a` / `an` articles before `{PH1}` placeholders or initialisms (`HTTP`, `XHR`)
90
+ when shorter article-free phrasing works. Use natural positive contractions
91
+ not checked by ESLint (`it’s`, `you’re`, `we’re`, `that’s`, with curly `’`),
92
+ and use prime (`′`) and double prime (`″`) for measurements or coordinates.
93
+ State how to recover in error messages (e.g., `Shorten filename to 64
94
+ characters or less` instead of `Invalid filename`).
95
+
96
+ ## 4. Localization Comments (`@description` & `@example`)
97
+
98
+ - **Explain UI role and concrete sub-location, never repeat the string:**
99
+ Inspect where `UIStrings.<key>` is called and name the UI element type (button
100
+ label, tooltip, column header, checkbox label, context menu item,
101
+ `aria-label`, status text) and concrete panel/sub-view location instead of
102
+ echoing the message text. Keep specific sub-locations such as `in the summary
103
+ view of the Performance panel` rather than collapsing them to `in the
104
+ Performance panel`.
105
+ - **No internal code or protocol names:** Do not reference C++ identifiers, CDP
106
+ enum names, or class names in `@description` comments. Describe the
107
+ user-visible state instead.
108
+ - **Verify `@example` values against the call site:** Check what
109
+ `i18nString(UIStrings.<key>, {PH1: ...})` passes at runtime (especially
110
+ whether units like `%` or `ms` are already formatted inside `{PH1}` vs.
111
+ outside in the template, e.g., `@example {12.34%} PH2`) and use realistic
112
+ runtime values rather than type names like `{string}`. Do not ask for
113
+ `@example` tags on ICU plural count variables.
114
+ - **Comment formatting:** Use straight apostrophes (`'`) and straight quotes
115
+ (`"`) in code comments (even when `UIStrings` uses curly `’`), and end every
116
+ `@description` with a period (`.`).
117
+
118
+ ```ts
119
+ // Bad: repeats the string, uses internal/legacy names, unlocked token, vague example
120
+ /**
121
+ * @description Text for preserve log checkbox in Timeline UIUtils Pane
122
+ * @example {string} PH1
123
+ */
124
+ preserveLog: 'Please preserve additional print log entries in {PH1}',
125
+
126
+ // Good: role + sub-location, sentence case, locked token, realistic example
127
+ /**
128
+ * @description Checkbox label in the summary view of the Performance panel to
129
+ * keep log entries across page loads.
130
+ * @example {https://example.com} PH1
131
+ */
132
+ keepLog: 'Keep more `print` log entries for {PH1}',
133
+ ```
134
+
135
+ ## 5. Neighbor, Module & Linter-Gap Consistency
136
+
137
+ - **Adjacent `UIStrings` & `-meta.ts` alignment:** Compare added or edited
138
+ entries against neighboring entries in the same `UIStrings` block and
139
+ companion `-meta.ts` file so panel names, feature casing, inline backticks,
140
+ and separators (`or` vs. `/`) stay consistent across sibling strings.
141
+ - **Quoted label renames:** When a CL renames a setting or button label (e.g.,
142
+ `Preserve log` -> `Keep log`), check sibling files in the same module for
143
+ explanatory `UIStrings` that quote the old label (e.g., `` '`console.clear()`
144
+ was prevented due to \'Keep log\'' ``) and update them together.
145
+ - **Unused keys in linter-exempt files:** `l10n-no-unused-message` skips
146
+ `ModuleUIStrings.ts` and `models/trace/insights/*.ts`; flag orphaned keys
147
+ left behind in those files when their last caller is removed.
package/DIR_METADATA CHANGED
@@ -16,6 +16,12 @@ agentic_review: {
16
16
  ".agents/skills/devtools-unicode-escaping/SKILL.md"
17
17
  ]
18
18
  }
19
+ capability_groups: {
20
+ path_expression: ["front_end/.*\\.ts"]
21
+ path_expression_exclusion: [".*\\.test\\.ts"]
22
+ content_patterns: ["UIStrings", "@description", "i18n(String|FormatString|Template)"]
23
+ review_capability_skills: [".agents/skills/devtools-uistrings/SKILL.md"]
24
+ }
19
25
  capability_groups: {
20
26
  path_expression: [
21
27
  "front_end/(core|models|entrypoints|generated)/.*\\.ts",
@@ -108,7 +108,7 @@ console.log(message2);
108
108
  4. The following commands would add the new strings to `en-US.json`:
109
109
 
110
110
  - `git cl presubmit --upload`, or
111
- - `node third_party/i18n/collect-strings.js` under the DevTools src folder
111
+ - `./dt collect-strings` in the DevTools checkout
112
112
 
113
113
  5. Strings containing possible plurals have a special format in ICU. This is
114
114
  because plurals work quite differently in other languages, e.g. special
package/eslint.config.mjs CHANGED
@@ -29,7 +29,6 @@ export default defineConfig([
29
29
  'front_end/diff/diff_match_patch.js',
30
30
  'front_end/models/javascript_metadata/NativeFunctions.ts',
31
31
  // All of these scripts are auto-generated so don't lint them.
32
- 'front_end/generated/Deprecation.ts',
33
32
  'front_end/generated/InspectorBackendCommands.ts',
34
33
  'front_end/generated/protocol-mapping.d.ts',
35
34
  'front_end/generated/protocol-proxy-api.d.ts',
@@ -299,7 +299,7 @@
299
299
  --color-continue-to-location-hover: var(--ref-palette-yellow40);
300
300
  --color-continue-to-location-hover-border: var(--ref-palette-yellow50);
301
301
  --color-continue-to-location-async: var(--ref-palette-green30);
302
- --color-continue-to-location-async-hover: var(--ref-palette-green4);
302
+ --color-continue-to-location-async-hover: var(--ref-palette-green40);
303
303
  --color-continue-to-location-async-hover-border: var(--ref-palette-green50);
304
304
  --color-evaluated-expression: var(--ref-palette-yellow30);
305
305
  --color-evaluated-expression-border: var(--ref-palette-yellow40);
@@ -27,15 +27,42 @@ import {
27
27
  Role,
28
28
  UserTier,
29
29
  } from './AidaClientTypes.js';
30
+ import {
31
+ AidaAbortError,
32
+ AidaBlockError,
33
+ classifyRequestError,
34
+ mapError,
35
+ StreamChunkParseError,
36
+ } from './AidaErrors.js';
30
37
  import {gcaChunkResponseToAidaChunkResponse} from './AidaGcaTranslation.js';
31
38
  import * as DispatchHttpRequestClient from './DispatchHttpRequestClient.js';
32
39
  import * as GcaClient from './GcaClient.js';
33
40
  import type {GenerateContentResponse} from './GcaTypes.js';
34
41
  import {InspectorFrontendHostInstance} from './InspectorFrontendHost.js';
35
- import type {AidaClientResult, AidaCodeCompleteResult, SyncInformation} from './InspectorFrontendHostAPI.js';
42
+ import {
43
+ type AidaClientResult,
44
+ type AidaCodeCompleteResult,
45
+ EnumeratedHistogram,
46
+ type SyncInformation,
47
+ } from './InspectorFrontendHostAPI.js';
36
48
  import {bindOutputStream, discardOutputStream} from './ResourceLoader.js';
49
+ import * as UserMetrics from './UserMetrics.js';
37
50
 
38
51
  export * from './AidaClientTypes.js';
52
+ export {
53
+ AidaAbortError,
54
+ AidaBlockError,
55
+ AidaClientError,
56
+ AidaInvalidJsonResponseError,
57
+ AidaPayloadTooLargeError,
58
+ AidaPermissionDeniedError,
59
+ AidaQuotaError,
60
+ AidaTimeoutError,
61
+ AidaUnknownError,
62
+ isPayloadTooLargeError,
63
+ isQuotaError,
64
+ mapError,
65
+ } from './AidaErrors.js';
39
66
 
40
67
  export const CLIENT_NAME = 'CHROME_DEVTOOLS';
41
68
  export const SERVICE_NAME = 'aidaService';
@@ -61,32 +88,36 @@ const AidaLanguageToMarkdown: Record<AidaInferenceLanguage, string> = {
61
88
  [AidaInferenceLanguage.UNKNOWN]: 'unknown',
62
89
  };
63
90
 
64
- export abstract class AidaClientError extends Error {
65
- override name = 'AidaClientError';
66
- }
67
- export class AidaUnknownError extends AidaClientError {
68
- override name = 'AidaUnknownError';
69
- }
70
- export class AidaAbortError extends AidaClientError {
71
- override name = 'AidaAbortError';
72
- }
73
- export class AidaBlockError extends AidaClientError {
74
- override name = 'AidaBlockError';
75
- }
76
- export class AidaQuotaError extends AidaClientError {
77
- override name = 'AidaQuotaError';
78
- }
79
- export class AidaPayloadTooLargeError extends AidaClientError {
80
- override name = 'AidaPayloadTooLargeError';
81
- }
82
- export class AidaPermissionDeniedError extends AidaClientError {
83
- override name = 'AidaPermissionDeniedError';
84
- }
85
- export class AidaTimeoutError extends AidaClientError {
86
- override name = 'AidaTimeoutError';
91
+ function conversationSurfaceHistogram(feature: ClientFeature): UserMetrics.AiClientSurfaceHistogram|undefined {
92
+ switch (feature) {
93
+ case ClientFeature.CHROME_DEVTOOLS_V2_AGENT:
94
+ return EnumeratedHistogram.AiClientRequestResultAiAssistance;
95
+ case ClientFeature.CHROME_CONSOLE_INSIGHTS:
96
+ return EnumeratedHistogram.AiClientRequestResultConsoleInsights;
97
+ case ClientFeature.CHROME_CONVERSATION_SUMMARY_AGENT:
98
+ return EnumeratedHistogram.AiClientRequestResultConversationSummary;
99
+ case ClientFeature.CHROME_PERFORMANCE_ANNOTATIONS_AGENT:
100
+ return EnumeratedHistogram.AiClientRequestResultPerformanceAnnotations;
101
+ default:
102
+ // Legacy V1 per-panel agents intentionally omit surface slices and record only to the aggregate histogram.
103
+ return undefined;
104
+ }
87
105
  }
88
- export class AidaInvalidJsonResponseError extends AidaClientError {
89
- override name = 'AidaInvalidJsonResponseError';
106
+
107
+ /**
108
+ * Returns a closure that records the request outcome histogram once per call.
109
+ * One-shot recording prevents early generator returns or nested catch/finally blocks from double-counting outcomes.
110
+ */
111
+ function createOutcomeRecorder(surfaceHistogram?: UserMetrics.AiClientSurfaceHistogram):
112
+ (result: UserMetrics.AiClientRequestResult) => void {
113
+ let recorded = false;
114
+ return (result: UserMetrics.AiClientRequestResult): void => {
115
+ if (recorded) {
116
+ return;
117
+ }
118
+ recorded = true;
119
+ UserMetrics.userMetrics.aiClientRequestResult(result, surfaceHistogram);
120
+ };
90
121
  }
91
122
 
92
123
  interface AiStream {
@@ -159,20 +190,21 @@ export class AidaClient {
159
190
  throw new Error('dispatchHttpRequest is not available');
160
191
  }
161
192
 
162
- if (options?.signal?.aborted) {
163
- throw new AidaAbortError();
164
- }
165
-
166
- // Disable logging for now.
167
- // For context, see b/454563259#comment35.
168
- // We should be able to remove this ~end of April.
169
- if (Root.Runtime.hostConfig.devToolsGeminiRebranding?.enabled) {
170
- request.metadata.disable_user_content_logging = true;
171
- }
172
-
193
+ const recordOutcome = createOutcomeRecorder(conversationSurfaceHistogram(request.client_feature));
173
194
  let abortListener: (() => void)|undefined;
174
195
  let streamId: number|undefined;
175
196
  try {
197
+ if (options?.signal?.aborted) {
198
+ throw new AidaAbortError();
199
+ }
200
+
201
+ // Disable logging for now.
202
+ // For context, see b/454563259#comment35.
203
+ // We should be able to remove this ~end of April.
204
+ if (Root.Runtime.hostConfig.devToolsGeminiRebranding?.enabled) {
205
+ request.metadata.disable_user_content_logging = true;
206
+ }
207
+
176
208
  const stream = (() => {
177
209
  let {promise, resolve, reject} = Promise.withResolvers<string|null>();
178
210
  // Prevent unhandled promise rejections if stream.fail() is called after
@@ -223,7 +255,13 @@ export class AidaClient {
223
255
  stream.fail(mapError(err));
224
256
  });
225
257
  yield* this.#handleResponseStream(stream);
258
+ recordOutcome(UserMetrics.AiClientRequestResult.SUCCESS);
259
+ } catch (err) {
260
+ recordOutcome(classifyRequestError(err));
261
+ throw err;
226
262
  } finally {
263
+ // Fallback when a caller exits the generator early (such as breaking out of a for-await loop) before stream completion.
264
+ recordOutcome(UserMetrics.AiClientRequestResult.ABORTED);
227
265
  if (options?.signal && abortListener) {
228
266
  options.signal.removeEventListener('abort', abortListener);
229
267
  }
@@ -246,7 +284,10 @@ export class AidaClient {
246
284
 
247
285
  for (const result of results) {
248
286
  if (result.metadata) {
249
- metadata = result.metadata;
287
+ metadata = {
288
+ ...metadata,
289
+ ...result.metadata,
290
+ };
250
291
  if (metadata?.attributionMetadata?.attributionAction === RecitationAction.BLOCK) {
251
292
  throw new AidaBlockError();
252
293
  }
@@ -326,7 +367,7 @@ export class AidaClient {
326
367
  try {
327
368
  return JSON.parse(chunk);
328
369
  } catch (error) {
329
- throw new Error('Cannot parse chunk: ' + chunk, {cause: error});
370
+ throw new StreamChunkParseError('Cannot parse chunk: ' + chunk, {cause: error});
330
371
  }
331
372
  }
332
373
 
@@ -367,54 +408,68 @@ export class AidaClient {
367
408
  request.metadata.disable_user_content_logging = true;
368
409
  }
369
410
 
370
- if (this.#gcaClient.enabled()) {
371
- try {
372
- return await this.#gcaClient.completeCode(request);
373
- } catch (err) {
374
- throw mapError(err);
411
+ const recordOutcome = createOutcomeRecorder(EnumeratedHistogram.AiClientRequestResultCodeComplete);
412
+ try {
413
+ if (this.#gcaClient.enabled()) {
414
+ try {
415
+ const result = await this.#gcaClient.completeCode(request);
416
+ recordOutcome(UserMetrics.AiClientRequestResult.SUCCESS);
417
+ return result;
418
+ } catch (err) {
419
+ recordOutcome(classifyRequestError(err));
420
+ throw mapError(err);
421
+ }
375
422
  }
376
- }
377
- const {promise, resolve} = Promise.withResolvers<AidaCodeCompleteResult>();
378
- InspectorFrontendHostInstance.aidaCodeComplete(JSON.stringify(request), resolve);
379
- const completeCodeResult = await promise;
423
+ const {promise, resolve} = Promise.withResolvers<AidaCodeCompleteResult>();
424
+ InspectorFrontendHostInstance.aidaCodeComplete(JSON.stringify(request), resolve);
425
+ const completeCodeResult = await promise;
380
426
 
381
- if (completeCodeResult.error) {
382
- throw mapError(completeCodeResult.error, completeCodeResult.detail);
383
- }
384
- const response = completeCodeResult.response;
385
- if (!response?.length) {
386
- throw new Error('Empty response');
387
- }
388
- let parsedResponse;
389
- try {
390
- parsedResponse = JSON.parse(response);
391
- } catch (error) {
392
- throw new Error('Cannot parse response: ' + response, {cause: error});
393
- }
427
+ if (completeCodeResult.error) {
428
+ recordOutcome(classifyRequestError(completeCodeResult.error, completeCodeResult.detail));
429
+ throw mapError(completeCodeResult.error, completeCodeResult.detail);
430
+ }
431
+ const response = completeCodeResult.response;
432
+ if (!response?.length) {
433
+ recordOutcome(UserMetrics.AiClientRequestResult.INVALID_JSON_RESPONSE);
434
+ throw new Error('Empty response');
435
+ }
436
+ let parsedResponse;
437
+ try {
438
+ parsedResponse = JSON.parse(response);
439
+ } catch (error) {
440
+ recordOutcome(UserMetrics.AiClientRequestResult.INVALID_JSON_RESPONSE);
441
+ throw new Error('Cannot parse response: ' + response, {cause: error});
442
+ }
394
443
 
395
- const generatedSamples: GenerationSample[] = [];
396
- let metadata: ResponseMetadata = {rpcGlobalId: 0};
397
- if ('metadata' in parsedResponse) {
398
- metadata = parsedResponse.metadata;
399
- }
444
+ const generatedSamples: GenerationSample[] = [];
445
+ let metadata: ResponseMetadata = {rpcGlobalId: 0};
446
+ if ('metadata' in parsedResponse) {
447
+ metadata = parsedResponse.metadata;
448
+ }
400
449
 
401
- if ('generatedSamples' in parsedResponse) {
402
- for (const generatedSample of parsedResponse.generatedSamples) {
403
- const sample: GenerationSample = {
404
- generationString: generatedSample.generationString,
405
- score: generatedSample.score,
406
- sampleId: generatedSample.sampleId,
407
- };
408
- if ('metadata' in generatedSample && 'attributionMetadata' in generatedSample.metadata) {
409
- sample.attributionMetadata = generatedSample.metadata.attributionMetadata;
450
+ if ('generatedSamples' in parsedResponse) {
451
+ for (const generatedSample of parsedResponse.generatedSamples) {
452
+ const sample: GenerationSample = {
453
+ generationString: generatedSample.generationString,
454
+ score: generatedSample.score,
455
+ sampleId: generatedSample.sampleId,
456
+ };
457
+ if ('metadata' in generatedSample && 'attributionMetadata' in generatedSample.metadata) {
458
+ sample.attributionMetadata = generatedSample.metadata.attributionMetadata;
459
+ }
460
+ generatedSamples.push(sample);
410
461
  }
411
- generatedSamples.push(sample);
462
+ } else {
463
+ recordOutcome(UserMetrics.AiClientRequestResult.SUCCESS);
464
+ return null;
412
465
  }
413
- } else {
414
- return null;
415
- }
416
466
 
417
- return {generatedSamples, metadata};
467
+ recordOutcome(UserMetrics.AiClientRequestResult.SUCCESS);
468
+ return {generatedSamples, metadata};
469
+ } catch (err) {
470
+ recordOutcome(classifyRequestError(err));
471
+ throw err;
472
+ }
418
473
  }
419
474
 
420
475
  async generateCode(request: GenerateCodeRequest, options?: {signal?: AbortSignal}): Promise<GenerateCodeResponse> {
@@ -425,25 +480,21 @@ export class AidaClient {
425
480
  request.metadata.disable_user_content_logging = true;
426
481
  }
427
482
 
428
- if (this.#gcaClient.enabled()) {
429
- // Inline and remove the else clause after migration
430
- try {
431
- return await this.#gcaClient.generateCode(request, options);
432
- } catch (err) {
433
- throw mapError(err);
434
- }
435
- }
483
+ const surfaceHistogram = EnumeratedHistogram.AiClientRequestResultCodeGenerate;
436
484
  try {
437
- const response = await DispatchHttpRequestClient.makeHttpRequest<GenerateCodeResponse>({
438
- service: SERVICE_NAME,
439
- path: '/v1/aida:generateCode',
440
- method: 'POST',
441
- body: JSON.stringify(request),
442
- },
443
- options);
444
-
485
+ const response = this.#gcaClient.enabled() ?
486
+ await this.#gcaClient.generateCode(request, options) :
487
+ await DispatchHttpRequestClient.makeHttpRequest<GenerateCodeResponse>({
488
+ service: SERVICE_NAME,
489
+ path: '/v1/aida:generateCode',
490
+ method: 'POST',
491
+ body: JSON.stringify(request),
492
+ },
493
+ options);
494
+ UserMetrics.userMetrics.aiClientRequestResult(UserMetrics.AiClientRequestResult.SUCCESS, surfaceHistogram);
445
495
  return response;
446
496
  } catch (err) {
497
+ UserMetrics.userMetrics.aiClientRequestResult(classifyRequestError(err), surfaceHistogram);
447
498
  throw mapError(err);
448
499
  }
449
500
  }
@@ -542,109 +593,3 @@ export const enum Events {
542
593
  export interface EventTypes {
543
594
  [Events.AIDA_AVAILABILITY_CHANGED]: AidaAccessPreconditions;
544
595
  }
545
-
546
- /**
547
- * Checks whether any of the provided error strings indicate a quota or rate-limit failure.
548
- *
549
- * AIDA and GCA surface quota errors across different fields (status codes, human-readable
550
- * messages, and serialized `google.rpc.ErrorInfo` details), so we check three substrings:
551
- * - `'quota'`: direct AIDA error messages or details (for example,
552
- * `"Quota exceeded for quota metric 'AiCodeCompleteService'"` or `"USER_QUOTA_EXCEEDED"`).
553
- * - `'resource_exhausted'`: the standard `google.rpc.Code` status string (for example,
554
- * `status: "RESOURCE_EXHAUSTED"` or `"RESOURCE_EXHAUSTED: quota exceeded"`).
555
- * - `'rate_limit_exceeded'`: the `reason` field inside `google.rpc.ErrorInfo` details when
556
- * the message itself does not mention `'quota'` (for example, GCA returning
557
- * `message: "You have exhausted your capacity on this model."` with
558
- * `details: [{"reason": "RATE_LIMIT_EXCEEDED", "domain": "cloudcode-pa.googleapis.com"}]`).
559
- */
560
- export function isQuotaError(...inputs: Array<string|undefined>): boolean {
561
- return inputs.some(input => {
562
- const lower = input?.toLowerCase();
563
- return lower?.includes('quota') || lower?.includes('resource_exhausted') || lower?.includes('rate_limit_exceeded');
564
- });
565
- }
566
-
567
- export function isPayloadTooLargeError(...inputs: Array<string|undefined>): boolean {
568
- return inputs.some(input => input?.toLowerCase().includes('payload size exceeds the limit'));
569
- }
570
-
571
- /**
572
- * Type guard that narrows an `unknown` error value in `mapError` to a plain key-value
573
- * object so structured `google.rpc.Status` fields (`code`, `status`, `message`, `details`)
574
- * can be safely inspected.
575
- */
576
- function isRecord(value: unknown): value is Record<string, unknown> {
577
- return typeof value === 'object' && value !== null && !Array.isArray(value);
578
- }
579
-
580
- /**
581
- * Maps AIDA-specific errors, DispatchHttpRequestErrors, strings, structured
582
- * error objects, and generic Errors to dedicated AidaClientError subclasses.
583
- */
584
- export function mapError(err: unknown, detail?: string): AidaClientError {
585
- if (err instanceof AidaClientError) {
586
- return err;
587
- }
588
-
589
- if (err instanceof DispatchHttpRequestClient.DispatchHttpRequestError) {
590
- if (err.type === DispatchHttpRequestClient.ErrorType.ABORT) {
591
- return new AidaAbortError();
592
- }
593
- const response = err.response;
594
- if (response) {
595
- if (response.statusCode === 429) {
596
- return new AidaQuotaError('Server responded: quota exceeded');
597
- }
598
- if (response.statusCode === 403) {
599
- return new AidaPermissionDeniedError('Server responded: permission denied');
600
- }
601
- if ('netErrorName' in response && response.netErrorName === 'net::ERR_TIMED_OUT') {
602
- return new AidaTimeoutError('AIDA request timed out');
603
- }
604
- if ('error' in response && response.error) {
605
- return mapError(response.error, response.detail);
606
- }
607
- // The dispatcher throws HTTP_RESPONSE_UNAVAILABLE with status code 200
608
- // when it successfully receives the HTTP response but fails to parse its JSON body.
609
- if (response.statusCode === 200 && err.type === DispatchHttpRequestClient.ErrorType.HTTP_RESPONSE_UNAVAILABLE) {
610
- return new AidaInvalidJsonResponseError('Server responded with invalid JSON', {cause: err});
611
- }
612
- if (response.statusCode !== 200) {
613
- return new AidaUnknownError(`Request failed: ${JSON.stringify(response)}`);
614
- }
615
- }
616
- }
617
-
618
- if (typeof err === 'string') {
619
- if (isQuotaError(err, detail)) {
620
- return new AidaQuotaError(`Cannot send request: ${err}${detail ? ` ${detail}` : ''}`);
621
- }
622
- if (isPayloadTooLargeError(err, detail)) {
623
- return new AidaPayloadTooLargeError(`Cannot send request: ${err}${detail ? ` ${detail}` : ''}`);
624
- }
625
- return new AidaUnknownError(`Cannot send request: ${err}${detail ? ` ${detail}` : ''}`);
626
- }
627
-
628
- if (err instanceof Error) {
629
- return new AidaUnknownError(err.message, {cause: err});
630
- }
631
-
632
- if (isRecord(err)) {
633
- const code = typeof err.code === 'number' ? err.code : undefined;
634
- const status = typeof err.status === 'string' ? err.status : undefined;
635
- const message = typeof err.message === 'string' ? err.message : undefined;
636
- const details = err.details !== undefined ? JSON.stringify(err.details) : undefined;
637
- if (code === 429 || isQuotaError(status, message, details)) {
638
- return new AidaQuotaError(message ?? 'Server responded: quota exceeded', {cause: err});
639
- }
640
- if (code === 403 || status === 'PERMISSION_DENIED') {
641
- return new AidaPermissionDeniedError(message ?? 'Server responded: permission denied', {cause: err});
642
- }
643
- if (isPayloadTooLargeError(message, details)) {
644
- return new AidaPayloadTooLargeError(message ?? 'Server responded: payload size exceeds the limit', {cause: err});
645
- }
646
- return new AidaUnknownError(message ?? JSON.stringify(err), {cause: err});
647
- }
648
-
649
- return new AidaUnknownError(String(err));
650
- }
@@ -398,11 +398,20 @@ export interface InferenceOptionMetadata {
398
398
  modelId: string;
399
399
  }
400
400
 
401
+ export interface UsageMetadata {
402
+ promptTokenCount?: number;
403
+ candidatesTokenCount?: number;
404
+ totalTokenCount?: number;
405
+ thoughtsTokenCount?: number;
406
+ cachedContentTokenCount?: number;
407
+ }
408
+
401
409
  export interface ResponseMetadata {
402
410
  rpcGlobalId?: RpcGlobalId;
403
411
  attributionMetadata?: AttributionMetadata;
404
412
  factualityMetadata?: FactualityMetadata;
405
413
  inferenceOptionMetadata?: InferenceOptionMetadata;
414
+ usageMetadata?: UsageMetadata;
406
415
  }
407
416
 
408
417
  export interface DoConversationResponse {