🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(trace-table): decode unicode in truncated JSONs (#9686)
Nimar53bfe18801b5
diff --git a/web/src/components/ui/IOTableCell.tsx b/web/src/components/ui/IOTableCell.tsxindex 965a4cec13..34fe7056ca 100644--- a/web/src/components/ui/IOTableCell.tsx+++ b/web/src/components/ui/IOTableCell.tsx@@ -11,6 +11,7 @@ import {HoverCardContent,HoverCardTrigger,} from "@/src/components/ui/hover-card";+import { decodeUnicodeEscapesOnly } from "@/src/utils/unicode";const IOTableCellContent = ({data,@@ -35,15 +36,18 @@ const IOTableCellContent = ({className,)}>- {stringifiedJson}+ {stringifiedJson+ ? decodeUnicodeEscapesOnly(stringifiedJson, true)+ : stringifiedJson}</div>) : shouldTruncate ? (<div className="ph-no-capture grid h-full grid-cols-1"><JSONView- json={+ json={decodeUnicodeEscapesOnly(stringifiedJson.slice(0, IO_TABLE_CHAR_LIMIT) +- `...[truncated ${stringifiedJson.length - IO_TABLE_CHAR_LIMIT} characters]`- }+ `...[truncated ${stringifiedJson.length - IO_TABLE_CHAR_LIMIT} characters]`,+ true, // greedy mode for double-escaped Unicode (e.g., \\uXXXX)+ )}className={cn("h-full w-full self-stretch rounded-sm", className)}codeClassName="py-1 px-2 min-h-0 h-full overflow-y-auto"collapseStringsAfterLength={null} // in table, show full strings as row height is fixed@@ -54,7 +58,9 @@ const IOTableCellContent = ({</div>) : (<JSONView- json={data}+ json={+ stringifiedJson ? decodeUnicodeEscapesOnly(stringifiedJson, true) : data+ }className={cn("ph-no-capture h-full w-full self-stretch rounded-sm",className,diff --git a/web/src/utils/unicode.clienttest.ts b/web/src/utils/unicode.clienttest.tsnew file mode 100644index 0000000000..c7a73b8d8a--- /dev/null+++ b/web/src/utils/unicode.clienttest.ts@@ -0,0 +1,73 @@+import { decodeUnicodeEscapesOnly } from "@/src/utils/unicode";++describe("decodeUnicodeEscapesOnly", () => {+ it("should decode basic Unicode escapes (Chinese, Korean)", () => {+ expect(decodeUnicodeEscapesOnly("\\u4f60\\u597d")).toBe("ä½ å¥½"); // Chinese "hello"+ expect(decodeUnicodeEscapesOnly("\\uc548\\ub155")).toBe("안녕"); // Korean "hello"+ });++ it("should decode surrogate pairs, i.e. emoji", () => {+ expect(decodeUnicodeEscapesOnly("\\ud83d\\ude00")).toBe("😀"); // grinning face+ expect(decodeUnicodeEscapesOnly("Hello \\ud83d\\udc4b World")).toBe(+ "Hello 👋 World",+ ); // waving hand+ });++ it("should handle multi-backslash scenarios", () => {+ // Even number of backslashes: literal backslash + uXXXX (not decoded)+ expect(decodeUnicodeEscapesOnly("\\\\u4f60")).toBe("\\u4f60");++ // Odd number (3): literal backslash + decoded unicode+ expect(decodeUnicodeEscapesOnly("\\\\\\u4f60")).toBe("\\ä½ ");+ });++ it("should be robust to truncation", () => {+ // Incomplete escape sequence at end+ expect(decodeUnicodeEscapesOnly("text \\u4f")).toBe("text \\u4f");++ // Incomplete surrogate pair (high surrogate only)+ expect(decodeUnicodeEscapesOnly("text \\ud83d")).toBe("text \\ud83d");++ // Invalid hex digits+ expect(decodeUnicodeEscapesOnly("\\uZZZZ")).toBe("\\uZZZZ");+ });++ it("should preserve other escape sequences", () => {+ expect(decodeUnicodeEscapesOnly('\\"hello\\"')).toBe('\\"hello\\"');+ expect(decodeUnicodeEscapesOnly("\\n\\t\\r")).toBe("\\n\\t\\r");+ expect(decodeUnicodeEscapesOnly("\\\\")).toBe("\\\\");+ });++ it("should handle mixed content", () => {+ expect(+ decodeUnicodeEscapesOnly(+ '{"name": "\\u4f60\\u597d", "emoji": "\\ud83d\\ude00"}',+ ),+ ).toBe('{"name": "ä½ å¥½", "emoji": "😀"}');+ });++ it("should handle no escapes", () => {+ expect(decodeUnicodeEscapesOnly("")).toBe("");+ expect(decodeUnicodeEscapesOnly("hello world")).toBe("hello world");+ expect(decodeUnicodeEscapesOnly("Hello 👋 World")).toBe("Hello 👋 World");+ });++ describe("greedy mode", () => {+ it("should decode double-escaped Unicode in greedy mode", () => {+ // \\uXXXX / \\\\uXXXX decodes to character+ expect(decodeUnicodeEscapesOnly("\\\\u4f60\\\\u597d", true)).toBe("ä½ å¥½");+ });++ it("should decode double-escaped surrogate pairs in greedy mode", () => {+ // Greedy mode with emoji+ expect(decodeUnicodeEscapesOnly("\\\\ud83d\\\\ude00", true)).toBe("😀");+ });++ it("should handle mixed content in greedy mode", () => {+ const input = '{"content": "\\\\uc885\\\\ubd80\\\\uc138"}';+ expect(decodeUnicodeEscapesOnly(input, true)).toBe(+ '{"content": "종부세"}',+ );+ });+ });+});diff --git a/web/src/utils/unicode.ts b/web/src/utils/unicode.tsnew file mode 100644index 0000000000..2c8e5b5a88--- /dev/null+++ b/web/src/utils/unicode.ts@@ -0,0 +1,203 @@+const BACKSLASH = 92;+const U_CHAR = 117;+// high surrogate is the first code of a surrogate pair (\uD83D\uDE00 -> 😀)+const HIGH_SURROGATE_START = 0xd800;+const HIGH_SURROGATE_END = 0xdbff;+// low surrogate is the 2nd pair.+const LOW_SURROGATE_START = 0xdc00;+const LOW_SURROGATE_END = 0xdfff;++/**+ * Decodes ONLY \uXXXX unicode escapes. Does not touch other escapes like \" \\n \\t etc.+ * Handles surrogate pairs (\uD83D\uDE00 -> 😀). Robust to truncation/invalid hex.+ * Invalid/truncated \uXXXX are left literal. Collapses paired backslashes before 'u' based on parity.+ * greedy mode decodes all \uXXXX patterns regardless of backslash escaping (e.g., \\u4F60 -> ä½ ).+ *+ * Used to make i.e. chinese characters render from truncated JSON strings where+ * JSON.parse would fail.+ *+ * Custom (i.e. no regex) implementation for performance to only have a single pass over characters.+ * Overoptimized? yes, probably..+ * see also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt+ *+ * @param input - The string to decode+ * @param greedy - If true, decodes all \uXXXX patterns (ignores backslash escaping rules)+ */+export function decodeUnicodeEscapesOnly(+ input: string,+ greedy: boolean = false,+): string {+ const n = input.length;+ const out: string[] = [];+ let i = 0;+ let lastEmit = 0;++ const hex = (cc: number): number => {+ if (cc >= 48 && cc <= 57) return cc - 48; // 0-9+ if (cc >= 65 && cc <= 70) return cc - 55; // A-F+ if (cc >= 97 && cc <= 102) return cc - 87; // a-f+ return -1;+ };++ // parse 4 hex digits (abcd) at given position, return unicode or -1 if invalid+ const parseHex4 = (str: string, pos: number): number => {+ const a = hex(str.charCodeAt(pos));+ const b = hex(str.charCodeAt(pos + 1));+ const c = hex(str.charCodeAt(pos + 2));+ const d = hex(str.charCodeAt(pos + 3));+ // bit shift instead of multiplication for performance, recreating the 16bit unicode+ return (a | b | c | d) >= 0 ? (a << 12) | (b << 8) | (c << 4) | d : -1;+ };++ // Try decoding surrogate pair starting at position (after first \uXXXX)+ // Returns decoded character + bytes consumed, or null if not valid+ const tryDecodeSurrogatePair = (+ str: string,+ pos: number,+ high: number,+ maxLen: number,+ ): { decoded: string; consumed: number } | null => {+ if (high < HIGH_SURROGATE_START || high > HIGH_SURROGATE_END) return null;+ if (pos + 6 > maxLen) return null;+ if (str.charCodeAt(pos) !== BACKSLASH) return null;+ if (str.charCodeAt(pos + 1) !== U_CHAR) return null;++ const low = parseHex4(str, pos + 2);+ if (low === -1) return null;+ if (low < LOW_SURROGATE_START || low > LOW_SURROGATE_END) return null;++ const cp =+ ((high - HIGH_SURROGATE_START) << 10) ++ (low - LOW_SURROGATE_START) ++ 0x10000;+ return { decoded: String.fromCodePoint(cp), consumed: 6 };+ };++ // Greedy mode: decode all \uXXXX patterns (ignores backslash parity)+ if (greedy) {+ while (i < n) {+ if (input.charCodeAt(i) !== BACKSLASH) {+ i++;+ continue;+ }++ // count backslashes before 'u'+ let j = i + 1;+ while (j < n && input.charCodeAt(j) === BACKSLASH) j++;++ // look for 'u' after backslashes+ if (j < n && input.charCodeAt(j) === U_CHAR && j + 5 <= n) {+ const codeUnit = parseHex4(input, j + 1);+ if (codeUnit !== -1) {+ // Emit everything up to the backslash run+ if (lastEmit < i) out.push(input.slice(lastEmit, i));++ // surrogate pair decoding+ const pair = tryDecodeSurrogatePair(input, j + 5, codeUnit, n);+ if (pair) {+ out.push(pair.decoded);+ i = j + 5 + pair.consumed;+ lastEmit = i;+ continue;+ }++ // regular unicode characters+ out.push(String.fromCharCode(codeUnit));+ i = j + 5;+ lastEmit = i;+ continue;+ }+ }++ // No valid \uXXXX pattern, move past the backslash(es)+ i = j;+ }++ if (lastEmit < n) out.push(input.slice(lastEmit));+ return out.join("");+ }++ // Non-greedy mode: respect backslash parity+ while (i < n) {+ // is not a '\'? continue+ if (input.charCodeAt(i) !== BACKSLASH) {+ i++;+ continue;+ }++ // count backslashes in run+ let j = i + 1;+ while (j < n && input.charCodeAt(j) === BACKSLASH) j++;+ const run = j - i;++ // only consider backslash if directly followed by 'u'+ if (j < n && input.charCodeAt(j) === U_CHAR) {+ // Emit preceding literal and collapse paired backslashes+ if (lastEmit < i) out.push(input.slice(lastEmit, i));+ const pairs = run >> 1;+ if (pairs) out.push("\\".repeat(pairs));++ if ((run & 1) === 0) {+ // Even run: the 'u' is not escaped -> leave it untouched+ i = j;+ lastEmit = i;+ continue;+ }++ // Odd run: attempt to decode \uXXXX starting at j+ if (j + 5 <= n) {+ const codeUnit = parseHex4(input, j + 1);+ if (codeUnit !== -1) {+ // Try surrogate pair decoding+ const pair = tryDecodeSurrogatePair(input, j + 5, codeUnit, n);+ if (pair) {+ out.push(pair.decoded);+ i = j + 5 + pair.consumed;+ lastEmit = i;+ continue;+ }++ // Lone high surrogate -> leave literal \uXXXX+ if (+ codeUnit >= HIGH_SURROGATE_START &&+ codeUnit <= HIGH_SURROGATE_END+ ) {+ out.push("\\u" + input.slice(j + 1, j + 5));+ i = j + 5;+ lastEmit = i;+ continue;+ }++ // Low surrogate alone? leave literal (ill-formed)+ if (+ codeUnit >= LOW_SURROGATE_START &&+ codeUnit <= LOW_SURROGATE_END+ ) {+ out.push("\\u" + input.slice(j + 1, j + 5));+ i = j + 5;+ lastEmit = i;+ continue;+ }++ // normal unicode code unit of BMP (non emoji unicode char)+ out.push(String.fromCharCode(codeUnit));+ i = j + 5;+ lastEmit = i;+ continue;+ }+ }++ // Odd run but invalid/truncated hex -> emit '\u' literally+ out.push("\\u");+ i = j + 1;+ lastEmit = i;+ continue;+ }++ // '\' not followed by 'u', don't do anything+ i = j;+ }++ if (lastEmit < n) out.push(input.slice(lastEmit));+ return out.join("");+}