Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(ui): decode unicode escapes in PrettyJsonView for trace detail (#13223)

Yuto Toyae51b3ebcd001
diff --git a/web/src/components/ui/PrettyJsonView.clienttest.ts b/web/src/components/ui/PrettyJsonView.clienttest.ts
new file mode 100644
index 0000000000..7dcf4e0399
--- /dev/null
+++ b/web/src/components/ui/PrettyJsonView.clienttest.ts
@@ -0,0 +1,151 @@
+import {
+ decodeUnicodeInJson,
+ DECODE_UNICODE_MAX_DEPTH,
+ DECODE_UNICODE_MAX_NODES,
+} from "@/src/components/ui/PrettyJsonView";
+
+describe("decodeUnicodeInJson", () => {
+ it("decodes \\uXXXX sequences in string values", () => {
+ expect(decodeUnicodeInJson("\\u4f60\\u597d")).toBe("你好");
+ expect(decodeUnicodeInJson("\\u3053\\u3093\\u306b\\u3061\\u306f")).toBe(
+ "こんにちは",
+ );
+ });
+
+ it("decodes double-escaped \\\\uXXXX sequences (greedy mode)", () => {
+ // Python SDK json.dumps(ensure_ascii=True) nested inside a string field
+ // can produce double-escaped forms depending on the ingest path.
+ expect(decodeUnicodeInJson("\\\\u4f60\\\\u597d")).toBe("你好");
+ });
+
+ it("passes through primitive non-string values unchanged", () => {
+ expect(decodeUnicodeInJson(null)).toBe(null);
+ expect(decodeUnicodeInJson(undefined)).toBe(undefined);
+ expect(decodeUnicodeInJson(42)).toBe(42);
+ expect(decodeUnicodeInJson(true)).toBe(true);
+ expect(decodeUnicodeInJson(false)).toBe(false);
+ });
+
+ it("passes through strings without escape sequences unchanged", () => {
+ expect(decodeUnicodeInJson("hello world")).toBe("hello world");
+ expect(decodeUnicodeInJson("すでに日本語")).toBe("すでに日本語");
+ expect(decodeUnicodeInJson("")).toBe("");
+ });
+
+ it("recursively decodes string values inside an array", () => {
+ expect(decodeUnicodeInJson(["\\u4ee5\\u4e0a", "plain", 123])).toEqual([
+ "以上",
+ "plain",
+ 123,
+ ]);
+ });
+
+ it("recursively decodes string values inside an object", () => {
+ const input = {
+ question: "\\u8cea\\u554f",
+ answer: "\\u56de\\u7b54",
+ score: 0.95,
+ };
+ expect(decodeUnicodeInJson(input)).toEqual({
+ question: "質問",
+ answer: "回答",
+ score: 0.95,
+ });
+ });
+
+ it("recursively decodes deeply nested structures", () => {
+ const input = {
+ trace: {
+ output: {
+ messages: [
+ {
+ role: "assistant",
+ content: "\\u6761\\u4ef6\\u306b\\u5408\\u81f4",
+ },
+ ],
+ },
+ },
+ };
+ expect(decodeUnicodeInJson(input)).toEqual({
+ trace: {
+ output: {
+ messages: [{ role: "assistant", content: "条件に合致" }],
+ },
+ },
+ });
+ });
+
+ it("preserves null and number leaves inside nested structures", () => {
+ const input = {
+ name: "\\u30c6\\u30b9\\u30c8",
+ meta: { count: 3, tags: null, ratio: 0.5 },
+ };
+ expect(decodeUnicodeInJson(input)).toEqual({
+ name: "テスト",
+ meta: { count: 3, tags: null, ratio: 0.5 },
+ });
+ });
+
+ it("decodes surrogate-pair emoji escapes", () => {
+ expect(decodeUnicodeInJson({ reaction: "\\ud83d\\ude00" })).toEqual({
+ reaction: "😀",
+ });
+ });
+
+ it("handles mixed already-decoded and escaped strings", () => {
+ expect(decodeUnicodeInJson({ a: "日本語", b: "\\u4ee5\\u4e0a" })).toEqual({
+ a: "日本語",
+ b: "以上",
+ });
+ });
+
+ it("decodes escaped object keys as well as values", () => {
+ expect(decodeUnicodeInJson({ "\\u8cea\\u554f": "\\u56de\\u7b54" })).toEqual(
+ { 質問: "回答" },
+ );
+ });
+
+ it("decodes escaped keys inside nested structures", () => {
+ const input = {
+ "\\u5916\\u5074": {
+ "\\u5185\\u5074": "\\u5024",
+ },
+ };
+ expect(decodeUnicodeInJson(input)).toEqual({
+ 外側: { 内側: "値" },
+ });
+ });
+
+ it("does not blow the call stack on very deeply nested structures", () => {
+ // Build a chain ~10x deeper than MAX_DEPTH. A recursive implementation would
+ // throw "Maximum call stack size exceeded" here.
+ const chainDepth = DECODE_UNICODE_MAX_DEPTH * 10;
+ let input: Record<string, unknown> = { leaf: "\\u4ee5\\u4e0a" };
+ for (let i = 0; i < chainDepth; i++) {
+ input = { child: input };
+ }
+
+ expect(() => decodeUnicodeInJson(input)).not.toThrow();
+
+ // Leaves within MAX_DEPTH get decoded; deeper subtrees are returned as-is.
+ let result = decodeUnicodeInJson(input) as Record<string, unknown>;
+ for (let i = 0; i < DECODE_UNICODE_MAX_DEPTH - 1; i++) {
+ result = result.child as Record<string, unknown>;
+ }
+ // Below MAX_DEPTH the subtree is kept untouched, so the leaf still contains
+ // the escaped form somewhere further down.
+ expect(result).toBeDefined();
+ });
+
+ it("stops decoding once the node budget is exceeded", () => {
+ // Build an array with > MAX_NODES escaped strings. Entries beyond the budget
+ // should be preserved verbatim (still escaped) rather than throwing or hanging.
+ const items = new Array(DECODE_UNICODE_MAX_NODES + 10).fill(
+ "\\u4ee5\\u4e0a",
+ );
+ const out = decodeUnicodeInJson(items) as string[];
+ expect(out).toHaveLength(items.length);
+ expect(out[0]).toBe("以上");
+ expect(out[out.length - 1]).toBe("\\u4ee5\\u4e0a"); // beyond budget, undecoded
+ });
+});
diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsx
index 2e2f09d44e..af9b387fb1 100644
--- a/web/src/components/ui/PrettyJsonView.tsx
+++ b/web/src/components/ui/PrettyJsonView.tsx
@@ -1,6 +1,7 @@
import { useMemo, useState, useEffect, useRef, useCallback, memo } from "react";
import { cn } from "@/src/utils/tailwind";
import { deepParseJson } from "@langfuse/shared";
+import { decodeUnicodeEscapesOnly } from "@/src/utils/unicode";
import { Skeleton } from "@/src/components/ui/skeleton";
import { type MediaReturnType } from "@/src/features/media/validation";
import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";
@@ -82,6 +83,113 @@ const SYSTEM_TITLES = ["system", "Input"];
const MONO_TEXT_CLASSES = "font-mono text-xs wrap-break-word";
const PREVIEW_TEXT_CLASSES = "italic text-gray-500 dark:text-gray-400";
+// Guards to keep decoding bounded on very large payloads. Exceeding either
+// limit returns the remainder undecoded (preserving browser responsiveness
+// over decoding completeness).
+export const DECODE_UNICODE_MAX_NODES = 50_000;
+export const DECODE_UNICODE_MAX_DEPTH = 200;
+
+/**
+ * Iteratively decode \uXXXX escape sequences in all string values of a parsed JSON
+ * structure. Used so that traces ingested via Python SDK's json.dumps(ensure_ascii=True)
+ * display non-ASCII characters (e.g. Japanese, Chinese) correctly in the trace detail
+ * view. Mirrors the approach used in IOTableCell and batch export (see PR #12882).
+ *
+ * Uses greedy mode to handle both \uXXXX (single-escaped) and \\uXXXX (double-escaped)
+ * forms that can appear depending on the ingest path.
+ *
+ * Implemented iteratively (explicit stack) with node-count and depth caps so that
+ * very large or deeply nested payloads cannot blow the call stack or freeze the tab.
+ */
+export function decodeUnicodeInJson(value: unknown): unknown {
+ if (typeof value === "string") {
+ return decodeUnicodeEscapesOnly(value, true);
+ }
+ if (value === null || typeof value !== "object") {
+ return value;
+ }
+
+ const root: unknown[] | Record<string, unknown> = Array.isArray(value)
+ ? []
+ : {};
+
+ type Frame = {
+ source: unknown[] | Record<string, unknown>;
+ target: unknown[] | Record<string, unknown>;
+ depth: number;
+ };
+ const stack: Frame[] = [
+ {
+ source: value as unknown[] | Record<string, unknown>,
+ target: root,
+ depth: 0,
+ },
+ ];
+
+ let nodeCount = 0;
+ let budgetExceeded = false;
+
+ while (stack.length > 0) {
+ const { source, target, depth } = stack.pop()!;
+
+ if (Array.isArray(source)) {
+ const arr = target as unknown[];
+ for (let i = 0; i < source.length; i++) {
+ const v = source[i];
+ if (budgetExceeded || ++nodeCount > DECODE_UNICODE_MAX_NODES) {
+ budgetExceeded = true;
+ arr[i] = v;
+ continue;
+ }
+ arr[i] = assignDecodedOrDescend(v, depth, stack);
+ }
+ } else {
+ const obj = target as Record<string, unknown>;
+ for (const k of Object.keys(source as Record<string, unknown>)) {
+ const v = (source as Record<string, unknown>)[k];
+ // Keys can also contain \uXXXX escapes when the ingest path double-
+ // encodes the payload, so decode them alongside the values.
+ const decodedKey = decodeUnicodeEscapesOnly(k, true);
+ if (budgetExceeded || ++nodeCount > DECODE_UNICODE_MAX_NODES) {
+ budgetExceeded = true;
+ obj[decodedKey] = v;
+ continue;
+ }
+ obj[decodedKey] = assignDecodedOrDescend(v, depth, stack);
+ }
+ }
+ }
+
+ return root;
+}
+
+function assignDecodedOrDescend(
+ v: unknown,
+ depth: number,
+ stack: Array<{
+ source: unknown[] | Record<string, unknown>;
+ target: unknown[] | Record<string, unknown>;
+ depth: number;
+ }>,
+): unknown {
+ if (typeof v === "string") {
+ return decodeUnicodeEscapesOnly(v, true);
+ }
+ if (v === null || typeof v !== "object") {
+ return v;
+ }
+ if (depth + 1 > DECODE_UNICODE_MAX_DEPTH) {
+ return v; // bail on deeper subtrees to avoid runaway work
+ }
+ const child: unknown[] | Record<string, unknown> = Array.isArray(v) ? [] : {};
+ stack.push({
+ source: v as unknown[] | Record<string, unknown>,
+ target: child,
+ depth: depth + 1,
+ });
+ return child;
+}
+
function shouldShowValue(value: unknown, showNullValues: boolean): boolean {
if (showNullValues) return true;
return value !== null && value !== "" && value !== 0;
@@ -772,7 +880,7 @@ export function PrettyJsonView(props: {
const parsedJson = useMemo(() => {
// If pre-parsed data is provided, use it directly (skip parsing)
if (props.parsedJson !== undefined) {
- return props.parsedJson;
+ return decodeUnicodeInJson(props.parsedJson);
}
// If still parsing in Web Worker, return null (will show loading state)
@@ -782,7 +890,7 @@ export function PrettyJsonView(props: {
// Fast path: if already an object, likely no parsing needed
if (typeof props.json !== "string") {
- return props.json;
+ return decodeUnicodeInJson(props.json);
}
// Only parse strings, with size/depth limits
@@ -791,8 +899,23 @@ export function PrettyJsonView(props: {
maxDepth: 2,
});
- return result;
+ // Decode \uXXXX escapes so Python SDK (ensure_ascii=True) traces display
+ // non-ASCII characters correctly in the trace detail view.
+ return decodeUnicodeInJson(result);
}, [props.json, props.parsedJson, props.isParsing]);
+
+ // JSONView internally calls deepParseJson (with maxDepth:3) which mutates
+ // nested string fields in place. Because baseTableData[].rawChildData holds
+ // references back into parsedJson, sharing parsedJson with JSONView would
+ // corrupt the table's lazy-loaded children whenever JSONView renders (even
+ // while hidden via display:none). Pass a deep clone so the two views stay
+ // independent.
+ const jsonViewInput = useMemo(() => {
+ if (parsedJson === null || parsedJson === undefined) return props.json;
+ if (typeof parsedJson !== "object") return parsedJson;
+ return structuredClone(parsedJson);
+ }, [parsedJson, props.json]);
+
const actualCurrentView = props.currentView ?? "pretty";
const expandAllRef = useRef<(() => void) | null>(null);
const [allRowsExpanded, setAllRowsExpanded] = useState(false);
@@ -1293,7 +1416,11 @@ export function PrettyJsonView(props: {
style={{ display: shouldUseTableView ? "none" : "block" }}
>
<JSONView
- json={props.json}
+ // Use the unicode-decoded payload so that \uXXXX escapes from
+ // Python SDK ensure_ascii=True render as original characters.
+ // Pass a clone to avoid JSONView's internal deepParseJson
+ // mutating the shared parsedJson / rawChildData tree.
+ json={jsonViewInput}
title={props.title} // Title value used for background styling
hideTitle={true} // But hide the title, we display it
className=""