Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(trace): decode unicode escapes in client-side trace downloads and copies (#15698)

Yuto Toya1663bbf79933
diff --git a/packages/shared/AGENTS.md b/packages/shared/AGENTS.md
index 8002ab6a06..56c12f9237 100644
--- a/packages/shared/AGENTS.md
+++ b/packages/shared/AGENTS.md
@@ -37,6 +37,10 @@
- `@langfuse/shared` via `src/index.ts`: default shared surface for
cross-runtime types, zod schemas, table definitions, domain models, prompt
helpers, eval/model-pricing helpers, and other frontend-safe utilities.
+ Includes the unicode-decoding JSON serialization helpers (`stringify`,
+ `stringifyForCsv` in `src/utils/stringify.ts`) used by both the server
+ trace-download route and client-side download/copy paths; the server barrel
+ re-exports them for compatibility.
- `@langfuse/shared/src/server` via `src/server/index.ts`: server-only barrel
for shared backend services, repositories, queue helpers/contracts, Redis and
ClickHouse helpers, auth helpers, logger/instrumentation, ingestion helpers,
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 130868ea1d..3468148ace 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -1,5 +1,6 @@
export * from "./constants";
export { decodeUnicodeEscapesOnly } from "./utils/unicode";
+export { stringify, stringifyForCsv } from "./utils/stringify";
export * from "./interfaces/filters";
export * from "./interfaces/orderBy";
export * from "./interfaces/cloudConfigSchema";
diff --git a/packages/shared/src/server/utils/transforms/index.ts b/packages/shared/src/server/utils/transforms/index.ts
index 5be024fedd..6dd51c3a1c 100644
--- a/packages/shared/src/server/utils/transforms/index.ts
+++ b/packages/shared/src/server/utils/transforms/index.ts
@@ -5,7 +5,10 @@ import { transformStreamToCsv } from "./transformStreamToCsv";
import { transformStreamToJson } from "./transformStreamToJson";
import { transformStreamToJsonl } from "./transformStreamToJsonl";
-export { stringify, stringifyForCsv } from "./stringify";
+// stringify lives in the client-safe utils so the web client (legacy trace
+// download, log view copy/download) serializes through the exact same helper
+// as the server-side trace download route.
+export { stringify, stringifyForCsv } from "../../../utils/stringify";
export const streamTransformations: Record<
BatchExportFileFormat,
diff --git a/packages/shared/src/server/utils/transforms/transformStreamToCsv.ts b/packages/shared/src/server/utils/transforms/transformStreamToCsv.ts
index eb174d65c2..3ee3f432bf 100644
--- a/packages/shared/src/server/utils/transforms/transformStreamToCsv.ts
+++ b/packages/shared/src/server/utils/transforms/transformStreamToCsv.ts
@@ -1,5 +1,5 @@
import { Transform, type TransformCallback } from "stream";
-import { stringifyForCsv } from "./stringify";
+import { stringifyForCsv } from "../../../utils/stringify";
const DELIMITER = ",";
const CSV_DOUBLE_QUOTE = /"/g;
diff --git a/packages/shared/src/server/utils/transforms/transformStreamToJson.ts b/packages/shared/src/server/utils/transforms/transformStreamToJson.ts
index 3f7b3cb88a..533e2b678e 100644
--- a/packages/shared/src/server/utils/transforms/transformStreamToJson.ts
+++ b/packages/shared/src/server/utils/transforms/transformStreamToJson.ts
@@ -1,5 +1,5 @@
import { Transform, type TransformCallback } from "stream";
-import { stringify } from "./stringify";
+import { stringify } from "../../../utils/stringify";
export function transformStreamToJson(): Transform {
let isFirstElement = true;
diff --git a/packages/shared/src/server/utils/transforms/transformStreamToJsonl.ts b/packages/shared/src/server/utils/transforms/transformStreamToJsonl.ts
index 4ece5c4890..e4df26308f 100644
--- a/packages/shared/src/server/utils/transforms/transformStreamToJsonl.ts
+++ b/packages/shared/src/server/utils/transforms/transformStreamToJsonl.ts
@@ -1,5 +1,5 @@
import { Transform, type TransformCallback } from "stream";
-import { stringify } from "./stringify";
+import { stringify } from "../../../utils/stringify";
export function transformStreamToJsonl(): Transform {
return new Transform({
diff --git a/worker/src/__tests__/stringify.test.ts b/packages/shared/src/utils/stringify.test.ts
similarity index 95%
rename from worker/src/__tests__/stringify.test.ts
rename to packages/shared/src/utils/stringify.test.ts
index 1368e2176e..fff42cc5b1 100644
--- a/worker/src/__tests__/stringify.test.ts
+++ b/packages/shared/src/utils/stringify.test.ts
@@ -1,8 +1,5 @@
import { describe, it, expect } from "vitest";
-import {
- stringify,
- stringifyForCsv,
-} from "../../../packages/shared/src/server/utils/transforms/stringify";
+import { stringify, stringifyForCsv } from "./stringify";
describe("stringify", () => {
it("serializes bigint values as numbers", () => {
diff --git a/packages/shared/src/server/utils/transforms/stringify.ts b/packages/shared/src/utils/stringify.ts
similarity index 95%
rename from packages/shared/src/server/utils/transforms/stringify.ts
rename to packages/shared/src/utils/stringify.ts
index 4fad83feaf..c772ecefae 100644
--- a/packages/shared/src/server/utils/transforms/stringify.ts
+++ b/packages/shared/src/utils/stringify.ts
@@ -1,4 +1,4 @@
-import { decodeUnicodeEscapesOnly } from "../../../utils/unicode";
+import { decodeUnicodeEscapesOnly } from "./unicode";
// Replacer that keeps bigints JSON-serializable and decodes \uXXXX escapes so
// that non-ASCII content (e.g. Japanese ingested with Python ensure_ascii=True)
diff --git a/web/src/components/trace/components/IOPreview/components/ChatMessage.clienttest.tsx b/web/src/components/trace/components/IOPreview/components/ChatMessage.clienttest.tsx
index 9eb71cd468..8524069ec8 100644
--- a/web/src/components/trace/components/IOPreview/components/ChatMessage.clienttest.tsx
+++ b/web/src/components/trace/components/IOPreview/components/ChatMessage.clienttest.tsx
@@ -1,6 +1,12 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { vi } from "vitest";
+const { copyTextToClipboard } = vi.hoisted(() => ({
+ copyTextToClipboard: vi.fn(),
+}));
+
+vi.mock("@/src/utils/clipboard", () => ({ copyTextToClipboard }));
+
import { ChatMessage } from "./ChatMessage";
import { type ChatMlMessage } from "./chat-message-utils";
import { MarkdownContextProvider } from "@/src/features/theming/useMarkdownContext";
@@ -270,3 +276,32 @@ describe("ChatMessage system prompt collapse", () => {
expect(collapseButton()).not.toBeInTheDocument();
});
});
+
+describe("ChatMessage copy", () => {
+ beforeEach(() => {
+ vi.stubGlobal("localStorage", createMemoryStorage());
+ vi.stubGlobal("sessionStorage", createMemoryStorage());
+ copyTextToClipboard.mockClear();
+ });
+
+ it("decodes \\uXXXX escapes when copying a tool-call-only message", () => {
+ // Escaped Japanese as ingested via the Python SDK's ensure_ascii=True.
+ renderChatMessage({
+ role: "assistant",
+ tool_calls: [
+ {
+ id: "call-1",
+ name: "search_traces",
+ arguments: '{"question":"\\u3053\\u3093\\u306b\\u3061\\u306f"}',
+ },
+ ],
+ } as unknown as ChatMlMessage);
+
+ fireEvent.click(screen.getAllByTitle("Copy to clipboard")[0]);
+
+ expect(copyTextToClipboard).toHaveBeenCalledTimes(1);
+ const copied = copyTextToClipboard.mock.calls[0][0] as string;
+ expect(copied).toContain("こんにけは");
+ expect(copied).not.toContain("\\u3053");
+ });
+});
diff --git a/web/src/components/trace/components/IOPreview/components/ChatMessage.tsx b/web/src/components/trace/components/IOPreview/components/ChatMessage.tsx
index 1ecf8bb966..a72ff75813 100644
--- a/web/src/components/trace/components/IOPreview/components/ChatMessage.tsx
+++ b/web/src/components/trace/components/IOPreview/components/ChatMessage.tsx
@@ -7,6 +7,7 @@ import {
} from "@/src/components/ui/MarkdownJsonView";
import { ToolCallInvocationsView } from "@/src/components/trace/components/ToolCallInvocationsView";
import { ListChevronsDownUp, ListChevronsUpDown } from "lucide-react";
+import { stringify } from "@langfuse/shared";
import { copyTextToClipboard } from "@/src/utils/clipboard";
import {
type ChatMlMessage,
@@ -144,7 +145,10 @@ export function ChatMessage({
title={title}
handleOnValueChange={() => {}}
handleOnCopy={() => {
- const rawText = JSON.stringify(message, null, 2);
+ // Shared stringify (not raw JSON.stringify) so \uXXXX escapes in
+ // string fields are copied as real characters, like the rendered
+ // view shows them.
+ const rawText = stringify(message, undefined, 2);
copyTextToClipboard(rawText);
}}
controlButtons={passthroughToggleButton}
diff --git a/web/src/components/trace/components/TraceLogView/useLogViewDownload.clienttest.ts b/web/src/components/trace/components/TraceLogView/useLogViewDownload.clienttest.ts
new file mode 100644
index 0000000000..59c089264e
--- /dev/null
+++ b/web/src/components/trace/components/TraceLogView/useLogViewDownload.clienttest.ts
@@ -0,0 +1,110 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useLogViewDownload } from "./useLogViewDownload";
+import { type ObservationIOData } from "./useLogViewAllObservationsIO";
+
+const { copyTextToClipboard } = vi.hoisted(() => ({
+ copyTextToClipboard: vi.fn(),
+}));
+
+vi.mock("@/src/utils/clipboard", () => ({ copyTextToClipboard }));
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), warning: vi.fn(), error: vi.fn() },
+}));
+
+// jsdom implements neither URL.createObjectURL nor Blob#text.
+const createObjectURL = vi.fn<(blob: Blob) => string>();
+const revokeObjectURL = vi.fn();
+let lastBlob: Blob | undefined;
+
+function readBlobAsText(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result));
+ reader.onerror = () => reject(reader.error);
+ reader.readAsText(blob);
+ });
+}
+
+// Escaped Japanese as ingested via the Python SDK's ensure_ascii=True.
+const observations: ObservationIOData[] = [
+ {
+ id: "obs-1",
+ type: "GENERATION",
+ name: "generation",
+ startTime: new Date("2026-01-01T00:00:00.000Z"),
+ depth: 0,
+ input: '{"question":"\\u3053\\u3093\\u306b\\u3061\\u306f"}',
+ output: "\\u3042\\u308a\\u304c\\u3068\\u3046",
+ },
+];
+
+function renderDownloadHook() {
+ return renderHook(() =>
+ useLogViewDownload({
+ traceId: "trace-1",
+ isCacheOnly: false,
+ allObservationsData: observations,
+ isLoadingAllData: false,
+ failedObservationIds: [],
+ loadAllData: async () => observations,
+ buildDataFromCache: () => observations,
+ }),
+ );
+}
+
+// jsdom ships no URL.createObjectURL, so capture whatever is (not) there and
+// restore it β€” Object.assign alone would leak the stub past this file if the
+// client project ever ran with a shared context.
+const originalCreateObjectURL = URL.createObjectURL;
+const originalRevokeObjectURL = URL.revokeObjectURL;
+
+describe("useLogViewDownload", () => {
+ beforeEach(() => {
+ lastBlob = undefined;
+ copyTextToClipboard.mockClear();
+ createObjectURL.mockImplementation((blob: Blob) => {
+ lastBlob = blob;
+ return "blob:mock";
+ });
+ Object.assign(URL, { createObjectURL, revokeObjectURL });
+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ Object.assign(URL, {
+ createObjectURL: originalCreateObjectURL,
+ revokeObjectURL: originalRevokeObjectURL,
+ });
+ vi.restoreAllMocks();
+ });
+
+ it("decodes \\uXXXX escapes in the copied JSON", async () => {
+ const { result } = renderDownloadHook();
+
+ await act(async () => {
+ await result.current.handleCopyJson();
+ });
+
+ expect(copyTextToClipboard).toHaveBeenCalledTimes(1);
+ const copied = copyTextToClipboard.mock.calls[0][0] as string;
+ expect(copied).toContain("こんにけは");
+ expect(copied).toContain("γ‚γ‚ŠγŒγ¨γ†");
+ expect(copied).not.toContain("\\u3053");
+ });
+
+ it("decodes \\uXXXX escapes in the downloaded JSON", async () => {
+ const { result } = renderDownloadHook();
+
+ await act(async () => {
+ await result.current.handleDownloadJson();
+ });
+
+ expect(lastBlob).toBeDefined();
+ const content = await readBlobAsText(lastBlob!);
+ expect(content).toContain("こんにけは");
+ expect(content).toContain("γ‚γ‚ŠγŒγ¨γ†");
+ expect(content).not.toContain("\\u3053");
+ });
+});
diff --git a/web/src/components/trace/components/TraceLogView/useLogViewDownload.ts b/web/src/components/trace/components/TraceLogView/useLogViewDownload.ts
index cb6e961d69..7b32aa421b 100644
--- a/web/src/components/trace/components/TraceLogView/useLogViewDownload.ts
+++ b/web/src/components/trace/components/TraceLogView/useLogViewDownload.ts
@@ -9,6 +9,7 @@
import { useState, useCallback } from "react";
import { toast } from "sonner";
+import { stringify } from "@langfuse/shared";
import { copyTextToClipboard } from "@/src/utils/clipboard";
import { type ObservationIOData } from "./useLogViewAllObservationsIO";
@@ -43,10 +44,13 @@ export function useLogViewDownload({
}: UseLogViewDownloadParams) {
const [isActionLoading, setIsActionLoading] = useState(false);
- // Helper to download JSON data
+ // Helper to download JSON data. Serializes through the shared stringify
+ // helper (not the raw JSON.stringify) so \uXXXX escapes in string fields
+ // (e.g. Japanese ingested with Python ensure_ascii=True) are decoded to
+ // real characters, matching the server-side trace download route.
const downloadJsonData = useCallback(
(data: unknown) => {
- const blob = new Blob([JSON.stringify(data, null, 2)], {
+ const blob = new Blob([stringify(data, undefined, 2)], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
@@ -67,7 +71,7 @@ export function useLogViewDownload({
setTimeout(() => {
try {
const data = buildDataFromCache();
- copyTextToClipboard(JSON.stringify(data, null, 2));
+ copyTextToClipboard(stringify(data, undefined, 2));
toast.success("Copied to clipboard (cache only)");
} finally {
setIsActionLoading(false);
@@ -76,7 +80,7 @@ export function useLogViewDownload({
} else {
// Load all mode: fetch all data if needed
if (allObservationsData) {
- copyTextToClipboard(JSON.stringify(allObservationsData, null, 2));
+ copyTextToClipboard(stringify(allObservationsData, undefined, 2));
// Show warning if some observations failed to load
if (failedObservationIds.length > 0) {
toast.warning(
@@ -89,7 +93,7 @@ export function useLogViewDownload({
setIsActionLoading(true);
try {
const data = await loadAllData();
- copyTextToClipboard(JSON.stringify(data, null, 2));
+ copyTextToClipboard(stringify(data, undefined, 2));
// Check for failures after loading
if (failedObservationIds.length > 0) {
toast.warning(
diff --git a/web/src/components/trace/lib/download-trace.clienttest.ts b/web/src/components/trace/lib/download-trace.clienttest.ts
new file mode 100644
index 0000000000..873262c044
--- /dev/null
+++ b/web/src/components/trace/lib/download-trace.clienttest.ts
@@ -0,0 +1,65 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { downloadLegacyTraceAsJson } from "./download-trace";
+
+// jsdom does not implement URL.createObjectURL, so we install our own to
+// capture the Blob the download helper builds instead of hitting navigation.
+const createObjectURL = vi.fn<(blob: Blob) => string>();
+const revokeObjectURL = vi.fn();
+
+let lastBlob: Blob | undefined;
+
+// jsdom's Blob has no text(); read it through FileReader instead.
+function readBlobAsText(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result));
+ reader.onerror = () => reject(reader.error);
+ reader.readAsText(blob);
+ });
+}
+
+// jsdom ships no URL.createObjectURL, so capture whatever is (not) there and
+// restore it β€” Object.assign alone would leak the stub past this file if the
+// client project ever ran with a shared context.
+const originalCreateObjectURL = URL.createObjectURL;
+const originalRevokeObjectURL = URL.revokeObjectURL;
+
+describe("downloadLegacyTraceAsJson", () => {
+ beforeEach(() => {
+ lastBlob = undefined;
+ createObjectURL.mockImplementation((blob: Blob) => {
+ lastBlob = blob;
+ return "blob:mock";
+ });
+ Object.assign(URL, { createObjectURL, revokeObjectURL });
+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ Object.assign(URL, {
+ createObjectURL: originalCreateObjectURL,
+ revokeObjectURL: originalRevokeObjectURL,
+ });
+ vi.restoreAllMocks();
+ });
+
+ it("decodes \\uXXXX escapes so non-ASCII content is downloaded as real characters", async () => {
+ downloadLegacyTraceAsJson({
+ trace: {
+ id: "trace-1",
+ input: '{"question":"\\u3053\\u3093\\u306b\\u3061\\u306f"}',
+ },
+ observations: [
+ { id: "obs-1", output: "\\u3042\\u308a\\u304c\\u3068\\u3046" },
+ ],
+ });
+
+ expect(lastBlob).toBeDefined();
+ const content = await readBlobAsText(lastBlob!);
+
+ expect(content).toContain("こんにけは");
+ expect(content).toContain("γ‚γ‚ŠγŒγ¨γ†");
+ expect(content).not.toContain("\\u3053");
+ });
+});
diff --git a/web/src/components/trace/lib/download-trace.ts b/web/src/components/trace/lib/download-trace.ts
index 7fe5cf4a12..a0eb5c2bb5 100644
--- a/web/src/components/trace/lib/download-trace.ts
+++ b/web/src/components/trace/lib/download-trace.ts
@@ -1,3 +1,5 @@
+import { stringify } from "@langfuse/shared";
+
export interface ServerTraceDownloadParams {
traceId: string;
projectId: string;
@@ -77,7 +79,11 @@ export function downloadLegacyTraceAsJson(params: LegacyTraceDownloadParams) {
};
downloadBlob({
- blob: new Blob([JSON.stringify(exportData, null, 2)], {
+ // Use the shared stringify helper (not the raw JSON.stringify) so that
+ // \uXXXX escapes in string fields (e.g. Japanese ingested with Python
+ // ensure_ascii=True) are decoded to real characters, matching the
+ // server-side download route in /api/traces/[traceId]/download.
+ blob: new Blob([stringify(exportData, undefined, 2)], {
type: "application/json; charset=utf-8",
}),
filename: filename || `trace-${trace.id}.json`,