🪢 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
fix(web): keep short JSON lists collapsed by default (#16574)
Nikita Kabardind18e160b842b
diff --git a/web/src/components/table/ValueCell.tsx b/web/src/components/table/ValueCell.tsxindex 302709d35e..b2fb0eb64c 100644--- a/web/src/components/table/ValueCell.tsx+++ b/web/src/components/table/ValueCell.tsx@@ -2,7 +2,12 @@ import { memo, type JSX, useState } from "react";import { useRouter } from "next/router";import { type Row } from "@tanstack/react-table";import { urlRegex } from "@langfuse/shared";-import { type JsonTableRow } from "@/src/components/table/utils/jsonExpansionUtils";+import {+ SMALL_ARRAY_THRESHOLD,+ SMALL_OBJECT_THRESHOLD,+ objectFitsInSingleRowPreview,+ type JsonTableRow,+} from "@/src/components/table/utils/jsonExpansionUtils";import { classifyMediaValue } from "@/src/components/ui/media/mediaUtils";import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";import { copyTextToClipboard } from "@/src/utils/clipboard";@@ -32,9 +37,7 @@ export type MetadataFilterActions = {const MAX_STRING_LENGTH_FOR_LINK_DETECTION = 1500;export const MAX_CELL_DISPLAY_CHARS = 2000;-const SMALL_ARRAY_THRESHOLD = 5;const ARRAY_PREVIEW_ITEMS = 3;-const OBJECT_PREVIEW_KEYS = 2;const MONO_TEXT_CLASSES = "font-mono text-xs wrap-break-word";const PREVIEW_TEXT_CLASSES = "italic text-gray-500 dark:text-gray-400";@@ -93,12 +96,12 @@ function renderArrayValue(arr: unknown[]): JSX.Element {const displayItems = arr.map((item) => {const itemType = getValueType(item);- if (itemType === "string") return `"${String(item)}"`;+ if (itemType === "string") return JSON.stringify(item);if (itemType === "object" && item !== null) {const obj = item as Record<string, unknown>;const keys = Object.keys(obj);if (keys.length === 0) return "{}";- if (keys.length <= OBJECT_PREVIEW_KEYS) {+ if (keys.length <= SMALL_OBJECT_THRESHOLD) {const keyPreview = keys.map((k) => `"${k}": ...`).join(", ");return `{${keyPreview}}`;}@@ -115,7 +118,7 @@ function renderArrayValue(arr: unknown[]): JSX.Element {.slice(0, ARRAY_PREVIEW_ITEMS).map((item) => {const itemType = getValueType(item);- if (itemType === "string") return `"${String(item)}"`;+ if (itemType === "string") return JSON.stringify(item);if (itemType === "object" || itemType === "array") return "...";return String(item);})@@ -127,11 +130,30 @@ function renderArrayValue(arr: unknown[]): JSX.Element {);}+function formatPreviewPrimitive(value: unknown): string {+ if (typeof value === "string") return JSON.stringify(value);+ if (value === null) return "null";+ return String(value);+}++function formatShortObjectPreview(obj: Record<string, unknown>): string | null {+ if (!objectFitsInSingleRowPreview(obj)) return null;+ const fields = Object.entries(obj).map(+ ([key, field]) =>+ `${JSON.stringify(key)}: ${formatPreviewPrimitive(field)}`,+ );+ return `{${fields.join(", ")}}`;+}+function renderObjectValue(obj: Record<string, unknown>): JSX.Element {const keys = Object.keys(obj);if (keys.length === 0) {return <span className={PREVIEW_TEXT_CLASSES}>empty object</span>;}+ const shortPreview = formatShortObjectPreview(obj);+ if (shortPreview) {+ return <span className={PREVIEW_TEXT_CLASSES}>{shortPreview}</span>;+ }return <span className={PREVIEW_TEXT_CLASSES}>{keys.length} items</span>;}@@ -426,6 +448,18 @@ export const ValueCell = memo(needsTruncation: false,};case "array": {+ // Hide the parent preview only when expanded children are actually+ // rendered. showNullValues={false} can filter every child out while+ // leaving the expand chevron (hasChildren is computed on the raw+ // array), and blanking the cell then loses the only remaining value.+ const hasVisibleChildRows =+ row.getIsExpanded() && row.subRows.length > 0;+ if (hasVisibleChildRows) {+ return {+ content: null,+ needsTruncation: false,+ };+ }const arrayValue = value as unknown[];// Arrays always show previews, never truncatereturn {@@ -434,6 +468,14 @@ export const ValueCell = memo(};}case "object": {+ const hasVisibleChildRows =+ row.getIsExpanded() && row.subRows.length > 0;+ if (hasVisibleChildRows) {+ return {+ content: null,+ needsTruncation: false,+ };+ }const objectValue = value as Record<string, unknown>;// Objects always show previews, never truncatereturn {diff --git a/web/src/components/table/utils/jsonExpansionUtils.clienttest.ts b/web/src/components/table/utils/jsonExpansionUtils.clienttest.tsnew file mode 100644index 0000000000..a071852ce0--- /dev/null+++ b/web/src/components/table/utils/jsonExpansionUtils.clienttest.ts@@ -0,0 +1,131 @@+import {+ arrayFitsInSingleRowPreview,+ getSmartExpansionState,+ objectFitsInSingleRowPreview,+ SMALL_ARRAY_THRESHOLD,+ SMALL_OBJECT_THRESHOLD,+ transformJsonToTableData,+} from "@/src/components/table/utils/jsonExpansionUtils";++const DEFAULT_MAX_ROWS = 20;++/** Same lazy top-level shape PrettyJsonView uses for smart expansion. */+const tableRows = (json: unknown) =>+ transformJsonToTableData(json, "", 0, "", true);++describe("arrayFitsInSingleRowPreview", () => {+ it("is true for a short list of primitives", () => {+ expect(arrayFitsInSingleRowPreview(["email", "paid_social"])).toBe(true);+ expect(arrayFitsInSingleRowPreview([1, 2, 3])).toBe(true);+ expect(arrayFitsInSingleRowPreview([true, null])).toBe(true);+ });++ it("is true at the preview size limit", () => {+ expect(+ arrayFitsInSingleRowPreview(+ Array.from({ length: SMALL_ARRAY_THRESHOLD }, (_, i) => `item-${i}`),+ ),+ ).toBe(true);+ });++ it("is false when the preview would truncate", () => {+ expect(+ arrayFitsInSingleRowPreview(+ Array.from(+ { length: SMALL_ARRAY_THRESHOLD + 1 },+ (_, i) => `item-${i}`,+ ),+ ),+ ).toBe(false);+ });++ it("is false for lists of objects or nested arrays", () => {+ expect(arrayFitsInSingleRowPreview([{ name: "Ada" }])).toBe(false);+ expect(arrayFitsInSingleRowPreview([[1, 2]])).toBe(false);+ });++ it("is false for empty arrays and non-arrays", () => {+ expect(arrayFitsInSingleRowPreview([])).toBe(false);+ expect(arrayFitsInSingleRowPreview({ a: 1 })).toBe(false);+ expect(arrayFitsInSingleRowPreview("email")).toBe(false);+ });+});++describe("objectFitsInSingleRowPreview", () => {+ it("is true for a short object of primitives", () => {+ expect(objectFitsInSingleRowPreview({ name: "Ada" })).toBe(true);+ expect(objectFitsInSingleRowPreview({ ok: true, n: 1 })).toBe(true);+ });++ it("is true at the preview size limit", () => {+ const value = Object.fromEntries(+ Array.from({ length: SMALL_OBJECT_THRESHOLD }, (_, i) => [`k${i}`, i]),+ );+ expect(objectFitsInSingleRowPreview(value)).toBe(true);+ });++ it("is false when the preview would omit fields or nest further", () => {+ expect(objectFitsInSingleRowPreview({ a: 1, b: 2, c: 3 })).toBe(false);+ expect(objectFitsInSingleRowPreview({ name: { first: "Ada" } })).toBe(+ false,+ );+ });++ it("is false for empty objects, arrays, and primitives", () => {+ expect(objectFitsInSingleRowPreview({})).toBe(false);+ expect(objectFitsInSingleRowPreview(["Ada"])).toBe(false);+ expect(objectFitsInSingleRowPreview("Ada")).toBe(false);+ });+});++describe("getSmartExpansionState", () => {+ it("does not expand a short primitive list whose preview already shows every item", () => {+ const rows = tableRows({+ brand: "Acme",+ channels: ["email", "paid_social"],+ });++ expect(getSmartExpansionState(rows, DEFAULT_MAX_ROWS)).toEqual({});+ });++ it("does not expand a short object whose preview already shows every field", () => {+ const rows = tableRows({+ user: { name: "Ada" },+ });++ expect(getSmartExpansionState(rows, DEFAULT_MAX_ROWS)).toEqual({});+ });++ it("still expands a list of objects whose preview is incomplete", () => {+ const rows = tableRows({+ users: [{ name: "Ada" }, { name: "Bob" }],+ });++ expect(getSmartExpansionState(rows, DEFAULT_MAX_ROWS)).toEqual({+ users: true,+ });+ });++ it("still expands a primitive list that does not fit in the single-row preview", () => {+ const rows = tableRows({+ tags: ["a", "b", "c", "d", "e", "f"],+ });++ expect(getSmartExpansionState(rows, DEFAULT_MAX_ROWS)).toEqual({+ tags: true,+ });+ });++ it("expands a nested object but leaves its short primitive list collapsed", () => {+ const rows = tableRows({+ config: {+ theme: "dark",+ channels: ["email", "paid_social"],+ },+ });++ expect(getSmartExpansionState(rows, DEFAULT_MAX_ROWS)).toEqual({+ config: true,+ });+ });+});diff --git a/web/src/components/table/utils/jsonExpansionUtils.ts b/web/src/components/table/utils/jsonExpansionUtils.tsindex 5580e5423b..5c0f27e4d2 100644--- a/web/src/components/table/utils/jsonExpansionUtils.ts+++ b/web/src/components/table/utils/jsonExpansionUtils.ts@@ -2,6 +2,14 @@* Utility functions for JSON expansion state management across traces*/+/** Arrays at or below this size show every item in the parent-row preview. */+export const SMALL_ARRAY_THRESHOLD = 5;++/** Objects at or below this many primitive fields show those fields inline. */+export const SMALL_OBJECT_THRESHOLD = 2;++const DEEPEST_DEFAULT_EXPANSION_LEVEL = 10;+// Convert row ID (e.g., "metadata-settings-theme") to key path (e.g., "metadata.settings.theme")export function convertRowIdToKeyPath(rowId: string): string {return rowId.replace(/-/g, ".");@@ -64,6 +72,144 @@ function hasChildren(value: unknown, valueType: JsonTableRow["type"]): boolean {);}+function isPrimitiveJsonValue(value: unknown): boolean {+ const type = getValueType(value);+ return type !== "object" && type !== "array";+}++/**+ * True when the table's single-row array preview already shows every item+ * completely (a short list of primitives). Those lists should stay collapsed+ * by default so the preview is not duplicated as child rows.+ */+export function arrayFitsInSingleRowPreview(value: unknown): boolean {+ if (!Array.isArray(value) || value.length === 0) return false;+ if (value.length > SMALL_ARRAY_THRESHOLD) return false;+ return value.every(isPrimitiveJsonValue);+}++/**+ * True when the table's single-row object preview already shows every field+ * completely (a short object of primitives). Those objects should stay+ * collapsed by default so the preview is not duplicated as child rows.+ */+export function objectFitsInSingleRowPreview(value: unknown): boolean {+ if (typeof value !== "object" || value === null || Array.isArray(value)) {+ return false;+ }+ const entries = Object.entries(value as Record<string, unknown>);+ if (entries.length === 0 || entries.length > SMALL_OBJECT_THRESHOLD) {+ return false;+ }+ return entries.every(([, field]) => isPrimitiveJsonValue(field));+}++function valueFitsInSingleRowPreview(value: unknown): boolean {+ return (+ arrayFitsInSingleRowPreview(value) || objectFitsInSingleRowPreview(value)+ );+}++function findOptimalExpansionLevel(+ data: JsonTableRow[],+ maxRows: number,+): number {+ if (data.length > maxRows) {+ return 0;+ }++ function findOptimalRecursively(+ rows: JsonTableRow[],+ currentLevel: number,+ cumulativeCount: number,+ visitedData = new WeakSet(),+ ): number {+ const rowsAtThisLevel = rows.length;+ const newCumulativeCount = cumulativeCount + rowsAtThisLevel;++ if (newCumulativeCount > maxRows) {+ return currentLevel - 1;+ }++ if (currentLevel >= DEEPEST_DEFAULT_EXPANSION_LEVEL) {+ return currentLevel;+ }++ let childRows: JsonTableRow[] = [];++ for (const row of rows) {+ // Short primitive lists stay collapsed; don't spend the row budget on+ // children the user will not see by default.+ if (valueFitsInSingleRowPreview(row.value)) continue;++ if (row.hasChildren && row.rawChildData) {+ if (typeof row.rawChildData !== "object" || row.rawChildData === null) {+ continue;+ }++ if (visitedData.has(row.rawChildData)) {+ continue;+ }++ visitedData.add(row.rawChildData);++ const children = getRowChildren(row);+ // Use concat instead of spread to avoid stack overflow with large arrays+ childRows = childRows.concat(children);+ }+ }++ if (childRows.length === 0) {+ return currentLevel;+ }++ return findOptimalRecursively(+ childRows,+ currentLevel + 1,+ newCumulativeCount,+ visitedData,+ );+ }++ return Math.max(0, findOptimalRecursively(data, 0, 0));+}++/**+ * Default expand/collapse map for the pretty JSON table.+ * Short primitive lists and short primitive objects stay collapsed because+ * their parent-row preview already shows the full contents.+ */+export function getSmartExpansionState(+ data: JsonTableRow[],+ maxRows: number,+): Record<string, boolean> {+ const optimalLevel = findOptimalExpansionLevel(data, maxRows);+ if (optimalLevel <= 0) return {};++ const smartExpanded: Record<string, boolean> = {};++ const expandRowsToLevel = (rows: JsonTableRow[], currentLevel: number) => {+ for (const row of rows) {+ if (+ !row.hasChildren ||+ currentLevel >= optimalLevel ||+ valueFitsInSingleRowPreview(row.value)+ ) {+ continue;+ }++ smartExpanded[convertRowIdToKeyPath(row.id)] = true;+ const children = getRowChildren(row);+ if (children.length > 0) {+ expandRowsToLevel(children, currentLevel + 1);+ }+ }+ };++ expandRowsToLevel(data, 0);+ return smartExpanded;+}+export function transformJsonToTableData(json: unknown,parentKey = "",diff --git a/web/src/components/ui/PrettyJsonView.expansion.clienttest.tsx b/web/src/components/ui/PrettyJsonView.expansion.clienttest.tsxnew file mode 100644index 0000000000..8a0d9a5c09--- /dev/null+++ b/web/src/components/ui/PrettyJsonView.expansion.clienttest.tsx@@ -0,0 +1,154 @@+import { fireEvent, render, screen, within } from "@testing-library/react";+import { type ReactNode } from "react";++vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({+ usePostHogClientCapture: () => vi.fn(),+}));++import { MarkdownContextProvider } from "@/src/features/theming/useMarkdownContext";+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";++function renderPrettyJson(ui: ReactNode) {+ return render(<MarkdownContextProvider>{ui}</MarkdownContextProvider>);+}++function prettyTable() {+ return screen.getByRole("table");+}++describe("PrettyJsonView short-list expansion", () => {+ it("keeps a short primitive list collapsed so the preview is not duplicated", () => {+ renderPrettyJson(+ <PrettyJsonView+ json={{+ brand: "Acme",+ channels: ["email", "paid_social"],+ }}+ title="Input"+ />,+ );++ const table = prettyTable();+ expect(within(table).getByText("channels")).toBeInTheDocument();+ expect(+ within(table).getByText('["email", "paid_social"]'),+ ).toBeInTheDocument();+ // Child index rows would repeat the same strings next to path 0 / 1.+ expect(within(table).queryByText("0")).not.toBeInTheDocument();+ expect(within(table).queryByText("1")).not.toBeInTheDocument();+ });++ it("hides the parent-row list preview after the user expands it", () => {+ renderPrettyJson(+ <PrettyJsonView+ json={{+ channels: ["email", "paid_social"],+ }}+ title="Input"+ />,+ );++ const table = prettyTable();+ const channelsRow = within(table).getByText("channels").closest("tr");+ expect(channelsRow).not.toBeNull();+ const expandButton = within(channelsRow as HTMLElement).getAllByRole(+ "button",+ )[0];+ fireEvent.click(expandButton!);++ const expandedTable = prettyTable();+ expect(+ within(expandedTable).queryByText('["email", "paid_social"]'),+ ).not.toBeInTheDocument();+ expect(within(expandedTable).getByText("0")).toBeInTheDocument();+ expect(within(expandedTable).getByText("1")).toBeInTheDocument();+ expect(within(expandedTable).getByText('"email"')).toBeInTheDocument();+ expect(+ within(expandedTable).getByText('"paid_social"'),+ ).toBeInTheDocument();+ });++ it("keeps the parent preview when every expanded child is hidden", () => {+ renderPrettyJson(+ <PrettyJsonView+ json={{+ flags: [null, 0, ""],+ }}+ title="Input"+ showNullValues={false}+ />,+ );++ const table = prettyTable();+ const flagsRow = within(table).getByText("flags").closest("tr");+ expect(flagsRow).not.toBeNull();+ const expandButton = within(flagsRow as HTMLElement).getAllByRole(+ "button",+ )[0];+ fireEvent.click(expandButton!);++ const expandedTable = prettyTable();+ expect(+ within(expandedTable).getByText('[null, 0, ""]'),+ ).toBeInTheDocument();+ expect(within(expandedTable).queryByText("null")).not.toBeInTheDocument();+ });++ it("escapes quotes in the collapsed list preview", () => {+ renderPrettyJson(+ <PrettyJsonView+ json={{+ quoted: ['a"b'],+ }}+ title="Input"+ />,+ );++ expect(within(prettyTable()).getByText('["a\\"b"]')).toBeInTheDocument();+ });++ it("still expands a short list of objects and previews the collapsed object fields", () => {+ renderPrettyJson(+ <PrettyJsonView+ json={{+ users: [{ name: "Ada" }],+ }}+ title="Input"+ />,+ );++ const table = prettyTable();+ // The list itself expands so each object is a child row. Nested object+ // keys stay collapsed; the object preview shows the short fields.+ expect(within(table).getByText("0")).toBeInTheDocument();+ expect(within(table).getByText('{"name": "Ada"}')).toBeInTheDocument();+ expect(within(table).queryByText("1 items")).not.toBeInTheDocument();+ expect(within(table).queryByText("name")).not.toBeInTheDocument();+ });++ it("hides a short object preview after the user expands it", () => {+ renderPrettyJson(+ <PrettyJsonView+ json={{+ users: [{ name: "Ada" }],+ }}+ title="Input"+ />,+ );++ const table = prettyTable();+ const objectRow = within(table).getByText("0").closest("tr");+ expect(objectRow).not.toBeNull();+ const expandButton = within(objectRow as HTMLElement).getAllByRole(+ "button",+ )[0];+ fireEvent.click(expandButton!);++ const expandedTable = prettyTable();+ expect(+ within(expandedTable).queryByText('{"name": "Ada"}'),+ ).not.toBeInTheDocument();+ expect(within(expandedTable).getByText("name")).toBeInTheDocument();+ expect(within(expandedTable).getByText('"Ada"')).toBeInTheDocument();+ });+});diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsxindex 7a1d0913fb..963a209d90 100644--- a/web/src/components/ui/PrettyJsonView.tsx+++ b/web/src/components/ui/PrettyJsonView.tsx@@ -51,7 +51,7 @@ import {import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";import {convertRowIdToKeyPath,- getRowChildren,+ getSmartExpansionState,type JsonTableRow,transformJsonToTableData,} from "@/src/components/table/utils/jsonExpansionUtils";@@ -77,7 +77,6 @@ const DEFAULT_MAX_ROWS = 20;// Used for root-level objects where user has no parent to expand from. Therefore,// set higher to ensure objects like metadata with many keys are still displayedconst DEFAULT_MAX_ROWS_IF_ROOT = 100;-const DEEPEST_DEFAULT_EXPANSION_LEVEL = 10;const MAX_CELL_DISPLAY_CHARS = 2000;@@ -269,70 +268,6 @@ function generateAllChildrenRecursively(}}-function findOptimalExpansionLevel(- data: JsonTableRow[],- maxRows: number,-): number {- if (data.length > maxRows) {- return 0;- }-- function findOptimalRecursively(- rows: JsonTableRow[],- currentLevel: number,- cumulativeCount: number,- visitedData = new WeakSet(),- ): number {- const rowsAtThisLevel = rows.length;- const newCumulativeCount = cumulativeCount + rowsAtThisLevel;-- // If expanding to this level exceeds maxRows, return previous level- if (newCumulativeCount > maxRows) {- return currentLevel - 1;- }-- if (currentLevel >= DEEPEST_DEFAULT_EXPANSION_LEVEL) {- return currentLevel;- }-- // Get all children for next level- let childRows: JsonTableRow[] = [];-- for (const row of rows) {- if (row.hasChildren && row.rawChildData) {- if (typeof row.rawChildData !== "object" || row.rawChildData === null) {- continue; // Skip non-objects- }-- // Skip if we've already processed this exact data to prevent cycles- if (visitedData.has(row.rawChildData)) {- continue;- }-- // Mark data as visited- visitedData.add(row.rawChildData);-- const children = getRowChildren(row);- // Use concat instead of spread to avoid stack overflow with large arrays- childRows = childRows.concat(children);- }- }-- if (childRows.length === 0) {- return currentLevel;- }-- return findOptimalRecursively(- childRows,- currentLevel + 1,- newCumulativeCount,- visitedData,- );- }-- return Math.max(0, findOptimalRecursively(data, 0, 0));-}-function handleRowExpansion(row: Row<JsonTableRow>,onLazyLoadChildren?: (rowId: string) => void,@@ -1037,37 +972,9 @@ export function PrettyJsonView(props: {return enhancedState;}- // No external state -> use smart expansion- const optimalLevel = findOptimalExpansionLevel(- baseTableData,- DEFAULT_MAX_ROWS,- );-- if (optimalLevel > 0) {- const smartExpanded: ExpandedState = {};-- const expandRowsToLevel = (- rows: JsonTableRow[],- currentLevel: number,- ) => {- rows.forEach((row) => {- if (row.hasChildren && currentLevel < optimalLevel) {- const keyPath = convertRowIdToKeyPath(row.id);- smartExpanded[keyPath] = true;-- const children = getRowChildren(row);- if (children.length > 0) {- expandRowsToLevel(children, currentLevel + 1);- }- }- });- };- expandRowsToLevel(baseTableData, 0);-- return smartExpanded;- }-- return {};+ // No external state -> use smart expansion. Short primitive lists stay+ // collapsed because the parent-row preview already shows their contents.+ return getSmartExpansionState(baseTableData, DEFAULT_MAX_ROWS);}, [baseTableData, props.externalExpansionState]);// actual expansion state used by the table (combines initial + user changes)