Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(browser-extension): preserve whole Unicode characters at byte limits (#943)

Rudy Mizrahi Celekli75e449ac4922
diff --git a/browser-extension/src/shared/normalize.ts b/browser-extension/src/shared/normalize.ts
index 8cd847f0..0d06e8fc 100644
--- a/browser-extension/src/shared/normalize.ts
+++ b/browser-extension/src/shared/normalize.ts
@@ -46,6 +46,10 @@ function capBytes(text: string, max = MAX_FIELD_BYTES): [string, boolean] {
if (encoder.encode(text.slice(0, mid)).length <= max) lo = mid;
else hi = mid - 1;
}
+ // UTF-16 indices may land between the two halves of an astral character.
+ if (lo > 0 && lo < text.length &&
+ text.charCodeAt(lo - 1) >= 0xd800 && text.charCodeAt(lo - 1) <= 0xdbff &&
+ text.charCodeAt(lo) >= 0xdc00 && text.charCodeAt(lo) <= 0xdfff) lo--;
return [text.slice(0, lo), true];
}
diff --git a/browser-extension/test/unit/unicode-prefix.test.ts b/browser-extension/test/unit/unicode-prefix.test.ts
new file mode 100644
index 00000000..c27d90be
--- /dev/null
+++ b/browser-extension/test/unit/unicode-prefix.test.ts
@@ -0,0 +1,28 @@
+import { expect, it } from 'vitest';
+import { normalizeTurn } from '../../src/shared/normalize.js';
+import { attrValue } from '../../src/shared/otlp.js';
+import { MAX_FIELD_BYTES } from '../../src/shared/vocab.js';
+import type { ChatTurn } from '../../src/shared/types.js';
+const turn = (over: Partial<ChatTurn> = {}): ChatTurn => ({ site: 'claude_web', sessionId: 'session', turnId: 'turn', promptText: 'hi', inputMessages: [], outputMessages: [], responseText: 'ok', toolCalls: [], usage: {}, startedAt: 1700000000000, captureMode: 'sse', ...over });
+it('keeps the largest complete Unicode prefix at each emoji byte boundary', () => {
+ for (const slack of [1, 2, 3, 4, 5]) {
+ const text = 'a'.repeat(MAX_FIELD_BYTES - slack) + '😀tail';
+ let oracle = '', bytes = 0;
+ for (const cp of text) {
+ const size = new TextEncoder().encode(cp).length;
+ if (bytes + size > MAX_FIELD_BYTES)
+ break;
+ oracle += cp;
+ bytes += size;
+ }
+ const r = normalizeTurn(turn({ promptText: text }), 'full').logRecords[0];
+ expect(attrValue(r.attributes, 'beacon.prompt.text')).toBe(oracle);
+ expect(attrValue(r.attributes, 'beacon.field_truncated')).toBe(true);
+ }
+});
+it('preserves complete text exactly at the limit', () => {
+ const text = 'a'.repeat(MAX_FIELD_BYTES - 4) + '😀';
+ const r = normalizeTurn(turn({ promptText: text }), 'full').logRecords[0];
+ expect(attrValue(r.attributes, 'beacon.prompt.text')).toBe(text);
+ expect(attrValue(r.attributes, 'beacon.field_truncated')).toBeUndefined();
+});