Chrome DevTools for coding agents
fix: keep surrogate pairs and emoji whole when truncating titles, names and bodies (#3215)
kevin058adcf6eb70
diff --git a/src/McpResponse.ts b/src/McpResponse.tsindex 9d7fc2d0..1222fd03 100644--- a/src/McpResponse.ts+++ b/src/McpResponse.ts@@ -74,6 +74,7 @@ import type {WithSymbolId} from './utils/id.js';import {stableIdSymbol} from './utils/id.js';import {paginate} from './utils/pagination.js';import {getFilterableResourceType} from './utils/resourceType.js';+import {truncateText} from './utils/text.js';import type {WaitForEventsResult} from './utils/WaitForHelper.js';const {formatBytesToKb} = DevTools.I18n.ByteUtilities;@@ -1871,10 +1872,7 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);}}function truncateTitle(title: string, maxLength = 50): string {- if (title.length <= maxLength) {- return title;- }- return title.slice(0, maxLength - 3) + '...';+ return truncateText(title, maxLength, {includeEllipsisInLength: true});}const collapseWhitespace = (value: string): string => {diff --git a/src/formatters/HeapSnapshotFormatter.ts b/src/formatters/HeapSnapshotFormatter.tsindex 6f89d876..d3227441 100644--- a/src/formatters/HeapSnapshotFormatter.ts+++ b/src/formatters/HeapSnapshotFormatter.ts@@ -13,6 +13,7 @@ import type {} from '../processors/HeapSnapshotManager.js';import {DevTools} from '../third_party/index.js';import type {ByteSizeRange} from '../utils/bytes.js';+import {truncateText} from '../utils/text.js';const {formatBytesToKb} = DevTools.I18n.ByteUtilities;@@ -43,10 +44,7 @@ export function formatName(* Truncates `value` to `maxLength`, appending an ellipsis if it was cut off.*/function truncateValue(value: string, maxLength = MAX_NAME_LENGTH): string {- if (value.length <= maxLength) {- return value;- }- return value.slice(0, maxLength) + '...';+ return truncateText(value, maxLength);}export interface ContextAnalysisReport {diff --git a/src/formatters/NetworkFormatter.ts b/src/formatters/NetworkFormatter.tsindex 4642dc10..326d5988 100644--- a/src/formatters/NetworkFormatter.ts+++ b/src/formatters/NetworkFormatter.ts@@ -11,6 +11,7 @@ import {type HTTPRequest,type HTTPResponse,} from '../third_party/index.js';+import {truncateText} from '../utils/text.js';const BODY_CONTEXT_SIZE_LIMIT = 10000;const URL_CONTEXT_SIZE_LIMIT = 255;@@ -302,10 +303,7 @@ export class NetworkFormatter {}function getSizeLimitedString(text: string, sizeLimit: number): string {- if (text.length > sizeLimit) {- return text.substring(0, sizeLimit) + '... <truncated>';- }- return text;+ return truncateText(text, sizeLimit, {ellipsis: '... <truncated>'});}function convertNetworkRequestConciseToString(diff --git a/src/utils/text.ts b/src/utils/text.tsindex b651b3fd..c3f70b65 100644--- a/src/utils/text.ts+++ b/src/utils/text.ts@@ -4,6 +4,10 @@* SPDX-License-Identifier: Apache-2.0*/+import {DevTools} from '../third_party/index.js';++const {StringUtilities} = DevTools.Platform;+const VALID_PLACEHOLDER_MATCH_PATTERN =/\{(PLACEHOLDER_[a-zA-Z][a-zA-Z0-9_]*)\}/g;@@ -22,3 +26,31 @@ export function substitutePlaceholders(},);}++/**+ * Truncates `text` to at most `maxLength` UTF-16 code units and appends+ * `ellipsis` when anything was cut off. The cut uses devtools-frontend's+ * `StringUtilities.truncateToCodeUnitLength`, which moves back to the last+ * grapheme boundary at or before the limit, so surrogate pairs and emoji+ * sequences stay whole and the result never contains a lone surrogate, which+ * `JSON.stringify` serializes as an escape like `\ud83d` that strict JSON+ * parsers (such as the one the Python MCP SDK uses) reject.+ *+ * With `includeEllipsisInLength`, the ellipsis counts toward `maxLength`.+ */+export function truncateText(+ text: string,+ maxLength: number,+ {+ ellipsis = '...',+ includeEllipsisInLength = false,+ }: {ellipsis?: string; includeEllipsisInLength?: boolean} = {},+): string {+ if (text.length <= maxLength) {+ return text;+ }+ const keep = includeEllipsisInLength+ ? Math.max(0, maxLength - ellipsis.length)+ : maxLength;+ return StringUtilities.truncateToCodeUnitLength(text, keep) + ellipsis;+}diff --git a/tests/McpResponse.test.ts b/tests/McpResponse.test.tsindex 75a7cc70..182012c8 100644--- a/tests/McpResponse.test.ts+++ b/tests/McpResponse.test.ts@@ -92,6 +92,30 @@ after(() => {});describe('McpResponse', () => {+ it('truncates a long page title without splitting a surrogate pair', async () => {+ // The 50 code unit limit leaves 47 for the title; the emoji sits at 46-47.+ const title = 'A'.repeat(46) + '\u{1F600}' + 'B'.repeat(10);+ const page = createMockMcpPage();+ Object.defineProperty(page, 'id', {value: 1});+ page.url.returns('https://example.com/emoji');+ page.getTitle.returns(title);+ const context = createMockMcpContext({selectedPage: page});+ context.getPages.returns([page]);+ context.isPageSelected.returns(true);+ const response = new McpResponse(createMockParsedArguments());+ response.setIncludePages(true);++ const result = await response.handle(context);++ assert.ok(+ getTextContent(result.content[0]).includes(+ `1: ${'A'.repeat(46)}... (https://example.com/emoji)`,+ ),+ getTextContent(result.content[0]),+ );+ assert.doesNotMatch(JSON.stringify(result), /\\ud83d/i);+ });+it('reports only pages opened by the attached action', async () => {const openedTarget = createMockPuppeteerTarget({url: 'https://example.com/opened',diff --git a/tests/formatters/HeapSnapshotFormatter.test.ts b/tests/formatters/HeapSnapshotFormatter.test.tsindex 1e883302..e591f8ba 100644--- a/tests/formatters/HeapSnapshotFormatter.test.ts+++ b/tests/formatters/HeapSnapshotFormatter.test.ts@@ -64,6 +64,14 @@ describe('HeapSnapshotFormatter', () => {assert.strictEqual(formatName(longName, {}), expected);});+ it('does not split a surrogate pair at the truncation point', () => {+ const name = 'a'.repeat(MAX_NAME_LENGTH - 1) + '\u{1F600}' + 'b';+ assert.strictEqual(+ formatName(name, {}),+ 'a'.repeat(MAX_NAME_LENGTH - 1) + '...',+ );+ });+it('escapes newlines in name', () => {assert.strictEqual(formatName('first\r\nsecond\nthird\rfourth', {}),diff --git a/tests/formatters/NetworkFormatter.test.ts b/tests/formatters/NetworkFormatter.test.tsindex 1f8c20f8..27af395a 100644--- a/tests/formatters/NetworkFormatter.test.ts+++ b/tests/formatters/NetworkFormatter.test.ts@@ -141,6 +141,23 @@ describe('NetworkFormatter', () => {assert.equal(formatter.toJSON().url, longUrl);});+ it('does not split a surrogate pair when truncating a url', async () => {+ // 254 characters, then an emoji straddling the 255 code unit mark.+ const prefix = `http://example.com/${'a'.repeat(235)}`;+ const url = `${prefix}\u{1F600}${'b'.repeat(20)}`;+ const request = getMockRequest({url});+ const formatter = await NetworkFormatter.from(request, {+ requestId: 1,+ saveFile: async () => ({filename: ''}),+ redactNetworkHeaders: false,+ });++ assert.equal(+ formatter.toString(),+ `reqid=1 GET ${prefix}... <truncated> [pending]`,+ );+ });+it('truncates data: urls', async () => {const dataUrl = `data:image/png;base64,${'A'.repeat(5000)}`;const request = getMockRequest({url: dataUrl});diff --git a/tests/utils/text.test.ts b/tests/utils/text.test.tsnew file mode 100644index 00000000..5e7f6072--- /dev/null+++ b/tests/utils/text.test.ts@@ -0,0 +1,77 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++import assert from 'node:assert';+import {describe, it} from 'node:test';++import {truncateText} from '../../src/utils/text.js';++const EMOJI = '\u{1F600}';+// Family emoji: four code points joined with zero-width joiners.+const FAMILY = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}';++describe('truncateText', () => {+ it('returns text within the limit unchanged', () => {+ assert.strictEqual(truncateText('abc', 3), 'abc');+ assert.strictEqual(truncateText('abc', 10), 'abc');+ });++ it('cuts plain text at the limit and appends the ellipsis', () => {+ assert.strictEqual(truncateText('abcdef', 4), 'abcd...');+ assert.strictEqual(+ truncateText('abcdef', 4, {ellipsis: '... <truncated>'}),+ 'abcd... <truncated>',+ );+ });++ it('counts the ellipsis toward the limit when asked', () => {+ assert.strictEqual(+ truncateText('abcdefgh', 6, {includeEllipsisInLength: true}),+ 'abc...',+ );+ assert.strictEqual(+ truncateText('abcdef', 6, {includeEllipsisInLength: true}),+ 'abcdef',+ );+ });++ it('moves the cut back before a surrogate pair that straddles the limit', () => {+ const text = 'ab' + EMOJI + 'cd';+ assert.strictEqual(truncateText(text, 3), 'ab...');+ assert.strictEqual(truncateText(text, 4), 'ab' + EMOJI + '...');+ // The result must survive a strict JSON round-trip without a lone escape.+ assert.doesNotMatch(JSON.stringify(truncateText(text, 3)), /\\ud83d/i);+ });++ it('counts the limit in UTF-16 code units', () => {+ // 4 graphemes but 5 code units: over a limit of 4.+ assert.strictEqual(+ truncateText('ab' + EMOJI + 'c', 4),+ 'ab' + EMOJI + '...',+ );+ assert.strictEqual(truncateText('ab' + EMOJI + 'c', 5), 'ab' + EMOJI + 'c');+ });++ it('bounds the output for text made of long grapheme clusters', () => {+ const text = FAMILY.repeat(20000);+ const result = truncateText(text, 10000);+ assert.ok(result.length <= 10000 + '...'.length, String(result.length));+ assert.ok(result.endsWith('...'));+ assert.strictEqual(result.slice(0, -3).length % FAMILY.length, 0);+ });++ it('does not break a joined emoji sequence', () => {+ const text = 'a' + FAMILY + 'b';+ // FAMILY is 11 code units long.+ assert.strictEqual(truncateText(text, 12), 'a' + FAMILY + '...');+ assert.strictEqual(truncateText(text, 11), 'a...');+ assert.strictEqual(truncateText(text, 1), 'a...');+ });++ it('returns only the ellipsis for a zero limit', () => {+ assert.strictEqual(truncateText('abc', 0), '...');+ });+});