🪢 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
refactor(web): Clean up single trace details components (#19299)
Ben Bachem4da02c687fec
diff --git a/web/.storybook/prisma-browser-stub.cjs b/web/.storybook/prisma-browser-stub.cjsindex d5feeb2ca6..7983262158 100644--- a/web/.storybook/prisma-browser-stub.cjs+++ b/web/.storybook/prisma-browser-stub.cjs@@ -7,7 +7,8 @@ const fail = () => {const enumLike = new Proxy({},{- get: (_target, prop) => (typeof prop === "symbol" ? undefined : String(prop)),+ get: (_target, prop) =>+ typeof prop === "symbol" ? undefined : String(prop),getOwnPropertyDescriptor: (_target, prop) => ({configurable: true,enumerable: true,diff --git a/web/src/components/ChatMessages/ToolCallCard.tsx b/web/src/components/ChatMessages/ToolCallCard.tsxindex d4ffe382f3..f9199a3c3e 100644--- a/web/src/components/ChatMessages/ToolCallCard.tsx+++ b/web/src/components/ChatMessages/ToolCallCard.tsx@@ -20,11 +20,13 @@ export const ToolCallCard: React.FC<{ toolCall: LLMToolCall }> = ({<div className="text-xs text-gray-500 dark:text-gray-400">Arguments</div>- <PrettyJsonView- json={toolCall.args}- codeClassName="border-none p-1"- currentView="pretty"- />+ <div className="p-1">+ <PrettyJsonView+ json={toolCall.args}+ borderless+ currentView="pretty"+ />+ </div></div><div className="flex w-[25%] flex-col overflow-hidden"><div className="text-xs text-gray-500 dark:text-gray-400">ID</div>diff --git a/web/src/components/ui/IOSection.stories.tsx b/web/src/components/ui/IOSection.stories.tsxindex 6cd9725dbc..3a4bc8ba98 100644--- a/web/src/components/ui/IOSection.stories.tsx+++ b/web/src/components/ui/IOSection.stories.tsx@@ -1,10 +1,11 @@+import { JsonViewController } from "@/src/components/ui/JsonViewController";import { useState } from "react";import preview from "../../../.storybook/preview";import { expect, fn, userEvent, within } from "storybook/test";import Image from "next/image";-import { FoldVertical, Pencil, Wrench } from "@langfuse/icons";+import { FoldVertical, UnfoldVertical, Pencil, Wrench } from "@langfuse/icons";import { IOSection } from "./IOSection";-import { PrettyJsonView } from "./PrettyJsonView";+import { PrettyJsonViewContent } from "./PrettyJsonViewContent";import { IO_STICKY_HEADERS_CLASS } from "@/src/features/traces/constants/ioSectionClasses";const meta = preview.meta({@@ -109,7 +110,32 @@ export const VariantMatrix = meta.story({</Example><Example caption="Table body: PrettyJsonView owns the section (variant table, py-1)">- <PrettyJsonView title="Input" json={TOOL_INPUT} currentView="pretty" />+ <JsonViewController json={TOOL_INPUT} currentView="pretty">+ {(state) => (+ <IOSection+ title="Input"+ onCopy={state.copy}+ actions={+ state.contentKind === "table" && state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : undefined+ }+ variant={state.contentKind === "table" ? "table" : "text"}+ >+ <PrettyJsonViewContent state={state} title="Input" borderless />+ </IOSection>+ )}+ </JsonViewController></Example><Example caption="Media body: tiles sit 12px from every edge (variant media)">@@ -152,12 +178,33 @@ export const VariantMatrix = meta.story({</Example><Example caption="Toned table: the plain table box with the tone as fill, neutral dividers">- <PrettyJsonView- title="Output"- json={ERROR_OUTPUT}- currentView="pretty"- tone="danger"- />+ <JsonViewController json={ERROR_OUTPUT} currentView="pretty">+ {(state) => (+ <IOSection+ title="Output"+ onCopy={state.copy}+ actions={+ state.contentKind === "table" && state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : undefined+ }+ variant={state.contentKind === "table" ? "table" : "text"}+ tone="danger"+ >+ <PrettyJsonViewContent state={state} title="Output" borderless />+ </IOSection>+ )}+ </JsonViewController></Example><Example caption="Collapsed: header only, body not rendered">diff --git a/web/src/components/ui/IOSection.tsx b/web/src/components/ui/IOSection.tsxindex f188f2713b..75111276da 100644--- a/web/src/components/ui/IOSection.tsx+++ b/web/src/components/ui/IOSection.tsx@@ -104,10 +104,12 @@ const TONE_TEXT_CLASSES: Record<IOSectionTone, string> = {neutral: "bg-surface-section text-foreground-secondary",};-/** Toned table boxes: the plain table box with the tone as its fill only. */+/** Toned table boxes retain their text colours while sharing the status frame. */const TONE_FILL_CLASSES: Record<IOSectionTone, string> = {- danger: "bg-red-50 dark:bg-light-red/35",- warning: "bg-yellow-50 dark:bg-light-yellow/35",+ danger:+ "border border-red-100 bg-red-50 dark:border-dark-red/20 dark:bg-light-red/35",+ warning:+ "border border-yellow-100 bg-yellow-50 dark:border-dark-yellow/20 dark:bg-light-yellow/35",muted: "bg-surface-section",neutral: "bg-surface-section",};@@ -306,8 +308,10 @@ function IOSectionControls({size="icon-xs"type="button"onClick={(event) => {+ event.preventDefault();setIsCopied(true);onCopy(event);+ event.currentTarget.focus();setTimeout(() => setIsCopied(false), 1000);}}className={HEADER_CONTROL_CLASSES}diff --git a/web/src/components/ui/JsonViewController.tsx b/web/src/components/ui/JsonViewController.tsxnew file mode 100644index 0000000000..1790cc0459--- /dev/null+++ b/web/src/components/ui/JsonViewController.tsx@@ -0,0 +1,712 @@+import {+ type ReactNode,+ type RefObject,+ useMemo,+ useState,+ useEffect,+ useRef,+ useCallback,+} from "react";+import { type ExpandedState } from "@tanstack/react-table";+import { deepParseJson } from "@langfuse/shared";+import { decodeUnicodeInJson } from "@/src/utils/decodeUnicodeInJson";+import { type MediaReturnType } from "@/src/features/media";+import { copyTextToClipboard } from "@/src/utils/clipboard";+import { ChatMlArraySchema } from "@/src/components/schemas/ChatMlSchema";+import {+ filterAlreadyRenderedMedia,+ getRenderedInlineMediaIds,+ getStandaloneMediaReferenceStrings,+} from "@/src/components/ui/markdown-media.utils";+import {+ StringOrMarkdownSchema,+ containsAnyMarkdown,+} from "@/src/components/schemas/MarkdownSchema";+import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";+import {+ convertRowIdToKeyPath,+ getSmartExpansionState,+ type JsonTableRow,+ transformJsonToTableData,+} from "@/src/components/table/utils/jsonExpansionUtils";+import { isLargeRenderString } from "@/src/components/ui/largeStringGate";++// Custom expanded state type that allows false ("user intentionally collapsed all")+type LangfuseExpandedState = ExpandedState | false;++// Constants for smart expansion logic+// Used for nested objects to control smart expansion depth+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 displayed+const DEFAULT_MAX_ROWS_IF_ROOT = 100;++function shouldShowValue(value: unknown, showNullValues: boolean): boolean {+ if (showNullValues) return true;+ return value !== null && value !== "" && value !== 0;+}++function filterTableRows(+ rows: JsonTableRow[],+ showNullValues: boolean,+): JsonTableRow[] {+ if (showNullValues) return rows;++ return rows+ .filter((row) => shouldShowValue(row.value, showNullValues))+ .map((row) => ({+ ...row,+ subRows: row.subRows+ ? filterTableRows(row.subRows, showNullValues)+ : row.subRows,+ }));+}++function isChatMLFormat(json: unknown): boolean {+ if (!json || typeof json !== "object") return false;++ if (Array.isArray(json)) {+ const directArray = ChatMlArraySchema.safeParse(json);+ if (directArray.success) {+ // had some false positives, so we really check for role AND content to validate ChatML+ const hasRoleAndContent = json.some(+ (item) =>+ typeof item === "object" &&+ item !== null &&+ "role" in item &&+ "content" in item,+ );+ return hasRoleAndContent;+ }+ }++ if ("messages" in json && Array.isArray(json.messages)) {+ const messagesArray = ChatMlArraySchema.safeParse(json.messages);+ if (messagesArray.success) return true;+ }++ if (Array.isArray(json) && json.length === 1 && Array.isArray(json[0])) {+ const nestedArray = ChatMlArraySchema.safeParse(json[0]);+ if (nestedArray.success) return true;+ }++ return false;+}++function isMarkdownContent(+ json: unknown,+ characterLimit: number,+): {+ isMarkdown: boolean;+ content?: string;+} {+ const contentSize = JSON.stringify(json || {}).length;+ if (contentSize > characterLimit) {+ return { isMarkdown: false };+ }++ if (typeof json === "string") {+ const markdownResult = StringOrMarkdownSchema.safeParse(json);+ if (markdownResult.success) {+ return { isMarkdown: true, content: json };+ }+ }++ // also render as MD if object has one key and the value is a markdown like string+ if (+ typeof json === "object" &&+ json !== null &&+ !Array.isArray(json) &&+ json.constructor === Object+ ) {+ const entries = Object.entries(json);+ if (entries.length === 1) {+ const [, value] = entries[0];+ if (typeof value === "string") {+ if (containsAnyMarkdown(value)) {+ return { isMarkdown: true, content: value };+ }+ }+ }+ }++ return { isMarkdown: false };+}++function getValueType(value: unknown): JsonTableRow["type"] {+ if (value === null) return "null";+ if (value === undefined) return "undefined";+ if (Array.isArray(value)) return "array";+ return typeof value as JsonTableRow["type"];+}++function hasChildren(value: unknown, valueType: JsonTableRow["type"]): boolean {+ return (+ (valueType === "object" &&+ Object.keys(value as Record<string, unknown>).length > 0) ||+ (valueType === "array" && Array.isArray(value) && value.length > 0)+ );+}++export function JsonViewController(props: {+ json?: unknown;+ parsedJson?: unknown; // Pre-parsed data (optional, from useParsedObservation hook)+ isLoading?: boolean;+ isParsing?: boolean;+ media?: MediaReturnType[];+ currentView?: "pretty" | "json";+ externalExpansionState?: Record<string, boolean> | boolean;+ onExternalExpansionChange?: (+ expansion: Record<string, boolean> | boolean,+ ) => void;+ showNullValues?: boolean;+ children: (state: JsonViewState) => ReactNode;+}) {+ // Large plain-string gate (LFE-10991): a multi-MB top-level string skips+ // deepParseJson's object-only `maxSize` guard, so without this it would run+ // several full-length main-thread passes (parse, the markdown-probe+ // `JSON.stringify`, unicode decode — some of them twice, including inside the+ // always-mounted hidden JSON viewer) and mount the unvirtualized react18-json+ // tree with the whole string, blocking the tab and inflating memory. The body+ // renders a bounded preview + download instead.+ //+ // Gate on the SETTLED value only. During an async worker parse the parsed+ // value is not ready (`parsedJson === undefined`, `isParsing` true) and the+ // raw `json` may be a *stringified* payload whose JSON-quoted form is itself+ // >2M chars (e.g. the JSON tab passes raw `json` alongside a not-yet-ready+ // `parsedJson`). Gating on that raw form would flash the fallback — and offer+ // a quoted-form download — before the parse settles to the real value. The+ // unvirtualized render we protect against does not run during parse anyway,+ // so fall through to the normal loading/parsing state in that window.+ const largeStringValue = useMemo(() => {+ if (props.isParsing) return null;+ const settled =+ props.parsedJson !== undefined ? props.parsedJson : props.json;+ return isLargeRenderString(settled) ? settled : null;+ }, [props.parsedJson, props.json, props.isParsing]);++ // Use pre-parsed data if available, otherwise parse on-demand+ const parsedJson = useMemo(() => {+ // Skip all parse/decode work on very large plain strings (see gate above);+ // the raw string is rendered through the bounded fallback, not decoded.+ if (largeStringValue !== null) {+ return largeStringValue;+ }++ // If pre-parsed data is provided, use it directly (skip parsing)+ if (props.parsedJson !== undefined) {+ return decodeUnicodeInJson(props.parsedJson);+ }++ // If still parsing in Web Worker, return null (will show loading state)+ if (props.isParsing) {+ return null;+ }++ // Fast path: if already an object, likely no parsing needed+ if (typeof props.json !== "string") {+ return decodeUnicodeInJson(props.json);+ }++ // Only parse strings, with size/depth limits+ const result = deepParseJson(props.json, {+ maxSize: 500_000,+ maxDepth: 2,+ });++ // 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, largeStringValue]);++ // 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);++ // For JSON view: derive collapsed state from external expansion state+ // false or empty object = collapsed, true or object with keys = expanded+ const deriveJsonCollapsedFromExternal = useCallback(+ (extState: Record<string, boolean> | boolean | undefined): boolean => {+ if (extState === undefined) return false; // default: not collapsed+ if (extState === false) return true; // explicitly collapsed+ if (extState === true) return false; // explicitly expanded+ // empty object = collapsed (user collapsed all)+ if (typeof extState === "object" && Object.keys(extState).length === 0)+ return true;+ return false; // has keys = not collapsed+ },+ [],+ );++ const [jsonIsCollapsed, setJsonIsCollapsed] = useState(() =>+ deriveJsonCollapsedFromExternal(props.externalExpansionState),+ );++ // Sync jsonIsCollapsed when external state changes (e.g., navigating between observations)+ const prevExternalStateRef = useRef(props.externalExpansionState);+ useEffect(() => {+ if (prevExternalStateRef.current !== props.externalExpansionState) {+ const newCollapsed = deriveJsonCollapsedFromExternal(+ props.externalExpansionState,+ );+ prevExternalStateRef.current = props.externalExpansionState;+ setJsonIsCollapsed(newCollapsed);+ }+ }, [props.externalExpansionState, deriveJsonCollapsedFromExternal]);+ const [expandedRowsWithChildren, setExpandedRowsWithChildren] = useState<+ Set<string>+ >(new Set());+ const [expandedCells, setExpandedCells] = useState<Set<string>>(new Set());+ const [, setForceUpdate] = useState(0);++ // View's own state, lower precedence than optionally supplied external expansion state+ const [internalExpansionState, setInternalExpansionState] =+ useState<LangfuseExpandedState>({});++ const isChatML = useMemo(() => isChatMLFormat(parsedJson), [parsedJson]);+ const characterLimit = useMarkdownRenderCharacterLimit();+ const { isMarkdown, content: markdownContent } = useMemo(+ // Skip the markdown probe for gated large strings: isMarkdownContent runs+ // `JSON.stringify` on the whole value, an O(n) pass over the multi-MB string.+ () =>+ largeStringValue !== null+ ? { isMarkdown: false as const, content: undefined }+ : isMarkdownContent(parsedJson, characterLimit),+ [parsedJson, largeStringValue, characterLimit],+ );++ const baseTableData = useMemo(() => {+ try {+ if (+ largeStringValue === null &&+ actualCurrentView === "pretty" &&+ parsedJson !== null &&+ parsedJson !== undefined &&+ !isChatML &&+ !isMarkdown+ ) {+ // early abort check for smart expansion+ if (parsedJson?.constructor === Object) {+ const topLevelKeys = Object.keys(+ parsedJson as Record<string, unknown>,+ );+ if (topLevelKeys.length > DEFAULT_MAX_ROWS_IF_ROOT) {+ // return empty array to skip expansion directly+ return [];+ }+ }++ // lazy load JSON data, generate only top-level rows initially; children on expand+ const createTopLevelRows = (+ obj: Record<string, unknown>,+ ): JsonTableRow[] => {+ const entries = Object.entries(obj);+ const rows: JsonTableRow[] = [];++ entries.forEach(([key, value]) => {+ const valueType = getValueType(value);+ const childrenExist = hasChildren(value, valueType);++ const row: JsonTableRow = {+ id: key,+ key,+ value,+ type: valueType,+ hasChildren: childrenExist,+ level: 0,+ childrenGenerated: false,+ };++ if (childrenExist) {+ row.rawChildData = value;+ row.subRows = []; // empty initially for lazy loading+ }+ rows.push(row);+ });+ return rows;+ };++ let result: JsonTableRow[];++ // top-level is an object, start with its properties directly+ if (parsedJson?.constructor === Object) {+ result = createTopLevelRows(parsedJson as Record<string, unknown>);+ } else {+ result = transformJsonToTableData(parsedJson, "", 0, "", true);+ }++ return result;+ }++ return [];+ } catch (error) {+ console.error("Error transforming JSON to table data:", error);+ return [];+ }+ }, [parsedJson, isChatML, isMarkdown, actualCurrentView, largeStringValue]);++ // state precedence: external state before smart expansion+ const finalExpansionState: ExpandedState = useMemo(() => {+ if (baseTableData.length === 0) return {};++ if (props.externalExpansionState === false) {+ // user collapsed all+ return {};+ }+ if (props.externalExpansionState === true) {+ // user expanded all+ return true;+ }+ if (+ typeof props.externalExpansionState === "object" &&+ props.externalExpansionState !== null &&+ Object.keys(props.externalExpansionState).length > 0+ ) {+ // user set specific expansions - apply with prefix matching++ // Extract expanded paths for prefix matching+ const expandedPaths = Object.entries(props.externalExpansionState)+ .filter(([, isExpanded]) => isExpanded)+ .map(([path]) => path);++ // Apply prefix matching: for each expanded path, expand all its ancestors+ // Example: if "messages.0.content.text" is expanded, also expand:+ // "messages", "messages.0", "messages.0.content"+ const enhancedState: Record<string, boolean> = {+ ...props.externalExpansionState,+ };++ expandedPaths.forEach((path) => {+ const parts = path.split(".");+ // Generate all ancestor paths+ for (let i = 1; i < parts.length; i++) {+ const ancestorPath = parts.slice(0, i).join(".");+ if (enhancedState[ancestorPath] === undefined) {+ enhancedState[ancestorPath] = true;+ }+ }+ });++ return enhancedState;+ }++ // 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)+ const actualExpansionState = useMemo(() => {+ if (finalExpansionState === true) return true;++ // Ensure both states are objects with fallback+ const finalState = (finalExpansionState as Record<string, boolean>) || {};+ const internalState =+ (internalExpansionState as Record<string, boolean>) || {};++ // Smart expansion only applies on initial load (when no user interactions yet)+ if (Object.keys(internalState).length > 0) {+ // user made changes, use them+ return internalState;+ } else if (internalExpansionState === false) {+ // user collapsed all+ return false;+ }+ return finalState;+ }, [finalExpansionState, internalExpansionState]);++ // table data with lazy-loaded children+ const tableData = useMemo(() => {+ const updateRowWithChildren = (rows: JsonTableRow[]): JsonTableRow[] => {+ return rows.map((row) => {+ let updatedRow = row;++ // Generate children if:+ // 1. Row is in expandedRowsWithChildren (user clicked lazy loading), OR+ // 2. Row should be expanded according to actualExpansionState (smart expansion)+ const keyPath = convertRowIdToKeyPath(row.id);+ const shouldHaveChildren =+ expandedRowsWithChildren.has(row.id) ||+ (actualExpansionState !== true &&+ actualExpansionState &&+ actualExpansionState[keyPath]);++ if (shouldHaveChildren && row.rawChildData && !row.childrenGenerated) {+ const children = transformJsonToTableData(+ row.rawChildData,+ row.key,+ row.level + 1,+ row.id,+ false,+ );+ updatedRow = {+ ...row,+ subRows: children,+ childrenGenerated: true,+ };+ }++ if (updatedRow.subRows && updatedRow.subRows.length > 0) {+ updatedRow = {+ ...updatedRow,+ subRows: updateRowWithChildren(updatedRow.subRows),+ };+ }++ return updatedRow;+ });+ };++ const dataWithChildren = updateRowWithChildren(baseTableData);+ return filterTableRows(dataWithChildren, props.showNullValues ?? true);+ }, [+ baseTableData,+ expandedRowsWithChildren,+ actualExpansionState,+ props.showNullValues,+ ]);++ const handleLazyLoadChildren = useCallback((rowId: string) => {+ setExpandedRowsWithChildren((prev) => {+ const newSet = new Set(prev);+ // we track the IDs for batch updates when lazy loading children+ if (rowId.includes(",")) {+ rowId.split(",").forEach((id) => newSet.add(id));+ } else {+ newSet.add(rowId);+ }++ return newSet;+ });+ }, []);++ const handleForceUpdate = useCallback(() => {+ setForceUpdate((prev) => prev + 1);+ }, []);++ const toggleCellExpansion = useCallback((cellId: string) => {+ setExpandedCells((prev) => {+ const newSet = new Set(prev);+ if (newSet.has(cellId)) {+ newSet.delete(cellId);+ } else {+ newSet.add(cellId);+ }+ return newSet;+ });+ }, []);++ const { onExternalExpansionChange } = props;+ const handleTableExpandedChange = useCallback(+ (+ updater:+ | ExpandedState+ | ((prev: ExpandedState) => ExpandedState)+ | boolean,+ ) => {+ // always update internal state of the table+ let newState: ExpandedState;+ if (typeof updater === "function") {+ newState = updater(+ actualExpansionState === false ? {} : actualExpansionState,+ );+ const finalState: LangfuseExpandedState =+ typeof newState === "object" && Object.keys(newState).length === 0+ ? false+ : newState;+ setInternalExpansionState(finalState);++ // update external state if state changed by user (callback provided)+ if (onExternalExpansionChange) {+ if (typeof newState === "boolean") {+ onExternalExpansionChange(newState);+ return;+ }++ const keyBasedState = Object.fromEntries(+ Object.entries(newState).filter(([, expanded]) => expanded),+ );++ // user collapsed all items -> set state to false (instead of empty object)+ const finalExternalState =+ Object.keys(keyBasedState).length === 0 ? false : keyBasedState;+ onExternalExpansionChange(finalExternalState);+ }+ } else if (typeof updater !== "boolean") {+ newState = updater;+ const finalState: LangfuseExpandedState =+ typeof newState === "object" && Object.keys(newState).length === 0+ ? false+ : newState;+ setInternalExpansionState(finalState);++ // Handle external state updates for expand/collapse all button+ if (onExternalExpansionChange && typeof newState === "object") {+ if (Object.keys(newState).length === 0) {+ // user collapsed all+ onExternalExpansionChange(false);+ } else {+ onExternalExpansionChange(newState);+ }+ }+ }+ },+ [onExternalExpansionChange, actualExpansionState],+ );++ const handleOnCopy = () => {+ const textToCopy = stringifyJsonNode(parsedJson);+ copyTextToClipboard(textToCopy);+ };++ const handleJsonToggleCollapse = () => {+ const newCollapsed = !jsonIsCollapsed;+ setJsonIsCollapsed(newCollapsed);+ if (props.onExternalExpansionChange) {+ props.onExternalExpansionChange(!newCollapsed);+ }+ };++ const hasExpandableRows = useMemo(() => {+ if (typeof parsedJson !== "object" || parsedJson === null) return false;+ return Object.values(parsedJson as Record<string, unknown>).some((value) =>+ hasChildren(value, getValueType(value)),+ );+ }, [parsedJson]);+ const isEmpty =+ parsedJson === null ||+ parsedJson === undefined ||+ parsedJson === "" ||+ (typeof parsedJson === "object" &&+ !Array.isArray(parsedJson) &&+ Object.keys(parsedJson).length === 0);+ const standaloneMediaReferenceStrings =+ typeof markdownContent === "string"+ ? getStandaloneMediaReferenceStrings(markdownContent)+ : [];+ const remainingMarkdownMedia = filterAlreadyRenderedMedia(+ props.media,+ getRenderedInlineMediaIds({+ markdown: markdownContent ?? "",+ }),+ );++ const contentKind = (() => {+ if (largeStringValue !== null) return "large-string";+ if (actualCurrentView === "json") return "json";+ if (isEmpty) return "empty";+ if (isMarkdown) return "markdown";+ if (isChatML) return "json";+ return "table";+ })();++ return props.children({+ contentKind,+ parsedJson,+ largeStringValue,+ jsonViewInput,+ isLoading: props.isLoading,+ isParsing: props.isParsing,+ media: props.media,+ markdownContent,+ currentView: actualCurrentView,+ isMarkdown,+ isChatML,+ isEmpty,+ standaloneMediaReferenceStrings,+ remainingMarkdownMedia,+ tableData,+ expandAllRef,+ allRowsExpanded,+ setAllRowsExpanded,+ actualExpansionState,+ handleTableExpandedChange,+ handleLazyLoadChildren,+ handleForceUpdate,+ expandedCells,+ toggleCellExpansion,+ jsonIsCollapsed,+ handleJsonToggleCollapse,+ hasExpandableRows,+ copy: handleOnCopy,+ toggleAllRows: () => expandAllRef.current?.(),+ });+}++export type JsonViewState = {+ contentKind: "large-string" | "json" | "empty" | "markdown" | "table";+ parsedJson: unknown;+ largeStringValue: string | null;+ jsonViewInput: unknown;+ isLoading?: boolean;+ isParsing?: boolean;+ media?: MediaReturnType[];+ markdownContent: string | undefined;+ currentView: "pretty" | "json";+ isMarkdown: boolean;+ isChatML: boolean;+ isEmpty: boolean;+ standaloneMediaReferenceStrings: string[];+ remainingMarkdownMedia: MediaReturnType[];+ tableData: JsonTableRow[];+ expandAllRef: RefObject<(() => void) | null>;+ allRowsExpanded: boolean;+ setAllRowsExpanded: (expanded: boolean) => void;+ actualExpansionState: LangfuseExpandedState;+ handleTableExpandedChange: (+ updater: ExpandedState | ((prev: ExpandedState) => ExpandedState),+ ) => void;+ handleLazyLoadChildren: (rowId: string) => void;+ handleForceUpdate: () => void;+ expandedCells: Set<string>;+ toggleCellExpansion: (cellId: string) => void;+ jsonIsCollapsed: boolean;+ handleJsonToggleCollapse: () => void;+ hasExpandableRows: boolean;+ copy: () => void;+ toggleAllRows: () => void;+};++// TODO: deduplicate with CodeJsonViewer.tsx+function stringifyJsonNode(node: unknown) {+ // return single string nodes without quotes+ if (typeof node === "string") {+ return node;+ }++ try {+ return JSON.stringify(+ node,+ (key, value) => {+ switch (typeof value) {+ case "bigint":+ return String(value) + "n";+ case "number":+ case "boolean":+ case "object":+ case "string":+ return value as string;+ default:+ return String(value);+ }+ },+ 4,+ );+ } catch (error) {+ console.error("JSON stringify error", error);+ return "Error: JSON.stringify failed";+ }+}diff --git a/web/src/components/ui/MarkdownJsonView.stories.tsx b/web/src/components/ui/MarkdownJsonView.stories.tsxnew file mode 100644index 0000000000..883e00c181--- /dev/null+++ b/web/src/components/ui/MarkdownJsonView.stories.tsx@@ -0,0 +1,30 @@+import preview from "../../../.storybook/preview";+import { expect } from "storybook/test";+import { MarkdownJsonView } from "./MarkdownJsonView";++const meta = preview.meta({+ component: MarkdownJsonView,+});++export const ContentOnly = meta.story({+ name: "(Test) Content only",+ args: {+ content: "Hover this message to reveal its header controls.",+ },+ play: async ({ canvas }) => {+ await expect(+ canvas.queryByTitle("Copy to clipboard"),+ ).not.toBeInTheDocument();+ },+});++export const JsonFallback = meta.story({+ name: "(Test) JSON fallback",+ args: { content: { status: "ready", count: 2 } },+ play: async ({ canvas }) => {+ await expect(canvas.getByText("ready")).toBeVisible();+ await expect(+ canvas.queryByTitle("Copy to clipboard"),+ ).not.toBeInTheDocument();+ },+});diff --git a/web/src/components/ui/MarkdownJsonView.tsx b/web/src/components/ui/MarkdownJsonView.tsxindex e2df8617a4..8aaab0fec1 100644--- a/web/src/components/ui/MarkdownJsonView.tsx+++ b/web/src/components/ui/MarkdownJsonView.tsx@@ -6,10 +6,9 @@ import {} from "@langfuse/shared";import { Button } from "@/src/components/ui/button";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";-import { MarkdownView } from "@/src/components/ui/MarkdownViewer";+import { MarkdownView } from "@/src/components/ui/MarkdownView";import { type MediaReturnType } from "@/src/features/media";-import { Check, Copy, type IconComponent } from "@langfuse/icons";-import { type IOSectionAction } from "@/src/components/ui/IOSection";+import { Check, Copy } from "@langfuse/icons";import { useMemo, useState } from "react";import { type z } from "zod";import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";@@ -126,43 +125,16 @@ const isOpenAIContentWithExternalS3Image = (content: unknown) => {return hasExternalS3Image && hasOnlyRenderableParts;};-// MarkdownJsonView renders markdown whenever the content is valid markdown-// (see canRenderContentAsMarkdown), otherwise it falls back to JSON.export function MarkdownJsonView({content,- title,- titleIcon,className,audio,media,- actions,- beforeContent,- afterContent,- isSystemPrompt,- defaultCollapsed,- collapsed,- onCollapsedChange,}: {content?: unknown;- title?: string;- titleIcon?: IconComponent;className?: string;audio?: OpenAIOutputAudioType;media?: MediaReturnType[];- /** Section header actions. */- actions?: IOSectionAction[];- /** Rendered inside the section box above the content (e.g. thinking blocks). */- beforeContent?: React.ReactNode;- /** Rendered inside the section box below the content (e.g. tool calls). */- afterContent?: React.ReactNode;- /** Long system prompts start collapsed (from raw `role === "system"`, since- the title can carry a message `name` instead of the role). */- isSystemPrompt?: boolean;- /** Initial collapsed state of the section; system prompts use their own rule. */- defaultCollapsed?: boolean;- /** Controlled collapsed state; long system prompts still follow their rule. */- collapsed?: boolean;- onCollapsedChange?: (collapsed: boolean) => void;}) {const characterLimit = useMarkdownRenderCharacterLimit();// Boxed so a renderable `null` content stays distinguishable from@@ -178,33 +150,16 @@ export function MarkdownJsonView({return markdownContent ? (<MarkdownViewmarkdown={markdownContent.value}- title={title}- titleIcon={titleIcon}audio={audio}media={media}- actions={actions}- beforeContent={beforeContent}- afterContent={afterContent}- isSystemPrompt={isSystemPrompt}- defaultCollapsed={defaultCollapsed}- collapsed={collapsed}- onCollapsedChange={onCollapsedChange}/>) : (- <PrettyJsonView- json={content ?? (audio ? { audio } : null)}- title={title}- titleIcon={titleIcon}- className={className}- media={media}- currentView="pretty"- actions={actions}- beforeContent={beforeContent}- afterContent={afterContent}- isSystemPrompt={isSystemPrompt}- defaultCollapsed={defaultCollapsed}- collapsed={collapsed}- onCollapsedChange={onCollapsedChange}- />+ <div className={className}>+ <PrettyJsonView+ json={content ?? (audio ? { audio } : null)}+ media={media}+ currentView="pretty"+ />+ </div>);}diff --git a/web/src/components/ui/MarkdownViewer.clienttest.tsx b/web/src/components/ui/MarkdownView.clienttest.tsxsimilarity index 77%rename from web/src/components/ui/MarkdownViewer.clienttest.tsxrename to web/src/components/ui/MarkdownView.clienttest.tsxindex aaa0879739..c4f9210a27 100644--- a/web/src/components/ui/MarkdownViewer.clienttest.tsx+++ b/web/src/components/ui/MarkdownView.clienttest.tsx@@ -1,10 +1,16 @@/* eslint-disable @repo/prefer-stories-over-client-tests */-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";import {MarkdownView,prependBasePathToInternalHref,-} from "@/src/components/ui/MarkdownViewer";+} from "@/src/components/ui/MarkdownView";+import { MarkdownViewContent } from "./MarkdownViewContent";import { MarkdownJsonView } from "@/src/components/ui/MarkdownJsonView";+import { MarkdownViewController } from "./MarkdownViewController";+import { IOSection } from "./IOSection";+import { copyTextToClipboard } from "@/src/utils/clipboard";++vi.mock("@/src/utils/clipboard", () => ({ copyTextToClipboard: vi.fn() }));vi.mock("next/router", () => ({useRouter: () => ({ query: { projectId: "project-1" } }),@@ -43,6 +49,76 @@ vi.mock("@/src/features/feature-flags", () => ({const renderMarkdown = (markdown: string) =>render(<MarkdownView markdown={markdown} />);+describe("MarkdownView composition", () => {+ it("renders content without a section header", () => {+ renderMarkdown("A **content-only** message");+ expect(screen.getByText("content-only")).toBeInTheDocument();+ expect(screen.queryByTitle("Copy to clipboard")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /Collapse/ }),+ ).not.toBeInTheDocument();+ });++ it("lets a host own the section and copy prepared content", () => {+ render(+ <MarkdownViewController+ markdown={[+ { type: "text", text: "First" },+ { type: "text", text: "Second" },+ ]}+ >+ {(state) => (+ <IOSection title="Host" onCopy={state.copy}>+ <MarkdownViewContent state={state} />+ </IOSection>+ )}+ </MarkdownViewController>,+ );+ expect(screen.getByText("First")).toBeInTheDocument();+ expect(screen.getByText("Second")).toBeInTheDocument();+ fireEvent.click(screen.getByTitle("Copy to clipboard"));+ expect(copyTextToClipboard).toHaveBeenLastCalledWith("First\nSecond");+ });++ it("renders MarkdownJsonView without section controls", () => {+ render(<MarkdownJsonView content="Message body" />);+ expect(screen.getByText("Message body")).toBeInTheDocument();+ expect(screen.queryByTitle("Copy to clipboard")).not.toBeInTheDocument();+ });++ it("renders multimodal content without a section", () => {+ render(+ <MarkdownJsonView+ content={[+ { type: "text", text: "Short instruction" },+ {+ type: "image_url",+ image_url: { url: `data:image/png;base64,${"A".repeat(1_000)}` },+ },+ ]}+ />,+ );+ expect(+ screen.queryByRole("button", { name: "Collapse system" }),+ ).not.toBeInTheDocument();+ expect(screen.getByText("Short instruction")).toBeInTheDocument();+ });++ it("does not collapse long content without a section caller", () => {+ render(+ <MarkdownJsonView content={"Long system instruction. ".repeat(30)} />,+ );+ expect(+ screen.getByText("Long system instruction. ".repeat(30).trim()),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", {+ name: /(?:Expand|Collapse) Named prompt/,+ }),+ ).not.toBeInTheDocument();+ });+});+describe("MarkdownView external S3 media", () => {it("renders a standalone S3 media URI as external media", () => {const uri = "s3://customer-bucket/media/photo.png";diff --git a/web/src/components/ui/MarkdownViewer.stories.tsx b/web/src/components/ui/MarkdownView.stories.tsxsimilarity index 81%rename from web/src/components/ui/MarkdownViewer.stories.tsxrename to web/src/components/ui/MarkdownView.stories.tsxindex a768e093da..21f93c9589 100644--- a/web/src/components/ui/MarkdownViewer.stories.tsx+++ b/web/src/components/ui/MarkdownView.stories.tsx@@ -1,12 +1,8 @@import preview from "../../../.storybook/preview";-import { expect, waitFor, within } from "storybook/test";-import { MarkdownView } from "./MarkdownViewer";+import { MarkdownView } from "./MarkdownView";const meta = preview.meta({component: MarkdownView,- args: {- title: "assistant",- },});export const Default = meta.story({@@ -153,19 +149,3 @@ trace.generation({ name: "answer" });- Compare cost`,},});--export const HeaderControlsOnFocus = meta.story({- name: "(Test) Reveals Header Controls On Focus",- args: {- markdown: "Hover this message to reveal its header controls.",- title: "assistant",- },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- const copyButton = canvas.getByTitle("Copy to clipboard");- await waitFor(() => expect(copyButton).not.toBeVisible());-- copyButton.focus();- await waitFor(() => expect(copyButton).toBeVisible());- },-});diff --git a/web/src/components/ui/MarkdownView.tsx b/web/src/components/ui/MarkdownView.tsxnew file mode 100644index 0000000000..835e18c3b0--- /dev/null+++ b/web/src/components/ui/MarkdownView.tsx@@ -0,0 +1,39 @@+/* eslint-disable @repo/no-style-props */+import { type ComponentProps } from "react";+import { useTheme } from "next-themes";+import { cn } from "@/src/utils/tailwind";+import { MarkdownViewController } from "./MarkdownViewController";+import { MarkdownViewContent } from "./MarkdownViewContent";++export { prependBasePathToInternalHref } from "./MarkdownViewContent";++export function MarkdownView({+ markdown,+ audio,+ media,+ className,+}: Pick<+ ComponentProps<typeof MarkdownViewController>,+ "markdown" | "audio" | "media"+> & {+ className?: string;+}) {+ const { forcedTheme, resolvedTheme } = useTheme();+ const theme = forcedTheme ?? resolvedTheme;++ return (+ <MarkdownViewController markdown={markdown} audio={audio} media={media}>+ {(state) => (+ <div+ className={cn(+ "io-message-content ph-no-capture px-1 pt-1 pb-2",+ className,+ )}+ key={theme}+ >+ <MarkdownViewContent state={state} />+ </div>+ )}+ </MarkdownViewController>+ );+}diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewContent.tsxsimilarity index 78%rename from web/src/components/ui/MarkdownViewer.tsxrename to web/src/components/ui/MarkdownViewContent.tsxindex e346114b3c..43967c622a 100644--- a/web/src/components/ui/MarkdownViewer.tsx+++ b/web/src/components/ui/MarkdownViewContent.tsx@@ -1,6 +1,7 @@-/* eslint-disable no-nested-ternary, @repo/component-file-structure */+/* eslint-disable no-nested-ternary *//* eslint-disable @repo/no-style-props */import { cn } from "@/src/utils/tailwind";+import { useTheme } from "next-themes";import {type FC,type ReactNode,@@ -19,16 +20,13 @@ import ReactMarkdown, {import remarkGfm from "remark-gfm";import { Codeblock as CodeBlock } from "@/src/components/design-system/Codeblock/Codeblock";import { normalizeCodeblockLanguage } from "@/src/utils/normalizeCodeblockLanguage";-import { useTheme } from "next-themes";-import { ImageOff, Info, type IconComponent } from "@langfuse/icons";+import { ImageOff, Info } from "@langfuse/icons";import { MentionBadge } from "@/src/features/comments/components/MentionBadge";import {OpenAIUrlImageUrl,MediaReferenceStringSchema,PromptDependencyRegex,type OpenAIContentParts,- type OpenAIContentSchema,- type OpenAIOutputAudioType,isOpenAITextContentPart,isMediaReferencePart,isAiSdkFileContentPart,@@ -36,12 +34,9 @@ import {import { type z } from "zod";import { ResizableImage } from "@/src/components/ui/ResizableImage";import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";-import { type MediaReturnType } from "@/src/features/media";import { JSONView } from "@/src/components/ui/CodeJsonViewer";-import { IOSection, type IOSectionAction } from "@/src/components/ui/IOSection";-import { copyTextToClipboard } from "@/src/utils/clipboard";+import { type MarkdownViewState } from "./MarkdownViewController";import { MENTION_USER_PREFIX } from "@/src/features/comments/lib/mentionParser";-import { useCollapsibleSystemPrompt } from "@/src/hooks/useCollapsibleSystemPrompt";import { getSafeImageUrl, getSafeLinkUrl } from "@/src/components/ui/safe-url";import { env } from "@/src/env.mjs";import {@@ -52,18 +47,9 @@ import {PromptReferenceButton,usePromptReferenceProjectId,} from "@/src/components/ui/PromptReferences";-import {- filterAlreadyRenderedMedia,- getRenderedInlineMediaIds,- getStandaloneMediaReferenceStrings,-} from "@/src/components/ui/markdown-media.utils";import { exceedsMarkdownRenderLimits } from "@/src/components/ui/markdown-render-limits";import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";-import {- classifyMediaValue,- splitStringByMediaReferences,- type MediaDescriptor,-} from "@/src/components/ui/media/mediaUtils";+import { classifyMediaValue } from "@/src/components/ui/media/mediaUtils";import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";type ReactMarkdownNode = ReactMarkdownExtraProps["node"];@@ -491,104 +477,15 @@ function MarkdownRenderer({);}}-const parseOpenAIContentParts = (- content: z.input<typeof OpenAIContentParts> | null,-): string => {- return (content ?? [])- .map((item) => {- if (typeof item === "string") {- return item;- } else if (item.type === "text") {- return item.text;- } else if (item.type === "image_url") {- return ``;- } else if (item.type === "input_audio") {- return ``;- }- })- .join("\n");-};--export function MarkdownView({- markdown,- title,- titleIcon,- audio,- media,- className,- actions,- beforeContent,- afterContent,- isSystemPrompt,- defaultCollapsed,- collapsed,- onCollapsedChange,-}: {- /** The UNPARSED content shape — see `canRenderContentAsMarkdown`. Media- reference strings must still be strings when they reach the part guards. */- markdown: string | z.input<typeof OpenAIContentSchema>;- title?: string;- titleIcon?: IconComponent;- audio?: OpenAIOutputAudioType;- media?: MediaReturnType[];- className?: string;- /** Section header actions. */- actions?: IOSectionAction[];- /** Rendered inside the section box above the content (e.g. thinking blocks). */- beforeContent?: React.ReactNode;- /** Rendered inside the section box below the content (e.g. tool calls). */- afterContent?: React.ReactNode;- /** Long system prompts start collapsed. Pass the raw message role check- (`role === "system"`) — the title can be a message `name` instead of the- role. Falls back to matching the title for callers without role data. */- isSystemPrompt?: boolean;- /** Initial collapsed state of the section; system prompts use their own rule. */- defaultCollapsed?: boolean;- /** Controlled collapsed state; long system prompts still follow their rule. */- collapsed?: boolean;- onCollapsedChange?: (collapsed: boolean) => void;-}) {- const { forcedTheme, resolvedTheme } = useTheme();- const theme = forcedTheme ?? resolvedTheme;-- const markdownContent =- typeof markdown === "string" ? markdown : parseOpenAIContentParts(markdown);- const standaloneMediaDescriptor: MediaDescriptor | null =- typeof markdown === "string" ? classifyMediaValue(markdown) : null;-- // Length is judged on text parts only: serialized image/audio parts- // (media-reference strings, base64 data URIs) must not make a prompt long.- const textContent =- typeof markdown === "string"- ? splitStringByMediaReferences(markdown)- .filter((s) => s.type === "text")- .map((s) => s.value)- .join("")- .trim()- : (markdown ?? [])- .filter(isOpenAITextContentPart)- .map((part) => part.text)- .join("\n");-- const systemPrompt = useCollapsibleSystemPrompt({- isSystemPrompt: Boolean(title) && (isSystemPrompt ?? title === "system"),- content: textContent,- });-- const handleOnCopy = () => {- copyTextToClipboard(markdownContent);- };-- const inlineMediaReferenceStrings =- typeof markdown === "string"- ? getStandaloneMediaReferenceStrings(markdown)- : [];- const remainingMedia = filterAlreadyRenderedMedia(- media,- getRenderedInlineMediaIds({ markdown, audio }),- );-- const body = (+export function MarkdownViewContent({ state }: { state: MarkdownViewState }) {+ const {+ markdown,+ audio,+ standaloneMediaDescriptor,+ inlineMediaReferenceStrings,+ remainingMedia,+ } = state;+ return (<div className="text-foreground-secondary grid grid-flow-row gap-2">{typeof markdown === "string" ? (// plain string@@ -637,41 +534,6 @@ export function MarkdownView({</div>);- if (!title) {- return (- <div- className={cn(- "io-message-content ph-no-capture px-1 pt-1 pb-2",- className,- )}- key={theme}- >- {body}- </div>- );- }-- return (- <IOSection- key={theme}- title={title}- titleIcon={titleIcon}- onCopy={handleOnCopy}- actions={actions}- defaultCollapsed={defaultCollapsed}- collapsed={collapsed}- onCollapsedChange={onCollapsedChange}- {...(systemPrompt.shouldBeCollapsible && {- collapsed: systemPrompt.isCollapsed,- onCollapsedChange: systemPrompt.toggleCollapsed,- })}- >- {beforeContent}- {body}- {afterContent}- </IOSection>- );-function renderContentPart(content: NonNullable<z.input<typeof OpenAIContentParts>>[number],index: number,diff --git a/web/src/components/ui/MarkdownViewController.tsx b/web/src/components/ui/MarkdownViewController.tsxnew file mode 100644index 0000000000..682c10738f--- /dev/null+++ b/web/src/components/ui/MarkdownViewController.tsx@@ -0,0 +1,86 @@+import { type ReactNode } from "react";+import {+ type OpenAIContentSchema,+ type OpenAIOutputAudioType,+ isOpenAITextContentPart,+} from "@langfuse/shared";+import { type z } from "zod";+import { type MediaReturnType } from "@/src/features/media";+import { copyTextToClipboard } from "@/src/utils/clipboard";+import {+ filterAlreadyRenderedMedia,+ getRenderedInlineMediaIds,+ getStandaloneMediaReferenceStrings,+} from "./markdown-media.utils";+import {+ classifyMediaValue,+ splitStringByMediaReferences,+} from "./media/mediaUtils";++export function MarkdownViewController({+ markdown,+ audio,+ media,+ children,+}: {+ /** Keep media references unparsed so content-part guards can recognize them. */+ markdown: string | z.input<typeof OpenAIContentSchema>;+ audio?: OpenAIOutputAudioType;+ media?: MediaReturnType[];+ children: (state: MarkdownViewState) => ReactNode;+}) {+ const markdownContent =+ typeof markdown === "string"+ ? markdown+ : (markdown ?? [])+ .map((item) => {+ if (typeof item === "string") return item;+ if (item.type === "text") return item.text;+ if (item.type === "image_url")+ return ``;+ if (item.type === "input_audio")+ return ``;+ return undefined;+ })+ .join("\n");++ // Media references and base64 payloads must not count towards prompt length.+ const textContent =+ typeof markdown === "string"+ ? splitStringByMediaReferences(markdown)+ .filter((part) => part.type === "text")+ .map((part) => part.value)+ .join("")+ .trim()+ : (markdown ?? [])+ .filter(isOpenAITextContentPart)+ .map((part) => part.text)+ .join("\n");++ return children({+ markdown,+ audio,+ textContent,+ copy: () => copyTextToClipboard(markdownContent),+ standaloneMediaDescriptor:+ typeof markdown === "string" ? classifyMediaValue(markdown) : null,+ inlineMediaReferenceStrings:+ typeof markdown === "string"+ ? getStandaloneMediaReferenceStrings(markdown)+ : [],+ remainingMedia: filterAlreadyRenderedMedia(+ media,+ getRenderedInlineMediaIds({ markdown, audio }),+ ),+ });+}++export type MarkdownViewState = {+ markdown: string | z.input<typeof OpenAIContentSchema>;+ audio: OpenAIOutputAudioType | undefined;+ textContent: string;+ copy: () => void;+ standaloneMediaDescriptor: ReturnType<typeof classifyMediaValue>;+ inlineMediaReferenceStrings: string[];+ remainingMedia: MediaReturnType[];+};diff --git a/web/src/components/ui/PrettyJsonView.expansion.clienttest.tsx b/web/src/components/ui/PrettyJsonView.expansion.clienttest.tsxdeleted file mode 100644index 2051c22e29..0000000000--- a/web/src/components/ui/PrettyJsonView.expansion.clienttest.tsx+++ /dev/null@@ -1,151 +0,0 @@-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 { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";--function renderPrettyJson(ui: ReactNode) {- return render(ui);-}--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.gate.clienttest.tsx b/web/src/components/ui/PrettyJsonView.gate.clienttest.tsxdeleted file mode 100644index 6748f2c15a..0000000000--- a/web/src/components/ui/PrettyJsonView.gate.clienttest.tsx+++ /dev/null@@ -1,111 +0,0 @@-/**- * PrettyJsonView must short-circuit a multi-MB top-level string to the bounded- * LargeStringFallback and NEVER mount the unvirtualized JSON viewer (JSONView /- * react18-json-view) or the lazy table with it (LFE-10991). These tests pin- * that branch selection: over-limit strings render the fallback only, while a- * normal small string still mounts the viewer.- */-import { render, screen } from "@testing-library/react";-import type * as CodeJsonViewerModule from "@/src/components/ui/CodeJsonViewer";--// LargeStringFallback's only provider-bound dependency — stub it so the test-// needs no PostHogProvider.-vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({- usePostHogClientCapture: () => vi.fn(),-}));--// JSONView is the unvirtualized react18-json-view path we must NOT reach for an-// over-limit string. Stub only it (keep the module's other exports) so its-// mounting is observable by test id.-vi.mock("@/src/components/ui/CodeJsonViewer", async (importOriginal) => {- const actual = await importOriginal<typeof CodeJsonViewerModule>();- return {- ...actual,- JSONView: (props: { title?: string }) => (- <div data-testid="json-view">{props.title}</div>- ),- };-});--import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";-import { LARGE_STRING_RENDER_CHAR_LIMIT } from "@/src/components/ui/largeStringGate";--describe("PrettyJsonView large-string gate (LFE-10991)", () => {- it("renders the bounded fallback and mounts neither the JSON viewer nor the table for an over-limit string", () => {- const huge = "x".repeat(LARGE_STRING_RENDER_CHAR_LIMIT + 1);- const { container } = render(<PrettyJsonView json={huge} title="Input" />);-- // Bounded fallback + download affordance are shown...- expect(screen.getByText(/Large string —/i)).toBeInTheDocument();- expect(- screen.getByRole("button", { name: /Download full value/i }),- ).toBeInTheDocument();-- // ...and the unvirtualized viewer + lazy table were never mounted.- expect(screen.queryByTestId("json-view")).not.toBeInTheDocument();- expect(container.querySelector("table")).toBeNull();-- // The multi-MB string is not dumped into the DOM (only the bounded preview).- expect(container.textContent?.length ?? 0).toBeLessThan(10_000);- });-- it("renders normally (JSON viewer mounted, no fallback) for small I/O", () => {- render(<PrettyJsonView json={{ foo: "bar", n: 1 }} title="Input" />);-- expect(screen.queryByText(/Large string —/i)).not.toBeInTheDocument();- expect(screen.getByTestId("json-view")).toBeInTheDocument();- });-- it("shows the loading/parsing state (not the fallback) while a parse is in-flight, even if the raw json string is over the limit", () => {- // The JSON tab passes the raw `json` (a stringified payload) alongside a- // not-yet-ready `parsedJson` during the worker-parse window. Its JSON-quoted- // form can itself exceed the limit — but gating on it would flash the- // fallback and offer a quoted-form download before the parse settles.- const hugeRawJson = JSON.stringify({- x: "y".repeat(LARGE_STRING_RENDER_CHAR_LIMIT),- });- expect(hugeRawJson.length).toBeGreaterThan(LARGE_STRING_RENDER_CHAR_LIMIT);-- render(- <PrettyJsonView- json={hugeRawJson}- parsedJson={undefined}- isParsing- title="Input"- />,- );-- // No fallback, no quoted-form download — the normal parsing state shows.- expect(screen.queryByText(/Large string —/i)).not.toBeInTheDocument();- expect(- screen.queryByRole("button", { name: /Download full value/i }),- ).not.toBeInTheDocument();- expect(screen.getByText(/Parsing in background/i)).toBeInTheDocument();- });-- it("still gates a genuinely huge SETTLED top-level string (parse finished)", () => {- const hugePlainString = "z".repeat(LARGE_STRING_RENDER_CHAR_LIMIT + 1);- render(- <PrettyJsonView- json="ignored-raw"- parsedJson={hugePlainString}- title="Input"- />,- );-- expect(screen.getByText(/Large string —/i)).toBeInTheDocument();- expect(screen.queryByTestId("json-view")).not.toBeInTheDocument();- });-- it("does not offer system-prompt collapse on a gated huge string", () => {- // The header collapse path must not split() the multi-MB string the- // large-string gate exists to keep off the main thread.- const huge = "x".repeat(LARGE_STRING_RENDER_CHAR_LIMIT + 1);- render(<PrettyJsonView json={huge} title="system" isSystemPrompt />);-- expect(screen.getByText(/Large string —/i)).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: /system prompt/i }),- ).not.toBeInTheDocument();- });-});diff --git a/web/src/components/ui/PrettyJsonView.media.clienttest.tsx b/web/src/components/ui/PrettyJsonView.media.clienttest.tsxdeleted file mode 100644index f6155bbfe3..0000000000--- a/web/src/components/ui/PrettyJsonView.media.clienttest.tsx+++ /dev/null@@ -1,37 +0,0 @@-import { render, screen } from "@testing-library/react";-import { MediaContentType } from "@langfuse/shared";--vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({- usePostHogClientCapture: () => vi.fn(),-}));--vi.mock("@/src/components/ui/LangfuseMediaView", () => ({- LangfuseMediaView: () => <div data-testid="media-item" />,-}));--import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";-import { LARGE_STRING_RENDER_CHAR_LIMIT } from "@/src/components/ui/largeStringGate";-import { MediaEnabledFields } from "@/src/features/media/validation";--describe("PrettyJsonView media layout", () => {- it("aligns attachment tiles with the section content", () => {- render(- <PrettyJsonView- json={"x".repeat(LARGE_STRING_RENDER_CHAR_LIMIT + 1)}- title="Output"- media={[- {- mediaId: "media-id",- contentType: MediaContentType.TXT,- contentLength: 1,- url: "https://example.com/media.txt",- urlExpiry: "2099-01-01T00:00:00.000Z",- field: MediaEnabledFields.Output,- },- ]}- />,- );-- expect(screen.getByTestId("media-item").parentElement).toHaveClass("px-2");- });-});diff --git a/web/src/components/ui/PrettyJsonView.stories.tsx b/web/src/components/ui/PrettyJsonView.stories.tsxnew file mode 100644index 0000000000..e6ddab540d--- /dev/null+++ b/web/src/components/ui/PrettyJsonView.stories.tsx@@ -0,0 +1,256 @@+import preview from "../../../.storybook/preview";+import { expect, spyOn, within } from "storybook/test";+import { type ComponentProps, type ReactNode, useState } from "react";+import { FoldVertical, UnfoldVertical } from "@langfuse/icons";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { createTRPCReact, getQueryKey } from "@trpc/react-query";+import { createTRPCClient, TRPCClientError } from "@trpc/client";+import { observable } from "@trpc/server/observable";+import { type AppRouter } from "@/src/server/api/root";+import { api } from "@/src/utils/api";+import { MediaContentType } from "@/src/features/media";+import { MediaEnabledFields } from "@/src/features/media/validation";+import { MarkdownRenderCharacterLimitContext } from "@/src/components/MarkdownRenderCharacterLimitProvider/MarkdownRenderCharacterLimitContext";+import { JsonViewController } from "./JsonViewController";+import { IOSection } from "./IOSection";+import { PrettyJsonView } from "./PrettyJsonView";+import { PrettyJsonViewContent } from "./PrettyJsonViewContent";+import { LARGE_STRING_RENDER_CHAR_LIMIT } from "./largeStringGate";++function SectionPreview(props: ComponentProps<typeof PrettyJsonView>) {+ const { title = "Input" } = props;+ return (+ <JsonViewController {...props}>+ {(state) => (+ <IOSection+ title={title}+ onCopy={state.copy}+ actions={+ state.contentKind === "table" && state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded ? FoldVertical : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : undefined+ }+ variant={state.contentKind === "table" ? "table" : "text"}+ >+ <PrettyJsonViewContent state={state} title={title} borderless />+ </IOSection>+ )}+ </JsonViewController>+ );+}++const meta = preview.meta({+ component: PrettyJsonView,+ render: (args) => <SectionPreview {...args} />,+ decorators: [+ (Story) => (+ <MarkdownRenderCharacterLimitContext.Provider value={5_000}>+ <Story />+ </MarkdownRenderCharacterLimitContext.Provider>+ ),+ ],+ args: { json: { channels: ["email", "paid_social"] } },+});++export const StandaloneExpansion = meta.story({+ name: "(Test) Owns expansion without a section",+ render: (args) => <PrettyJsonView {...args} />,+ play: async ({ canvas, userEvent }) => {+ const table = within(canvas.getByRole("table"));+ await expect(table.queryByText("email")).not.toBeInTheDocument();+ await userEvent.click(+ table.getByRole("button", { name: "Expand channels" }),+ );+ await expect(await table.findByText("email")).toBeVisible();+ },+});++export const SectionControls = meta.story({+ name: "(Test) Section controls copying and row expansion",+ play: async ({ args, canvas, userEvent }) => {+ const table = within(canvas.getByRole("table"));+ const expand = canvas.getByRole("button", { name: "Expand all rows" });+ expand.focus();+ await userEvent.click(expand);+ await expect(await table.findByText("email")).toBeVisible();+ await userEvent.click(+ await canvas.findByRole("button", { name: "Collapse all rows" }),+ );+ await expect(table.queryByText("email")).not.toBeInTheDocument();+ const writeText = spyOn(+ navigator.clipboard,+ "writeText",+ ).mockResolvedValue();+ try {+ const copy = canvas.getByRole("button", { name: "Copy to clipboard" });+ copy.focus();+ await userEvent.click(copy);+ await expect(writeText).toHaveBeenCalled();+ await expect(JSON.parse(writeText.mock.calls[0]![0])).toEqual(args.json);+ } finally {+ writeText.mockRestore();+ }+ },+});++export const ExpandedPrimitiveList = meta.story({+ name: "(Test) Primitive lists can be expanded and collapsed",+ play: async ({ canvas, userEvent }) => {+ const table = within(canvas.getByRole("table"));+ await expect(table.queryByText("email")).not.toBeInTheDocument();+ await userEvent.click(+ table.getByRole("button", { name: "Expand channels" }),+ );+ for (const text of ["email", "paid_social"]) {+ await expect(table.getByText(text)).toBeVisible();+ }+ await userEvent.click(+ table.getByRole("button", { name: "Collapse channels" }),+ );+ await expect(table.queryByText("email")).not.toBeInTheDocument();+ await expect(table.getByText(/email.*paid_social/)).toBeVisible();+ },+});++export const HiddenChildren = meta.story({+ name: "(Test) Keeps the parent preview when all children are hidden",+ args: { json: { flags: [null, 0, ""] }, showNullValues: false },+ play: async ({ canvas, userEvent }) => {+ const table = within(canvas.getByRole("table"));+ await userEvent.click(table.getByRole("button", { name: "Expand flags" }));+ await expect(table.getByText('[null, 0, ""]')).toBeVisible();+ await expect(table.queryByText("null")).not.toBeInTheDocument();+ },+});++export const ExpandedObjectPreview = meta.story({+ name: "(Test) Nested objects can be expanded and collapsed",+ args: { json: { users: [{ name: "Ada" }] } },+ play: async ({ canvas, userEvent }) => {+ const table = within(canvas.getByRole("table"));+ await expect(table.queryByText("Ada")).not.toBeInTheDocument();+ await userEvent.click(table.getByRole("button", { name: "Expand 0" }));+ await expect(table.getByText("name")).toBeVisible();+ await expect(table.getByText("Ada")).toBeVisible();+ await userEvent.click(table.getByRole("button", { name: "Collapse 0" }));+ await expect(table.queryByText("Ada")).not.toBeInTheDocument();+ await expect(table.getByText(/Ada/)).toBeVisible();+ },+});++export const LargeString = meta.story({+ name: "(Test) Large strings show a bounded fallback and download control",+ args: { json: "x".repeat(LARGE_STRING_RENDER_CHAR_LIMIT + 1) },+ play: async ({ canvas, canvasElement }) => {+ await expect(canvas.getByText(/Large string —/i)).toBeVisible();+ await expect(+ canvas.getByRole("button", { name: /Download full value/i }),+ ).toBeVisible();+ await expect(canvasElement.textContent?.length ?? 0).toBeLessThan(10_000);+ },+});++export const ParsingLargePayload = meta.story({+ name: "(Test) Parsing takes precedence over the large-string fallback",+ args: {+ json: JSON.stringify({ x: "y".repeat(LARGE_STRING_RENDER_CHAR_LIMIT) }),+ parsedJson: undefined,+ isParsing: true,+ },+ play: async ({ canvas }) => {+ await expect(canvas.queryByText(/Large string —/i)).not.toBeInTheDocument();+ await expect(+ canvas.queryByRole("button", { name: /Download full value/i }),+ ).not.toBeInTheDocument();+ await expect(canvas.getByText(/Parsing in background/i)).toBeVisible();+ },+});++export const SettledLargeString = meta.story({+ name: "(Test) Settled large strings use the fallback",+ args: {+ json: "ignored-raw",+ parsedJson: "z".repeat(LARGE_STRING_RENDER_CHAR_LIMIT + 1),+ },+ play: async ({ canvas }) => {+ await expect(canvas.getByText(/Large string —/i)).toBeVisible();+ },+});++const attachment = {+ mediaId: "media-id",+ contentType: MediaContentType.TXT,+ contentLength: 1,+ url: "https://example.com/media.txt",+ urlExpiry: "2099-01-01T00:00:00.000Z",+ field: MediaEnabledFields.Output,+};+const storyApi = createTRPCReact<AppRouter>();++function MediaProviders({ children }: { children: ReactNode }) {+ const [queryClient] = useState(() => {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ client.setQueryData(+ getQueryKey(+ api.media.getById,+ { mediaId: attachment.mediaId, projectId: "storybook-project" },+ "query",+ ),+ attachment,+ );+ return client;+ });+ const [client] = useState(() =>+ createTRPCClient<AppRouter>({+ links: [+ () => () =>+ observable((observer) => {+ observer.error(+ new TRPCClientError<AppRouter>(+ "Unexpected API request in PrettyJsonView media story",+ ),+ );+ }),+ ],+ }),+ );+ return (+ <storyApi.Provider client={client} queryClient={queryClient}>+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ </storyApi.Provider>+ );+}++export const LargeStringWithAttachment = meta.story({+ name: "(Test) Large-string fallback retains attachments",+ decorators: [+ (Story) => (+ <MediaProviders>+ <Story />+ </MediaProviders>+ ),+ ],+ parameters: {+ nextjs: { router: { query: { projectId: "storybook-project" } } },+ },+ args: {+ json: "x".repeat(LARGE_STRING_RENDER_CHAR_LIMIT + 1),+ title: "Output",+ media: [attachment],+ },+ play: async ({ canvas }) => {+ await expect(canvas.getByText(/Large string —/i)).toBeVisible();+ const file = await canvas.findByRole("button", { name: /media\.txt/ });+ await expect(file).toBeVisible();+ },+});diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsxindex e1aeebabf9..9429e29953 100644--- a/web/src/components/ui/PrettyJsonView.tsx+++ b/web/src/components/ui/PrettyJsonView.tsx@@ -1,1450 +1,70 @@-/* eslint-disable no-nested-ternary, react/no-unstable-nested-components */-/* eslint-disable @repo/no-style-props */-import React, {- useMemo,- useState,- useEffect,- useRef,- useCallback,- memo,-} from "react";-import { cn } from "@/src/utils/tailwind";-import { deepParseJson } from "@langfuse/shared";-import { decodeUnicodeInJson } from "@/src/utils/decodeUnicodeInJson";-import { Skeleton } from "@/src/components/ui/skeleton";-import { type MediaReturnType } from "@/src/features/media";-import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";-import { IOSection, type IOSectionAction } from "@/src/components/ui/IOSection";-import { useCollapsibleSystemPrompt } from "@/src/hooks/useCollapsibleSystemPrompt";-import { copyTextToClipboard } from "@/src/utils/clipboard";-import { JSONView } from "@/src/components/ui/CodeJsonViewer";-import { Button } from "@/src/components/ui/button";-import { useClickWithoutSelection } from "@/src/hooks/useClickWithoutSelection";-import {- ChevronDown,- ChevronRight,- UnfoldVertical,- FoldVertical,- type IconComponent,-} from "@langfuse/icons";-import {- useReactTable,- getCoreRowModel,- getExpandedRowModel,- flexRender,- type ExpandedState,- type Row,-} from "@tanstack/react-table";-import { type LangfuseColumnDef } from "@/src/components/table/types";--// Custom expanded state type that allows false ("user intentionally collapsed all")-type LangfuseExpandedState = ExpandedState | false;-import { ChatMlArraySchema } from "@/src/components/schemas/ChatMlSchema";-import { MarkdownView } from "@/src/components/ui/MarkdownViewer";-import {- filterAlreadyRenderedMedia,- getRenderedInlineMediaIds,- getStandaloneMediaReferenceStrings,-} from "@/src/components/ui/markdown-media.utils";-import {- StringOrMarkdownSchema,- containsAnyMarkdown,-} from "@/src/components/schemas/MarkdownSchema";--import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";-import {- convertRowIdToKeyPath,- getSmartExpansionState,- type JsonTableRow,- transformJsonToTableData,-} from "@/src/components/table/utils/jsonExpansionUtils";-import {- ValueCell,- getValueStringLength,-} from "@/src/components/table/ValueCell";-import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";-import { isLargeRenderString } from "@/src/components/ui/largeStringGate";-import { LargeStringFallback } from "@/src/components/ui/LargeStringFallback";--const INDENTATION_PER_LEVEL = 16;-const INDENTATION_BASE = 12;-const KEY_CLASSES = "text-muted-foreground font-mono text-xs/5 wrap-break-word";-const CELL_CLASSES =- "border-border/60 py-1 pr-2 pl-1 align-top whitespace-normal";--// Constants for smart expansion logic-// Used for nested objects to control smart expansion depth-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 displayed-const DEFAULT_MAX_ROWS_IF_ROOT = 100;--const MAX_CELL_DISPLAY_CHARS = 2000;--const PREVIEW_TEXT_CLASSES = "text-gray-500 dark:text-gray-400";--type PrettyJsonViewTone = "danger" | "warning" | "muted" | "neutral";--// decodeUnicodeInJson was extracted to a standalone module so that other JSON-// viewers (e.g. CodeJsonViewer) can reuse it without creating an import cycle.-// Re-exported here for backward compatibility with existing imports and tests.-export {- decodeUnicodeInJson,- DECODE_UNICODE_MAX_NODES,- DECODE_UNICODE_MAX_DEPTH,-} from "@/src/utils/decodeUnicodeInJson";--function shouldShowValue(value: unknown, showNullValues: boolean): boolean {- if (showNullValues) return true;- return value !== null && value !== "" && value !== 0;-}--function filterTableRows(- rows: JsonTableRow[],- showNullValues: boolean,-): JsonTableRow[] {- if (showNullValues) return rows;-- return rows- .filter((row) => shouldShowValue(row.value, showNullValues))- .map((row) => ({- ...row,- subRows: row.subRows- ? filterTableRows(row.subRows, showNullValues)- : row.subRows,- }));-}--function getEmptyValueDisplay(value: unknown): string | null {- if (value === null) return "null";- if (value === undefined) return "undefined";- if (value === "") return "empty string";- if (- typeof value === "object" &&- value !== null &&- !Array.isArray(value) &&- Object.keys(value).length === 0- ) {- return "empty object";- }- return null;-}--/** Borderless bodies sit inside a section box, which owns fill and inset. */-function getContainerClasses(- scrollable: boolean | undefined,- codeClassName: string | undefined,- baseClasses = "whitespace-pre-wrap wrap-break-word p-3 text-xs",- borderless = false,-) {- return cn(- baseClasses,- borderless- ? "rounded-md overflow-clip p-0"- : scrollable- ? ""- : "rounded-sm border",- codeClassName,- );-}--function isChatMLFormat(json: unknown): boolean {- if (!json || typeof json !== "object") return false;-- if (Array.isArray(json)) {- const directArray = ChatMlArraySchema.safeParse(json);- if (directArray.success) {- // had some false positives, so we really check for role AND content to validate ChatML- const hasRoleAndContent = json.some(- (item) =>- typeof item === "object" &&- item !== null &&- "role" in item &&- "content" in item,- );- return hasRoleAndContent;- }- }-- if ("messages" in json && Array.isArray((json as any).messages)) {- const messagesArray = ChatMlArraySchema.safeParse((json as any).messages);- if (messagesArray.success) return true;- }-- if (Array.isArray(json) && json.length === 1 && Array.isArray(json[0])) {- const nestedArray = ChatMlArraySchema.safeParse(json[0]);- if (nestedArray.success) return true;- }-- return false;-}--function isMarkdownContent(- json: unknown,- characterLimit: number,-): {- isMarkdown: boolean;- content?: string;-} {- const contentSize = JSON.stringify(json || {}).length;- if (contentSize > characterLimit) {- return { isMarkdown: false };- }-- if (typeof json === "string") {- const markdownResult = StringOrMarkdownSchema.safeParse(json);- if (markdownResult.success) {- return { isMarkdown: true, content: json };- }- }-- // also render as MD if object has one key and the value is a markdown like string- if (- typeof json === "object" &&- json !== null &&- !Array.isArray(json) &&- json.constructor === Object- ) {- const entries = Object.entries(json);- if (entries.length === 1) {- const [, value] = entries[0];- if (typeof value === "string") {- if (containsAnyMarkdown(value)) {- return { isMarkdown: true, content: value };- }- }- }- }-- return { isMarkdown: false };-}--function getValueType(value: unknown): JsonTableRow["type"] {- if (value === null) return "null";- if (value === undefined) return "undefined";- if (Array.isArray(value)) return "array";- return typeof value as JsonTableRow["type"];-}--function hasChildren(value: unknown, valueType: JsonTableRow["type"]): boolean {- return (- (valueType === "object" &&- Object.keys(value as Record<string, unknown>).length > 0) ||- (valueType === "array" && Array.isArray(value) && value.length > 0)- );-}--function generateChildRows(row: JsonTableRow): JsonTableRow[] {- if (!row.rawChildData || row.childrenGenerated) {- return row.subRows || [];- }-- const children = transformJsonToTableData(- row.rawChildData,- row.key,- row.level + 1,- row.id,- false, // Don't use lazy loading for children- );-- return children;-}--function generateAllChildrenRecursively(- row: JsonTableRow,- onRowGenerated?: (rowId: string) => void,-): void {- if (row.rawChildData && !row.childrenGenerated) {- const children = generateChildRows(row);- row.subRows = children;- row.childrenGenerated = true;-- // this row now has generated children for state preservation (expand all)- onRowGenerated?.(row.id);-- children.forEach((child) => {- generateAllChildrenRecursively(child, onRowGenerated);- });- }-}--function handleRowExpansion(- row: Row<JsonTableRow>,- onLazyLoadChildren?: (rowId: string) => void,- expandedCells?: Set<string>,- toggleCellExpansion?: (cellId: string) => void,-) {- // row expansion takes precedence over cell expansion- if (row.original.hasChildren) {- const originalRow = row.original;- if (originalRow.rawChildData && !originalRow.childrenGenerated) {- onLazyLoadChildren?.(originalRow.id);- }- row.toggleExpanded();- return;- }-- // does the row have children, then expand row- const cellId = `${row.id}-value`;- const { value } = row.original;- const valueStringLength = getValueStringLength(value);- const needsCellExpansion = valueStringLength > MAX_CELL_DISPLAY_CHARS;-- if (needsCellExpansion && expandedCells && toggleCellExpansion) {- toggleCellExpansion(cellId);- }-}--interface JsonTableRowProps {- row: Row<JsonTableRow>;- rowIndex: number;- topLevelRowRef?: React.RefObject<HTMLTableRowElement | null>;- onLazyLoadChildren?: (rowId: string) => void;- expandedCells: Set<string>;- toggleCellExpansion: (cellId: string) => void;- stickyTopLevelKey: boolean;-}--const JsonTableRowComponent = memo(- ({- row,- rowIndex,- topLevelRowRef,- onLazyLoadChildren,- expandedCells,- toggleCellExpansion,- stickyTopLevelKey,- }: JsonTableRowProps) => {- // Hook is now at top level of this component ✅- const isExpandable =- row.original.hasChildren ||- getValueStringLength(row.original.value) > MAX_CELL_DISPLAY_CHARS;-- const { props: rowClickProps } = useClickWithoutSelection({- onClick: () => {- handleRowExpansion(- row,- onLazyLoadChildren,- expandedCells,- toggleCellExpansion,- );- },- enabled: isExpandable,- });-- return (- <tr- ref={- rowIndex === 0 && row.original.level === 0- ? topLevelRowRef- : undefined- }- data-observation-id={row.id}- {...rowClickProps}- className={cn(- "hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",- isExpandable ? "cursor-pointer" : "",- row.original.level === 0 && stickyTopLevelKey- ? "bg-background sticky top-0 z-10 shadow-xs"- : "",- )}- >- {row.getVisibleCells().map((cell) => (- <td- key={cell.id}- className={cn(- "h-full border-b [:last-child_>_&]:border-b-0",- CELL_CLASSES,- cell.column.id === "value" && "[&>div]:wrap-anywhere",- )}- style={{ width: `${cell.column.columnDef.size}%` }}- >- {flexRender(cell.column.columnDef.cell, cell.getContext())}- </td>- ))}- </tr>- );- },-);--JsonTableRowComponent.displayName = "JsonTableRow";--function JsonPrettyTable({- data,- expandAllRef,- onExpandStateChange,- noBorder = false,- expanded,- onExpandedChange,- onLazyLoadChildren,- onForceUpdate,- smartDefaultsLevel,- expandedCells,- toggleCellExpansion,- stickyTopLevelKey = false,- showObservationTypeBadge = false,+import { type ComponentProps } from "react";+import { JsonViewController } from "./JsonViewController";+import { PrettyJsonViewContent } from "./PrettyJsonViewContent";++export function PrettyJsonView({+ json,+ parsedJson,+ isLoading,+ isParsing,+ media,+ currentView,+ externalExpansionState,+ onExternalExpansionChange,+ showNullValues,+ title,+ collapseStringsAfterLength,+ scrollable,+ borderless,+ stickyTopLevelKey,+ showObservationTypeBadge,rowActions,-}: {- data: JsonTableRow[];- expandAllRef?: React.RefObject<(() => void) | null>;- onExpandStateChange?: (allExpanded: boolean) => void;- noBorder?: boolean;- expanded: ExpandedState;- onExpandedChange: (- updater: ExpandedState | ((prev: ExpandedState) => ExpandedState),- ) => void;- onLazyLoadChildren?: (rowId: string) => void;- onForceUpdate?: () => void;- smartDefaultsLevel?: number | null;- expandedCells: Set<string>;- toggleCellExpansion: (cellId: string) => void;- stickyTopLevelKey?: boolean;- showObservationTypeBadge?: boolean;- rowActions?: React.ComponentProps<typeof ValueCell>["rowActions"];- /** Drop the Path / Value header row. */-}) {- const topLevelRowRef = useRef<HTMLTableRowElement>(null);- const [topLevelRowHeight, setTopLevelRowHeight] = useState(32);-- useEffect(() => {- if (stickyTopLevelKey && topLevelRowRef.current) {- setTopLevelRowHeight(topLevelRowRef.current.offsetHeight);- }- }, [stickyTopLevelKey, data, expanded]);-- const indentationWidthFor = (row: Row<JsonTableRow>) =>- row.original.level * INDENTATION_PER_LEVEL + INDENTATION_BASE;-- const renderKeyText = (key: string) =>- key.includes(".")- ? key.split(".").map((segment, index, segments) => (- <span key={index}>- {segment}- {index < segments.length - 1 && (- <>- .<wbr />- </>- )}- </span>- ))- : key;-- const renderKey = (row: Row<JsonTableRow>) => {- const indentationWidth = indentationWidthFor(row);-- const itemBadgeType =- showObservationTypeBadge &&- row.original.level === 0 &&- row.original.value &&- typeof row.original.value === "object" &&- !Array.isArray(row.original.value) &&- "type" in row.original.value &&- typeof (row.original.value as any).type === "string" &&- (row.original.value as any).type- ? ((row.original.value as any).type as LangfuseItemType)- : null;-- return (- <div className="flex w-max max-w-[40cqw] min-w-40 items-start gap-1 text-xs/5 wrap-break-word">- <div- className="flex h-[1lh] shrink-0 items-center justify-end"- style={{ width: `${indentationWidth}px` }}- >- {row.original.hasChildren ? (- <Button- variant="ghost"- size="sm"- aria-label={`${row.getIsExpanded() ? "Collapse" : "Expand"} ${row.original.key}`}- aria-expanded={row.getIsExpanded()}- onClick={(e) => {- e.stopPropagation();- handleRowExpansion(- row,- onLazyLoadChildren,- expandedCells,- toggleCellExpansion,- );- }}- className="text-muted-foreground hover:text-foreground h-4 w-4 p-0 hover:bg-transparent"- >- {row.getIsExpanded() ? (- <ChevronDown size="base" color="default" />- ) : (- <ChevronRight size="base" color="default" />- )}- </Button>- ) : null}- </div>- <span className={cn("min-w-0 cursor-text", KEY_CLASSES)}>- {itemBadgeType && (- <span className="mr-1 inline-block align-middle">- <ItemBadge type={itemBadgeType} isSmall={true} />- </span>- )}- {renderKeyText(row.original.key)}- </span>- </div>- );- };-- const renderValue = (row: Row<JsonTableRow>) => (- <ValueCell- row={row}- expandedCells={expandedCells}- toggleCellExpansion={toggleCellExpansion}- preserveStringWhitespace={row.original.key === "code_eval_source_code"}- rowActions={rowActions}- />- );-- const keyColumn: LangfuseColumnDef<JsonTableRow, unknown> = {- accessorKey: "key",- header: "Path",- size: 1,- cell: ({ row }) => {- const content = renderKey(row);- const valueLength = getValueStringLength(row.original.value);- const isLongValue = valueLength > MAX_CELL_DISPLAY_CHARS / 3; // already long if we don't truncate-- if (isLongValue) {- // Offset by the section header where the host pins it (--io-header-h).- const headerOffset = "var(--io-header-h, 0px)";- let topPosition = headerOffset;- if (stickyTopLevelKey && row.original.level !== 0) {- topPosition = `calc(${headerOffset} + ${topLevelRowHeight}px)`;- }-- return (- <div className="sticky z-5 -my-1 py-1" style={{ top: topPosition }}>- {content}- </div>- );- }-- return content;- },- };-- const valueColumn: LangfuseColumnDef<JsonTableRow, unknown> = {- accessorKey: "value",- header: "Value",- size: 99,- cell: ({ row }) => renderValue(row),- };-- const columns: LangfuseColumnDef<JsonTableRow, unknown>[] = [- keyColumn,- valueColumn,- ];-- const table = useReactTable({- data,- columns,- getCoreRowModel: getCoreRowModel(),- getExpandedRowModel: getExpandedRowModel(),- getSubRows: (row) => row.subRows,- getRowId: (row) => convertRowIdToKeyPath(row.id),- state: {- expanded,- },- onExpandedChange: onExpandedChange,- enableColumnResizing: false,- autoResetExpanded: false,- });-- const allRowsExpanded = useMemo(() => {- const allRows = table.getRowModel().flatRows;- const expandableRows = allRows.filter((row) => row.original.hasChildren);- return (- expandableRows.length > 0 &&- expandableRows.every((row) => row.getIsExpanded())- );- // expanded is required for the collapse button to work- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [table, expanded]);-- // Notify parent of expand state changes- useEffect(() => {- onExpandStateChange?.(allRowsExpanded);- }, [allRowsExpanded, onExpandStateChange]);-- const expandRowsWithLazyLoading = useCallback(- (- rowFilter: (rows: Row<JsonTableRow>[]) => Row<JsonTableRow>[],- shouldCollapse = false,- ) => {- if (shouldCollapse) {- onExpandedChange({});- return;- }-- const allRows = table.getRowModel().flatRows;- const expandableRows = allRows.filter((row) => row.original.hasChildren);- const targetRows = rowFilter(expandableRows);-- const rowsNeedingParsing = targetRows.filter(- (row) => row.original.rawChildData && !row.original.childrenGenerated,- );-- if (rowsNeedingParsing.length > 0) {- const generatedRowIds: string[] = [];-- rowsNeedingParsing.forEach((row) => {- generateAllChildrenRecursively(row.original, (rowId) => {- generatedRowIds.push(rowId);- });- });-- if (generatedRowIds.length > 0) {- onLazyLoadChildren?.(generatedRowIds.join(","));- }-- onForceUpdate?.();- // setTimeout re-renders table once new data is available- setTimeout(() => {- const newExpanded: ExpandedState = {};- const updatedAllRows = table.getRowModel().flatRows;- const updatedExpandableRows = updatedAllRows.filter(- (row) => row.original.hasChildren,- );- const updatedTargetRows = rowFilter(updatedExpandableRows);-- updatedTargetRows.forEach((row) => {- newExpanded[row.id] = true;- });-- onExpandedChange(newExpanded);- }, 0);- } else {- // No lazy loading needed, just set expansion state- const newExpanded: ExpandedState = {};- targetRows.forEach((row) => {- newExpanded[row.id] = true;- });- onExpandedChange(newExpanded);- }- },- [table, onExpandedChange, onLazyLoadChildren, onForceUpdate],- );-- const handleToggleExpandAll = useCallback(() => {- expandRowsWithLazyLoading(- (expandableRows) => expandableRows, // All expandable rows- allRowsExpanded, // Should collapse if already expanded- );- }, [allRowsExpanded, expandRowsWithLazyLoading]);-- useEffect(() => {- if (expandAllRef) {- expandAllRef.current = handleToggleExpandAll;- }- }, [expandAllRef, handleToggleExpandAll]);-- useEffect(() => {- if (smartDefaultsLevel != null && smartDefaultsLevel > 0) {- expandRowsWithLazyLoading((expandableRows) =>- expandableRows.filter((row) => row.depth < smartDefaultsLevel),- );- }- }, [smartDefaultsLevel, expandRowsWithLazyLoading]);-+}: Pick<+ ComponentProps<typeof JsonViewController>,+ | "json"+ | "parsedJson"+ | "isLoading"+ | "isParsing"+ | "media"+ | "currentView"+ | "externalExpansionState"+ | "onExternalExpansionChange"+ | "showNullValues"+> &+ Pick<+ ComponentProps<typeof PrettyJsonViewContent>,+ | "title"+ | "collapseStringsAfterLength"+ | "scrollable"+ | "borderless"+ | "stickyTopLevelKey"+ | "showObservationTypeBadge"+ | "rowActions"+ >) {return (- <div className={cn("w-full", !noBorder && "rounded-sm border")}>- <table className="w-full table-auto caption-bottom border-separate border-spacing-0 space-y-4 overflow-auto text-sm">- <thead className="sr-only">- <tr>- <th scope="col">Path</th>- <th scope="col">Value</th>- </tr>- </thead>- <tbody className="text-xs [&_tr:last-child]:border-0">- {table.getRowModel().rows.map((row, rowIndex) => (- <JsonTableRowComponent- key={row.id}- row={row}- rowIndex={rowIndex}- topLevelRowRef={- rowIndex === 0 && row.original.level === 0- ? topLevelRowRef- : undefined- }- onLazyLoadChildren={onLazyLoadChildren}- expandedCells={expandedCells}- toggleCellExpansion={toggleCellExpansion}- stickyTopLevelKey={stickyTopLevelKey}- />- ))}- </tbody>- </table>- </div>- );-}--export function PrettyJsonView(props: {- json?: unknown;- parsedJson?: unknown; // Pre-parsed data (optional, from useParsedObservation hook)- title?: string;- titleIcon?: IconComponent;- /** Drop the Path / Value header row. */- className?: string;- isLoading?: boolean;- isParsing?: boolean;- codeClassName?: string;- collapseStringsAfterLength?: number | null;- media?: MediaReturnType[];- scrollable?: boolean;- /** Section header actions, after the table's own. */- actions?: IOSectionAction[];- currentView?: "pretty" | "json";- externalExpansionState?: Record<string, boolean> | boolean;- onExternalExpansionChange?: (- expansion: Record<string, boolean> | boolean,- ) => void;- showNullValues?: boolean;- stickyTopLevelKey?: boolean;- showObservationTypeBadge?: boolean;- tone?: PrettyJsonViewTone;- /** Rendered inside the section box above the content (e.g. thinking blocks). */- beforeContent?: React.ReactNode;- /** Rendered inside the section box below the content (e.g. tool calls). */- afterContent?: React.ReactNode;- /** Initial collapsed state of the section; system prompts use their own rule. */- defaultCollapsed?: boolean;- /** Controlled collapsed state; long system prompts still follow their rule. */- collapsed?: boolean;- onCollapsedChange?: (collapsed: boolean) => void;- /** Shows an actions menu instead of the default one-click copy button. */- rowActions?: React.ComponentProps<typeof ValueCell>["rowActions"];- /** Long system prompts start collapsed (from raw `role === "system"`,- since the title can carry a message `name` instead of the role). */- isSystemPrompt?: boolean;-}) {- const codeClassName = props.codeClassName;- // Large plain-string gate (LFE-10991): a multi-MB top-level string skips- // deepParseJson's object-only `maxSize` guard, so without this it would run- // several full-length main-thread passes (parse, the markdown-probe- // `JSON.stringify`, unicode decode — some of them twice, including inside the- // always-mounted hidden JSON viewer) and mount the unvirtualized react18-json- // tree with the whole string, blocking the tab and inflating memory. The body- // renders a bounded preview + download instead.- //- // Gate on the SETTLED value only. During an async worker parse the parsed- // value is not ready (`parsedJson === undefined`, `isParsing` true) and the- // raw `json` may be a *stringified* payload whose JSON-quoted form is itself- // >2M chars (e.g. the JSON tab passes raw `json` alongside a not-yet-ready- // `parsedJson`). Gating on that raw form would flash the fallback — and offer- // a quoted-form download — before the parse settles to the real value. The- // unvirtualized render we protect against does not run during parse anyway,- // so fall through to the normal loading/parsing state in that window.- const largeStringValue = useMemo(() => {- if (props.isParsing) return null;- const settled =- props.parsedJson !== undefined ? props.parsedJson : props.json;- return isLargeRenderString(settled) ? settled : null;- }, [props.parsedJson, props.json, props.isParsing]);-- // Use pre-parsed data if available, otherwise parse on-demand- const parsedJson = useMemo(() => {- // Skip all parse/decode work on very large plain strings (see gate above);- // the raw string is rendered through the bounded fallback, not decoded.- if (largeStringValue !== null) {- return largeStringValue;- }-- // If pre-parsed data is provided, use it directly (skip parsing)- if (props.parsedJson !== undefined) {- return decodeUnicodeInJson(props.parsedJson);- }-- // If still parsing in Web Worker, return null (will show loading state)- if (props.isParsing) {- return null;- }-- // Fast path: if already an object, likely no parsing needed- if (typeof props.json !== "string") {- return decodeUnicodeInJson(props.json);- }-- // Only parse strings, with size/depth limits- const result = deepParseJson(props.json, {- maxSize: 500_000,- maxDepth: 2,- });-- // 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, largeStringValue]);-- // The section box frames titled tables, toned ones included.- const tableBorderless = Boolean(props.title);-- // 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);-- // For JSON view: derive collapsed state from external expansion state- // false or empty object = collapsed, true or object with keys = expanded- const deriveJsonCollapsedFromExternal = useCallback(- (extState: Record<string, boolean> | boolean | undefined): boolean => {- if (extState === undefined) return false; // default: not collapsed- if (extState === false) return true; // explicitly collapsed- if (extState === true) return false; // explicitly expanded- // empty object = collapsed (user collapsed all)- if (typeof extState === "object" && Object.keys(extState).length === 0)- return true;- return false; // has keys = not collapsed- },- [],- );-- const [jsonIsCollapsed, setJsonIsCollapsed] = useState(() =>- deriveJsonCollapsedFromExternal(props.externalExpansionState),- );-- // Sync jsonIsCollapsed when external state changes (e.g., navigating between observations)- const prevExternalStateRef = useRef(props.externalExpansionState);- useEffect(() => {- if (prevExternalStateRef.current !== props.externalExpansionState) {- const newCollapsed = deriveJsonCollapsedFromExternal(- props.externalExpansionState,- );- prevExternalStateRef.current = props.externalExpansionState;- setJsonIsCollapsed(newCollapsed);- }- }, [props.externalExpansionState, deriveJsonCollapsedFromExternal]);- const [expandedRowsWithChildren, setExpandedRowsWithChildren] = useState<- Set<string>- >(new Set());- const [expandedCells, setExpandedCells] = useState<Set<string>>(new Set());- const [, setForceUpdate] = useState(0);-- // View's own state, lower precedence than optionally supplied external expansion state- const [internalExpansionState, setInternalExpansionState] =- useState<LangfuseExpandedState>({});-- const isChatML = useMemo(() => isChatMLFormat(parsedJson), [parsedJson]);- const characterLimit = useMarkdownRenderCharacterLimit();- const { isMarkdown, content: markdownContent } = useMemo(- // Skip the markdown probe for gated large strings: isMarkdownContent runs- // `JSON.stringify` on the whole value, an O(n) pass over the multi-MB string.- () =>- largeStringValue !== null- ? { isMarkdown: false as const, content: undefined }- : isMarkdownContent(parsedJson, characterLimit),- [parsedJson, largeStringValue, characterLimit],- );-- const baseTableData = useMemo(() => {- try {- if (- largeStringValue === null &&- actualCurrentView === "pretty" &&- parsedJson !== null &&- parsedJson !== undefined &&- !isChatML &&- !isMarkdown- ) {- // early abort check for smart expansion- if (parsedJson?.constructor === Object) {- const topLevelKeys = Object.keys(- parsedJson as Record<string, unknown>,- );- if (topLevelKeys.length > DEFAULT_MAX_ROWS_IF_ROOT) {- // return empty array to skip expansion directly- return [];- }- }-- // lazy load JSON data, generate only top-level rows initially; children on expand- const createTopLevelRows = (- obj: Record<string, unknown>,- ): JsonTableRow[] => {- const entries = Object.entries(obj);- const rows: JsonTableRow[] = [];-- entries.forEach(([key, value]) => {- const valueType = getValueType(value);- const childrenExist = hasChildren(value, valueType);-- const row: JsonTableRow = {- id: key,- key,- value,- type: valueType,- hasChildren: childrenExist,- level: 0,- childrenGenerated: false,- };-- if (childrenExist) {- row.rawChildData = value;- row.subRows = []; // empty initially for lazy loading- }- rows.push(row);- });- return rows;- };-- let result: JsonTableRow[];-- // top-level is an object, start with its properties directly- if (parsedJson?.constructor === Object) {- result = createTopLevelRows(parsedJson as Record<string, unknown>);- } else {- result = transformJsonToTableData(parsedJson, "", 0, "", true);- }-- return result;- }-- return [];- } catch (error) {- console.error("Error transforming JSON to table data:", error);- return [];- }- }, [parsedJson, isChatML, isMarkdown, actualCurrentView, largeStringValue]);-- // state precedence: external state before smart expansion- const finalExpansionState: ExpandedState = useMemo(() => {- if (baseTableData.length === 0) return {};-- if (props.externalExpansionState === false) {- // user collapsed all- return {};- }- if (props.externalExpansionState === true) {- // user expanded all- return true;- }- if (- typeof props.externalExpansionState === "object" &&- props.externalExpansionState !== null &&- Object.keys(props.externalExpansionState).length > 0- ) {- // user set specific expansions - apply with prefix matching-- // Extract expanded paths for prefix matching- const expandedPaths = Object.entries(props.externalExpansionState)- .filter(([, isExpanded]) => isExpanded)- .map(([path]) => path);-- // Apply prefix matching: for each expanded path, expand all its ancestors- // Example: if "messages.0.content.text" is expanded, also expand:- // "messages", "messages.0", "messages.0.content"- const enhancedState: Record<string, boolean> = {- ...props.externalExpansionState,- };-- expandedPaths.forEach((path) => {- const parts = path.split(".");- // Generate all ancestor paths- for (let i = 1; i < parts.length; i++) {- const ancestorPath = parts.slice(0, i).join(".");- if (enhancedState[ancestorPath] === undefined) {- enhancedState[ancestorPath] = true;- }- }- });-- return enhancedState;- }-- // 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)- const actualExpansionState = useMemo(() => {- if (finalExpansionState === true) return true;-- // Ensure both states are objects with fallback- const finalState = (finalExpansionState as Record<string, boolean>) || {};- const internalState =- (internalExpansionState as Record<string, boolean>) || {};-- // Smart expansion only applies on initial load (when no user interactions yet)- if (Object.keys(internalState).length > 0) {- // user made changes, use them- return internalState;- } else if (internalExpansionState === false) {- // user collapsed all- return false;- }- return finalState;- }, [finalExpansionState, internalExpansionState]);-- // table data with lazy-loaded children- const tableData = useMemo(() => {- const updateRowWithChildren = (rows: JsonTableRow[]): JsonTableRow[] => {- return rows.map((row) => {- let updatedRow = row;-- // Generate children if:- // 1. Row is in expandedRowsWithChildren (user clicked lazy loading), OR- // 2. Row should be expanded according to actualExpansionState (smart expansion)- const keyPath = convertRowIdToKeyPath(row.id);- const shouldHaveChildren =- expandedRowsWithChildren.has(row.id) ||- (actualExpansionState !== true &&- actualExpansionState &&- actualExpansionState[keyPath]);-- if (shouldHaveChildren && row.rawChildData && !row.childrenGenerated) {- const children = generateChildRows(row);- updatedRow = {- ...row,- subRows: children,- childrenGenerated: true,- };- }-- if (updatedRow.subRows && updatedRow.subRows.length > 0) {- updatedRow = {- ...updatedRow,- subRows: updateRowWithChildren(updatedRow.subRows),- };- }-- return updatedRow;- });- };-- const dataWithChildren = updateRowWithChildren(baseTableData);- return filterTableRows(dataWithChildren, props.showNullValues ?? true);- }, [- baseTableData,- expandedRowsWithChildren,- actualExpansionState,- props.showNullValues,- ]);-- const handleLazyLoadChildren = useCallback((rowId: string) => {- setExpandedRowsWithChildren((prev) => {- const newSet = new Set(prev);- // we track the IDs for batch updates when lazy loading children- if (rowId.includes(",")) {- rowId.split(",").forEach((id) => newSet.add(id));- } else {- newSet.add(rowId);- }-- return newSet;- });- }, []);-- const handleForceUpdate = useCallback(() => {- setForceUpdate((prev) => prev + 1);- }, []);-- const toggleCellExpansion = useCallback((cellId: string) => {- setExpandedCells((prev) => {- const newSet = new Set(prev);- if (newSet.has(cellId)) {- newSet.delete(cellId);- } else {- newSet.add(cellId);- }- return newSet;- });- }, []);-- const { onExternalExpansionChange } = props;- const handleTableExpandedChange = useCallback(- (- updater:- | ExpandedState- | ((prev: ExpandedState) => ExpandedState)- | boolean,- ) => {- // always update internal state of the table- let newState: ExpandedState;- if (typeof updater === "function") {- newState = updater(- actualExpansionState === false ? {} : actualExpansionState,- );- const finalState: LangfuseExpandedState =- typeof newState === "object" && Object.keys(newState).length === 0- ? false- : newState;- setInternalExpansionState(finalState);-- // update external state if state changed by user (callback provided)- if (onExternalExpansionChange) {- if (typeof newState === "boolean") {- onExternalExpansionChange(newState);- return;- }-- const keyBasedState = Object.fromEntries(- Object.entries(newState).filter(([, expanded]) => expanded),- );-- // user collapsed all items -> set state to false (instead of empty object)- const finalExternalState =- Object.keys(keyBasedState).length === 0 ? false : keyBasedState;- onExternalExpansionChange(finalExternalState);- }- } else if (typeof updater !== "boolean") {- newState = updater;- const finalState: LangfuseExpandedState =- typeof newState === "object" && Object.keys(newState).length === 0- ? false- : newState;- setInternalExpansionState(finalState);-- // Handle external state updates for expand/collapse all button- if (onExternalExpansionChange && typeof newState === "object") {- if (Object.keys(newState).length === 0) {- // user collapsed all- onExternalExpansionChange(false);- } else {- onExternalExpansionChange(newState);- }- }- }- },- [onExternalExpansionChange, actualExpansionState],- );-- const handleOnCopy = (event?: React.MouseEvent<HTMLButtonElement>) => {- if (event) {- event.preventDefault();- }- const textToCopy = stringifyJsonNode(parsedJson);- copyTextToClipboard(textToCopy);-- if (event) {- event.currentTarget.focus();- }- };-- const handleJsonToggleCollapse = () => {- const newCollapsed = !jsonIsCollapsed;- setJsonIsCollapsed(newCollapsed);- if (props.onExternalExpansionChange) {- props.onExternalExpansionChange(!newCollapsed);- }- };-- const hasExpandableRows = useMemo(() => {- if (typeof parsedJson !== "object" || parsedJson === null) return false;- return Object.values(parsedJson as Record<string, unknown>).some((value) =>- hasChildren(value, getValueType(value)),- );- }, [parsedJson]);- const emptyValueDisplay = getEmptyValueDisplay(parsedJson);- const isPrettyView = actualCurrentView === "pretty";- const isMarkdownMode = isMarkdown && isPrettyView;- const standaloneMediaReferenceStrings =- typeof markdownContent === "string"- ? getStandaloneMediaReferenceStrings(markdownContent)- : [];- const shouldRenderStandaloneMedia =- isMarkdownMode && standaloneMediaReferenceStrings.length > 0;- const systemPrompt = useCollapsibleSystemPrompt({- isSystemPrompt:- Boolean(props.title) &&- !!props.isSystemPrompt &&- isMarkdownMode &&- !shouldRenderStandaloneMedia,- content: markdownContent ?? "",- });- const remainingMarkdownMedia = filterAlreadyRenderedMedia(- props.media,- getRenderedInlineMediaIds({- markdown: markdownContent ?? "",- }),- );- const shouldUseTableView =- largeStringValue === null &&- isPrettyView &&- !isChatML &&- !isMarkdown &&- !emptyValueDisplay;-- const body = (- <>- {largeStringValue !== null ? (- <LargeStringFallback title={props.title} value={largeStringValue} />- ) : props.isLoading || props.isParsing ? (- <div className="io-message-content ph-no-capture">- <div- className={cn(- getContainerClasses(- props.scrollable,- codeClassName,- undefined,- tableBorderless,- ),- )}- >- <div className="space-y-2">- <Skeleton className="h-3 w-3/4" />- <Skeleton className="h-3 w-1/2" />- <Skeleton className="h-3 w-2/3" />- {props.isParsing && (- <div className="text-muted-foreground mt-2 text-xs">- Parsing in background...- </div>- )}- </div>- </div>- </div>- ) : emptyValueDisplay && isPrettyView ? (- <div className="io-message-content ph-no-capture">- <div- className={cn(- "flex items-center",- getContainerClasses(- props.scrollable,- codeClassName,- undefined,- tableBorderless,- ),- )}- >- <span className={`font-mono ${PREVIEW_TEXT_CLASSES}`}>- {emptyValueDisplay}- </span>- </div>- </div>- ) : isMarkdownMode ? (- <div className="io-message-content ph-no-capture">- {shouldRenderStandaloneMedia ? (- standaloneMediaReferenceStrings.map((referenceString, index) => (- <LangfuseMediaView- key={`${referenceString}-${index}`}- mediaReferenceString={referenceString}- />- ))- ) : (- <MarkdownView- markdown={markdownContent || ""}- media={props.media}- className={cn(props.title && "p-0")}- />- )}- </div>- ) : (- <>- {/* Always render JsonPrettyTable to preserve internal React Table state */}- <div- className="io-message-content ph-no-capture"- style={{ display: shouldUseTableView ? "flex" : "none" }}- >- <div- className={cn(- getContainerClasses(- props.scrollable,- codeClassName,- "flex text-xs wrap-break-word whitespace-pre-wrap",- tableBorderless,- ),- "@container w-full",- )}- >- {props.isLoading ? (- <Skeleton className="m-3 h-3 w-3/4" />- ) : (- <JsonPrettyTable- data={tableData}- expandAllRef={expandAllRef}- onExpandStateChange={setAllRowsExpanded}- noBorder={true}- expanded={- actualExpansionState === false ? {} : actualExpansionState- }- onExpandedChange={handleTableExpandedChange}- onLazyLoadChildren={handleLazyLoadChildren}- onForceUpdate={handleForceUpdate}- smartDefaultsLevel={null}- expandedCells={expandedCells}- toggleCellExpansion={toggleCellExpansion}- stickyTopLevelKey={props.stickyTopLevelKey}- showObservationTypeBadge={props.showObservationTypeBadge}- rowActions={props.rowActions}- />- )}- </div>- </div>-- {/* Always render JSONView to preserve its state too */}- <div- className="io-message-content ph-no-capture"- style={{ display: shouldUseTableView ? "none" : "block" }}- >- <JSONView- // 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}- className=""- borderless={Boolean(props.title)}- isLoading={props.isLoading}- codeClassName={codeClassName}- collapseStringsAfterLength={props.collapseStringsAfterLength}- media={props.media}- scrollable={props.scrollable}- externalJsonCollapsed={jsonIsCollapsed}- onToggleCollapse={handleJsonToggleCollapse}- />- </div>- </>- )}- {shouldRenderStandaloneMedia && remainingMarkdownMedia.length > 0 && (- <>- <div className="text-muted-foreground my-1 px-2 py-1 text-xs">- Media- </div>- <div className="ph-no-capture flex flex-wrap gap-2 px-2 pt-1 pb-4">- {remainingMarkdownMedia.map((m) => (- <LangfuseMediaView- mediaAPIReturnValue={m}- variant="icon"- key={m.mediaId}- />- ))}- </div>- </>- )}- {props.media &&- props.media.length > 0 &&- isPrettyView &&- !isMarkdownMode && (- <>- <div className="text-muted-foreground my-1 px-2 py-1 text-xs">- Media- </div>- <div className="ph-no-capture flex flex-wrap gap-2 px-2 pt-1 pb-4">- {props.media.map((m) => (- <LangfuseMediaView- mediaAPIReturnValue={m}- variant="icon"- key={m.mediaId}- />- ))}- </div>- </>- )}- </>- );-- const expandAllAction: IOSectionAction | undefined =- shouldUseTableView && hasExpandableRows- ? {- icon: allRowsExpanded ? FoldVertical : UnfoldVertical,- label: allRowsExpanded ? "Collapse all rows" : "Expand all rows",- onClick: () => expandAllRef.current?.(),- }- : undefined;- const sectionActions = [- ...(expandAllAction ? [expandAllAction] : []),- ...(props.actions ?? []),- ];-- const scrollableBody = props.scrollable ? (- <div- className={cn(- "flex h-full min-h-0 overflow-hidden",- isMarkdownMode || (shouldUseTableView && tableBorderless)- ? ""- : "rounded-sm border",- )}+ <JsonViewController+ json={json}+ parsedJson={parsedJson}+ isLoading={isLoading}+ isParsing={isParsing}+ media={media}+ currentView={currentView}+ externalExpansionState={externalExpansionState}+ onExternalExpansionChange={onExternalExpansionChange}+ showNullValues={showNullValues}>- <div className="max-h-full min-h-0 w-full overflow-y-auto">{body}</div>- </div>- ) : (- body- );-- if (!props.title) {- return (- <div- className={cn(- "flex max-h-full min-h-0 flex-col",- props.className,- props.scrollable ? "overflow-hidden" : "",- )}- >- {scrollableBody}- </div>- );- }-- return (- <div- className={cn(- "flex max-h-full min-h-0 flex-col",- props.className,- props.scrollable ? "overflow-hidden" : "",+ {(state) => (+ <PrettyJsonViewContent+ state={state}+ title={title}+ collapseStringsAfterLength={collapseStringsAfterLength}+ scrollable={scrollable}+ borderless={borderless}+ stickyTopLevelKey={stickyTopLevelKey}+ showObservationTypeBadge={showObservationTypeBadge}+ rowActions={rowActions}+ />)}- >- <IOSection- title={props.title}- titleIcon={props.titleIcon}- onCopy={handleOnCopy}- actions={sectionActions.length > 0 ? sectionActions : undefined}- defaultCollapsed={props.defaultCollapsed}- collapsed={props.collapsed}- onCollapsedChange={props.onCollapsedChange}- variant={shouldUseTableView ? "table" : "text"}- tone={props.tone}- {...(systemPrompt.shouldBeCollapsible && {- collapsed: systemPrompt.isCollapsed,- onCollapsedChange: systemPrompt.toggleCollapsed,- })}- >- {props.beforeContent}- {scrollableBody}- {props.afterContent}- </IOSection>- </div>+ </JsonViewController>);}--// TODO: deduplicate with CodeJsonViewer.tsx-function stringifyJsonNode(node: unknown) {- // return single string nodes without quotes- if (typeof node === "string") {- return node;- }-- try {- return JSON.stringify(- node,- (key, value) => {- switch (typeof value) {- case "bigint":- return String(value) + "n";- case "number":- case "boolean":- case "object":- case "string":- return value as string;- default:- return String(value);- }- },- 4,- );- } catch (error) {- console.error("JSON stringify error", error);- return "Error: JSON.stringify failed";- }-}diff --git a/web/src/components/ui/PrettyJsonViewContent.tsx b/web/src/components/ui/PrettyJsonViewContent.tsxnew file mode 100644index 0000000000..c911dde26f--- /dev/null+++ b/web/src/components/ui/PrettyJsonViewContent.tsx@@ -0,0 +1,753 @@+/* eslint-disable no-nested-ternary, react/no-unstable-nested-components */+/* eslint-disable @repo/no-style-props */+import { type JsonViewState } from "./JsonViewController";+import React, {+ useMemo,+ useState,+ useEffect,+ useRef,+ useCallback,+ memo,+} from "react";+import { cn } from "@/src/utils/tailwind";++import { Skeleton } from "@/src/components/ui/skeleton";+import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";++import { JSONView } from "@/src/components/ui/CodeJsonViewer";+import { Button } from "@/src/components/ui/button";+import { useClickWithoutSelection } from "@/src/hooks/useClickWithoutSelection";+import { ChevronDown, ChevronRight } from "@langfuse/icons";+import {+ useReactTable,+ getCoreRowModel,+ getExpandedRowModel,+ flexRender,+ type ExpandedState,+ type Row,+} from "@tanstack/react-table";+import { type LangfuseColumnDef } from "@/src/components/table/types";++import { MarkdownView } from "@/src/components/ui/MarkdownView";++import {+ convertRowIdToKeyPath,+ transformJsonToTableData,+ type JsonTableRow,+} from "@/src/components/table/utils/jsonExpansionUtils";+import {+ ValueCell,+ getValueStringLength,+} from "@/src/components/table/ValueCell";+import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";++import { LargeStringFallback } from "@/src/components/ui/LargeStringFallback";++const INDENTATION_PER_LEVEL = 16;+const INDENTATION_BASE = 12;+const KEY_CLASSES = "text-muted-foreground font-mono text-xs/5 wrap-break-word";+const CELL_CLASSES =+ "border-border/60 py-1 pr-2 pl-1 align-top whitespace-normal";++const MAX_CELL_DISPLAY_CHARS = 2000;++const PREVIEW_TEXT_CLASSES = "text-gray-500 dark:text-gray-400";++function getEmptyValueDisplay(value: unknown): string | null {+ if (value === null) return "null";+ if (value === undefined) return "undefined";+ if (value === "") return "empty string";+ if (+ typeof value === "object" &&+ !Array.isArray(value) &&+ Object.keys(value).length === 0+ )+ return "empty object";+ return null;+}++/** Borderless bodies sit inside a section box, which owns fill and inset. */+function getContainerClasses(+ scrollable: boolean | undefined,+ codeClassName: string | undefined,+ baseClasses = "whitespace-pre-wrap wrap-break-word p-3 text-xs",+ borderless = false,+) {+ return cn(+ baseClasses,+ borderless+ ? "rounded-md overflow-clip p-0"+ : scrollable+ ? ""+ : "rounded-sm border",+ codeClassName,+ );+}++function handleRowExpansion(+ row: Row<JsonTableRow>,+ onLazyLoadChildren?: (rowId: string) => void,+ expandedCells?: Set<string>,+ toggleCellExpansion?: (cellId: string) => void,+) {+ // row expansion takes precedence over cell expansion+ if (row.original.hasChildren) {+ const originalRow = row.original;+ if (originalRow.rawChildData && !originalRow.childrenGenerated) {+ onLazyLoadChildren?.(originalRow.id);+ }+ row.toggleExpanded();+ return;+ }++ // does the row have children, then expand row+ const cellId = `${row.id}-value`;+ const { value } = row.original;+ const valueStringLength = getValueStringLength(value);+ const needsCellExpansion = valueStringLength > MAX_CELL_DISPLAY_CHARS;++ if (needsCellExpansion && expandedCells && toggleCellExpansion) {+ toggleCellExpansion(cellId);+ }+}++function generateAllChildrenRecursively(+ row: JsonTableRow,+ onRowGenerated?: (rowId: string) => void,+): void {+ if (row.rawChildData && !row.childrenGenerated) {+ row.subRows = transformJsonToTableData(+ row.rawChildData,+ row.key,+ row.level + 1,+ row.id,+ false,+ );+ row.childrenGenerated = true;+ onRowGenerated?.(row.id);+ row.subRows.forEach((child) => {+ generateAllChildrenRecursively(child, onRowGenerated);+ });+ }+}++interface JsonTableRowProps {+ row: Row<JsonTableRow>;+ rowIndex: number;+ topLevelRowRef?: React.RefObject<HTMLTableRowElement | null>;+ onLazyLoadChildren?: (rowId: string) => void;+ expandedCells: Set<string>;+ toggleCellExpansion: (cellId: string) => void;+ stickyTopLevelKey: boolean;+}++const JsonTableRowComponent = memo(+ ({+ row,+ rowIndex,+ topLevelRowRef,+ onLazyLoadChildren,+ expandedCells,+ toggleCellExpansion,+ stickyTopLevelKey,+ }: JsonTableRowProps) => {+ // Hook is now at top level of this component ✅+ const isExpandable =+ row.original.hasChildren ||+ getValueStringLength(row.original.value) > MAX_CELL_DISPLAY_CHARS;++ const { props: rowClickProps } = useClickWithoutSelection({+ onClick: () => {+ handleRowExpansion(+ row,+ onLazyLoadChildren,+ expandedCells,+ toggleCellExpansion,+ );+ },+ enabled: isExpandable,+ });++ return (+ <tr+ ref={+ rowIndex === 0 && row.original.level === 0+ ? topLevelRowRef+ : undefined+ }+ data-observation-id={row.id}+ {...rowClickProps}+ className={cn(+ "hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",+ isExpandable ? "cursor-pointer" : "",+ row.original.level === 0 && stickyTopLevelKey+ ? "bg-background sticky top-0 z-10 shadow-xs"+ : "",+ )}+ >+ {row.getVisibleCells().map((cell) => (+ <td+ key={cell.id}+ className={cn(+ "h-full border-b [:last-child_>_&]:border-b-0",+ CELL_CLASSES,+ cell.column.id === "value" && "[&>div]:wrap-anywhere",+ )}+ style={{ width: `${cell.column.columnDef.size}%` }}+ >+ {flexRender(cell.column.columnDef.cell, cell.getContext())}+ </td>+ ))}+ </tr>+ );+ },+);++JsonTableRowComponent.displayName = "JsonTableRow";++function JsonPrettyTable({+ data,+ expandAllRef,+ onExpandStateChange,+ noBorder = false,+ expanded,+ onExpandedChange,+ onLazyLoadChildren,+ onForceUpdate,+ smartDefaultsLevel,+ expandedCells,+ toggleCellExpansion,+ stickyTopLevelKey = false,+ showObservationTypeBadge = false,+ rowActions,+}: {+ data: JsonTableRow[];+ expandAllRef?: React.RefObject<(() => void) | null>;+ onExpandStateChange?: (allExpanded: boolean) => void;+ noBorder?: boolean;+ expanded: ExpandedState;+ onExpandedChange: (+ updater: ExpandedState | ((prev: ExpandedState) => ExpandedState),+ ) => void;+ onLazyLoadChildren?: (rowId: string) => void;+ onForceUpdate?: () => void;+ smartDefaultsLevel?: number | null;+ expandedCells: Set<string>;+ toggleCellExpansion: (cellId: string) => void;+ stickyTopLevelKey?: boolean;+ showObservationTypeBadge?: boolean;+ rowActions?: React.ComponentProps<typeof ValueCell>["rowActions"];+ /** Drop the Path / Value header row. */+}) {+ const topLevelRowRef = useRef<HTMLTableRowElement>(null);+ const [topLevelRowHeight, setTopLevelRowHeight] = useState(32);++ useEffect(() => {+ if (stickyTopLevelKey && topLevelRowRef.current) {+ setTopLevelRowHeight(topLevelRowRef.current.offsetHeight);+ }+ }, [stickyTopLevelKey, data, expanded]);++ const indentationWidthFor = (row: Row<JsonTableRow>) =>+ row.original.level * INDENTATION_PER_LEVEL + INDENTATION_BASE;++ const renderKeyText = (key: string) =>+ key.includes(".")+ ? key.split(".").map((segment, index, segments) => (+ <span key={index}>+ {segment}+ {index < segments.length - 1 && (+ <>+ .<wbr />+ </>+ )}+ </span>+ ))+ : key;++ const renderKey = (row: Row<JsonTableRow>) => {+ const indentationWidth = indentationWidthFor(row);++ const itemBadgeType =+ showObservationTypeBadge &&+ row.original.level === 0 &&+ row.original.value &&+ typeof row.original.value === "object" &&+ !Array.isArray(row.original.value) &&+ "type" in row.original.value &&+ typeof row.original.value.type === "string" &&+ row.original.value.type+ ? (row.original.value.type as LangfuseItemType)+ : null;++ return (+ <div className="flex w-max max-w-[40cqw] min-w-40 items-start gap-1 text-xs/5 wrap-break-word">+ <div+ className="flex h-[1lh] shrink-0 items-center justify-end"+ style={{ width: `${indentationWidth}px` }}+ >+ {row.original.hasChildren ? (+ <Button+ variant="ghost"+ size="sm"+ aria-label={`${row.getIsExpanded() ? "Collapse" : "Expand"} ${row.original.key}`}+ aria-expanded={row.getIsExpanded()}+ onClick={(e) => {+ e.stopPropagation();+ handleRowExpansion(+ row,+ onLazyLoadChildren,+ expandedCells,+ toggleCellExpansion,+ );+ }}+ className="text-muted-foreground hover:text-foreground h-4 w-4 p-0 hover:bg-transparent"+ >+ {row.getIsExpanded() ? (+ <ChevronDown size="base" color="default" />+ ) : (+ <ChevronRight size="base" color="default" />+ )}+ </Button>+ ) : null}+ </div>+ <span className={cn("min-w-0 cursor-text", KEY_CLASSES)}>+ {itemBadgeType && (+ <span className="mr-1 inline-block align-middle">+ <ItemBadge type={itemBadgeType} isSmall={true} />+ </span>+ )}+ {renderKeyText(row.original.key)}+ </span>+ </div>+ );+ };++ const renderValue = (row: Row<JsonTableRow>) => (+ <ValueCell+ row={row}+ expandedCells={expandedCells}+ toggleCellExpansion={toggleCellExpansion}+ preserveStringWhitespace={row.original.key === "code_eval_source_code"}+ rowActions={rowActions}+ />+ );++ const keyColumn: LangfuseColumnDef<JsonTableRow, unknown> = {+ accessorKey: "key",+ header: "Path",+ size: 1,+ cell: ({ row }) => {+ const content = renderKey(row);+ const valueLength = getValueStringLength(row.original.value);+ const isLongValue = valueLength > MAX_CELL_DISPLAY_CHARS / 3; // already long if we don't truncate++ if (isLongValue) {+ // Offset by the section header where the host pins it (--io-header-h).+ const headerOffset = "var(--io-header-h, 0px)";+ let topPosition = headerOffset;+ if (stickyTopLevelKey && row.original.level !== 0) {+ topPosition = `calc(${headerOffset} + ${topLevelRowHeight}px)`;+ }++ return (+ <div className="sticky z-5 -my-1 py-1" style={{ top: topPosition }}>+ {content}+ </div>+ );+ }++ return content;+ },+ };++ const valueColumn: LangfuseColumnDef<JsonTableRow, unknown> = {+ accessorKey: "value",+ header: "Value",+ size: 99,+ cell: ({ row }) => renderValue(row),+ };++ const columns: LangfuseColumnDef<JsonTableRow, unknown>[] = [+ keyColumn,+ valueColumn,+ ];++ const table = useReactTable({+ data,+ columns,+ getCoreRowModel: getCoreRowModel(),+ getExpandedRowModel: getExpandedRowModel(),+ getSubRows: (row) => row.subRows,+ getRowId: (row) => convertRowIdToKeyPath(row.id),+ state: {+ expanded,+ },+ onExpandedChange: onExpandedChange,+ enableColumnResizing: false,+ autoResetExpanded: false,+ });++ const allRowsExpanded = useMemo(() => {+ const allRows = table.getRowModel().flatRows;+ const expandableRows = allRows.filter((row) => row.original.hasChildren);+ return (+ expandableRows.length > 0 &&+ expandableRows.every((row) => row.getIsExpanded())+ );+ // expanded is required for the collapse button to work+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [table, expanded]);++ // Notify parent of expand state changes+ useEffect(() => {+ onExpandStateChange?.(allRowsExpanded);+ }, [allRowsExpanded, onExpandStateChange]);++ const expandRowsWithLazyLoading = useCallback(+ (+ rowFilter: (rows: Row<JsonTableRow>[]) => Row<JsonTableRow>[],+ shouldCollapse = false,+ ) => {+ if (shouldCollapse) {+ onExpandedChange({});+ return;+ }++ const allRows = table.getRowModel().flatRows;+ const expandableRows = allRows.filter((row) => row.original.hasChildren);+ const targetRows = rowFilter(expandableRows);++ const rowsNeedingParsing = targetRows.filter(+ (row) => row.original.rawChildData && !row.original.childrenGenerated,+ );++ if (rowsNeedingParsing.length > 0) {+ const generatedRowIds: string[] = [];++ rowsNeedingParsing.forEach((row) => {+ generateAllChildrenRecursively(row.original, (rowId) => {+ generatedRowIds.push(rowId);+ });+ });++ if (generatedRowIds.length > 0) {+ onLazyLoadChildren?.(generatedRowIds.join(","));+ }++ onForceUpdate?.();+ // setTimeout re-renders table once new data is available+ setTimeout(() => {+ const newExpanded: ExpandedState = {};+ const updatedAllRows = table.getRowModel().flatRows;+ const updatedExpandableRows = updatedAllRows.filter(+ (row) => row.original.hasChildren,+ );+ const updatedTargetRows = rowFilter(updatedExpandableRows);++ updatedTargetRows.forEach((row) => {+ newExpanded[row.id] = true;+ });++ onExpandedChange(newExpanded);+ }, 0);+ } else {+ // No lazy loading needed, just set expansion state+ const newExpanded: ExpandedState = {};+ targetRows.forEach((row) => {+ newExpanded[row.id] = true;+ });+ onExpandedChange(newExpanded);+ }+ },+ [table, onExpandedChange, onLazyLoadChildren, onForceUpdate],+ );++ const handleToggleExpandAll = useCallback(() => {+ expandRowsWithLazyLoading(+ (expandableRows) => expandableRows, // All expandable rows+ allRowsExpanded, // Should collapse if already expanded+ );+ }, [allRowsExpanded, expandRowsWithLazyLoading]);++ useEffect(() => {+ if (expandAllRef) {+ expandAllRef.current = handleToggleExpandAll;+ }+ }, [expandAllRef, handleToggleExpandAll]);++ useEffect(() => {+ if (smartDefaultsLevel != null && smartDefaultsLevel > 0) {+ expandRowsWithLazyLoading((expandableRows) =>+ expandableRows.filter((row) => row.depth < smartDefaultsLevel),+ );+ }+ }, [smartDefaultsLevel, expandRowsWithLazyLoading]);++ return (+ <div className={cn("w-full", !noBorder && "rounded-sm border")}>+ <table className="w-full table-auto caption-bottom border-separate border-spacing-0 space-y-4 overflow-auto text-sm">+ <thead className="sr-only">+ <tr>+ <th scope="col">Path</th>+ <th scope="col">Value</th>+ </tr>+ </thead>+ <tbody className="text-xs [&_tr:last-child]:border-0">+ {table.getRowModel().rows.map((row, rowIndex) => (+ <JsonTableRowComponent+ key={row.id}+ row={row}+ rowIndex={rowIndex}+ topLevelRowRef={+ rowIndex === 0 && row.original.level === 0+ ? topLevelRowRef+ : undefined+ }+ onLazyLoadChildren={onLazyLoadChildren}+ expandedCells={expandedCells}+ toggleCellExpansion={toggleCellExpansion}+ stickyTopLevelKey={stickyTopLevelKey}+ />+ ))}+ </tbody>+ </table>+ </div>+ );+}++export function PrettyJsonViewContent(props: {+ state: JsonViewState;+ title?: string;+ className?: string;+ codeClassName?: string;+ collapseStringsAfterLength?: number | null;+ scrollable?: boolean;+ borderless?: boolean;+ stickyTopLevelKey?: boolean;+ showObservationTypeBadge?: boolean;+ rowActions?: React.ComponentProps<typeof ValueCell>["rowActions"];+}) {+ const {+ largeStringValue,+ jsonViewInput,+ markdownContent,+ standaloneMediaReferenceStrings,+ remainingMarkdownMedia,+ tableData,+ expandAllRef,+ setAllRowsExpanded,+ actualExpansionState,+ handleTableExpandedChange,+ handleLazyLoadChildren,+ handleForceUpdate,+ expandedCells,+ toggleCellExpansion,+ jsonIsCollapsed,+ handleJsonToggleCollapse,+ isLoading,+ isParsing,+ media,+ } = props.state;+ const codeClassName = props.codeClassName;+ const tableBorderless = props.borderless ?? false;+ const contentKind = props.state.contentKind;+ const isPrettyView = props.state.currentView === "pretty";+ const isMarkdownMode = contentKind === "markdown";+ const shouldUseTableView = contentKind === "table";+ const shouldRenderStandaloneMedia =+ isMarkdownMode && standaloneMediaReferenceStrings.length > 0;+ const emptyValueDisplay = getEmptyValueDisplay(props.state.parsedJson);++ const body = (+ <>+ {largeStringValue !== null ? (+ <LargeStringFallback title={props.title} value={largeStringValue} />+ ) : isLoading || isParsing ? (+ <div className="io-message-content ph-no-capture">+ <div+ className={cn(+ getContainerClasses(+ props.scrollable,+ codeClassName,+ undefined,+ tableBorderless,+ ),+ )}+ >+ <div className="space-y-2">+ <Skeleton className="h-3 w-3/4" />+ <Skeleton className="h-3 w-1/2" />+ <Skeleton className="h-3 w-2/3" />+ {isParsing && (+ <div className="text-muted-foreground mt-2 text-xs">+ Parsing in background...+ </div>+ )}+ </div>+ </div>+ </div>+ ) : emptyValueDisplay && isPrettyView ? (+ <div className="io-message-content ph-no-capture">+ <div+ className={cn(+ "flex items-center",+ getContainerClasses(+ props.scrollable,+ codeClassName,+ undefined,+ tableBorderless,+ ),+ )}+ >+ <span className={`font-mono ${PREVIEW_TEXT_CLASSES}`}>+ {emptyValueDisplay}+ </span>+ </div>+ </div>+ ) : isMarkdownMode ? (+ <div className="io-message-content ph-no-capture">+ {shouldRenderStandaloneMedia ? (+ standaloneMediaReferenceStrings.map((referenceString, index) => (+ <LangfuseMediaView+ key={`${referenceString}-${index}`}+ mediaReferenceString={referenceString}+ />+ ))+ ) : (+ <MarkdownView+ markdown={markdownContent || ""}+ media={media}+ className={cn(tableBorderless && "p-0")}+ />+ )}+ </div>+ ) : (+ <>+ {/* Always render JsonPrettyTable to preserve internal React Table state */}+ <div+ className="io-message-content ph-no-capture"+ style={{ display: shouldUseTableView ? "flex" : "none" }}+ >+ <div+ className={cn(+ getContainerClasses(+ props.scrollable,+ codeClassName,+ "flex text-xs wrap-break-word whitespace-pre-wrap",+ tableBorderless,+ ),+ "@container w-full",+ )}+ >+ {isLoading ? (+ <Skeleton className="m-3 h-3 w-3/4" />+ ) : (+ <JsonPrettyTable+ data={tableData}+ expandAllRef={expandAllRef}+ onExpandStateChange={setAllRowsExpanded}+ noBorder={true}+ expanded={+ actualExpansionState === false ? {} : actualExpansionState+ }+ onExpandedChange={handleTableExpandedChange}+ onLazyLoadChildren={handleLazyLoadChildren}+ onForceUpdate={handleForceUpdate}+ smartDefaultsLevel={null}+ expandedCells={expandedCells}+ toggleCellExpansion={toggleCellExpansion}+ stickyTopLevelKey={props.stickyTopLevelKey}+ showObservationTypeBadge={props.showObservationTypeBadge}+ rowActions={props.rowActions}+ />+ )}+ </div>+ </div>++ {/* Always render JSONView to preserve its state too */}+ <div+ className="io-message-content ph-no-capture"+ style={{ display: shouldUseTableView ? "none" : "block" }}+ >+ <JSONView+ // 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}+ className=""+ borderless={tableBorderless}+ isLoading={isLoading}+ codeClassName={codeClassName}+ collapseStringsAfterLength={props.collapseStringsAfterLength}+ media={media}+ scrollable={props.scrollable}+ externalJsonCollapsed={jsonIsCollapsed}+ onToggleCollapse={handleJsonToggleCollapse}+ />+ </div>+ </>+ )}+ {shouldRenderStandaloneMedia && remainingMarkdownMedia.length > 0 && (+ <>+ <div className="text-muted-foreground my-1 px-2 py-1 text-xs">+ Media+ </div>+ <div className="ph-no-capture flex flex-wrap gap-2 px-2 pt-1 pb-4">+ {remainingMarkdownMedia.map((m) => (+ <LangfuseMediaView+ mediaAPIReturnValue={m}+ variant="icon"+ key={m.mediaId}+ />+ ))}+ </div>+ </>+ )}+ {media && media.length > 0 && isPrettyView && !isMarkdownMode && (+ <>+ <div className="text-muted-foreground my-1 px-2 py-1 text-xs">+ Media+ </div>+ <div className="ph-no-capture flex flex-wrap gap-2 px-2 pt-1 pb-4">+ {media.map((m) => (+ <LangfuseMediaView+ mediaAPIReturnValue={m}+ variant="icon"+ key={m.mediaId}+ />+ ))}+ </div>+ </>+ )}+ </>+ );++ const scrollableBody = props.scrollable ? (+ <div+ className={cn(+ "flex h-full min-h-0 overflow-hidden",+ isMarkdownMode || (shouldUseTableView && tableBorderless)+ ? ""+ : "rounded-sm border",+ )}+ >+ <div className="max-h-full min-h-0 w-full overflow-y-auto">{body}</div>+ </div>+ ) : (+ body+ );++ return (+ <div+ className={cn(+ "flex max-h-full min-h-0 flex-col",+ props.className,+ props.scrollable ? "overflow-hidden" : "",+ )}+ >+ {scrollableBody}+ </div>+ );+}diff --git a/web/src/features/comments/components/CommentCard.tsx b/web/src/features/comments/components/CommentCard.tsxindex 38d551a04c..5610d3fa3f 100644--- a/web/src/features/comments/components/CommentCard.tsx+++ b/web/src/features/comments/components/CommentCard.tsx@@ -2,7 +2,7 @@ import { type ReactNode } from "react";import { cva } from "class-variance-authority";import { Avatar } from "@/src/components/design-system/Avatar/Avatar";-import { MarkdownView } from "@/src/components/ui/MarkdownViewer";+import { MarkdownView } from "@/src/components/ui/MarkdownView";import { cn } from "@/src/utils/tailwind";const commentCardVariants = cva(diff --git a/web/src/features/comments/index.ts b/web/src/features/comments/index.tsindex 225638b445..f85256ab3a 100644--- a/web/src/features/comments/index.ts+++ b/web/src/features/comments/index.ts@@ -4,7 +4,7 @@//// CommentCountIcon, MentionBadge, mentionParser, and the IOPreview// inline-comment components stay deep: putting them here would load the-// drawer into SpanContent, MarkdownViewer, and IOPreviewJSON. Pages and+// drawer into SpanContent, MarkdownView, and IOPreviewJSON. Pages and// commentsRouter stay off this door.export {CommentDrawerController,diff --git a/web/src/features/datasets/components/DatasetItemField.tsx b/web/src/features/datasets/components/DatasetItemField.tsxindex e30c874334..a67d955eb3 100644--- a/web/src/features/datasets/components/DatasetItemField.tsx+++ b/web/src/features/datasets/components/DatasetItemField.tsx@@ -165,11 +165,7 @@ export const DatasetItemField = ({/>)}{!isFormField && showPrettyView && pretty.scalar === null && (- <PrettyJsonView- json={pretty.json}- currentView="pretty"- className="w-full"- />+ <PrettyJsonView json={pretty.json} currentView="pretty" />)}{!isFormField && showPrettyView && pretty.scalar !== null && (<div className="ph-no-capture rounded-sm border py-1 pr-2 pl-4 font-mono text-xs/5 wrap-break-word whitespace-pre-wrap">diff --git a/web/src/features/evals/components/CodeEvalTestRunCard.tsx b/web/src/features/evals/components/CodeEvalTestRunCard.tsxindex 842bfd6f7b..52cc081ad6 100644--- a/web/src/features/evals/components/CodeEvalTestRunCard.tsx+++ b/web/src/features/evals/components/CodeEvalTestRunCard.tsx@@ -1,3 +1,4 @@+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import { CodeMirrorEditor } from "@/src/components/editor";import { TablePeekViewTraceDetail } from "@/src/components/table/peek/TablePeekViewTraceDetail";import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";@@ -5,7 +6,7 @@ import { Badge } from "@/src/components/design-system/Badge/Badge";import { Button } from "@/src/components/ui/button";import { Card } from "@/src/components/ui/card";import { Skeleton } from "@/src/components/ui/skeleton";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import {type PreviewData,usePreviewData,@@ -289,16 +290,16 @@ function CodeEvalTestRunInputCards({Evaluator input</span></div>- <PrettyJsonView- json={inputPreviewJson}- currentView="pretty"- isLoading={false}- showNullValues={true}- stickyTopLevelKey={false}- showObservationTypeBadge={false}- scrollable={true}- className="max-h-[40dvh] [&_.border]:border-0 [&_.rounded-sm]:rounded-none"- />+ <div className="max-h-[40dvh] overflow-y-auto">+ <PrettyJsonView+ json={inputPreviewJson}+ currentView="pretty"+ showNullValues+ stickyTopLevelKey={false}+ showObservationTypeBadge={false}+ borderless+ />+ </div></div>);}diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelStatePreview/DecisionModelStatePreview.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelStatePreview/DecisionModelStatePreview.tsxindex bf47e8093f..46ca1c73fe 100644--- a/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelStatePreview/DecisionModelStatePreview.tsx+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelStatePreview/DecisionModelStatePreview.tsx@@ -1,8 +1,8 @@+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import { useMemo, useState } from "react";import { deepParseJsonIterative } from "@langfuse/shared";import { ChevronDown, TriangleAlert } from "@langfuse/icons";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import { extractVariableMappingValue } from "@/src/features/evals/v2/fns/variableMapping/extractVariableMappingValue";import type { VariableFieldState } from "@/src/features/evals/v2/types/variableMapping";import { cn } from "@/src/utils/tailwind";@@ -96,16 +96,14 @@ export function DecisionModelStatePreview({/></button>{open && statePreview ? (- <div className="border-t">+ <div className="max-h-80 overflow-y-auto border-t"><PrettyJsonViewjson={statePreview}currentView="pretty"- isLoading={false}- showNullValues={true}+ showNullValuesstickyTopLevelKey={false}showObservationTypeBadge={false}- scrollable={true}- className="max-h-80 [&_.border]:border-0 [&_.rounded-sm]:rounded-none"+ borderless/></div>) : null}diff --git a/web/src/features/evals/v2/components/Evaluators/Testing/components/TestResultPanelView/TestResultPanelView.tsx b/web/src/features/evals/v2/components/Evaluators/Testing/components/TestResultPanelView/TestResultPanelView.tsxindex bd1e8de382..50ef875cbb 100644--- a/web/src/features/evals/v2/components/Evaluators/Testing/components/TestResultPanelView/TestResultPanelView.tsx+++ b/web/src/features/evals/v2/components/Evaluators/Testing/components/TestResultPanelView/TestResultPanelView.tsx@@ -1,8 +1,9 @@+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import { type ReactNode } from "react";import { Clock, Coins } from "@langfuse/icons";import { Switch } from "@/src/components/design-system/Switch/Switch";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import {DecisionModelResultView,type DecisionModelQuestionResult,@@ -113,16 +114,15 @@ function RawOutputView({ rawOutput }: { rawOutput: unknown | null }) {}return (- <PrettyJsonView- json={rawOutput}- currentView="json"- isLoading={false}- showNullValues={true}- stickyTopLevelKey={false}- showObservationTypeBadge={false}- scrollable={true}- className="max-h-96"- />+ <div className="max-h-96 overflow-y-auto">+ <PrettyJsonView+ json={rawOutput}+ currentView="json"+ showNullValues+ stickyTopLevelKey={false}+ showObservationTypeBadge={false}+ />+ </div>);}diff --git a/web/src/features/evals/v2/components/VariableMapping/components/EditableVariableMapping/EditableVariableMapping.tsx b/web/src/features/evals/v2/components/VariableMapping/components/EditableVariableMapping/EditableVariableMapping.tsxindex 027415d184..7a9e3a08e5 100644--- a/web/src/features/evals/v2/components/VariableMapping/components/EditableVariableMapping/EditableVariableMapping.tsx+++ b/web/src/features/evals/v2/components/VariableMapping/components/EditableVariableMapping/EditableVariableMapping.tsx@@ -1,8 +1,9 @@/* eslint-disable no-nested-ternary */++import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import { useMemo, useState, type ReactNode } from "react";import { TriangleAlert } from "@langfuse/icons";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";import {classifyMediaValue,@@ -61,16 +62,16 @@ function MappedValuePreview({ value }: { value: string }) {return (<div>{isJson ? (- <PrettyJsonView- json={parsed}- currentView="pretty"- isLoading={false}- showNullValues={true}- stickyTopLevelKey={false}- showObservationTypeBadge={false}- scrollable={true}- className="max-h-96 [&_.border]:border-0 [&_.rounded-sm]:rounded-none"- />+ <div className="max-h-96 overflow-y-auto">+ <PrettyJsonView+ json={parsed}+ currentView="pretty"+ showNullValues+ stickyTopLevelKey={false}+ showObservationTypeBadge={false}+ borderless+ />+ </div>) : hasMedia ? (<divdata-testid="mapped-media-preview"diff --git a/web/src/features/experiments/components/ExperimentMetadataSection.tsx b/web/src/features/experiments/components/ExperimentMetadataSection.tsxindex 74ce0a3c2a..3224388068 100644--- a/web/src/features/experiments/components/ExperimentMetadataSection.tsx+++ b/web/src/features/experiments/components/ExperimentMetadataSection.tsx@@ -31,11 +31,7 @@ export const ExperimentMetadataSection = ({</button></CollapsibleTrigger><CollapsibleContent className="mt-2">- <PrettyJsonView- json={metadata}- currentView="pretty"- className="w-full"- />+ <PrettyJsonView json={metadata} currentView="pretty" /></CollapsibleContent></div></Collapsible>diff --git a/web/src/features/prompts/components/PromptDetail.tsx b/web/src/features/prompts/components/PromptDetail.tsxindex 42e58755da..a75b868d6d 100644--- a/web/src/features/prompts/components/PromptDetail.tsx+++ b/web/src/features/prompts/components/PromptDetail.tsx@@ -8,7 +8,8 @@ import {withDefault,} from "use-query-params";import type { z } from "zod";-import { ChatMessageList, getMessageTitle } from "@/src/features/traces";+import { shouldRenderMessageForContentMode } from "@/src/features/traces";+import { PromptMessagePreview } from "./PromptMessagePreview/PromptMessagePreview";import { Tabs } from "@/src/components/design-system/Tabs/Tabs";import { BadgeShell } from "@/src/components/design-system/Badge/Badge";import { IconButton } from "@/src/components/design-system/IconButton/IconButton";@@ -721,14 +722,28 @@ export const PromptDetail = ({<PromptReferenceProvider projectId={projectId}>{prompt.type === PromptType.Chat && chatMessages ? (<div className="w-full">- <ChatMessageList- messages={chatMessages}- shouldRenderMarkdown={true}- currentView="pretty"- messageToToolCallNumbers={new Map()}- collapseLongHistory={false}- getMessageTitle={getMessageTitle}- />+ <div className="flex max-h-full min-h-0 flex-col gap-2">+ <div className="flex max-h-full min-h-0 flex-col gap-2">+ <div className="flex flex-col gap-2">+ {chatMessages.map((message, index) => {+ if (+ !shouldRenderMessageForContentMode(+ message,+ "all",+ undefined,+ )+ )+ return null;+ return (+ <PromptMessagePreview+ key={index}+ message={message}+ />+ );+ })}+ </div>+ </div>+ </div></div>) : typeof prompt.prompt === "string" ? (resolutionMode === "resolved" &&diff --git a/web/src/features/prompts/components/PromptMessagePreview/PromptMessagePreview.stories.tsx b/web/src/features/prompts/components/PromptMessagePreview/PromptMessagePreview.stories.tsxnew file mode 100644index 0000000000..da70e3144b--- /dev/null+++ b/web/src/features/prompts/components/PromptMessagePreview/PromptMessagePreview.stories.tsx@@ -0,0 +1,131 @@+import preview from "../../../../../.storybook/preview";+import { expect, spyOn } from "storybook/test";+import { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";+import { MarkdownRenderCharacterLimitContext } from "@/src/components/MarkdownRenderCharacterLimitProvider/MarkdownRenderCharacterLimitContext";+import { PromptMessagePreview } from "./PromptMessagePreview";++const meta = preview.meta({+ component: PromptMessagePreview,+ decorators: [+ (Story) => (+ <MarkdownRenderCharacterLimitContext.Provider value={5_000}>+ <Story />+ </MarkdownRenderCharacterLimitContext.Provider>+ ),+ ],+ beforeEach: () => {+ const preferences = new Map(+ ["collapseSystemPrompt", "traceSystemPrompt:collapsed"].map(+ (key) => [key, localStorage.getItem(key)] as const,+ ),+ );+ const toolsCollapsed = sessionStorage.getItem("toolsSectionCollapsed");+ for (const key of preferences.keys()) localStorage.removeItem(key);+ sessionStorage.removeItem("toolsSectionCollapsed");+ return () => {+ for (const [key, value] of preferences) {+ if (value === null) localStorage.removeItem(key);+ else localStorage.setItem(key, value);+ }+ if (toolsCollapsed === null)+ sessionStorage.removeItem("toolsSectionCollapsed");+ else sessionStorage.setItem("toolsSectionCollapsed", toolsCollapsed);+ };+ },+});++export const UserMessage = meta.story({+ name: "(Test) Renders role and copies message content",+ args: {+ message: ChatMlMessageSchema.parse({+ role: "user",+ content: "Where is my refund?",+ }),+ },+ play: async ({ canvas, userEvent }) => {+ await expect(+ canvas.getByRole("button", { name: "Collapse user" }),+ ).toBeInTheDocument();+ await expect(canvas.getByText("Where is my refund?")).toBeVisible();+ const writeText = spyOn(+ navigator.clipboard,+ "writeText",+ ).mockResolvedValue();+ try {+ await userEvent.hover(+ canvas.getByRole("button", { name: "Collapse user" }),+ );+ await userEvent.click(canvas.getByTitle("Copy to clipboard"));+ await expect(writeText).toHaveBeenCalledWith("Where is my refund?");+ } finally {+ writeText.mockRestore();+ }+ },+});++export const Placeholder = meta.story({+ name: "(Test) Renders placeholders",+ args: {+ message: ChatMlMessageSchema.parse({+ type: "placeholder",+ name: "conversation",+ }),+ },+ play: async ({ canvas }) => {+ await expect(+ canvas.getByRole("button", { name: "Collapse Placeholder" }),+ ).toBeInTheDocument();+ await expect(canvas.getByText("conversation")).toBeVisible();+ },+});++export const FullHistory = meta.story({+ name: "(Test) Keeps every message open without history folding",+ render: () => (+ <>+ {Array.from({ length: 8 }, (_, index) => (+ <PromptMessagePreview+ key={index}+ message={ChatMlMessageSchema.parse({+ role: "user",+ name: `Turn ${index + 1}`,+ content: `Prompt content ${index + 1}`,+ })}+ />+ ))}+ </>+ ),+ play: async ({ canvas }) => {+ for (let index = 1; index <= 8; index++) {+ await expect(+ canvas.getByRole("button", { name: `Collapse Turn ${index}` }),+ ).toBeInTheDocument();+ await expect(canvas.getByText(`Prompt content ${index}`)).toBeVisible();+ }+ await expect(+ canvas.queryByRole("button", { name: /other messages/ }),+ ).not.toBeInTheDocument();+ },+});++export const LongNamedSystemPrompt = meta.story({+ name: "(Test) Collapses long named system prompts",+ args: {+ message: ChatMlMessageSchema.parse({+ role: "system",+ name: "Instructions",+ content: Array.from(+ { length: 12 },+ (_, index) => `Instruction ${index + 1}: ${"Be helpful. ".repeat(8)}`,+ ).join("\n"),+ }),+ },+ play: async ({ canvas, userEvent }) => {+ await expect(canvas.queryByText(/Instruction 1:/)).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand Instructions" }),+ );+ await expect(canvas.getByText(/Instruction 1:/)).toBeVisible();+ await expect(localStorage.getItem("collapseSystemPrompt")).toBe("false");+ },+});diff --git a/web/src/features/prompts/components/PromptMessagePreview/PromptMessagePreview.tsx b/web/src/features/prompts/components/PromptMessagePreview/PromptMessagePreview.tsxnew file mode 100644index 0000000000..f7634e5d18--- /dev/null+++ b/web/src/features/prompts/components/PromptMessagePreview/PromptMessagePreview.tsx@@ -0,0 +1,197 @@+import { useTheme } from "next-themes";+import { FoldVertical, UnfoldVertical } from "@langfuse/icons";+import { ChatMessageController } from "@/src/features/traces/components/IOPreview/components/ChatMessageController";+import { ChatMessageContent } from "@/src/features/traces/components/IOPreview/components/ChatMessageContent";+import { SystemPromptCollapseController } from "@/src/features/traces/components/IOPreview/components/SystemPromptCollapseController";+import { getMessageTitle } from "@/src/features/traces/fns/chatMessageUtils";+import { IOSection } from "@/src/components/ui/IOSection";+import { JsonViewController } from "@/src/components/ui/JsonViewController";+import { PrettyJsonViewContent } from "@/src/components/ui/PrettyJsonViewContent";+import { MarkdownViewController } from "@/src/components/ui/MarkdownViewController";+import { MarkdownViewContent } from "@/src/components/ui/MarkdownViewContent";+import { canRenderContentAsMarkdown } from "@/src/components/ui/MarkdownJsonView";+import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";+import { assertUnreachable } from "@/src/utils/types";++export function PromptMessagePreview({+ message,+}: Pick<React.ComponentProps<typeof ChatMessageController>, "message">) {+ const characterLimit = useMarkdownRenderCharacterLimit();+ const { forcedTheme, resolvedTheme } = useTheme();++ return (+ <ChatMessageController+ message={message}+ title={getMessageTitle(message)}+ isOutputMessage+ contentMode="all"+ defaultCollapsed={false}+ >+ {function renderPromptMessage({+ title,+ data,+ body,+ actions,+ isSystemPrompt,+ collapsed,+ setCollapsed,+ copy,+ }): React.ReactNode {+ if (data.kind === "collapsed" || data.kind === "tools") {+ return (+ <IOSection+ title={title}+ onCopy={data.kind === "tools" ? copy : undefined}+ actions={actions.length > 0 ? actions : undefined}+ collapsed={collapsed}+ onCollapsedChange={setCollapsed}+ >+ {data.kind === "tools" && (+ <ChatMessageContent+ body={body}+ renderToolResponse={(response) => (+ <ChatMessageController+ message={response}+ title={getMessageTitle(response)}+ contentMode="all"+ >+ {renderPromptMessage}+ </ChatMessageController>+ )}+ />+ )}+ </IOSection>+ );+ }++ if (+ data.kind === "message" &&+ canRenderContentAsMarkdown(data.content, characterLimit)+ ) {+ return (+ <MarkdownViewController markdown={data.content} audio={data.audio}>+ {(state) => (+ <SystemPromptCollapseController+ isSystemPrompt={isSystemPrompt}+ text={state.textContent}+ collapsed={collapsed}+ setCollapsed={setCollapsed}+ >+ {({+ collapsed: sectionCollapsed,+ setCollapsed: setSectionCollapsed,+ }) => (+ <IOSection+ key={forcedTheme ?? resolvedTheme}+ title={title}+ onCopy={state.copy}+ actions={actions.length > 0 ? actions : undefined}+ collapsed={sectionCollapsed}+ onCollapsedChange={setSectionCollapsed}+ >+ {!sectionCollapsed && (+ <ChatMessageContent+ body={body}+ renderToolResponse={(response) => (+ <ChatMessageController+ message={response}+ title={getMessageTitle(response)}+ contentMode="all"+ >+ {renderPromptMessage}+ </ChatMessageController>+ )}+ >+ <MarkdownViewContent state={state} />+ </ChatMessageContent>+ )}+ </IOSection>+ )}+ </SystemPromptCollapseController>+ )}+ </MarkdownViewController>+ );+ }++ if (data.kind === "data" || data.kind === "message") {+ return (+ <JsonViewController+ json={data.kind === "data" ? data.value : data.content}+ currentView="pretty"+ >+ {(state) => {+ const kind = state.contentKind;+ const sectionActions = [+ ...(kind === "table" && state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : []),+ ...actions,+ ];+ return (+ <SystemPromptCollapseController+ isSystemPrompt={+ isSystemPrompt &&+ kind === "markdown" &&+ state.standaloneMediaReferenceStrings.length === 0+ }+ text={state.markdownContent ?? ""}+ collapsed={collapsed}+ setCollapsed={setCollapsed}+ >+ {({+ collapsed: sectionCollapsed,+ setCollapsed: setSectionCollapsed,+ }) => (+ <IOSection+ title={title}+ onCopy={state.copy}+ actions={+ sectionActions.length > 0 ? sectionActions : undefined+ }+ collapsed={sectionCollapsed}+ onCollapsedChange={setSectionCollapsed}+ variant={kind === "table" ? "table" : "text"}+ >+ {!sectionCollapsed && (+ <ChatMessageContent+ body={body}+ renderToolResponse={(response) => (+ <ChatMessageController+ message={response}+ title={getMessageTitle(response)}+ contentMode="all"+ >+ {renderPromptMessage}+ </ChatMessageController>+ )}+ >+ <PrettyJsonViewContent+ state={state}+ title={title}+ borderless+ />+ </ChatMessageContent>+ )}+ </IOSection>+ )}+ </SystemPromptCollapseController>+ );+ }}+ </JsonViewController>+ );+ }+ return assertUnreachable(data);+ }}+ </ChatMessageController>+ );+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart.tsxindex f8d7368c2e..54e2836b0f 100644--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart.tsx@@ -1,4 +1,16 @@-import { FileIcon, Wrench } from "@langfuse/icons";+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { JsonViewController } from "@/src/components/ui/JsonViewController";+import {+ FoldVertical,+ UnfoldVertical,+ FileIcon,+ Wrench,+ ChevronDown,+ ChevronRight,+ Copy,+ Check,+} from "@langfuse/icons";+import { Button } from "@/src/components/ui/button";import { useState, type ComponentProps, type ReactNode } from "react";import { SessionTimelineCollapsibleRow } from "../SessionTimelineCollapsibleRow/SessionTimelineCollapsibleRow";import { assertUnreachable } from "@langfuse/shared";@@ -10,8 +22,8 @@ import {import { SessionTimelineCollapsiblePart } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart";import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";import { ExternalMediaView } from "@/src/components/ui/media/ExternalMediaView";-import { MarkdownView } from "@/src/components/ui/MarkdownViewer";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { MarkdownView } from "@/src/components/ui/MarkdownView";+import { PrettyJsonViewContent } from "@/src/components/ui/PrettyJsonViewContent";import {classifyMediaValue,type MediaDescriptor,@@ -29,6 +41,9 @@ export function SessionTimelinePart({trailingContent?: ReactNode;mediaVariant?: "tool-output";}) {+ const [customCollapsed, setCustomCollapsed] = useState(false);+ const [isCopied, setIsCopied] = useState(false);+if (part.type === "text") {if (part.refusal) {return (@@ -95,11 +110,87 @@ export function SessionTimelinePart({if (part.type === "custom") {return (- <PrettyJsonView- title={part.kind}- json={part.value}- currentView="pretty"- />+ <JsonViewController json={part.value} currentView="pretty">+ {(state) => {+ const Caret = customCollapsed ? ChevronRight : ChevronDown;+ const ExpansionIcon = state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical;+ const expansionLabel = state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows";++ return (+ <div className="group/custom-part flex flex-col overflow-clip">+ <div className="flex h-8 items-center justify-between gap-2">+ <button+ type="button"+ className="ph-no-capture focus-visible:ring-ring flex h-full min-w-0 flex-1 items-center gap-2 rounded-sm text-left text-sm font-bold capitalize focus-visible:ring-2 focus-visible:outline-hidden"+ aria-expanded={!customCollapsed}+ aria-label={`${customCollapsed ? "Expand" : "Collapse"} ${part.kind}`}+ onClick={() => setCustomCollapsed((current) => !current)}+ >+ <Caret size="base" color="default" aria-hidden />+ {part.kind}+ </button>+ {!customCollapsed && (+ <div className="mr-1 flex shrink-0 items-center gap-1 opacity-0 transition-opacity group-hover/custom-part:opacity-100 focus-within:opacity-100 pointer-coarse:opacity-100">+ {state.contentKind === "table" &&+ state.hasExpandableRows && (+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ title={expansionLabel}+ aria-label={expansionLabel}+ onClick={state.toggleAllRows}+ className="text-muted-foreground hover:text-foreground hover:bg-transparent"+ >+ <ExpansionIcon size="base" color="default" />+ </Button>+ )}+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ title="Copy to clipboard"+ aria-label="Copy to clipboard"+ onClick={() => {+ state.copy();+ setIsCopied(true);+ setTimeout(() => setIsCopied(false), 1000);+ }}+ className="text-muted-foreground hover:text-foreground hover:bg-transparent"+ >+ {isCopied ? (+ <Check size="base" color="default" />+ ) : (+ <Copy size="base" color="default" />+ )}+ </Button>+ </div>+ )}+ </div>+ {!customCollapsed && (+ <div className="ph-no-capture pt-1">+ <div+ className={cn(+ "bg-surface-section overflow-hidden rounded-md px-3",+ state.contentKind === "table" ? "py-1" : "py-2",+ )}+ >+ <PrettyJsonViewContent+ state={state}+ title={part.kind}+ borderless+ />+ </div>+ </div>+ )}+ </div>+ );+ }}+ </JsonViewController>);}diff --git a/web/src/features/skills/components/SkillFilePreview.tsx b/web/src/features/skills/components/SkillFilePreview.tsxindex 950d9e507a..fce8799516 100644--- a/web/src/features/skills/components/SkillFilePreview.tsx+++ b/web/src/features/skills/components/SkillFilePreview.tsx@@ -1,7 +1,7 @@import { isMap, parseDocument, stringify } from "yaml";import { Codeblock } from "@/src/components/design-system/Codeblock/Codeblock";import { normalizeCodeblockLanguage } from "@/src/utils/normalizeCodeblockLanguage";-import { MarkdownView } from "@/src/components/ui/MarkdownViewer";+import { MarkdownView } from "@/src/components/ui/MarkdownView";export function SkillFilePreview({path,diff --git a/web/src/features/traces/components/ChatMessageList.clienttest.tsx b/web/src/features/traces/components/ChatMessageList.clienttest.tsxdeleted file mode 100644index ded6566bd3..0000000000--- a/web/src/features/traces/components/ChatMessageList.clienttest.tsx+++ /dev/null@@ -1,227 +0,0 @@-import { fireEvent, render, screen } from "@testing-library/react";-import { vi } from "vitest";--// The list logic under test lives in ChatMessageList; stub the per-message-// renderer (recording its collapse default) and the media strip.-vi.mock(- "@/src/features/traces/components/IOPreview/components/ChatMessage",- () => ({- ChatMessage: ({- message,- defaultCollapsed,- }: {- message: { role: string };- defaultCollapsed?: boolean;- }) => (- <div- data-testid="chat-message"- data-role={message.role}- data-collapsed={String(defaultCollapsed)}- />- ),- }),-);-vi.mock(- "@/src/features/traces/components/IOPreview/components/SectionMedia",- () => ({- SectionMedia: ({ media }: { media: { mediaId: string }[] }) => (- <div- data-testid="section-media"- data-media-ids={media.map((m) => m.mediaId).join(",")}- />- ),- }),-);--import { ChatMessageList } from "@/src/features/traces/components/ChatMessageList";-import {- type ChatMlMessage,- getMessageTitle,-} from "@/src/features/traces/fns/chatMessageUtils";-import { type MediaReturnType } from "@/src/features/media";-// Pin the limit so the test does not depend on the ambient .env value.-const { TEST_LIMIT } = vi.hoisted(() => ({ TEST_LIMIT: 1_000 }));-vi.mock("@/src/hooks/useMarkdownRenderCharacterLimit", () => ({- useMarkdownRenderCharacterLimit: () => TEST_LIMIT,-}));--const MEDIA_REF = "@@@langfuseMedia:type=image/png|id=media-1|source=base64@@@";-const AUDIO_REF = "@@@langfuseMedia:type=audio/wav|id=audio-1|source=base64@@@";--const renderList = (message: ChatMlMessage, mediaIds: string[]) =>- render(- <ChatMessageList- messages={[message]}- shouldRenderMarkdown={true}- media={mediaIds.map((mediaId) => ({ mediaId }) as MediaReturnType)}- currentView="pretty"- messageToToolCallNumbers={new Map()}- getMessageTitle={getMessageTitle}- />,- );--describe("ChatMessageList long history", () => {- const conversation = [- { role: "system", content: "Be brief." },- { role: "user", content: "one" },- { role: "assistant", content: "two" },- { role: "user", content: "three" },- { role: "assistant", content: "four" },- { role: "user", content: "five" },- ] as ChatMlMessage[];-- const collapsedFlags = () =>- screen- .getAllByTestId("chat-message")- .map((el) => el.getAttribute("data-collapsed"));-- it("starts earlier messages collapsed and keeps the last three open", () => {- render(- <ChatMessageList- messages={conversation}- shouldRenderMarkdown={true}- currentView="pretty"- messageToToolCallNumbers={new Map()}- getMessageTitle={getMessageTitle}- />,- );-- // system follows its own long-prompt rule, so it is left open here- expect(collapsedFlags()).toEqual([- "false",- "true",- "true",- "false",- "false",- "false",- ]);- });-- const longConversation = [- { role: "system", content: "Be brief." },- ...Array.from({ length: 7 }, (_, i) => ({- role: i % 2 === 0 ? "user" : "assistant",- content: `turn ${i + 1}`,- })),- ] as ChatMlMessage[];-- const renderLong = (messages: ChatMlMessage[]) =>- render(- <ChatMessageList- messages={messages}- shouldRenderMarkdown={true}- currentView="pretty"- messageToToolCallNumbers={new Map()}- getMessageTitle={getMessageTitle}- />,- );-- it("shows no fold row for six or fewer messages", () => {- renderLong(conversation);-- expect(- screen.queryByRole("button", { name: /other message/ }),- ).not.toBeInTheDocument();- });-- it("folds the middle of a long chat behind one row until it is opened", () => {- renderLong(longConversation);-- // 8 rendered: first + 4 folded + last 3- const row = screen.getByRole("button", { name: "4 other messages" });- expect(row).toHaveAttribute("aria-expanded", "false");- expect(screen.getAllByTestId("chat-message")).toHaveLength(4);- expect(collapsedFlags()).toEqual(["false", "false", "false", "false"]);- const list = row.parentElement!;- expect(Array.from(list.children).indexOf(row)).toBe(1);-- fireEvent.click(row);-- expect(row).toHaveAttribute("aria-expanded", "true");- expect(screen.getAllByTestId("chat-message")).toHaveLength(8);- // the revealed messages start collapsed; first and last three stay open- expect(collapsedFlags()).toEqual([- "false",- "true",- "true",- "true",- "true",- "false",- "false",- "false",- ]);- expect(Array.from(list.children).indexOf(row)).toBe(1);-- fireEvent.click(row);- expect(screen.getAllByTestId("chat-message")).toHaveLength(4);- });-- it("does not count an empty message toward the tail", () => {- renderLong([- ...longConversation.slice(0, 6),- { role: "assistant" } as ChatMlMessage,- ...longConversation.slice(6),- ]);-- // the empty message never renders, so the fold still hides 4 and shows the- // last three real messages- expect(- screen.getByRole("button", { name: "4 other messages" }),- ).toBeInTheDocument();- expect(- screen- .getAllByTestId("chat-message")- .map((el) => el.getAttribute("data-role")),- ).toEqual(["system", "user", "assistant", "user"]);- });-- it("leaves every message open when history collapsing is off", () => {- render(- <ChatMessageList- messages={conversation}- shouldRenderMarkdown={true}- currentView="pretty"- messageToToolCallNumbers={new Map()}- getMessageTitle={getMessageTitle}- collapseLongHistory={false}- />,- );-- expect(collapsedFlags()).toEqual(Array(6).fill("false"));- });-});--describe("ChatMessageList media dedup", () => {- it("filters media that the markdown path renders inline", () => {- renderList({ role: "user", content: MEDIA_REF } as ChatMlMessage, [- "media-1",- ]);-- expect(screen.queryByTestId("section-media")).not.toBeInTheDocument();- });-- it("keeps referenced media and audio when over-limit content falls back to JSON", () => {- renderList(- {- role: "assistant",- content: MEDIA_REF.repeat(- Math.ceil((TEST_LIMIT + 1) / MEDIA_REF.length),- ),- audio: {- data: {- type: "base64",- id: "audio-1",- source: "",- referenceString: AUDIO_REF,- },- },- } as ChatMlMessage,- ["media-1", "audio-1"],- );-- expect(screen.getByTestId("section-media")).toHaveAttribute(- "data-media-ids",- "media-1,audio-1",- );- });-});diff --git a/web/src/features/traces/components/ChatMessageList.tsx b/web/src/features/traces/components/ChatMessageList.tsxdeleted file mode 100644index b2da3e34ad..0000000000--- a/web/src/features/traces/components/ChatMessageList.tsx+++ /dev/null@@ -1,224 +0,0 @@-import { Fragment, useMemo, useState } from "react";-import { ChevronDown, ChevronRight } from "@langfuse/icons";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";-import {- filterAlreadyRenderedMedia,- getRenderedInlineMediaIds,-} from "@/src/components/ui/markdown-media.utils";-import { canRenderContentAsMarkdown } from "@/src/components/ui/MarkdownJsonView";-import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";-import {- ChatMessage,- type ViewMode,-} from "@/src/features/traces/components/IOPreview/components/ChatMessage";-import { SectionMedia } from "@/src/features/traces/components/IOPreview/components/SectionMedia";-import {- type ChatMlMessage,- shouldRenderMessageForContentMode,-} from "@/src/features/traces/fns/chatMessageUtils";-import { type MediaReturnType } from "@/src/features/media";-import { type IOPreviewContentMode } from "@/src/features/traces/components/IOPreview/IOPreview";-import { type IOSectionAction } from "@/src/components/ui/IOSection";--/** Only the last N messages start expanded in a long conversation. */-const EXPANDED_TAIL_LENGTH = 3;-/** Chats longer than this fold everything between the first message and the- tail behind one "N other messages" row. */-const FOLD_ABOVE_MESSAGES = 6;--function otherMessagesLabel(count: number) {- return `${count} other ${count === 1 ? "message" : "messages"}`;-}--// ChatMessageList props-export interface ChatMessageListProps {- messages: ChatMlMessage[];- shouldRenderMarkdown: boolean;- media?: MediaReturnType[];- additionalInput?: Record<string, unknown>;- currentView: ViewMode;- messageToToolCallNumbers: Map<number, number[]>;- collapseLongHistory?: boolean;- inputMessageCount?: number;- contentMode?: IOPreviewContentMode;- showSystemPrompt?: boolean;- /** Section title per message; the caller owns the rule. */- getMessageTitle: (message: ChatMlMessage, side: "input" | "output") => string;- /** Header actions for the last output-side message (e.g. Correct output). */- outputActions?: IOSectionAction[];-}--/**- * ChatMessageList renders a list of ChatML messages, one section each.- *- * Features:- * - Filters out empty messages- * - Collapses long history: earlier messages start collapsed, and chats with- * more than six messages fold them behind one "N other messages" row that- * mounts them only when opened- * - Renders additional input section- * - Renders media section- */-export function ChatMessageList({- messages,- shouldRenderMarkdown,- media,- additionalInput,- currentView,- messageToToolCallNumbers,- collapseLongHistory = true,- inputMessageCount,- contentMode = "all",- showSystemPrompt,- getMessageTitle,- outputActions,-}: ChatMessageListProps) {- // Filter messages to only those with renderable content- const messagesToRender = useMemo(- () =>- messages- .map((message, originalIndex) => ({ message, originalIndex }))- .filter(({ message }) =>- shouldRenderMessageForContentMode(- message,- contentMode,- showSystemPrompt,- ),- ),- [contentMode, messages, showSystemPrompt],- );-- // System prompts follow their own long-prompt rule, not the history rule.- const startsCollapsed = (filteredIndex: number, message: ChatMlMessage) =>- collapseLongHistory &&- message.role !== "system" &&- filteredIndex < messagesToRender.length - EXPANDED_TAIL_LENGTH;-- // Long chats: first message, one row for the rest, then the open tail.- const foldsMiddle =- collapseLongHistory && messagesToRender.length > FOLD_ABOVE_MESSAGES;- const foldEnd = messagesToRender.length - EXPANDED_TAIL_LENGTH;- const [othersOpen, setOthersOpen] = useState(false);- const isFolded = (filteredIndex: number) =>- foldsMiddle && filteredIndex > 0 && filteredIndex < foldEnd;-- const lastOutputIndex = messagesToRender.reduce(- (last, { originalIndex }, index) =>- originalIndex >= (inputMessageCount ?? 0) ? index : last,- -1,- );-- const characterLimit = useMarkdownRenderCharacterLimit();-- const remainingMedia = useMemo(() => {- if (!shouldRenderMarkdown) {- return media ?? [];- }-- const renderedMediaIds = new Set<string>();-- messagesToRender.forEach(({ message }) => {- const content = message.content || "";-- // Only content that ChatMessage renders through MarkdownView shows its- // media inline; anything falling back to a JSON table still needs the- // shared strip, so ask the renderer's own predicate.- if (canRenderContentAsMarkdown(content, characterLimit)) {- getRenderedInlineMediaIds({- markdown: content,- audio: message.audio,- }).forEach((mediaId) => renderedMediaIds.add(mediaId));- }- });-- return filterAlreadyRenderedMedia(media, renderedMediaIds);- }, [media, shouldRenderMarkdown, messagesToRender, characterLimit]);-- return (- <div className="flex max-h-full min-h-0 flex-col gap-2">- <div className="flex max-h-full min-h-0 flex-col gap-2">- <div className="flex flex-col gap-2">- {messagesToRender.map(({ message, originalIndex }, filteredIndex) => {- const isOutputMessage = originalIndex >= (inputMessageCount ?? 0);- const folded = isFolded(filteredIndex);- // Folded messages do not mount (no parsing) until the row opens.- if (folded && !othersOpen) return null;- const chatMessage = (- <ChatMessage- key={originalIndex}- message={message}- title={getMessageTitle(- message,- isOutputMessage ? "output" : "input",- )}- shouldRenderMarkdown={shouldRenderMarkdown}- currentView={currentView}- toolCallNumbers={messageToToolCallNumbers.get(originalIndex)}- isOutputMessage={isOutputMessage}- contentMode={contentMode}- defaultCollapsed={- foldsMiddle ? folded : startsCollapsed(filteredIndex, message)- }- actions={- filteredIndex === lastOutputIndex ? outputActions : undefined- }- />- );- // The row sits right after the first message and stays there.- if (foldsMiddle && filteredIndex === 0) {- return (- <Fragment key={originalIndex}>- {chatMessage}- <OtherMessagesRow- count={foldEnd - 1}- open={othersOpen}- onToggle={() => setOthersOpen((open) => !open)}- />- </Fragment>- );- }- return chatMessage;- })}- </div>-- {/* Additional input section */}- {contentMode !== "conversation" && additionalInput && (- <PrettyJsonView- title="Additional Input"- json={additionalInput}- currentView={shouldRenderMarkdown ? "pretty" : "json"}- />- )}-- {/* Media section */}- {remainingMedia.length > 0 && <SectionMedia media={remainingMedia} />}- </div>- </div>- );-}--/** Collapsed-header lookalike that reveals the folded middle of a long chat. */-function OtherMessagesRow({- count,- open,- onToggle,-}: {- count: number;- open: boolean;- onToggle: () => void;-}) {- const label = otherMessagesLabel(count);- const Caret = open ? ChevronDown : ChevronRight;- return (- <button- type="button"- className="io-message-header text-muted-foreground focus-visible:ring-ring flex h-8 w-full cursor-pointer items-center gap-2 rounded-sm text-left text-sm focus-visible:ring-2 focus-visible:outline-hidden"- aria-expanded={open}- aria-label={label}- onClick={onToggle}- >- <Caret size="base" color="default" aria-hidden />- {label}- </button>- );-}diff --git a/web/src/features/traces/components/DetailAttributesTab.clienttest.tsx b/web/src/features/traces/components/DetailAttributesTab.clienttest.tsxindex 20c9256904..07ba5f5b78 100644--- a/web/src/features/traces/components/DetailAttributesTab.clienttest.tsx+++ b/web/src/features/traces/components/DetailAttributesTab.clienttest.tsx@@ -1,19 +1,23 @@/** @vitest-environment jsdom */import { cleanup, render } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { JsonViewController } from "@/src/components/ui/JsonViewController";import { DetailAttributesTab } from "./DetailAttributesTab";import { MediaContentType } from "@langfuse/shared";import { MediaEnabledFields } from "@/src/features/media/validation";-vi.mock("@/src/components/ui/PrettyJsonView", () => ({- PrettyJsonView: vi.fn(() => null),+vi.mock("@/src/components/ui/JsonViewController", () => ({+ JsonViewController: vi.fn(() => null),}));vi.mock("@/src/features/feature-flags", () => ({useInternalFeaturesEnabled: () => false,}));vi.mock("next/router", () => ({- useRouter: () => ({ asPath: "/project/project/traces", push: vi.fn() }),+ useRouter: () => ({+ asPath: "/project/project/traces",+ query: { projectId: "project" },+ push: vi.fn(),+ }),}));vi.mock("@/src/features/posthog-analytics", () => ({usePostHogClientCapture: () => vi.fn(),@@ -50,7 +54,7 @@ describe("DetailAttributesTab metadata expansion", () => {]}/>,);- expect(vi.mocked(PrettyJsonView).mock.calls[0]?.[0].media).toEqual([+ expect(vi.mocked(JsonViewController).mock.calls[0]?.[0].media).toEqual([attachment,]);});@@ -72,7 +76,7 @@ describe("DetailAttributesTab metadata expansion", () => {onJsonMetadataExpandedChange={onJsonMetadataExpandedChange}/>,);- const props = vi.mocked(PrettyJsonView).mock.calls[0]?.[0];+ const props = vi.mocked(JsonViewController).mock.calls[0]?.[0];if (!props) throw new Error("Metadata viewer was not rendered");expect(props.externalExpansionState).toEqual(currentView === "pretty" ? metadataExpansionState : false,diff --git a/web/src/features/traces/components/DetailAttributesTab.tsx b/web/src/features/traces/components/DetailAttributesTab.tsxindex 507fd5e296..0380bcfba7 100644--- a/web/src/features/traces/components/DetailAttributesTab.tsx+++ b/web/src/features/traces/components/DetailAttributesTab.tsx@@ -1,10 +1,12 @@/** Trace metadata, or observation attributes, model parameters and metadata. */+import { JsonViewController } from "@/src/components/ui/JsonViewController";+import { FoldVertical, UnfoldVertical } from "@langfuse/icons";import { useMemo } from "react";import { useRouter } from "next/router";import { type MediaReturnType } from "@/src/features/media";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { PrettyJsonViewContent } from "@/src/components/ui/PrettyJsonViewContent";import { IOSection } from "@/src/components/ui/IOSection";import { cn } from "@/src/utils/tailwind";import { IO_STICKY_HEADERS_CLASS } from "@/src/features/traces/constants/ioSectionClasses";@@ -68,29 +70,85 @@ export function DetailAttributesTab({><div className="space-y-2 pt-3">{observation && hasAttributes ? (- <PrettyJsonView- title="Attributes"+ <JsonViewControllerjson={observation.attributes}currentView={currentView}- rowActions={(row) =>- getAttributeRowActions({- row,- projectId,- filterTarget: "observations",- anchorTime: observation.attributesAnchorTime,- analyticsTable: "attributes",- router,- capture,- })- }- />+ >+ {(state) => (+ <IOSection+ title="Attributes"+ onCopy={state.copy}+ actions={+ state.contentKind === "table" && state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : undefined+ }+ variant={state.contentKind === "table" ? "table" : "text"}+ >+ <PrettyJsonViewContent+ state={state}+ title="Attributes"+ borderless+ rowActions={(row) =>+ getAttributeRowActions({+ row,+ projectId,+ filterTarget: "observations",+ anchorTime: observation.attributesAnchorTime,+ analyticsTable: "attributes",+ router,+ capture,+ })+ }+ />+ </IOSection>+ )}+ </JsonViewController>) : null}{observation?.modelParameters ? (- <PrettyJsonView- title="Model parameters"+ <JsonViewControllerjson={observation.modelParameters}currentView={currentView}- />+ >+ {(state) => (+ <IOSection+ title="Model parameters"+ onCopy={state.copy}+ actions={+ state.contentKind === "table" && state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : undefined+ }+ variant={state.contentKind === "table" ? "table" : "text"}+ >+ <PrettyJsonViewContent+ state={state}+ title="Model parameters"+ borderless+ />+ </IOSection>+ )}+ </JsonViewController>) : null}{hasMetadata ? (<div>@@ -106,22 +164,13 @@ export function DetailAttributesTab({/></IOSection>) : (- <PrettyJsonView- title="Metadata"+ <JsonViewControllerjson={metadata}parsedJson={parsedMetadata}- currentView={currentView}- rowActions={(row) =>- getMetadataRowActions({- row,- projectId,- filterTarget: observation ? "observations" : "traces",- router,- })- }media={media?.filter((attachment) => attachment.field === "metadata",)}+ currentView={currentView}externalExpansionState={currentView === "pretty"? metadataExpansionState@@ -134,7 +183,44 @@ export function DetailAttributesTab({}onMetadataExpansionChange?.(expansion);}}- />+ >+ {(state) => (+ <IOSection+ title="Metadata"+ onCopy={state.copy}+ actions={+ state.contentKind === "table" && state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : undefined+ }+ variant={state.contentKind === "table" ? "table" : "text"}+ >+ <PrettyJsonViewContent+ state={state}+ title="Metadata"+ borderless+ rowActions={(row) =>+ getMetadataRowActions({+ row,+ projectId,+ filterTarget: observation ? "observations" : "traces",+ router,+ })+ }+ />+ </IOSection>+ )}+ </JsonViewController>)}</div>) : null}diff --git a/web/src/features/traces/components/IOPreview/IOPreview.tsx b/web/src/features/traces/components/IOPreview/IOPreview.tsxindex ee9efc9367..1e27f4ca76 100644--- a/web/src/features/traces/components/IOPreview/IOPreview.tsx+++ b/web/src/features/traces/components/IOPreview/IOPreview.tsx@@ -20,7 +20,6 @@ import {import { IOPreviewJSON, type IOPreviewJSONProps } from "./IOPreviewJSON";import { IOPreviewJSONSimple } from "./IOPreviewJSONSimple";import { IOPreviewPretty } from "./IOPreviewPretty";-import type { SectionSkillsProps } from "./components/SectionSkills";import { type ChatMLParserResult } from "../../hooks/useChatMLParser";import { Button } from "@/src/components/ui/button";import { ActionButton } from "@/src/components/ActionButton";@@ -63,7 +62,7 @@ export interface ExpansionStateProps {}export interface IOPreviewProps extends ExpansionStateProps {- skills?: SectionSkillsProps["skills"];+ skills?: React.ComponentProps<typeof IOPreviewPretty>["skills"];input?: Prisma.JsonValue;output?: Prisma.JsonValue;status?: ObservationStatusMessage;diff --git a/web/src/features/traces/components/IOPreview/IOPreviewJSON.tsx b/web/src/features/traces/components/IOPreview/IOPreviewJSON.tsxindex 7288fdc1b6..cebef804e0 100644--- a/web/src/features/traces/components/IOPreview/IOPreviewJSON.tsx+++ b/web/src/features/traces/components/IOPreview/IOPreviewJSON.tsx@@ -44,7 +44,7 @@ import {// `needsVirtualization` note below.const VIRTUALIZATION_THRESHOLD = JSON_VIEW_RENDER_ROW_LIMIT;-// Light values are Tailwind red-50 / yellow-50, matching StatusMessageSection.+// Light values are Tailwind red-50 / yellow-50, matching status IOSection tones.function statusMessageBackgroundColor(level: ObservationStatusMessage["level"],isDark: boolean,diff --git a/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.clienttest.tsx b/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.clienttest.tsxdeleted file mode 100644index 178b1fe046..0000000000--- a/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.clienttest.tsx+++ /dev/null@@ -1,150 +0,0 @@-/**- * The JSON view must never hand a multi-MB field to the unvirtualized- * react18-json-view (LFE-10989). These tests pin the branch selection in- * IOPreviewJSONSimple: over-limit fields render the bounded fallback and skip- * PrettyJsonView entirely, while normal fields render exactly as before.- */-import { fireEvent, render, screen } from "@testing-library/react";--// PrettyJsonView is the unvirtualized render path we must NOT reach for-// over-limit fields — mock it so its presence is observable by test id.-vi.mock("@/src/components/ui/PrettyJsonView", () => ({- PrettyJsonView: (props: { title?: string }) => (- <div data-testid="pretty-json-view">{props.title}</div>- ),-}));--vi.mock("./components/CorrectedOutputField", () => ({- CorrectedOutputField: () => <div data-testid="corrected-output" />,- useCorrectOutputAction: () => ({- icon: () => null,- label: "Correct output",- onClick: vi.fn(),- }),-}));--vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({- usePostHogClientCapture: () => vi.fn(),-}));--// deepParseJson is the only runtime import from the shared barrel here; stub it-// so the test stays light and deterministic (identity is fine for these cases).-vi.mock("@langfuse/shared", () => ({- deepParseJson: (value: unknown) => value,-}));--import { IOPreviewJSONSimple } from "./IOPreviewJSONSimple";-import { JSON_VIEW_RENDER_CHAR_LIMIT } from "./fns/jsonViewSizeGate";--const FALLBACK_TEXT = /too large to render in JSON view/i;--describe("IOPreviewJSONSimple size gating", () => {- it("renders the fallback and NOT PrettyJsonView for an over-limit field", () => {- const huge = "x".repeat(JSON_VIEW_RENDER_CHAR_LIMIT + 1);- render(- <IOPreviewJSONSimple- input={huge}- hideOutput- hideIfNull- showCorrections={false}- projectId="p"- traceId="t"- />,- );-- // Fallback shown for the input field...- expect(screen.getByText(FALLBACK_TEXT)).toBeInTheDocument();- expect(- screen.getByRole("button", { name: /Download Input/i }),- ).toBeInTheDocument();- // ...and the unvirtualized viewer was never mounted.- expect(screen.queryByTestId("pretty-json-view")).not.toBeInTheDocument();- });-- it("downloads a string field as raw text (.txt), not JSON-wrapped", () => {- // The huge-IO seed is a base64 string; JSON.stringify-ing it would add- // quotes + escapes and over-encode the download. The fallback must write- // the raw text.- const rawString = "eyJhIjoxfQ==" + "A".repeat(JSON_VIEW_RENDER_CHAR_LIMIT);- const blobCalls: { part: string; type: string }[] = [];- let downloadName = "";-- // Capture the exact content handed to the Blob (jsdom's Blob has no- // readable .text() in this env, so intercept at construction).- class MockBlob {- type: string;- constructor(parts: BlobPart[], opts?: BlobPropertyBag) {- this.type = opts?.type ?? "";- blobCalls.push({ part: String(parts[0]), type: this.type });- }- }- vi.stubGlobal("Blob", MockBlob);- vi.stubGlobal("URL", {- ...URL,- createObjectURL: vi.fn(() => "blob:mock"),- revokeObjectURL: vi.fn(),- });- // Capture the download filename and neutralize navigation.- vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (- this: HTMLAnchorElement,- ) {- downloadName = this.download;- });-- render(- <IOPreviewJSONSimple- input={rawString}- hideOutput- hideIfNull- showCorrections={false}- projectId="p"- traceId="t"- />,- );-- fireEvent.click(screen.getByRole("button", { name: /Download Input/i }));-- expect(blobCalls).toHaveLength(1);- expect(blobCalls[0].part).toBe(rawString); // raw, no surrounding quotes- expect(blobCalls[0].part.startsWith('"')).toBe(false);- expect(blobCalls[0].type).toContain("text/plain");- expect(downloadName).toBe("input-t.txt");-- vi.restoreAllMocks();- vi.unstubAllGlobals();- });-- it("hides a null field with hideIfNull and shows no fallback", () => {- render(- <IOPreviewJSONSimple- input={null}- hideOutput- hideIfNull- showCorrections={false}- projectId="p"- traceId="t"- />,- );-- expect(screen.queryByText(FALLBACK_TEXT)).not.toBeInTheDocument();- expect(screen.queryByTestId("pretty-json-view")).not.toBeInTheDocument();- });-- it("renders PrettyJsonView (not the fallback) for normal small I/O", () => {- render(- <IOPreviewJSONSimple- input={{ messages: [{ role: "user", content: "hi" }] }}- hideOutput- hideIfNull- showCorrections={false}- projectId="p"- traceId="t"- />,- );-- const viewers = screen.getAllByTestId("pretty-json-view");- expect(viewers).toHaveLength(1);- expect(viewers[0]).toHaveTextContent("Input");- expect(screen.queryByText(FALLBACK_TEXT)).not.toBeInTheDocument();- });-});diff --git a/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.stories.tsx b/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.stories.tsxnew file mode 100644index 0000000000..93c4a30957--- /dev/null+++ b/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.stories.tsx@@ -0,0 +1,156 @@+import preview from "../../../../../.storybook/preview";+import { expect, spyOn, userEvent } from "storybook/test";+import { IOPreviewJSONSimple } from "./IOPreviewJSONSimple";+import { JSON_VIEW_RENDER_CHAR_LIMIT } from "./fns/jsonViewSizeGate";++const meta = preview.meta({+ component: IOPreviewJSONSimple,+ args: {+ projectId: "storybook-project",+ traceId: "storybook-trace",+ showCorrections: false,+ hideInput: true,+ hideOutput: true,+ hideMetadata: true,+ },+});++export const DefaultStatus = meta.story({+ args: {+ status: {+ level: "DEFAULT",+ message: "The observation completed with additional status details.",+ },+ },+});++export const DebugStatus = meta.story({+ args: {+ status: {+ level: "DEBUG",+ message: "Detailed diagnostic information for this observation.",+ },+ },+});++export const WarningStatus = meta.story({+ args: {+ status: {+ level: "WARNING",+ message: "The observation completed with a recoverable warning.",+ },+ },+});++export const ErrorStatus = meta.story({+ name: "(Test) Renders Error Message",+ args: {+ status: {+ level: "ERROR",+ message: "Upstream model request timed out after 30 seconds.",+ },+ },+ play: async ({ canvas }) => {+ await expect(canvas.getByText("Error")).toBeVisible();+ await expect(+ canvas.getByText("Upstream model request timed out after 30 seconds."),+ ).toBeVisible();+ },+});++export const StructuredStatus = meta.story({+ name: "(Test) Structured status",+ args: {+ status: {+ level: "ERROR",+ message: '{"error":{"code":"timeout","retryable":true}}',+ },+ },+ play: async ({ canvas }) => {+ await expect(canvas.getByText("Error")).toBeVisible();+ await expect(+ canvas.queryByRole("button", { name: "Expand all rows" }),+ ).not.toBeInTheDocument();+ },+});++const oversizedInput = "eyJhIjoxfQ==" + "A".repeat(JSON_VIEW_RENDER_CHAR_LIMIT);++export const OversizedInput = meta.story({+ name: "(Test) Oversized input uses bounded fallback",+ args: { input: oversizedInput, hideInput: false, hideIfNull: true },+ play: async ({ canvas }) => {+ await expect(+ canvas.getByText(/too large to render in JSON view/i),+ ).toBeVisible();+ await expect(+ canvas.getByRole("button", { name: /Download Input/i }),+ ).toBeVisible();+ await expect(canvas.queryByText(oversizedInput)).not.toBeInTheDocument();+ },+});++export const DownloadOversizedString = meta.story({+ name: "(Test) Downloads oversized strings as raw text",+ args: { input: oversizedInput, hideInput: false, hideIfNull: true },+ play: async ({ canvas }) => {+ const createObjectURL = spyOn(URL, "createObjectURL").mockReturnValue(+ "blob:mock",+ );+ const revokeObjectURL = spyOn(URL, "revokeObjectURL").mockImplementation(+ () => {},+ );+ const downloads: HTMLAnchorElement[] = [];+ const click = spyOn(+ HTMLAnchorElement.prototype,+ "click",+ ).mockImplementation(function (this: HTMLAnchorElement) {+ downloads.push(this);+ });+ try {+ await userEvent.click(+ canvas.getByRole("button", { name: /Download Input/i }),+ );+ await expect(createObjectURL).toHaveBeenCalledTimes(1);+ const blob = createObjectURL.mock.calls[0]?.[0];+ if (!(blob instanceof Blob))+ throw new Error("Expected a downloadable Blob");+ await expect(await blob.text()).toBe(oversizedInput);+ await expect(blob.type).toContain("text/plain");+ await expect(downloads[0]?.download).toBe("input-storybook-trace.txt");+ } finally {+ createObjectURL.mockRestore();+ revokeObjectURL.mockRestore();+ click.mockRestore();+ }+ },+});++export const NullInput = meta.story({+ name: "(Test) Null input is hidden without a size fallback",+ args: { input: null, hideInput: false, hideIfNull: true },+ play: async ({ canvas }) => {+ await expect(canvas.queryByText("Input")).not.toBeInTheDocument();+ await expect(+ canvas.queryByText(/too large to render in JSON view/i),+ ).not.toBeInTheDocument();+ },+});++export const SmallInput = meta.story({+ name: "(Test) Small input renders without a size fallback",+ args: {+ input: { messages: [{ role: "user", content: "hi" }] },+ hideInput: false,+ hideIfNull: true,+ },+ play: async ({ canvas }) => {+ await expect(canvas.getByText("Input")).toBeVisible();+ await expect(+ canvas.getAllByText(/hi/).some((element) => element.checkVisibility()),+ ).toBe(true);+ await expect(+ canvas.queryByText(/too large to render in JSON view/i),+ ).not.toBeInTheDocument();+ },+});diff --git a/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.tsx b/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.tsxindex 56cb4c5765..1b2c5db9c8 100644--- a/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.tsx+++ b/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.tsx@@ -1,6 +1,7 @@+import { JsonViewController } from "@/src/components/ui/JsonViewController";import { useMemo, useState } from "react";import { type Prisma, type ScoreDomain, deepParseJson } from "@langfuse/shared";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { PrettyJsonViewContent } from "@/src/components/ui/PrettyJsonViewContent";import { type MediaReturnType } from "@/src/features/media";import {CorrectedOutputField,@@ -13,8 +14,9 @@ import {JSON_VIEW_RENDER_CHAR_LIMIT,probeJsonField,} from "./fns/jsonViewSizeGate";-import { StatusMessageSection } from "./components/StatusMessageSection";-import type { ObservationStatusMessage } from "./components/statusMessagePresentation";+import { type ObservationStatusMessage } from "./components/statusMessagePresentation";+import { useStatusMessage } from "./hooks/useStatusMessage";+import { copyTextToClipboard } from "@/src/utils/clipboard";export interface IOPreviewJSONSimpleProps {input?: Prisma.JsonValue;@@ -90,6 +92,7 @@ export function IOPreviewJSONSimple({environment = "default",showCorrections = true,}: IOPreviewJSONSimpleProps) {+ const { statusPresentation, parsedStatusMessage } = useStatusMessage(status);// Size-gate each field: the JSON view renders through react18-json-view,// which is not virtualized, so multi-MB payloads freeze and crash the tab// (LFE-10989). Probe the raw prop — it drives both the main-thread parse@@ -163,9 +166,39 @@ export function IOPreviewJSONSimple({return (<div className="space-y-2 pt-3">- {status ? (- <StatusMessageSection status={status} currentView="json" />- ) : null}+ {status && statusPresentation && (+ <JsonViewController+ json={status.message}+ parsedJson={+ // Do not retry parsing text rejected by the status parser's size limit.+ parsedStatusMessage ?? null+ }+ currentView="json"+ >+ {(state) => (+ <IOSection+ title={statusPresentation.title}+ onCopy={+ parsedStatusMessage !== undefined+ ? state.copy+ : () => copyTextToClipboard(status.message)+ }+ variant="text"+ tone={statusPresentation.tone}+ >+ {parsedStatusMessage !== undefined ? (+ <PrettyJsonViewContent+ state={state}+ title={statusPresentation.title}+ borderless+ />+ ) : (+ status.message+ )}+ </IOSection>+ )}+ </JsonViewController>+ )}{showInput &&(inputTooLarge ? (<IOSection title="Input">@@ -179,8 +212,7 @@ export function IOPreviewJSONSimple({/></IOSection>) : (- <PrettyJsonView- title="Input"+ <JsonViewControllerjson={input}parsedJson={effectiveInput}isLoading={isLoading}@@ -188,13 +220,19 @@ export function IOPreviewJSONSimple({media={media?.filter((m) => m.field === "input") ?? []}currentView="json"externalExpansionState={inputExpanded}- // Cast: PrettyJsonView accepts union type, but JSON view only uses boolean+ // The controller supports per-row expansion; this view persists only a boolean.onExternalExpansionChange={onInputExpandedChange as (expansion: boolean | Record<string, boolean>,) => void}- />+ >+ {(state) => (+ <IOSection title="Input" onCopy={state.copy}>+ <PrettyJsonViewContent state={state} title="Input" borderless />+ </IOSection>+ )}+ </JsonViewController>))}{showOutput &&(outputTooLarge ? (@@ -209,22 +247,34 @@ export function IOPreviewJSONSimple({/></IOSection>) : (- <PrettyJsonView- title="Output"+ <JsonViewControllerjson={output}parsedJson={effectiveOutput}isLoading={isLoading}isParsing={isParsing}media={media?.filter((m) => m.field === "output") ?? []}currentView="json"- actions={outputActions}externalExpansionState={outputExpanded}onExternalExpansionChange={onOutputExpandedChange as (expansion: boolean | Record<string, boolean>,) => void}- />+ >+ {(state) => (+ <IOSection+ title="Output"+ onCopy={state.copy}+ actions={outputActions}+ >+ <PrettyJsonViewContent+ state={state}+ title="Output"+ borderless+ />+ </IOSection>+ )}+ </JsonViewController>))}{/* When the output is over-limit, effectiveOutput is undefined, so thecorrection editor opens without a baseline actual-output to diff@@ -258,8 +308,7 @@ export function IOPreviewJSONSimple({/></IOSection>) : (- <PrettyJsonView- title="Metadata"+ <JsonViewControllerjson={metadata}parsedJson={effectiveMetadata}isLoading={isLoading}@@ -272,7 +321,17 @@ export function IOPreviewJSONSimple({expansion: boolean | Record<string, boolean>,) => void}- />+ >+ {(state) => (+ <IOSection title="Metadata" onCopy={state.copy}>+ <PrettyJsonViewContent+ state={state}+ title="Metadata"+ borderless+ />+ </IOSection>+ )}+ </JsonViewController>))}</div>);diff --git a/web/src/features/traces/components/IOPreview/IOPreviewPretty.stories.tsx b/web/src/features/traces/components/IOPreview/IOPreviewPretty.stories.tsxindex c504cb3684..5f395676a5 100644--- a/web/src/features/traces/components/IOPreview/IOPreviewPretty.stories.tsx+++ b/web/src/features/traces/components/IOPreview/IOPreviewPretty.stories.tsx@@ -1,9 +1,58 @@import preview from "../../../../../.storybook/preview";-import { expect, within } from "storybook/test";+import { expect, spyOn, userEvent, within, waitFor } from "storybook/test";import { IOPreviewPretty } from "./IOPreviewPretty";+import type { ToolDefinition } from "./components/ToolCallDefinitionCard";+import type {+ ChatMLParserResult,+ ToolCallInvocation,+} from "../../hooks/useChatMLParser";+import { useState, type ComponentProps, type ReactNode } from "react";+import { SessionProvider } from "next-auth/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { createTRPCReact, getQueryKey } from "@trpc/react-query";+import { createTRPCClient, TRPCClientError } from "@trpc/client";+import { observable } from "@trpc/server/observable";+import type { AppRouter } from "@/src/server/api/root";+import { api } from "@/src/utils/api";+import { MarkdownRenderCharacterLimitContext } from "@/src/components/MarkdownRenderCharacterLimitProvider/MarkdownRenderCharacterLimitContext";+import { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";+import { MediaContentType, type MediaReturnType } from "@/src/features/media";+import { MediaEnabledFields } from "@/src/features/media/validation";+import { useCollapseSystemPromptPreference } from "@/src/hooks/useCollapsibleSystemPrompt";++const TOOLS_COLLAPSED_KEY = "toolsSectionCollapsed";const meta = preview.meta({component: IOPreviewPretty,+ beforeEach: () => {+ const previousCollapsed = sessionStorage.getItem(TOOLS_COLLAPSED_KEY);+ const storage = window.localStorage;+ const preferences = new Map(+ ["collapseSystemPrompt", "traceSystemPrompt:collapsed"].map(+ (key) => [key, storage.getItem(key)] as const,+ ),+ );+ for (const key of preferences.keys()) storage.removeItem(key);+ sessionStorage.removeItem(TOOLS_COLLAPSED_KEY);+ return () => {+ for (const [key, value] of preferences) {+ if (value === null) storage.removeItem(key);+ else storage.setItem(key, value);+ }+ if (previousCollapsed === null) {+ sessionStorage.removeItem(TOOLS_COLLAPSED_KEY);+ } else {+ sessionStorage.setItem(TOOLS_COLLAPSED_KEY, previousCollapsed);+ }+ };+ },+ decorators: [+ (Story) => (+ <MarkdownRenderCharacterLimitContext.Provider value={5_000}>+ <Story />+ </MarkdownRenderCharacterLimitContext.Provider>+ ),+ ],args: {projectId: "storybook-project",traceId: "storybook-trace",@@ -34,7 +83,67 @@ export const OversizedSibling = meta.story({},});+export const DefaultStatus = meta.story({+ args: {+ status: {+ level: "DEFAULT",+ message: "The observation completed with additional status details.",+ },+ },+});++export const DebugStatus = meta.story({+ args: {+ status: {+ level: "DEBUG",+ message: "Detailed diagnostic information for this observation.",+ },+ },+});++export const WarningStatus = meta.story({+ args: {+ status: {+ level: "WARNING",+ message: "The observation completed with a recoverable warning.",+ },+ },+});++export const ErrorStatus = meta.story({+ name: "(Test) Renders Error Message",+ args: {+ status: {+ level: "ERROR",+ message: "Upstream model request timed out after 30 seconds.",+ },+ },+ play: async ({ canvas }) => {+ await expect(canvas.getByText("Error")).toBeVisible();+ await expect(+ canvas.getByText("Upstream model request timed out after 30 seconds."),+ ).toBeVisible();+ },+});++export const StructuredStatus = meta.story({+ name: "(Test) Structured status",+ args: {+ status: {+ level: "ERROR",+ message: '{"error":{"code":"timeout","retryable":true}}',+ },+ },+ play: async ({ canvas }) => {+ await expect(canvas.getByText("Error")).toBeVisible();+ await expect(+ canvas.getByRole("button", { name: /(?:Expand|Collapse) all rows/ }),+ ).toBeInTheDocument();+ },+});+export const LongSystemPrompt = meta.story({+ name: "(Test) Long system prompt collapses and persists its preference",args: {input: {messages: [@@ -57,6 +166,28 @@ export const LongSystemPrompt = meta.story({content: "Stay within the listed role and constraints.",},},+ play: async ({ canvas }) => {+ await expect(+ canvas.getAllByRole("button", { name: "Expand system" }),+ ).toHaveLength(1);+ await expect(+ canvas.queryByText(/system-prompt-line-1 /),+ ).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand system" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Collapse system" }),+ ).toBeVisible();+ await expect(localStorage.getItem("collapseSystemPrompt")).toBe("false");+ await userEvent.click(+ canvas.getByRole("button", { name: "Collapse system" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Expand system" }),+ ).toBeVisible();+ await expect(localStorage.getItem("collapseSystemPrompt")).toBe("true");+ },});export const MarkdownWithCodeBlock = meta.story({@@ -219,6 +350,727 @@ export const SpanWithPlainText = meta.story({},});+export const AvailableSkills = meta.story({+ args: {+ hideInput: true,+ hideOutput: true,+ skills: {+ kind: "available",+ items: [+ {+ skillName: "refund-policy",+ langfuseSkillId: "refund",+ skillVersion: 3,+ },+ {+ skillName: "shipping-policy",+ langfuseSkillId: "shipping",+ skillVersion: 1,+ },+ {+ skillName: "subscription-support",+ langfuseSkillId: "subscription",+ skillVersion: 2,+ },+ { skillName: "account-security" },+ { skillName: "billing-support" },+ { skillName: "return-policy" },+ { skillName: "order-tracking" },+ { skillName: "customer-escalation" },+ { skillName: "tone-of-voice" },+ { skillName: "product-guide" },+ ],+ },+ },+});++export const RequestedSkills = meta.story({+ name: "(Test) Requested skills",+ args: {+ ...toolPreviewArgs(+ [],+ new Map([["langfuse_loadSkillResource", 1]]),+ new Map([+ [+ "langfuse_loadSkillResource",+ [+ {+ id: "read-refund-policy",+ name: "langfuse_loadSkillResource",+ arguments: {+ name: "refund-policy",+ path: "references/refunds.md",+ },+ invocationNumber: 1,+ },+ ],+ ],+ ]),+ ),+ skills: {+ kind: "available",+ items: [{ skillName: "refund-policy" }, { skillName: "shipping-policy" }],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ (await canvas.findByText("Requested", { exact: true })).closest(+ '[role="tab"]',+ ),+ ).toHaveAttribute("aria-selected", "true");+ await userEvent.click(+ canvas.getByRole("button", { name: "2 available skills show" }),+ );+ const files = canvas.getByRole("button", {+ name: "Files requested for refund-policy",+ });+ await userEvent.click(files);+ await expect(canvas.getByText("references/refunds.md")).toBeVisible();+ await expect(+ canvas.queryByText("shipping-policy", { exact: true }),+ ).not.toBeInTheDocument();+ await userEvent.click(canvas.getByText("Not requested", { exact: true }));+ await expect(+ canvas.getByText("shipping-policy", { exact: true }),+ ).toBeVisible();+ await expect(+ canvas.queryByRole("button", {+ name: "Files requested for refund-policy",+ }),+ ).not.toBeInTheDocument();+ await userEvent.click(canvas.getByText("Requested", { exact: true }));+ await expect(+ canvas.getByRole("button", { name: "Files requested for refund-policy" }),+ ).toHaveAttribute("aria-expanded", "false");+ },+});++export const LoadedSkills = meta.story({+ name: "(Test) Loaded skills",+ args: {+ hideInput: true,+ hideOutput: true,+ skills: {+ kind: "loaded",+ items: [+ {+ skillName: "refund-policy",+ langfuseSkillId: "refund",+ skillVersion: 3,+ filePath: "SKILL.md",+ },+ {+ skillName: "refund-policy",+ langfuseSkillId: "refund",+ skillVersion: 3,+ filePath: "references/refunds.md",+ },+ {+ skillName: "shipping-policy",+ langfuseSkillId: "shipping",+ skillVersion: 1,+ filePath: "references/international-shipping.md",+ },+ { skillName: "local-customer-support", filePath: "SKILL.md" },+ ],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const summary = canvas.getByRole("button", {+ name: "3 loaded skills show",+ });+ await expect(summary).toHaveAttribute("aria-expanded", "false");+ await userEvent.click(summary);+ const refundFiles = canvas.getByRole("button", {+ name: "Files loaded for refund-policy",+ });+ await userEvent.click(refundFiles);+ await expect(canvas.getByText("references/refunds.md")).toBeVisible();+ await userEvent.click(summary);+ await userEvent.click(summary);+ await expect(canvas.getByText("references/refunds.md")).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Files loaded for shipping-policy" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Files loaded for refund-policy" }),+ ).toHaveAttribute("aria-expanded", "false");+ await expect(+ canvas.getByText("references/international-shipping.md"),+ ).toBeVisible();+ },+});++const baseTools: ToolDefinition[] = [+ {+ name: "search_docs",+ description: "Searches product docs for relevant troubleshooting steps.",+ parameters: {+ type: "object",+ properties: {+ query: { type: "string", description: "What to search for" },+ limit: { type: "number", description: "Maximum number of results" },+ },+ required: ["query"],+ },+ },+];++const baseToolCalls = new Map<string, ToolCallInvocation[]>([+ [+ "search_docs",+ [+ {+ id: "call_01HXYZ123",+ name: "search_docs",+ invocationNumber: 1,+ arguments: JSON.stringify({ query: "rate limits", limit: 3 }),+ },+ ],+ ],+]);++function toolPreviewArgs(+ tools: ToolDefinition[],+ toolCallCounts: Map<string, number>,+ toolCallsByName: Map<string, ToolCallInvocation[]>,+) {+ return {+ hideInput: true,+ hideOutput: true,+ chatMLParserResult: {+ canDisplayAsChat: false,+ allMessages: [],+ additionalInput: undefined,+ allTools: tools,+ toolCallCounts,+ toolCallsByName,+ messageToToolCallNumbers: new Map(),+ inputMessageCount: 0,+ } satisfies ChatMLParserResult,+ };+}++export const UncalledTool = meta.story({+ args: toolPreviewArgs(baseTools, new Map([["search_docs", 0]]), new Map()),+});++export const CalledTool = meta.story({+ args: toolPreviewArgs(+ baseTools,+ new Map([["search_docs", 1]]),+ baseToolCalls,+ ),+});++export const MultipleTools = meta.story({+ args: toolPreviewArgs(+ [+ ...baseTools,+ {+ name: "create_ticket",+ description: "Creates a support escalation ticket.",+ parameters: {+ type: "object",+ properties: {+ title: { type: "string" },+ priority: { type: "string", enum: ["low", "high"] },+ },+ required: ["title", "priority"],+ },+ },+ { name: "notify_team" },+ ],+ new Map([+ ["search_docs", 2],+ ["create_ticket", 1],+ ["notify_team", 0],+ ]),+ new Map([+ [+ "search_docs",+ [+ ...baseToolCalls.get("search_docs")!,+ {+ id: "call_01HXYZ124",+ name: "search_docs",+ invocationNumber: 2,+ arguments: JSON.stringify({ query: "retry policy" }),+ },+ ],+ ],+ [+ "create_ticket",+ [+ {+ id: "call_01HXYZ200",+ name: "create_ticket",+ invocationNumber: 1,+ arguments: { title: "API requests failing", priority: "high" },+ },+ ],+ ],+ ]),+ ),+});++const longToolName =+ "search_enterprise_customer_documentation_for_multistep_api_rate_limit_troubleshooting_and_backoff_recommendations";+const longUncalledToolName =+ "create_cross_functional_incident_escalation_ticket_with_customer_context_and_internal_follow_up_requirements";++export const WithLongToolNames = meta.story({+ args: toolPreviewArgs(+ [+ {+ name: longToolName,+ description:+ "Looks up long-form support guidance for enterprise API incidents.",+ parameters: {+ type: "object",+ properties: { query: { type: "string" } },+ required: ["query"],+ },+ },+ {+ name: longUncalledToolName,+ description: "Creates a detailed incident escalation ticket.",+ },+ ],+ new Map([+ [longToolName, 1],+ [longUncalledToolName, 0],+ ]),+ new Map([+ [+ longToolName,+ [+ {+ id: "call_long_01",+ name: longToolName,+ invocationNumber: 1,+ arguments: JSON.stringify({ query: "429 retry guidance" }),+ },+ ],+ ],+ ]),+ ),+});++const manyToolNames = [+ "langfuse_getPrompt",+ "langfuse_getPromptUnresolved",+ "langfuse_listPrompts",+ "langfuse_listObservations",+ "langfuse_getObservation",+ "langfuse_getObservationFieldSchema",+ "langfuse_getObservationFilterSchema",+ "langfuse_getObservationFilterValues",+ "langfuse_listAnnotationQueues",+ "langfuse_getAnnotationQueue",+ "langfuse_listAnnotationQueueItems",+ "langfuse_createScoreConfigForProject",+ "langfuse_searchLangfuseDocs",+ "langfuse_proposeRedirect",+ "langfuse_listDatasets",+ "langfuse_getDataset",+ "langfuse_listSessions",+ "langfuse_getSession",+];+const calledNames = new Set(manyToolNames.slice(12));++export const ManyTools = meta.story({+ beforeEach: () => {+ sessionStorage.setItem(TOOLS_COLLAPSED_KEY, "false");+ },+ args: toolPreviewArgs(+ manyToolNames.map((name) => ({ name })),+ new Map(manyToolNames.map((name) => [name, calledNames.has(name) ? 1 : 0])),+ new Map(),+ ),+});++export const NoneCalled = meta.story({+ beforeEach: () => {+ sessionStorage.setItem(TOOLS_COLLAPSED_KEY, "false");+ },+ args: toolPreviewArgs(+ manyToolNames.map((name) => ({ name })),+ new Map(manyToolNames.map((name) => [name, 0])),+ new Map(),+ ),+});++export const AllCalled = meta.story({+ beforeEach: () => {+ sessionStorage.setItem(TOOLS_COLLAPSED_KEY, "false");+ },+ args: toolPreviewArgs(+ manyToolNames.map((name) => ({ name })),+ new Map(manyToolNames.map((name) => [name, 1])),+ new Map(),+ ),+});++export const NotCalledTab = meta.story({+ name: "(Test) Tools expand and filter by invocation status",+ args: ManyTools.input.args,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.queryByRole("tab")).not.toBeInTheDocument();+ await userEvent.click(canvas.getByRole("button", { name: "Expand Tools" }));+ await expect(+ canvas.getByRole("tab", { name: /^Called\s*6$/ }),+ ).toHaveAttribute("aria-selected", "true");+ await expect(+ canvas.getByRole("button", {+ name: /langfuse_searchLangfuseDocs$/,+ }),+ ).toBeVisible();+ await userEvent.click(+ canvas.getByRole("tab", { name: /^Not called\s*12$/ }),+ );+ await expect(+ canvas.getByRole("button", { name: /langfuse_getPrompt$/ }),+ ).toBeVisible();+ await expect(canvas.queryByText("langfuse_getSession")).toBeNull();+ },+});++export const NoSwitchWhenOneSideEmpty = meta.story({+ name: "(Test) No Switch When One Side Empty",+ beforeEach: () => {+ sessionStorage.setItem(TOOLS_COLLAPSED_KEY, "false");+ },+ args: NoneCalled.input.args,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.queryByRole("tab")).toBeNull();+ await expect(+ canvas.getByRole("button", { name: /langfuse_getSession$/ }),+ ).toBeVisible();+ },+});++export const RowTogglesDetails = meta.story({+ name: "(Test) Row Toggles Details",+ beforeEach: () => {+ sessionStorage.removeItem(TOOLS_COLLAPSED_KEY);+ },+ args: CalledTool.input.args,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const row = canvas.getByRole("button", { name: /^1\.\s*search_docs$/ });+ await expect(row).toHaveAttribute("aria-expanded", "false");+ await expect(canvas.queryByText(baseTools[0]!.description!)).toBeNull();+ await userEvent.click(row);+ await expect(row).toHaveAttribute("aria-expanded", "true");+ await expect(canvas.getByText(baseTools[0]!.description!)).toBeVisible();+ await userEvent.click(row);+ await expect(row).toHaveAttribute("aria-expanded", "false");+ },+});++const conversation = [+ { role: "system", name: "Instructions", content: "Be brief." },+ ...Array.from({ length: 5 }, (_, index) => ({+ role: index % 2 === 0 ? "user" : "assistant",+ name: `Turn ${index + 1}`,+ content: `Message content ${index + 1}`,+ })),+];+const longConversation = [+ ...conversation,+ { role: "assistant", name: "Turn 6", content: "Message content 6" },+ { role: "user", name: "Turn 7", content: "Message content 7" },+];++function conversationPreviewArgs(messages: unknown[]) {+ return {+ chatMLParserResult: {+ canDisplayAsChat: true,+ allMessages: messages.map((message) =>+ ChatMlMessageSchema.parse(message),+ ),+ additionalInput: undefined,+ allTools: [],+ toolCallCounts: new Map(),+ toolCallsByName: new Map(),+ messageToToolCallNumbers: new Map(),+ inputMessageCount: 0,+ } satisfies ChatMLParserResult,+ };+}++export const HeaderControlsOnFocus = meta.story({+ name: "(Test) Reveals Message Header Controls On Focus",+ args: conversationPreviewArgs([+ {+ role: "assistant",+ content: "Hover this message to reveal its header controls.",+ },+ ]),+ play: async ({ canvas }) => {+ const copyButton = canvas.getByRole("button", {+ name: "Copy to clipboard",+ });+ copyButton.focus();+ await expect(copyButton).toHaveFocus();+ await waitFor(() => expect(copyButton).toBeVisible());+ },+});++export const EarlierMessagesCollapsed = meta.story({+ name: "(Test) Earlier messages collapsed",+ args: conversationPreviewArgs(conversation),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ canvas.queryByRole("button", { name: /other messages?/ }),+ ).not.toBeInTheDocument();+ await expect(+ canvas.getByRole("button", { name: "Collapse Instructions" }),+ ).toBeVisible();+ await expect(+ canvas.getByRole("button", { name: "Expand Turn 1" }),+ ).toHaveAttribute("aria-expanded", "false");+ await expect(+ canvas.queryByText("Message content 1"),+ ).not.toBeInTheDocument();+ for (const turn of [3, 5]) {+ await expect(+ canvas.getByRole("button", { name: `Collapse Turn ${turn}` }),+ ).toHaveAttribute("aria-expanded", "true");+ await expect(+ canvas+ .getAllByText(`Message content ${turn}`)+ .some((element) => element.checkVisibility()),+ ).toBe(true);+ }+ },+});++export const FoldedConversation = meta.story({+ name: "(Test) Folded conversation",+ args: conversationPreviewArgs(longConversation),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const row = canvas.getByRole("button", { name: "4 other messages" });+ await expect(row).toHaveAttribute("aria-expanded", "false");+ for (const turn of [1, 2, 3, 4]) {+ await expect(+ canvas.queryByRole("button", { name: `Expand Turn ${turn}` }),+ ).not.toBeInTheDocument();+ }+ for (const turn of [5, 6, 7]) {+ await expect(+ canvas+ .getAllByText(`Message content ${turn}`)+ .some((element) => element.checkVisibility()),+ ).toBe(true);+ }+ await userEvent.click(row);+ await expect(row).toHaveAttribute("aria-expanded", "true");+ for (const turn of [1, 2, 3, 4]) {+ await expect(+ canvas.getByRole("button", { name: `Expand Turn ${turn}` }),+ ).toHaveAttribute("aria-expanded", "false");+ await expect(+ canvas.queryByText(`Message content ${turn}`),+ ).not.toBeInTheDocument();+ }+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand Turn 1" }),+ );+ await expect(+ canvas+ .getAllByText("Message content 1")+ .some((element) => element.checkVisibility()),+ ).toBe(true);+ await userEvent.click(row);+ await expect(+ canvas.queryByText("Message content 1"),+ ).not.toBeInTheDocument();+ await expect(+ canvas.queryByRole("button", { name: "Expand Turn 2" }),+ ).not.toBeInTheDocument();+ },+});++export const EmptyMessagesDoNotTakeTailSlots = meta.story({+ name: "(Test) Empty messages do not take tail slots",+ args: conversationPreviewArgs([+ ...longConversation.slice(0, 6),+ { role: "assistant" },+ ...longConversation.slice(6),+ ]),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(+ canvas.getByRole("button", { name: "4 other messages" }),+ ).toBeVisible();+ await expect(+ canvas.getAllByRole("button", {+ name: /^(Expand|Collapse) (Instructions|Turn \d)$/,+ }),+ ).toHaveLength(4);+ for (const turn of [5, 6, 7]) {+ await expect(+ canvas+ .getAllByText(`Message content ${turn}`)+ .some((element) => element.checkVisibility()),+ ).toBe(true);+ }+ },+});++const MEDIA_REF = "@@@langfuseMedia:type=image/png|id=media-1|source=base64@@@";+const AUDIO_REF = "@@@langfuseMedia:type=audio/wav|id=audio-1|source=base64@@@";+const TEST_MARKDOWN_LIMIT = 1_000;+const imageUrl = "/favicon-32x32.png";+const conversationMedia: MediaReturnType[] = [+ {+ mediaId: "media-1",+ contentType: MediaContentType.PNG,+ contentLength: 68,+ url: imageUrl,+ urlExpiry: "2099-01-01T00:00:00Z",+ field: MediaEnabledFields.Input,+ },+ {+ mediaId: "audio-1",+ contentType: MediaContentType.WAV,+ contentLength: 44,+ url: "/storybook-audio.wav",+ urlExpiry: "2099-01-01T00:00:00Z",+ field: MediaEnabledFields.Output,+ },+];++const storyApi = createTRPCReact<AppRouter>();++function ConversationMediaProviders({ children }: { children: ReactNode }) {+ const [queryClient] = useState(() => {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ for (const media of [+ ...conversationMedia,+ { ...conversationMedia[0], mediaId: "media-2" },+ ]) {+ client.setQueryData(+ getQueryKey(+ api.media.getById,+ { mediaId: media.mediaId, projectId: "storybook-project" },+ "query",+ ),+ media,+ );+ }+ return client;+ });+ const [client] = useState(() =>+ createTRPCClient<AppRouter>({+ links: [+ () => () =>+ observable((observer) => {+ observer.error(+ new TRPCClientError<AppRouter>(+ "Unexpected API request in conversation media story",+ ),+ );+ }),+ ],+ }),+ );+ return (+ <SessionProvider+ session={{+ expires: "2099-01-01T00:00:00Z",+ user: null,+ environment: {+ enableExperimentalFeatures: false,+ selfHostedInstancePlan: null,+ },+ }}+ refetchOnWindowFocus={false}+ >+ <storyApi.Provider client={client} queryClient={queryClient}>+ <QueryClientProvider client={queryClient}>+ <MarkdownRenderCharacterLimitContext.Provider+ value={TEST_MARKDOWN_LIMIT}+ >+ {children}+ </MarkdownRenderCharacterLimitContext.Provider>+ </QueryClientProvider>+ </storyApi.Provider>+ </SessionProvider>+ );+}++export const InlineMediaNotDuplicated = meta.story({+ name: "(Test) Inline media not duplicated",+ decorators: [+ (Story) => (+ <ConversationMediaProviders>+ <Story />+ </ConversationMediaProviders>+ ),+ ],+ parameters: {+ nextjs: { router: { query: { projectId: "storybook-project" } } },+ },+ args: {+ ...conversationPreviewArgs([{ role: "user", content: MEDIA_REF }]),+ media: [conversationMedia[0]],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(await canvas.findByRole("img")).toBeVisible();+ await expect(canvas.getAllByRole("img")).toHaveLength(1);+ await expect(+ canvas.queryByRole("button", { name: "Collapse Media" }),+ ).not.toBeInTheDocument();+ },+});++export const JsonFallbackKeepsMedia = meta.story({+ name: "(Test) JSON fallback keeps media",+ decorators: [+ (Story) => (+ <ConversationMediaProviders>+ <Story />+ </ConversationMediaProviders>+ ),+ ],+ parameters: {+ nextjs: { router: { query: { projectId: "storybook-project" } } },+ },+ args: {+ ...conversationPreviewArgs([+ {+ role: "assistant",+ content: MEDIA_REF.repeat(+ Math.ceil((TEST_MARKDOWN_LIMIT + 1) / MEDIA_REF.length),+ ),+ audio: {+ data: AUDIO_REF,+ },+ },+ ]),+ media: conversationMedia,+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const mediaHeader = canvas.getByRole("button", { name: "Collapse Media" });+ await expect(mediaHeader).toBeVisible();+ await expect(await canvas.findByRole("img")).toBeVisible();+ await expect(await canvas.findByText("storybook-audio.wav")).toBeVisible();+ },+});+export const Empty = meta.story({name: "(Test) Empty",args: { input: undefined, output: undefined },@@ -229,3 +1081,708 @@ export const Empty = meta.story({).toHaveLength(2);},});++const systemPrompt = Array.from(+ { length: 12 },+ (_, index) =>+ `system-prompt-line-${index + 1} lorem ipsum dolor sit amet consectetur adipiscing elit`,+).join("\n");++function messagePreviewArgs(+ message: unknown,+ {+ collapsedHistory = false,+ budgetExceeded = false,+ asOutput = false,+ }: {+ collapsedHistory?: boolean;+ budgetExceeded?: boolean;+ asOutput?: boolean;+ } = {},+) {+ // Parser projections can include paired tool results that the wire schema drops.+ const messages = [+ message,+ ...(collapsedHistory+ ? [1, 2, 3].map((index) =>+ ChatMlMessageSchema.parse({+ role: "user",+ name: `Recent ${index}`,+ content: `Recent content ${index}`,+ }),+ )+ : []),+ ] as ChatMLParserResult["allMessages"];+ return {+ hideOutput: !asOutput,+ hideIfNull: true,+ parsedInput: budgetExceeded ? "x".repeat(10_000) : undefined,+ chatMLParserResult: {+ canDisplayAsChat: true,+ allMessages: messages,+ additionalInput: undefined,+ allTools: [],+ toolCallCounts: new Map<string, number>(),+ toolCallsByName: new Map<string, ToolCallInvocation[]>(),+ messageToToolCallNumbers: new Map<number, number[]>(),+ inputMessageCount: asOutput ? 0 : messages.length,+ } satisfies ChatMLParserResult,+ };+}++export const ConversationOmitsToolDetails = meta.story({+ name: "(Test) Conversation mode retains content without tool details",+ args: {+ ...messagePreviewArgs({+ role: "assistant",+ content: "I will check that for you.",+ tool_calls: [+ { id: "call-1", name: "search_traces", arguments: '{"limit":10}' },+ ],+ }),+ contentMode: "conversation",+ },+ play: async ({ canvas }) => {+ await expect(+ canvas+ .getAllByText("I will check that for you.")+ .some((element) => element.checkVisibility()),+ ).toBe(true);+ await expect(canvas.queryByText("search_traces")).not.toBeInTheDocument();+ },+});++export const MessageHeaderToggles = meta.story({+ name: "(Test) Message header toggles its body without controls toggling it",+ args: messagePreviewArgs({ role: "user", content: "Where is my refund?" }),+ play: async ({ canvas }) => {+ await expect(canvas.getAllByText("Where is my refund?")[0]).toBeVisible();+ await userEvent.click(canvas.getAllByText("user")[0]);+ for (const body of canvas.queryAllByText("Where is my refund?"))+ await expect(body).not.toBeVisible();+ await userEvent.click(canvas.getByRole("button", { name: "Expand user" }));+ await expect(canvas.getAllByText("Where is my refund?")[0]).toBeVisible();+ const copy = spyOn(navigator.clipboard, "writeText").mockResolvedValue();+ try {+ await userEvent.click(+ canvas.getByRole("button", { name: "Copy to clipboard" }),+ );+ await expect(copy).toHaveBeenCalledWith("Where is my refund?");+ await expect(+ canvas.getByRole("button", { name: "Collapse user" }),+ ).toHaveAttribute("aria-expanded", "true");+ await expect(canvas.getAllByText("Where is my refund?")[0]).toBeVisible();+ } finally {+ copy.mockRestore();+ }+ },+});++const passthroughMessage = {+ role: "user",+ content: "Where is my refund?",+ json: { role: "user", content: "Where is my refund?", channel: "web" },+};++export const PassthroughAfterCollapsedHistory = meta.story({+ name: "(Test) Passthrough JSON preserves expanded history state",+ args: messagePreviewArgs(passthroughMessage, { collapsedHistory: true }),+ play: async ({ canvas }) => {+ await expect(+ canvas.getByRole("button", { name: "Expand user" }),+ ).toHaveAttribute("aria-expanded", "false");+ await expect(+ canvas.queryByText("Where is my refund?"),+ ).not.toBeInTheDocument();+ await userEvent.click(canvas.getByRole("button", { name: "Expand user" }));+ await userEvent.click(+ canvas.getByRole("button", { name: "Show passthrough JSON data" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Collapse user" }),+ ).toHaveAttribute("aria-expanded", "true");+ await expect(+ canvas+ .getAllByText("channel")+ .some((element) => element.checkVisibility()),+ ).toBe(true);+ },+});++export const PassthroughAfterJsonHistory = meta.story({+ name: "(Test) Passthrough JSON stays visible when the markdown budget is exceeded",+ args: messagePreviewArgs(passthroughMessage, {+ collapsedHistory: true,+ budgetExceeded: true,+ }),+ play: async ({ canvas }) => {+ await expect(+ canvas.queryByText("Where is my refund?"),+ ).not.toBeInTheDocument();+ await userEvent.click(canvas.getByRole("button", { name: "Expand user" }));+ await userEvent.click(+ canvas.getByRole("button", { name: "Show passthrough JSON data" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Collapse user" }),+ ).toHaveAttribute("aria-expanded", "true");+ await expect(+ canvas+ .getAllByText("channel")+ .some((element) => element.checkVisibility()),+ ).toBe(true);+ },+});++export const RolelessOutputControls = meta.story({+ name: "(Test) Role-less output retains thinking, tools, and correction controls",+ args: {+ ...messagePreviewArgs(+ {+ content: "Checking that for you.",+ thinking: [{ content: "Need the trace first." }],+ tool_calls: [{ id: "call-1", name: "search_traces", arguments: "{}" }],+ },+ { asOutput: true },+ ),+ // Only the disabled header action is mounted; no correction editor or API is used.+ showCorrections: true,+ },+ play: async ({ canvas }) => {+ await expect(+ canvas.getByRole("button", { name: "Collapse Output" }),+ ).toBeVisible();+ await expect(canvas.getAllByText(/search_traces/)[0]).toBeVisible();+ await expect(canvas.getAllByText("Need the trace first.")[0]).toBeVisible();+ await expect(+ canvas.getByRole("button", { name: "Correct output" }),+ ).toBeDisabled();+ },+});++function MarkdownBudgetSwitcher({ children }: { children: ReactNode }) {+ const [overBudget, setOverBudget] = useState(false);+ return (+ <MarkdownRenderCharacterLimitContext.Provider+ value={overBudget ? 1 : 5_000}+ >+ <button onClick={() => setOverBudget((value) => !value)}>+ Toggle markdown budget+ </button>+ {children}+ </MarkdownRenderCharacterLimitContext.Provider>+ );+}++export const TableExpansionSurvivesViewSwitch = meta.story({+ name: "(Test) Table expansion survives switching between mounted view paths",+ decorators: [+ (Story) => (+ <MarkdownBudgetSwitcher>+ <Story />+ </MarkdownBudgetSwitcher>+ ),+ ],+ args: messagePreviewArgs({+ role: "user",+ content: { details: { status: "pending" } },+ }),+ play: async ({ canvas }) => {+ await userEvent.click(+ await canvas.findByRole("button", { name: "Expand all rows" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Collapse all rows" }),+ ).toBeInTheDocument();+ await expect(canvas.getByText("pending")).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Toggle markdown budget" }),+ );+ await expect(+ await canvas.findByRole("button", { name: "Expand all rows" }),+ ).toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "Toggle markdown budget" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Collapse all rows" }),+ ).toBeInTheDocument();+ await expect(canvas.getByText("pending")).toBeVisible();+ },+});++export const NestedToolResponses = meta.story({+ name: "(Test) Nested paired tool responses collapse independently",+ args: messagePreviewArgs({+ role: "assistant",+ tool_calls: [+ {+ id: "search-1",+ name: "search",+ arguments: "{}",+ response: {+ output: "Search body",+ message: {+ role: "tool",+ name: "Search result",+ content: "Search body",+ tool_calls: [+ {+ id: "lookup-1",+ name: "lookup",+ arguments: "{}",+ response: {+ output: "Leaf result",+ message: {+ role: "tool",+ name: "Lookup result",+ content: "Leaf result",+ },+ },+ },+ ],+ },+ },+ },+ ],+ }),+ play: async ({ canvas }) => {+ await expect(canvas.getAllByText("Leaf result")[0]).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Collapse Search result" }),+ );+ await expect(canvas.queryByText("Leaf result")).not.toBeInTheDocument();+ await expect(canvas.getByText("search")).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand Search result" }),+ );+ await expect(canvas.getAllByText("Leaf result")[0]).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Collapse Lookup result" }),+ );+ for (const body of canvas.queryAllByText("Leaf result"))+ await expect(body).not.toBeVisible();+ await expect(canvas.getAllByText("Search body")[0]).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand Lookup result" }),+ );+ await expect(canvas.getAllByText("Leaf result")[0]).toBeVisible();+ },+});++export const NamedSystemPrompt = meta.story({+ name: "(Test) Named system prompts collapse by raw role",+ args: messagePreviewArgs({+ role: "system",+ name: "planner-instructions",+ content: systemPrompt,+ }),+ play: async ({ canvas }) => {+ await expect(+ canvas.getByRole("button", { name: "Expand planner-instructions" }),+ ).toBeVisible();+ },+});++function RemountablePreview(props: ComponentProps<typeof IOPreviewPretty>) {+ const [mount, setMount] = useState(0);+ return (+ <>+ <button onClick={() => setMount((value) => value + 1)}>+ Remount preview+ </button>+ <IOPreviewPretty key={mount} {...props} />+ </>+ );+}++export const JsonSystemPrompt = meta.story({+ name: "(Test) JSON system-prompt expansion persists after remounting",+ render: (args) => <RemountablePreview {...args} />,+ args: messagePreviewArgs(+ { role: "system", content: systemPrompt },+ { budgetExceeded: true },+ ),+ play: async ({ canvas }) => {+ await expect(+ canvas.getAllByRole("button", { name: "Expand system" }),+ ).toHaveLength(1);+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand system" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Collapse system" }),+ ).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Remount preview" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Collapse system" }),+ ).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Collapse system" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Expand system" }),+ ).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Remount preview" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Expand system" }),+ ).toBeVisible();+ },+});++export const PersistedSystemPrompt = meta.story({+ name: "(Test) Persisted expanded system-prompt preference is respected",+ render: (args) => <RemountablePreview {...args} />,+ beforeEach: () => {+ localStorage.setItem("collapseSystemPrompt", "false");+ },+ args: messagePreviewArgs({ role: "system", content: systemPrompt }),+ play: async ({ canvas }) => {+ await expect(+ canvas.queryByRole("button", { name: "Expand system" }),+ ).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "Collapse system" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Expand system" }),+ ).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Remount preview" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Expand system" }),+ ).toBeVisible();+ },+});++export const LegacySystemPromptPreference = meta.story({+ name: "(Test) Legacy expanded system-prompt preference is migrated",+ render: (args) => <RemountablePreview {...args} />,+ beforeEach: () => {+ localStorage.setItem("traceSystemPrompt:collapsed", "false");+ },+ args: messagePreviewArgs({ role: "system", content: systemPrompt }),+ play: async ({ canvas }) => {+ await expect(+ canvas.getByRole("button", { name: "Collapse system" }),+ ).toBeVisible();+ localStorage.removeItem("traceSystemPrompt:collapsed");+ await userEvent.click(+ canvas.getByRole("button", { name: "Remount preview" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Collapse system" }),+ ).toBeVisible();+ },+});++export const SystemPromptContentParts = meta.story({+ name: "(Test) Text content parts participate in system-prompt collapse",+ args: messagePreviewArgs({+ role: "system",+ content: [{ type: "text", text: systemPrompt }],+ }),+ play: async ({ canvas }) => {+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand system" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Collapse system" }),+ ).toBeVisible();+ await expect(+ canvas+ .getAllByText(/system-prompt-line-1 /)+ .some((element) => element.checkVisibility()),+ ).toBe(true);+ },+});++export const ReadableSystemPrompt = meta.story({+ name: "(Test) A readable system prompt stays open above the character threshold",+ args: messagePreviewArgs({+ role: "system",+ content: Array.from(+ { length: 3 },+ (_, index) => `line-${index + 1} ${"x".repeat(90)}`,+ ).join("\n"),+ }),+ play: async ({ canvas }) => {+ await expect(+ canvas.getByRole("button", { name: "Collapse system" }),+ ).toBeVisible();+ await expect(+ canvas.queryByRole("button", { name: "Expand system" }),+ ).not.toBeInTheDocument();+ },+});++export const LongUserMessage = meta.story({+ name: "(Test) Long non-system messages do not auto-collapse",+ args: messagePreviewArgs({ role: "user", content: systemPrompt }),+ play: async ({ canvas }) => {+ await expect(+ canvas.getByRole("button", { name: "Collapse user" }),+ ).toBeVisible();+ await expect(+ canvas+ .getAllByText(/system-prompt-line-1 /)+ .some((element) => element.checkVisibility()),+ ).toBe(true);+ },+});++export const SystemPromptWithoutStorage = meta.story({+ name: "(Test) System-prompt toggle works with blocked localStorage",+ render: function StorageUnavailablePreview(args) {+ const [, setCollapsed] = useCollapseSystemPromptPreference();+ return (+ <>+ <button onClick={() => setCollapsed(true)}>+ Reset prompt preference+ </button>+ <IOPreviewPretty {...args} />+ </>+ );+ },+ beforeEach: () => {+ const descriptor = Object.getOwnPropertyDescriptor(window, "localStorage");+ const denyStorageAccess = () => {+ throw new Error("Storage blocked");+ };+ Object.defineProperty(window, "localStorage", {+ configurable: true,+ value: {+ length: 0,+ clear: denyStorageAccess,+ getItem: denyStorageAccess,+ key: () => null,+ removeItem: denyStorageAccess,+ setItem: denyStorageAccess,+ } satisfies Storage,+ });+ return () => {+ if (descriptor) Object.defineProperty(window, "localStorage", descriptor);+ else Reflect.deleteProperty(window, "localStorage");+ };+ },+ args: messagePreviewArgs({ role: "system", content: systemPrompt }),+ play: async ({ canvas }) => {+ await userEvent.click(+ canvas.getByRole("button", { name: "Reset prompt preference" }),+ );+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand system" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Collapse system" }),+ ).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: "Collapse system" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Expand system" }),+ ).toBeVisible();+ },+});++export const UnicodeToolCopy = meta.story({+ name: "(Test) Tool-only copy decodes Unicode escapes",+ args: messagePreviewArgs({+ role: "assistant",+ tool_calls: [+ {+ id: "call-1",+ name: "search_traces",+ arguments: '{"question":"\\u3053\\u3093\\u306b\\u3061\\u306f"}',+ },+ ],+ }),+ play: async ({ canvas }) => {+ const copy = spyOn(navigator.clipboard, "writeText").mockResolvedValue();+ try {+ await userEvent.click(+ canvas.getByRole("button", { name: "Copy to clipboard" }),+ );+ await expect(copy).toHaveBeenCalled();+ await expect(copy.mock.calls[0]?.[0]).toContain("こんにちは");+ await expect(copy.mock.calls[0]?.[0]).not.toContain("\\u3053");+ } finally {+ copy.mockRestore();+ }+ },+});++export const EmptyParsedMessage = meta.story({+ name: "(Test) Materialized empty messages have no header",+ args: messagePreviewArgs(ChatMlMessageSchema.parse({})),+ play: async ({ canvas }) => {+ await expect(+ canvas.queryByRole("button", { name: /^(Expand|Collapse) / }),+ ).not.toBeInTheDocument();+ },+});++export const FallbackOmitsUnsetFields = meta.story({+ name: "(Test) Whole-message fallback omits unset ChatML fields",+ args: messagePreviewArgs(+ ChatMlMessageSchema.parse({ role: "user", name: "Agent", content: "" }),+ ),+ play: async ({ canvas }) => {+ await expect(canvas.queryByText("undefined")).not.toBeInTheDocument();+ await expect(canvas.queryByText("tool_call_id")).not.toBeInTheDocument();+ },+});++export const ImageContentPart = meta.story({+ name: "(Test) OpenAI image parts retain their media reference",+ decorators: [+ (Story) => (+ <ConversationMediaProviders>+ <Story />+ </ConversationMediaProviders>+ ),+ ],+ parameters: {+ nextjs: { router: { query: { projectId: "storybook-project" } } },+ },+ args: messagePreviewArgs({+ role: "user",+ content: [+ { type: "text", text: "here is the thermostat" },+ { type: "image_url", image_url: { url: MEDIA_REF } },+ ],+ }),+ play: async ({ canvas }) => {+ await expect(canvas.getByText("here is the thermostat")).toBeVisible();+ await expect(await canvas.findByRole("img")).toHaveProperty(+ "src",+ new URL(imageUrl, window.location.href).href,+ );+ },+});++export const FileContentPart = meta.story({+ name: "(Test) AI SDK file parts retain their media reference",+ decorators: [+ (Story) => (+ <ConversationMediaProviders>+ <Story />+ </ConversationMediaProviders>+ ),+ ],+ parameters: {+ nextjs: { router: { query: { projectId: "storybook-project" } } },+ },+ args: messagePreviewArgs({+ role: "user",+ content: [+ { type: "text", text: "attached report" },+ { type: "file", data: MEDIA_REF, mediaType: "image/png" },+ ],+ }),+ play: async ({ canvas }) => {+ await expect(canvas.getByText("attached report")).toBeVisible();+ await expect(await canvas.findByRole("img")).toHaveProperty(+ "src",+ new URL(imageUrl, window.location.href).href,+ );+ },+});++export const BareMediaArray = meta.story({+ name: "(Test) Arrays of bare media references render inline",+ decorators: [+ (Story) => (+ <ConversationMediaProviders>+ <Story />+ </ConversationMediaProviders>+ ),+ ],+ parameters: {+ nextjs: { router: { query: { projectId: "storybook-project" } } },+ },+ args: messagePreviewArgs({+ role: "user",+ content: [MEDIA_REF, MEDIA_REF.replace("media-1", "media-2")],+ }),+ play: async ({ canvas }) => {+ await waitFor(() => expect(canvas.getAllByRole("img")).toHaveLength(2));+ for (const image of canvas.getAllByRole("img"))+ await expect(image).toHaveProperty(+ "src",+ new URL(imageUrl, window.location.href).href,+ );+ },+});++export const ShortSystemPromptWithMedia = meta.story({+ name: "(Test) Media payloads do not make a short system prompt collapse",+ decorators: [+ (Story) => (+ <ConversationMediaProviders>+ <Story />+ </ConversationMediaProviders>+ ),+ ],+ parameters: {+ nextjs: { router: { query: { projectId: "storybook-project" } } },+ },+ args: messagePreviewArgs({+ role: "system",+ content: [+ { type: "text", text: "Short system prompt." },+ ...Array.from({ length: 4 }, () => ({+ type: "image_url",+ image_url: { url: MEDIA_REF },+ })),+ ],+ }),+ play: async ({ canvas }) => {+ await expect(+ canvas.getByRole("button", { name: "Collapse system" }),+ ).toBeVisible();+ await expect(+ canvas.queryByRole("button", { name: "Expand system" }),+ ).not.toBeInTheDocument();+ },+});++export const CollapsedSystemPromptMedia = meta.story({+ name: "(Test) System-prompt attachments mount only after expansion",+ decorators: [+ (Story) => (+ <ConversationMediaProviders>+ <MarkdownRenderCharacterLimitContext.Provider value={5_000}>+ <Story />+ </MarkdownRenderCharacterLimitContext.Provider>+ </ConversationMediaProviders>+ ),+ ],+ parameters: {+ nextjs: { router: { query: { projectId: "storybook-project" } } },+ },+ args: messagePreviewArgs({+ role: "system",+ content: [+ { type: "text", text: systemPrompt },+ { type: "image_url", image_url: { url: MEDIA_REF } },+ ],+ }),+ play: async ({ canvas }) => {+ await expect(+ canvas.queryByRole("img", { hidden: true }),+ ).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "Expand system" }),+ );+ await expect(await canvas.findByRole("img")).toHaveProperty(+ "src",+ new URL(imageUrl, window.location.href).href,+ );+ },+});diff --git a/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsx b/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsxindex bd16542183..0e1bf2b05a 100644--- a/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsx+++ b/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsx@@ -1,13 +1,36 @@/* eslint-disable no-nested-ternary */-import { useEffect, useMemo, useRef, useState } from "react";+import { JsonViewController } from "@/src/components/ui/JsonViewController";+import { MarkdownViewController } from "@/src/components/ui/MarkdownViewController";+import { MarkdownViewContent } from "@/src/components/ui/MarkdownViewContent";+import { useTheme } from "next-themes";+import { assertUnreachable } from "@/src/utils/types";+import { Fragment, useEffect, useMemo, useRef, useState } from "react";import {type ObservationType,type Prisma,type ScoreDomain,+ type SkillsAvailable,+ type SkillsResourceLoaded,deepParseJson,} from "@langfuse/shared";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";-import { type IOSectionAction } from "@/src/components/ui/IOSection";+import { PrettyJsonViewContent } from "@/src/components/ui/PrettyJsonViewContent";+import { IOSection, type IOSectionAction } from "@/src/components/ui/IOSection";+import {+ FoldVertical,+ UnfoldVertical,+ ChevronDown,+ ChevronRight,+ FileCode2,+ FileText,+} from "@langfuse/icons";+import { LinkBadge } from "@/src/components/design-system/LinkBadge/LinkBadge";+import { Badge } from "@/src/components/design-system/Badge/Badge";+import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/src/components/ui/collapsible";import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";import { type MediaReturnType } from "@/src/features/media";import { type ChatMLParserResult } from "../../hooks/useChatMLParser";@@ -16,12 +39,20 @@ import {useIOPreviewParser,} from "../../hooks/useIOPreviewParser";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";-import { ChatMessageList, type ChatMessageListProps } from "../ChatMessageList";-import { SectionToolDefinitions } from "./components/SectionToolDefinitions";+import { ChatMessageController } from "./components/ChatMessageController";+import { ChatMessageContent } from "./components/ChatMessageContent";+import { SystemPromptCollapseController } from "./components/SystemPromptCollapseController";+import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";+import { canRenderContentAsMarkdown } from "@/src/components/ui/MarkdownJsonView";import {- SectionSkills,- type SectionSkillsProps,-} from "./components/SectionSkills";+ filterAlreadyRenderedMedia,+ getRenderedInlineMediaIds,+} from "@/src/components/ui/markdown-media.utils";+import useSessionStorage from "@/src/components/useSessionStorage";+import {+ ToolCallDefinitionCard,+ type ToolDefinition,+} from "./components/ToolCallDefinitionCard";import {type ExpansionStateProps,type IOPreviewContentMode,@@ -35,8 +66,16 @@ import {getMessageTitle,shouldRenderMessageForContentMode,} from "@/src/features/traces/fns/chatMessageUtils";-import { StatusMessageSection } from "./components/StatusMessageSection";-import type { ObservationStatusMessage } from "./components/statusMessagePresentation";+import { type ObservationStatusMessage } from "./components/statusMessagePresentation";+import { useStatusMessage } from "./hooks/useStatusMessage";+import { copyTextToClipboard } from "@/src/utils/clipboard";+import { getSkillLoadRequests } from "../../fns/getSkillLoadRequests";++const TOOLS_COLLAPSE_THRESHOLD = 5;+// The user's collapse choice lasts the session, across observations.+const TOOLS_COLLAPSED_KEY = "toolsSectionCollapsed";+const EXPANDED_TAIL_LENGTH = 3;+const FOLD_ABOVE_MESSAGES = 6;interface JsonInputOutputViewProps {parsedInput: unknown;@@ -80,8 +119,7 @@ function JsonInputOutputView({return (<div className="space-y-2">{showInput && (- <PrettyJsonView- title="Input"+ <JsonViewControllerjson={parsedInput}isLoading={isLoading}isParsing={isParsing}@@ -89,20 +127,69 @@ function JsonInputOutputView({currentView="pretty"externalExpansionState={inputExpansionState}onExternalExpansionChange={onInputExpansionChange}- />+ >+ {(state) => (+ <IOSection+ title="Input"+ onCopy={state.copy}+ actions={+ state.contentKind === "table" && state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : undefined+ }+ variant={state.contentKind === "table" ? "table" : "text"}+ >+ <PrettyJsonViewContent state={state} title="Input" borderless />+ </IOSection>+ )}+ </JsonViewController>)}{showOutput && (- <PrettyJsonView- title="Output"+ <JsonViewControllerjson={parsedOutput}isLoading={isLoading}isParsing={isParsing}media={media?.filter((m) => m.field === "output") ?? []}currentView="pretty"- actions={outputActions}externalExpansionState={outputExpansionState}onExternalExpansionChange={onOutputExpansionChange}- />+ >+ {(state) => (+ <IOSection+ title="Output"+ onCopy={state.copy}+ actions={+ state.contentKind === "table" && state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ...(outputActions ?? []),+ ]+ : outputActions+ }+ variant={state.contentKind === "table" ? "table" : "text"}+ >+ <PrettyJsonViewContent state={state} title="Output" borderless />+ </IOSection>+ )}+ </JsonViewController>)}</div>);@@ -133,7 +220,9 @@ function isChatIO(value: unknown): boolean {const SIDE_TITLES = { input: "Input", output: "Output" } as const;export interface IOPreviewPrettyProps extends ExpansionStateProps {- skills?: SectionSkillsProps["skills"];+ skills?:+ | { kind: "available"; items: SkillsAvailable }+ | { kind: "loaded"; items: SkillsResourceLoaded };input?: Prisma.JsonValue;output?: Prisma.JsonValue;status?: ObservationStatusMessage;@@ -202,6 +291,45 @@ export function IOPreviewPretty({contentMode = "all",showSystemPrompt,}: IOPreviewPrettyProps) {+ const { forcedTheme, resolvedTheme } = useTheme();+ const { statusPresentation, parsedStatusMessage } = useStatusMessage(status);+ const [isSkillsExpanded, setSkillsExpanded] = useState(false);+ const [expandedSkillKey, setExpandedSkillKey] = useState("");+ const [activeSkillTab, setActiveSkillTab] = useState("requested");+ const [othersOpen, setOthersOpen] = useState(false);+ const [activeToolTab, setActiveToolTab] = useState<"called" | "not-called">(+ "called",+ );+ const [storedToolsCollapsed, setStoredToolsCollapsed] = useSessionStorage<+ boolean | null+ >(TOOLS_COLLAPSED_KEY, null);+ const skillGroups = new Map<+ string,+ {+ key: string;+ skill: SkillsAvailable[number];+ files: Set<string>;+ }+ >();+ const skillItems =+ skills?.kind === "loaded"+ ? skills.items.map((skill) => ({ skill, filePath: skill.filePath }))+ : (skills?.items ?? []).map((skill) => ({ skill, filePath: undefined }));+ for (const { skill, filePath } of skillItems) {+ const key = JSON.stringify([+ skill.langfuseSkillId ?? null,+ skill.skillName,+ skill.skillVersion ?? null,+ ]);+ const group = skillGroups.get(key) ?? {+ key,+ skill,+ files: new Set<string>(),+ };+ skillGroups.set(key, group);+ if (filePath !== undefined) group.files.add(filePath);+ }+// Use pre-parsed data if available (from useParsedObservation hook),// otherwise parse with size/depth limits to prevent UI freeze// IMPORTANT: Don't parse while isParsing=true to avoid double-parsing with different object references@@ -252,6 +380,49 @@ export function IOPreviewPretty({inputMessageCount,} = parserResult;+ const skillLoadRequests = getSkillLoadRequests(+ skills?.kind === "available"+ ? Array.from(skillGroups.values(), ({ skill }) => skill)+ : [],+ toolCallsByName,+ );+ const requestedSkillGroups = Array.from(skillGroups.values()).filter(+ ({ skill }) => skillLoadRequests.has(skill),+ );+ const notRequestedSkillGroups = Array.from(skillGroups.values()).filter(+ ({ skill }) => !skillLoadRequests.has(skill),+ );+ const hasSkillTabs =+ requestedSkillGroups.length > 0 && notRequestedSkillGroups.length > 0;+ const visibleSkillGroups = (() => {+ if (!hasSkillTabs) return Array.from(skillGroups.values());+ return activeSkillTab === "requested"+ ? requestedSkillGroups+ : notRequestedSkillGroups;+ })();++ const { calledTools, notCalledTools } = useMemo(+ () =>+ allTools.reduce(+ (groups, tool) => {+ if ((toolCallCounts.get(tool.name) ?? 0) > 0) {+ groups.calledTools.push(tool);+ } else {+ groups.notCalledTools.push(tool);+ }+ return groups;+ },+ {+ calledTools: [] as ToolDefinition[],+ notCalledTools: [] as ToolDefinition[],+ },+ ),+ [allTools, toolCallCounts],+ );+ const hasToolTabs = calledTools.length > 0 && notCalledTools.length > 0;+ const tabTools = activeToolTab === "called" ? calledTools : notCalledTools;+ const visibleTools = hasToolTabs ? tabTools : allTools;+const characterLimit = useMarkdownRenderCharacterLimit();// Determine if markdown is safe to render (content size check)@@ -290,6 +461,45 @@ export function IOPreviewPretty({return shouldRender;}, [parsedInput, parsedOutput, allMessages, characterLimit]);+ const messagesToRender = useMemo(+ () =>+ allMessages+ .map((message, originalIndex) => ({ message, originalIndex }))+ .filter(({ message }) =>+ shouldRenderMessageForContentMode(+ message,+ contentMode,+ showSystemPrompt,+ ),+ ),+ [allMessages, contentMode, showSystemPrompt],+ );+ const foldsMiddle = messagesToRender.length > FOLD_ABOVE_MESSAGES;+ const foldEnd = messagesToRender.length - EXPANDED_TAIL_LENGTH;+ const otherMessagesCount = foldEnd - 1;+ const otherMessagesLabel = `${otherMessagesCount} other ${otherMessagesCount === 1 ? "message" : "messages"}`;+ const HistoryCaret = othersOpen ? ChevronDown : ChevronRight;+ const lastOutputIndex = messagesToRender.reduce(+ (last, { originalIndex }, index) =>+ originalIndex >= (inputMessageCount ?? 0) ? index : last,+ -1,+ );+ const remainingMedia = useMemo(() => {+ if (!shouldRenderMarkdown) return media ?? [];+ const renderedMediaIds = new Set<string>();+ messagesToRender.forEach(({ message }) => {+ const content = message.content || "";+ // JSON fallbacks do not render media inline and still need the media section.+ if (canRenderContentAsMarkdown(content, characterLimit)) {+ getRenderedInlineMediaIds({+ markdown: content,+ audio: message.audio,+ }).forEach((mediaId) => renderedMediaIds.add(mediaId));+ }+ });+ return filterAlreadyRenderedMedia(media, renderedMediaIds);+ }, [media, shouldRenderMarkdown, messagesToRender, characterLimit]);+// Prepare additional input (only if non-empty)const additionalInputToShow = useMemo(() => {if (!additionalInput || Object.keys(additionalInput).length === 0) {@@ -373,48 +583,772 @@ export function IOPreviewPretty({input: canTitleBySide && !isChatIO(parsedInput),output: canTitleBySide && !isChatIO(parsedOutput),};- const messageTitle: ChatMessageListProps["getMessageTitle"] = (- message,- side,- ) => (titleBySide[side] ? SIDE_TITLES[side] : getMessageTitle(message));return (<div className="space-y-2 pt-3">- {showData && status ? (- <StatusMessageSection status={status} currentView="pretty" />- ) : null}+ {showData && status && statusPresentation && (+ <JsonViewController+ json={status.message}+ parsedJson={+ // Do not retry parsing text rejected by the status parser's size limit.+ parsedStatusMessage ?? null+ }+ currentView="pretty"+ >+ {(state) => (+ <IOSection+ title={statusPresentation.title}+ onCopy={+ parsedStatusMessage !== undefined+ ? state.copy+ : () => copyTextToClipboard(status.message)+ }+ actions={+ parsedStatusMessage !== undefined &&+ state.contentKind === "table" &&+ state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : undefined+ }+ variant={+ parsedStatusMessage !== undefined &&+ state.contentKind === "table"+ ? "table"+ : "text"+ }+ tone={statusPresentation.tone}+ >+ {parsedStatusMessage !== undefined ? (+ <PrettyJsonViewContent+ state={state}+ title={statusPresentation.title}+ borderless+ />+ ) : (+ status.message+ )}+ </IOSection>+ )}+ </JsonViewController>+ )}{showData && allTools.length > 0 ? (- <SectionToolDefinitions- tools={allTools}- toolCallCounts={toolCallCounts}- toolCallsByName={toolCallsByName}- />+ <IOSection+ title="Tools"+ variant="table"+ collapsed={+ storedToolsCollapsed ?? allTools.length > TOOLS_COLLAPSE_THRESHOLD+ }+ onCollapsedChange={setStoredToolsCollapsed}+ tabs={+ hasToolTabs+ ? {+ value: activeToolTab,+ onValueChange: (value) => {+ if (value === "called" || value === "not-called")+ setActiveToolTab(value);+ },+ items: [+ {+ value: "called",+ label: "Called",+ count: calledTools.length,+ },+ {+ value: "not-called",+ label: "Not called",+ count: notCalledTools.length,+ },+ ],+ }+ : undefined+ }+ >+ <ToolCallDefinitionCard+ key={activeToolTab}+ tools={visibleTools}+ toolCallsByName={toolCallsByName}+ />+ </IOSection>) : null}{showData && skills && skills.items.length > 0 ? (- <SectionSkills- projectId={projectId}- skills={skills}- toolCallsByName={toolCallsByName}- />+ <IOSection+ title="Skills"+ count={hasSkillTabs ? undefined : skillGroups.size}+ tabs={+ hasSkillTabs+ ? {+ value: activeSkillTab,+ onValueChange: (value) => {+ setActiveSkillTab(value);+ setExpandedSkillKey("");+ },+ items: [+ {+ value: "requested",+ label: "Requested",+ count: requestedSkillGroups.length,+ },+ {+ value: "not-requested",+ label: "Not requested",+ count: notRequestedSkillGroups.length,+ },+ ],+ }+ : undefined+ }+ info={+ skillLoadRequests.size > 0+ ? {+ label: "About skill load requests",+ text: `${skillLoadRequests.size} of ${skillGroups.size} available skills requested by this generation's output tool calls. A request does not confirm that the skill was loaded successfully.`,+ }+ : undefined+ }+ >+ <Collapsible+ open={isSkillsExpanded}+ onOpenChange={setSkillsExpanded}+ className="flex flex-col gap-2"+ >+ <CollapsibleTrigger className="hover:bg-muted/20 flex w-full items-center justify-between gap-2 rounded-sm border px-3 py-2 text-left text-sm font-bold">+ <span className="flex min-w-0 flex-1 items-center gap-2">+ <FileCode2 size="base" color="muted" aria-hidden />+ <span>+ {skillGroups.size}{" "}+ {skills.kind === "available" ? "available" : "loaded"}{" "}+ {skillGroups.size === 1 ? "skill" : "skills"}+ </span>+ </span>+ <Badge+ color="filled"+ size="sm"+ text={isSkillsExpanded ? "hide" : "show"}+ />+ <DropdownIndicator+ direction={isSkillsExpanded ? "down" : "right"}+ />+ </CollapsibleTrigger>+ <CollapsibleContent asChild>+ <ul className="flex flex-col gap-2">+ {visibleSkillGroups.map(+ ({ key, skill, files: loadedFiles }) => {+ const files =+ skills.kind === "available"+ ? (skillLoadRequests.get(skill) ?? new Set<string>())+ : loadedFiles;+ return (+ <Collapsible+ key={key}+ asChild+ open={expandedSkillKey === key}+ onOpenChange={(open) =>+ setExpandedSkillKey(open ? key : "")+ }+ >+ <li className="min-w-0 overflow-hidden rounded-sm border">+ <div className="flex min-w-0 items-center gap-2 px-3 py-1.5">+ <FileCode2 size="base" color="muted" aria-hidden />+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1">+ {skill.langfuseSkillId &&+ skill.skillVersion != null ? (+ <LinkBadge+ href={`/project/${projectId}/skills/${encodeURIComponent(skill.skillName)}?version=${skill.skillVersion}`}+ text={skill.skillName}+ newTab+ noCapture+ />+ ) : (+ <Badge+ color="ghost"+ font="mono"+ text={skill.skillName}+ />+ )}+ {skill.skillVersion != null ? (+ <Badge+ color="filled"+ size="sm"+ text={`v${skill.skillVersion}`}+ />+ ) : null}+ </div>+ {files.size > 0 ? (+ <CollapsibleTrigger+ className="hover:bg-muted/20 flex shrink-0 items-center gap-1.5 rounded-sm px-1 py-0.5"+ aria-label={`Files ${skills.kind === "available" ? "requested" : "loaded"} for ${skill.skillName}`}+ >+ <Badge+ color="green"+ size="sm"+ text={`${files.size} ${files.size === 1 ? "file" : "files"}`}+ />+ <DropdownIndicator+ direction={+ expandedSkillKey === key ? "down" : "right"+ }+ />+ </CollapsibleTrigger>+ ) : null}+ </div>+ {files.size > 0 ? (+ <CollapsibleContent asChild>+ <ul className="bg-muted/30 flex flex-col gap-2 border-t px-3 py-3">+ {Array.from(files, (filePath) => (+ <li+ key={filePath}+ className="flex min-w-0 items-start gap-2"+ >+ <FileText+ size="base"+ color="muted"+ __rawClassName="mt-0.5"+ aria-hidden+ />+ <span className="min-w-0 font-mono text-xs leading-relaxed break-all">+ {filePath}+ </span>+ </li>+ ))}+ </ul>+ </CollapsibleContent>+ ) : null}+ </li>+ </Collapsible>+ );+ },+ )}+ </ul>+ </CollapsibleContent>+ </Collapsible>+ </IOSection>) : null}{shouldRenderMessages ? (<div>- <ChatMessageList- messages={allMessages}- shouldRenderMarkdown={shouldRenderMarkdown}- additionalInput={additionalInputToShow}- media={media ?? []}- currentView="pretty"- messageToToolCallNumbers={messageToToolCallNumbers}- inputMessageCount={inputMessageCount}- contentMode={contentMode}- showSystemPrompt={showSystemPrompt}- getMessageTitle={messageTitle}- outputActions={outputActions}- />+ <div className="flex max-h-full min-h-0 flex-col gap-2">+ <div className="flex max-h-full min-h-0 flex-col gap-2">+ <div className="flex flex-col gap-2">+ {messagesToRender.map(+ ({ message, originalIndex }, filteredIndex) => {+ const isOutputMessage =+ originalIndex >= (inputMessageCount ?? 0);+ const side = isOutputMessage ? "output" : "input";+ const folded =+ foldsMiddle &&+ filteredIndex > 0 &&+ filteredIndex < foldEnd;+ // Folded messages do not mount (no parsing) until the row opens.+ if (folded && !othersOpen) return null;+ const chatMessage = (+ <ChatMessageController+ key={originalIndex}+ message={message}+ title={+ titleBySide[side]+ ? SIDE_TITLES[side]+ : getMessageTitle(message)+ }+ toolCallNumbers={messageToToolCallNumbers.get(+ originalIndex,+ )}+ isOutputMessage={isOutputMessage}+ contentMode={contentMode}+ defaultCollapsed={+ foldsMiddle+ ? folded+ : message.role !== "system" &&+ filteredIndex <+ messagesToRender.length - EXPANDED_TAIL_LENGTH+ }+ actions={+ filteredIndex === lastOutputIndex+ ? outputActions+ : undefined+ }+ >+ {function renderMessage({+ title,+ data,+ body,+ actions,+ isSystemPrompt,+ collapsed,+ setCollapsed,+ copy,+ }): React.ReactNode {+ if (+ data.kind === "collapsed" ||+ data.kind === "tools"+ ) {+ return (+ <div className="transition-colors">+ <IOSection+ title={title}+ onCopy={+ data.kind === "tools" ? copy : undefined+ }+ actions={+ actions.length > 0 ? actions : undefined+ }+ collapsed={collapsed}+ onCollapsedChange={setCollapsed}+ variant="text"+ >+ {data.kind === "tools" && (+ <ChatMessageContent+ body={body}+ renderToolResponse={(response) => (+ <ChatMessageController+ message={response}+ title={getMessageTitle(response)}+ contentMode={contentMode}+ >+ {renderMessage}+ </ChatMessageController>+ )}+ />+ )}+ </IOSection>+ </div>+ );+ }+ if (data.kind === "data") {+ return (+ <JsonViewController+ json={data.value}+ currentView="pretty"+ >+ {(state) => {+ const kind = state.contentKind;+ const sectionActions = [+ ...(kind === "table" &&+ state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : []),+ ...actions,+ ];+ return (+ <div className="transition-colors">+ <IOSection+ title={title}+ onCopy={state.copy}+ actions={+ sectionActions.length > 0+ ? sectionActions+ : undefined+ }+ collapsed={collapsed}+ onCollapsedChange={setCollapsed}+ variant={+ kind === "table" ? "table" : "text"+ }+ >+ {!collapsed && (+ <ChatMessageContent+ body={body}+ renderToolResponse={(response) => (+ <ChatMessageController+ message={response}+ title={getMessageTitle(+ response,+ )}+ contentMode={contentMode}+ >+ {renderMessage}+ </ChatMessageController>+ )}+ >+ <PrettyJsonViewContent+ state={state}+ title={title}+ borderless+ />+ </ChatMessageContent>+ )}+ </IOSection>+ </div>+ );+ }}+ </JsonViewController>+ );+ }+ if (data.kind === "message") {+ const markdownContent = canRenderContentAsMarkdown(+ data.content,+ characterLimit,+ ) && {+ content: data.content,+ };+ // Keep both paths mounted to preserve each view's state.+ return (+ <>+ {markdownContent && (+ <MarkdownViewController+ markdown={markdownContent.content}+ audio={data.audio}+ >+ {(state) => (+ <SystemPromptCollapseController+ isSystemPrompt={isSystemPrompt}+ text={state.textContent}+ collapsed={collapsed}+ setCollapsed={setCollapsed}+ >+ {({+ collapsed: sectionCollapsed,+ setCollapsed: setSectionCollapsed,+ }) => (+ <div+ className="transition-colors"+ hidden={!shouldRenderMarkdown}+ >+ <IOSection+ key={forcedTheme ?? resolvedTheme}+ title={title}+ onCopy={state.copy}+ actions={+ actions.length > 0+ ? actions+ : undefined+ }+ collapsed={sectionCollapsed}+ onCollapsedChange={+ setSectionCollapsed+ }+ variant="text"+ >+ {!sectionCollapsed && (+ <ChatMessageContent+ body={body}+ renderToolResponse={(+ response,+ ) => (+ <ChatMessageController+ message={response}+ title={getMessageTitle(+ response,+ )}+ contentMode={contentMode}+ >+ {renderMessage}+ </ChatMessageController>+ )}+ >+ <MarkdownViewContent+ state={state}+ />+ </ChatMessageContent>+ )}+ </IOSection>+ </div>+ )}+ </SystemPromptCollapseController>+ )}+ </MarkdownViewController>+ )}+ {!markdownContent && (+ <JsonViewController+ json={+ data.content ??+ (data.audio+ ? { audio: data.audio }+ : null)+ }+ currentView="pretty"+ >+ {(state) => {+ const kind = state.contentKind;+ const sectionActions = [+ ...(kind === "table" &&+ state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : []),+ ...actions,+ ];+ return (+ <SystemPromptCollapseController+ isSystemPrompt={+ isSystemPrompt &&+ kind === "markdown" &&+ state+ .standaloneMediaReferenceStrings+ .length === 0+ }+ text={state.markdownContent ?? ""}+ collapsed={collapsed}+ setCollapsed={setCollapsed}+ >+ {({+ collapsed: sectionCollapsed,+ setCollapsed: setSectionCollapsed,+ }) => (+ <div+ className="transition-colors"+ hidden={!shouldRenderMarkdown}+ >+ <IOSection+ title={title}+ onCopy={state.copy}+ actions={+ sectionActions.length > 0+ ? sectionActions+ : undefined+ }+ collapsed={sectionCollapsed}+ onCollapsedChange={+ setSectionCollapsed+ }+ variant={+ kind === "table"+ ? "table"+ : "text"+ }+ >+ {!sectionCollapsed && (+ <ChatMessageContent+ body={body}+ renderToolResponse={(+ response,+ ) => (+ <ChatMessageController+ message={response}+ title={getMessageTitle(+ response,+ )}+ contentMode={+ contentMode+ }+ >+ {renderMessage}+ </ChatMessageController>+ )}+ >+ <PrettyJsonViewContent+ state={state}+ title={title}+ borderless+ />+ </ChatMessageContent>+ )}+ </IOSection>+ </div>+ )}+ </SystemPromptCollapseController>+ );+ }}+ </JsonViewController>+ )}+ <JsonViewController+ json={data.originalContent}+ currentView="pretty"+ >+ {(state) => {+ const kind = state.contentKind;+ const sectionActions = [+ ...(kind === "table" &&+ state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : []),+ ...actions,+ ];+ return (+ <SystemPromptCollapseController+ isSystemPrompt={+ isSystemPrompt &&+ kind === "markdown" &&+ state.standaloneMediaReferenceStrings+ .length === 0+ }+ text={state.markdownContent ?? ""}+ collapsed={collapsed}+ setCollapsed={setCollapsed}+ >+ {({+ collapsed: sectionCollapsed,+ setCollapsed: setSectionCollapsed,+ }) => (+ <div+ className="transition-colors"+ hidden={shouldRenderMarkdown}+ >+ <IOSection+ title={title}+ onCopy={state.copy}+ actions={+ sectionActions.length > 0+ ? sectionActions+ : undefined+ }+ collapsed={sectionCollapsed}+ onCollapsedChange={+ setSectionCollapsed+ }+ variant={+ kind === "table"+ ? "table"+ : "text"+ }+ >+ {!sectionCollapsed && (+ <ChatMessageContent+ body={body}+ renderToolResponse={(+ response,+ ) => (+ <ChatMessageController+ message={response}+ title={getMessageTitle(+ response,+ )}+ contentMode={contentMode}+ >+ {renderMessage}+ </ChatMessageController>+ )}+ >+ <PrettyJsonViewContent+ state={state}+ title={title}+ borderless+ />+ </ChatMessageContent>+ )}+ </IOSection>+ </div>+ )}+ </SystemPromptCollapseController>+ );+ }}+ </JsonViewController>+ </>+ );+ }+ return assertUnreachable(data);+ }}+ </ChatMessageController>+ );+ if (foldsMiddle && filteredIndex === 0) {+ return (+ <Fragment key={originalIndex}>+ {chatMessage}+ <button+ type="button"+ className="io-message-header text-muted-foreground focus-visible:ring-ring flex h-8 w-full cursor-pointer items-center gap-2 rounded-sm text-left text-sm focus-visible:ring-2 focus-visible:outline-hidden"+ aria-expanded={othersOpen}+ aria-label={otherMessagesLabel}+ onClick={() => setOthersOpen((open) => !open)}+ >+ <HistoryCaret+ size="base"+ color="default"+ aria-hidden+ />+ {otherMessagesLabel}+ </button>+ </Fragment>+ );+ }+ return chatMessage;+ },+ )}+ </div>+ {showData && additionalInputToShow && (+ <JsonViewController+ json={additionalInputToShow}+ currentView={shouldRenderMarkdown ? "pretty" : "json"}+ >+ {(state) => (+ <IOSection+ title="Additional Input"+ onCopy={state.copy}+ actions={+ state.contentKind === "table" && state.hasExpandableRows+ ? [+ {+ icon: state.allRowsExpanded+ ? FoldVertical+ : UnfoldVertical,+ label: state.allRowsExpanded+ ? "Collapse all rows"+ : "Expand all rows",+ onClick: state.toggleAllRows,+ },+ ]+ : undefined+ }+ variant={state.contentKind === "table" ? "table" : "text"}+ >+ <PrettyJsonViewContent+ state={state}+ title="Additional Input"+ borderless+ />+ </IOSection>+ )}+ </JsonViewController>+ )}+ {remainingMedia.length > 0 && (+ <IOSection title="Media" variant="media">+ <div className="flex flex-wrap gap-2">+ {remainingMedia.map((media) => (+ <LangfuseMediaView+ mediaAPIReturnValue={media}+ variant={+ media.contentType.startsWith("image")+ ? "inline"+ : "icon"+ }+ key={media.mediaId}+ />+ ))}+ </div>+ </IOSection>+ )}+ </div>+ </div>{correctedOutputField}</div>) : showData ? (diff --git a/web/src/features/traces/components/IOPreview/components/ChatMessage.clienttest.tsx b/web/src/features/traces/components/IOPreview/components/ChatMessage.clienttest.tsxdeleted file mode 100644index 9d7f02697e..0000000000--- a/web/src/features/traces/components/IOPreview/components/ChatMessage.clienttest.tsx+++ /dev/null@@ -1,611 +0,0 @@-import { fireEvent, render, screen } from "@testing-library/react";-import { Pencil } from "@langfuse/icons";-import { vi } from "vitest";--const { copyTextToClipboard } = vi.hoisted(() => ({- copyTextToClipboard: vi.fn(),-}));--vi.mock("@/src/utils/clipboard", () => ({ copyTextToClipboard }));--// ChatMessage mounts both render paths (one is display:none), so the JSON-// path's media tag resolves too — stub its project/URL lookups.-vi.mock("@/src/hooks/useProjectIdFromURL", () => ({ default: () => "p1" }));-vi.mock("@/src/components/ui/media/useResolvedMedia", () => ({- useResolvedMedia: () => ({- status: "idle",- url: undefined,- refreshIfNeeded: async () => undefined,- }),-}));--// Stands in for the real media renderer (it needs a session + signed-URL-// query); the contract under test is which reference reaches it.-vi.mock("@/src/components/ui/LangfuseMediaView", () => ({- LangfuseMediaView: ({- mediaReferenceString,- }: {- mediaReferenceString?: unknown;- }) => (- <div- data-testid="langfuse-media"- data-media-ref={- typeof mediaReferenceString === "string"- ? mediaReferenceString- : (mediaReferenceString as { referenceString?: string })- ?.referenceString- }- />- ),-}));--import { ChatMlArraySchema } from "@langfuse/shared";--import { ChatMessage } from "./ChatMessage";-import {- type ChatMlMessage,- getMessageTitle,-} from "../../../fns/chatMessageUtils";-import { type IOPreviewContentMode } from "../IOPreview";--function createMemoryStorage(): Storage {- const store = new Map<string, string>();-- return {- get length() {- return store.size;- },- clear: () => store.clear(),- getItem: (key) => store.get(key) ?? null,- key: (index) => Array.from(store.keys())[index] ?? null,- removeItem: (key) => {- store.delete(key);- },- setItem: (key, value) => {- store.set(key, value);- },- };-}--// 12 lines, well above the 250-char collapse threshold-const longSystemPrompt = Array.from(- { length: 12 },- (_, i) =>- `system-prompt-line-${i + 1} lorem ipsum dolor sit amet consectetur adipiscing elit`,-).join("\n");--function renderChatMessage(- message: ChatMlMessage,- {- shouldRenderMarkdown = true,- contentMode = "all",- defaultCollapsed,- }: {- shouldRenderMarkdown?: boolean;- contentMode?: IOPreviewContentMode;- defaultCollapsed?: boolean;- } = {},-) {- return render(- <ChatMessage- message={message}- title={getMessageTitle(message)}- shouldRenderMarkdown={shouldRenderMarkdown}- currentView="pretty"- contentMode={contentMode}- defaultCollapsed={defaultCollapsed}- />,- );-}--describe("ChatMessage content modes", () => {- const assistantWithToolCall = {- role: "assistant",- content: "I will check that for you.",- tool_calls: [- {- id: "call-1",- name: "search_traces",- arguments: '{"limit":10}',- },- ],- } as unknown as ChatMlMessage;-- beforeEach(() => {- vi.stubGlobal("localStorage", createMemoryStorage());- vi.stubGlobal("sessionStorage", createMemoryStorage());- });-- it("keeps assistant content but removes tool details in conversation mode", () => {- renderChatMessage(assistantWithToolCall, { contentMode: "conversation" });-- expect(- screen.getAllByText("I will check that for you.").length,- ).toBeGreaterThan(0);- expect(screen.queryByText("search_traces")).not.toBeInTheDocument();- });-});--// getByRole ignores elements hidden via display:none, so queries only see the-// active render path (markdown vs json), even though ChatMessage mounts both.-// The section caret is labelled by the section title (the message role).-const expandButtons = () =>- screen.queryAllByRole("button", { name: /^expand system/i });-const collapseButtons = () =>- screen.queryAllByRole("button", { name: /^collapse system/i });-const expandButton = () => expandButtons()[0] ?? null;-const collapseButton = () => collapseButtons()[0] ?? null;--describe("ChatMessage section caret", () => {- beforeEach(() => {- vi.stubGlobal("localStorage", createMemoryStorage());- vi.stubGlobal("sessionStorage", createMemoryStorage());- });-- it("hides and restores the message body", () => {- renderChatMessage({- role: "user",- content: "Where is my refund?",- } as ChatMlMessage);- // The hidden JSON path keeps its own copy of the text, so check visibility.- const bodies = () => screen.queryAllByText("Where is my refund?");-- expect(bodies()[0]).toBeVisible();-- fireEvent.click(screen.getByRole("button", { name: "Collapse user" }));-- bodies().forEach((body) => expect(body).not.toBeVisible());-- fireEvent.click(screen.getByRole("button", { name: "Expand user" }));-- expect(bodies()[0]).toBeVisible();- });-- it("toggles from the header row, not from its controls", () => {- renderChatMessage({- role: "user",- content: "Where is my refund?",- } as ChatMlMessage);- const bodies = () => screen.queryAllByText("Where is my refund?");-- // Clicking the title text (inside the row button) collapses.- fireEvent.click(screen.getAllByText("user")[0]);- bodies().forEach((body) => expect(body).not.toBeVisible());-- fireEvent.click(screen.getAllByText("user")[0]);- expect(bodies()[0]).toBeVisible();-- // The copy control sits beside the row button and does not toggle.- fireEvent.click(screen.getAllByTitle("Copy to clipboard")[0]);- expect(bodies()[0]).toBeVisible();- expect(- screen.getByRole("button", { name: "Collapse user" }),- ).toHaveAttribute("aria-expanded", "true");- });-- it("keeps the open state when switching to the passthrough JSON view", () => {- renderChatMessage(- {- role: "user",- content: "Where is my refund?",- json: { role: "user", content: "Where is my refund?", channel: "web" },- } as unknown as ChatMlMessage,- { defaultCollapsed: true },- );-- fireEvent.click(screen.getByRole("button", { name: "Expand user" }));- fireEvent.click(screen.getAllByTitle("Show passthrough JSON data")[0]);-- expect(- screen.queryByRole("button", { name: "Expand user" }),- ).not.toBeInTheDocument();- expect(- screen.getByRole("button", { name: "Collapse user" }),- ).toHaveAttribute("aria-expanded", "true");- expect(screen.getAllByText("channel")[0]).toBeInTheDocument();- });-- it("gives a role-less message a header and keeps its tool calls and thinking", () => {- render(- <ChatMessage- message={- {- content: "Checking that for you.",- thinking: [{ content: "Need the trace first." }],- tool_calls: [- { id: "call-1", name: "search_traces", arguments: "{}" },- ],- } as unknown as ChatMlMessage- }- title=""- shouldRenderMarkdown- currentView="pretty"- actions={[{ icon: Pencil, label: "Correct output", onClick: () => {} }]}- />,- );-- expect(- screen.getByRole("button", { name: "Collapse Input" }),- ).toBeInTheDocument();- expect(screen.getAllByText(/search_traces/)[0]).toBeInTheDocument();- expect(screen.getAllByText("Need the trace first.")[0]).toBeInTheDocument();- expect(- screen.getByRole("button", { name: "Correct output" }),- ).toBeInTheDocument();- });-- it("mounts only the header while collapsed", () => {- renderChatMessage(- { role: "user", content: "Where is my refund?" } as ChatMlMessage,- { defaultCollapsed: true },- );-- expect(screen.queryAllByText("Where is my refund?")).toHaveLength(0);-- fireEvent.click(screen.getByRole("button", { name: "Expand user" }));-- expect(screen.getAllByText("Where is my refund?")[0]).toBeVisible();- });-- it("starts collapsed when asked, keeping the header", () => {- renderChatMessage(- { role: "user", content: "Where is my refund?" } as ChatMlMessage,- { defaultCollapsed: true },- );-- expect(screen.queryByText("Where is my refund?")).not.toBeInTheDocument();- expect(screen.getByRole("button", { name: "Expand user" })).toHaveAttribute(- "aria-expanded",- "false",- );- });-});--describe("ChatMessage system prompt collapse", () => {- beforeEach(() => {- vi.stubGlobal("localStorage", createMemoryStorage());- vi.stubGlobal("sessionStorage", createMemoryStorage());- });-- it("collapses a long system message on the markdown path", () => {- renderChatMessage({- role: "system",- content: longSystemPrompt,- } as ChatMlMessage);-- // One caret in the section header; the body is not rendered.- expect(expandButtons()).toHaveLength(1);- expect(expandButton()!.closest(".io-message-header")).not.toBeNull();- expect(screen.queryByText(/system-prompt-line-1 /)).not.toBeInTheDocument();- });-- it("collapses a long system message that carries a name", () => {- // A `name` makes the display title the name instead of the role; collapse- // must still key off the raw role.- renderChatMessage({- role: "system",- name: "planner-instructions",- content: longSystemPrompt,- } as ChatMlMessage);-- expect(- screen.getByRole("button", { name: /^expand planner-instructions/i }),- ).toBeInTheDocument();- });-- it("collapses a long system message on the json/pretty path (markdown off)", () => {- renderChatMessage(- { role: "system", content: longSystemPrompt } as ChatMlMessage,- { shouldRenderMarkdown: false },- );-- // The caret in the section header is the one collapse control here too.- expect(expandButtons()).toHaveLength(1);- expect(expandButtons()[0].closest(".io-message-header")).not.toBeNull();- });-- it("expands on click and persists the expanded preference", () => {- renderChatMessage({- role: "system",- content: longSystemPrompt,- } as ChatMlMessage);-- fireEvent.click(expandButton()!);-- expect(collapseButton()).toBeInTheDocument();- expect(screen.getAllByText(/system-prompt-line-1 /).length).toBeGreaterThan(- 0,- );- expect(localStorage.getItem("collapseSystemPrompt")).toBe("false");- });-- it("respects a persisted expanded preference and collapses back on click", () => {- localStorage.setItem("collapseSystemPrompt", "false");-- renderChatMessage({- role: "system",- content: longSystemPrompt,- } as ChatMlMessage);-- // rendered expanded, with the caret offering to collapse- expect(expandButtons()).toHaveLength(0);- expect(collapseButtons()).toHaveLength(1);-- fireEvent.click(collapseButton()!);-- expect(expandButtons().length).toBeGreaterThan(0);- expect(localStorage.getItem("collapseSystemPrompt")).toBe("true");- });-- it("collapses a long system prompt from the header on the json/pretty path", () => {- localStorage.setItem("collapseSystemPrompt", "false");-- renderChatMessage(- { role: "system", content: longSystemPrompt } as ChatMlMessage,- { shouldRenderMarkdown: false },- );-- expect(collapseButtons()).toHaveLength(1);-- fireEvent.click(collapseButton()!);-- expect(expandButtons()).toHaveLength(1);- expect(localStorage.getItem("collapseSystemPrompt")).toBe("true");- });-- it("migrates the legacy expanded preference key and writes it through", () => {- // pre-existing "user expanded" choice under the old global key- localStorage.setItem("traceSystemPrompt:collapsed", "false");-- renderChatMessage({- role: "system",- content: longSystemPrompt,- } as ChatMlMessage);-- expect(expandButton()).not.toBeInTheDocument();- expect(collapseButton()).toBeInTheDocument();- // the choice lands under the new key even without user interaction- expect(localStorage.getItem("collapseSystemPrompt")).toBe("false");- });-- it("collapses a long system prompt sent as content parts", () => {- renderChatMessage({- role: "system",- content: [{ type: "text", text: longSystemPrompt }],- } as unknown as ChatMlMessage);-- expect(expandButton()).toBeInTheDocument();-- fireEvent.click(expandButton()!);-- expect(collapseButton()).toBeInTheDocument();- });-- it("starts open when only media parts push a system prompt over the threshold", () => {- // short text + a large image part: the serialized media must not count- // toward the long-prompt threshold- renderChatMessage({- role: "system",- content: [- { type: "text", text: "Short system prompt." },- {- type: "image_url",- image_url: { url: `data:image/png;base64,${"A".repeat(1000)}` },- },- ],- } as unknown as ChatMlMessage);-- expect(expandButton()).not.toBeInTheDocument();- expect(collapseButton()).toBeInTheDocument();- });-- it("starts open when the prompt is short enough to read at a glance", () => {- // above the char threshold, but fits within 4 lines / 500 chars- const content = Array.from(- { length: 3 },- (_, i) => `line-${i + 1} ${"x".repeat(90)}`,- ).join("\n");-- renderChatMessage({ role: "system", content } as ChatMlMessage);-- expect(expandButton()).not.toBeInTheDocument();- expect(collapseButton()).toBeInTheDocument();- });-- it("keeps the toggle functional in-session when localStorage is blocked", () => {- const throwingStorage: Storage = {- get length() {- return 0;- },- clear: () => {- throw new Error("storage blocked");- },- getItem: () => {- throw new Error("storage blocked");- },- key: () => null,- removeItem: () => {- throw new Error("storage blocked");- },- setItem: () => {- throw new Error("storage blocked");- },- };- vi.stubGlobal("localStorage", throwingStorage);-- renderChatMessage({- role: "system",- content: longSystemPrompt,- } as ChatMlMessage);-- // initial state comes from the in-memory session fallback; whichever- // toggle is offered, clicking it must flip the state- const startedExpanded = collapseButton() !== null;- fireEvent.click((startedExpanded ? collapseButton() : expandButton())!);-- if (startedExpanded) {- expect(expandButton()).toBeInTheDocument();- expect(collapseButton()).not.toBeInTheDocument();- } else {- expect(collapseButton()).toBeInTheDocument();- expect(expandButton()).not.toBeInTheDocument();- }- });-- it("does not collapse long non-system messages", () => {- renderChatMessage({- role: "user",- content: longSystemPrompt,- } as ChatMlMessage);-- expect(expandButton()).not.toBeInTheDocument();- expect(collapseButton()).not.toBeInTheDocument();- });-- it("does not collapse short system messages", () => {- renderChatMessage({- role: "system",- content: "You are a helpful assistant.",- } as ChatMlMessage);-- expect(expandButton()).not.toBeInTheDocument();- expect(collapseButton()).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");- });-});--describe("ChatMessage media content parts", () => {- const mediaId = "abc123def456ghi789jkl0";- const referenceString = `@@@langfuseMedia:type=image/png|id=${mediaId}|source=base64_data_uri@@@`;-- beforeEach(() => {- vi.stubGlobal("localStorage", createMemoryStorage());- vi.stubGlobal("sessionStorage", createMemoryStorage());- });-- // LFE-14815 / LFE-13602: OpenAIContentSchema's url union parses the media- // reference into an object, so a renderer re-validating the untransformed- // schema drops the part silently.- it("renders an image_url part carrying a langfuse media reference", () => {- renderChatMessage({- role: "user",- content: [- { type: "text", text: "here is the thermostat" },- { type: "image_url", image_url: { url: referenceString } },- ],- } as unknown as ChatMlMessage);-- expect(screen.getByText("here is the thermostat")).toBeInTheDocument();- expect(screen.getByTestId("langfuse-media")).toHaveAttribute(- "data-media-ref",- referenceString,- );- });-- it("renders an AI SDK file part carrying a langfuse media reference", () => {- renderChatMessage({- role: "user",- content: [- { type: "text", text: "attached report" },- {- type: "file",- data: referenceString,- mediaType: "image/png",- },- ],- } as unknown as ChatMlMessage);-- expect(screen.getByText("attached report")).toBeInTheDocument();- expect(screen.getByTestId("langfuse-media")).toHaveAttribute(- "data-media-ref",- referenceString,- );- });-- // LFE-9577: a single reference string renders inline, and so do several in- // one string — but an ARRAY of bare references failed OpenAIContentParts- // (which only accepted `{type, …}` objects) and dropped to a JSON table.- it("renders an array of bare media reference strings inline", () => {- const second = referenceString.replace(mediaId, "zzz987yxw654vut321srq0");- renderChatMessage({- role: "user",- content: [referenceString, second],- } as unknown as ChatMlMessage);-- expect(- screen- .getAllByTestId("langfuse-media")- .map((el) => el.getAttribute("data-media-ref")),- ).toEqual([referenceString, second]);- });-- // The ChatML transform materializes all 10 schema keys, so a message that- // normalized to `{}` used to table out one `undefined` row per key.- it("renders nothing for a parsed message that carries no data", () => {- const parsed = ChatMlArraySchema.parse([{}]);- const { container } = renderChatMessage(parsed[0] as ChatMlMessage);-- expect(container).toBeEmptyDOMElement();- });-- // Same materialized keys, but this shape has one real field so it still- // renders through the whole-message fallback table.- it("omits unset ChatML keys from the fallback table", () => {- const parsed = ChatMlArraySchema.parse([- { role: "user", name: "Agent", content: "" },- ]);- renderChatMessage(parsed[0] as ChatMlMessage);-- expect(screen.queryByText("undefined")).not.toBeInTheDocument();- expect(screen.queryByText("tool_call_id")).not.toBeInTheDocument();- });-- // A collapsed section hides its attachments with the text; expanding the- // long system prompt brings them back inline.- it("shows media parts once a long system prompt is expanded", () => {- renderChatMessage({- role: "system",- content: [- { type: "text", text: longSystemPrompt },- { type: "image_url", image_url: { url: referenceString } },- ],- } as unknown as ChatMlMessage);-- expect(screen.queryByTestId("langfuse-media")).not.toBeInTheDocument();-- fireEvent.click(expandButton()!);-- expect(screen.getByTestId("langfuse-media")).toHaveAttribute(- "data-media-ref",- referenceString,- );- });-});diff --git a/web/src/features/traces/components/IOPreview/components/ChatMessage.tsx b/web/src/features/traces/components/IOPreview/components/ChatMessage.tsxdeleted file mode 100644index 1d890f9eb3..0000000000--- a/web/src/features/traces/components/IOPreview/components/ChatMessage.tsx+++ /dev/null@@ -1,300 +0,0 @@-/* eslint-disable @repo/no-null-render */-import { useState } from "react";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";-import { MarkdownJsonView } from "@/src/components/ui/MarkdownJsonView";-import { IOSection, type IOSectionAction } from "@/src/components/ui/IOSection";-import { ToolCallInvocationsView } from "@/src/features/traces/components/ToolCallInvocationsView";-import { ListChevronsDownUp, ListChevronsUpDown } from "@langfuse/icons";-import { stringify } from "@langfuse/shared";-import { copyTextToClipboard } from "@/src/utils/clipboard";-import {- type ChatMlMessage,- getMessageTitle,- hasRenderableContent,- hasAdditionalData,- hasPassthroughJson,- isPlaceholderMessage,- isOnlyJsonMessage,- parseToolCallsFromMessage,- hasThinkingContent,- hasRedactedThinkingContent,- withoutUnsetFields,-} from "../../../fns/chatMessageUtils";-import { ThinkingBlock } from "../../ThinkingBlock";-import { RedactedThinkingBlock } from "../../RedactedThinkingBlock";-import { type IOPreviewContentMode } from "../IOPreview";--// View mode for pretty/json toggle-export type ViewMode = "pretty" | "json";--// ChatMessage props-export interface ChatMessageProps {- message: ChatMlMessage;- shouldRenderMarkdown: boolean;- currentView: ViewMode;- toolCallNumbers?: number[];- isOutputMessage?: boolean;- contentMode?: IOPreviewContentMode;- /** Render the message section collapsed to its header. */- defaultCollapsed?: boolean;- /** Section title; the caller decides (role, name, or Input / Output). */- title: string;- /** Extra header actions, after the message's own. */- actions?: IOSectionAction[];-}--/**- * ChatMessage renders a single ChatML message with appropriate view.- *- * Handles different message types:- * - Placeholder messages- * - JSON-only messages (non-ChatML objects)- * - Content messages with optional tool calls- * - Tool-call-only messages (no content)- */-export function ChatMessage({- message,- shouldRenderMarkdown,- currentView,- toolCallNumbers,- isOutputMessage,- contentMode = "all",- defaultCollapsed,- title,- actions: extraActions,-}: ChatMessageProps) {- const [showTableView, setShowTableView] = useState(false);- // The section's collapsed state lives here, so switching between the- // formatted and passthrough views keeps what the user set.- const [collapsed, setCollapsed] = useState(defaultCollapsed ?? false);- // Role-less messages still get a header (and with it their actions).- const sectionTitle = title || (isOutputMessage ? "Output" : "Input");-- const renderToolResponse = (response: ChatMlMessage) => (- <ChatMessage- message={response}- title={getMessageTitle(response)}- shouldRenderMarkdown={shouldRenderMarkdown}- currentView={currentView}- contentMode={contentMode}- />- );-- const toolCalls = parseToolCallsFromMessage(message);- const hasContent = hasRenderableContent(message);- // Collapse from the raw role: the title is the message `name` when present,- // so name-bearing system prompts would otherwise never collapse.- const isSystemPrompt = message.role === "system";- const showData = contentMode !== "conversation";-- // Toggle between the formatted message and its passthrough JSON- const passthroughAction: IOSectionAction | undefined =- showData && hasPassthroughJson(message)- ? {- icon: showTableView ? ListChevronsDownUp : ListChevronsUpDown,- label: showTableView- ? "Show formatted view"- : "Show passthrough JSON data",- onClick: () => setShowTableView((v) => !v),- active: showTableView,- }- : undefined;- const allActions = [- ...(passthroughAction ? [passthroughAction] : []),- ...(extraActions ?? []),- ];- const actions = allActions.length > 0 ? allActions : undefined;-- // A collapsed message mounts only its header: the formatted and JSON views- // (and their parsing) wait until it is expanded.- if (collapsed) {- return (- <div className="transition-colors">- <IOSection- title={sectionTitle}- collapsed- onCollapsedChange={setCollapsed}- >- {null}- </IOSection>- </div>- );- }-- // Placeholder message- if (isPlaceholderMessage(message)) {- return (- <div className="transition-colors">- <div style={{ display: shouldRenderMarkdown ? "block" : "none" }}>- <MarkdownJsonView- title="Placeholder"- content={message.name || "Unnamed placeholder"}- actions={actions}- collapsed={collapsed}- onCollapsedChange={setCollapsed}- />- </div>- <div style={{ display: shouldRenderMarkdown ? "none" : "block" }}>- <PrettyJsonView- title="Placeholder"- json={message.name || "Unnamed placeholder"}- currentView={currentView}- actions={actions}- collapsed={collapsed}- onCollapsedChange={setCollapsed}- />- </div>- </div>- );- }-- // JSON-only message (non-ChatML object)- if (isOnlyJsonMessage(message)) {- return (- <div className="transition-colors">- <PrettyJsonView- title={sectionTitle}- json={message.json}- currentView={currentView}- actions={actions}- collapsed={collapsed}- onCollapsedChange={setCollapsed}- />- </div>- );- }-- // User toggled to show passthrough JSON- if (showTableView) {- return (- <div className="transition-colors">- <PrettyJsonView- title={sectionTitle}- json={message.json}- currentView="pretty"- actions={actions}- collapsed={collapsed}- onCollapsedChange={setCollapsed}- />- </div>- );- }-- // Tool-call-only message (no content, no thinking)- if (- !hasContent &&- !hasThinkingContent(message) &&- !hasRedactedThinkingContent(message) &&- toolCalls.length > 0- ) {- return (- <IOSection- title={sectionTitle}- onCopy={() => {- // 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);- }}- actions={actions}- collapsed={collapsed}- onCollapsedChange={setCollapsed}- >- <ToolCallInvocationsView- message={message}- toolCallNumbers={toolCallNumbers}- renderResponse={renderToolResponse}- />- </IOSection>- );- }-- // Content message (with optional tool calls and thinking)- if (- hasContent ||- hasThinkingContent(message) ||- hasRedactedThinkingContent(message)- ) {- // Thinking blocks render at the top of the section box- const thinkingBlocks = (- <>- {hasThinkingContent(message) &&- message.thinking?.map((t, i) => (- <ThinkingBlock- key={`thinking-${i}`}- content={t.content}- summary={t.summary}- />- ))}- {hasRedactedThinkingContent(message) &&- message.redacted_thinking?.map((t, i) => (- <RedactedThinkingBlock key={`redacted-${i}`} data={t.data} />- ))}- </>- );-- // Tool calls render at the bottom of the same section box- const toolCallsView =- showData && toolCalls.length > 0 ? (- <ToolCallInvocationsView- className="mt-2"- message={message}- toolCallNumbers={toolCallNumbers}- renderResponse={renderToolResponse}- />- ) : undefined;-- return (- <div className="transition-colors">- {/* Markdown view */}- <div style={{ display: shouldRenderMarkdown ? "block" : "none" }}>- <MarkdownJsonView- title={sectionTitle}- content={message.content || ""}- audio={message.audio}- actions={actions}- beforeContent={thinkingBlocks}- afterContent={toolCallsView}- isSystemPrompt={isSystemPrompt}- collapsed={collapsed}- onCollapsedChange={setCollapsed}- />- </div>-- {/* JSON view */}- <div style={{ display: shouldRenderMarkdown ? "none" : "block" }}>- <PrettyJsonView- title={sectionTitle}- json={message.content}- currentView={currentView}- actions={actions}- beforeContent={thinkingBlocks}- afterContent={toolCallsView}- isSystemPrompt={isSystemPrompt}- collapsed={collapsed}- onCollapsedChange={setCollapsed}- />- </div>- </div>- );- }-- // Fallback: message with additional data but no content- if (hasAdditionalData(message)) {- return (- <div className="transition-colors">- <PrettyJsonView- title={sectionTitle}- json={withoutUnsetFields(message)}- currentView={currentView}- actions={actions}- collapsed={collapsed}- onCollapsedChange={setCollapsed}- />- </div>- );- }-- return null;-}diff --git a/web/src/features/traces/components/IOPreview/components/ChatMessageContent.tsx b/web/src/features/traces/components/IOPreview/components/ChatMessageContent.tsxnew file mode 100644index 0000000000..10269dd58f--- /dev/null+++ b/web/src/features/traces/components/IOPreview/components/ChatMessageContent.tsx@@ -0,0 +1,53 @@+import { ToolCallInvocationsView } from "@/src/features/traces/components/ToolCallInvocationsView";+import {+ hasThinkingContent,+ hasRedactedThinkingContent,+} from "../../../fns/chatMessageUtils";+import { ThinkingBlock } from "../../ThinkingBlock";+import { RedactedThinkingBlock } from "../../RedactedThinkingBlock";+import { type ChatMessageBody } from "./ChatMessageController";++export function ChatMessageContent({+ body,+ renderToolResponse,+ children,+}: {+ body: ChatMessageBody;+ renderToolResponse: React.ComponentProps<+ typeof ToolCallInvocationsView+ >["renderResponse"];+ children?: React.ReactNode;+}) {+ const { message, toolCallNumbers, showThinking, showToolCalls } = body;++ return (+ <>+ {showThinking &&+ hasThinkingContent(message) &&+ message.thinking?.map((thinking, index) => (+ <ThinkingBlock+ key={`thinking-${index}`}+ content={thinking.content}+ summary={thinking.summary}+ />+ ))}+ {showThinking &&+ hasRedactedThinkingContent(message) &&+ message.redacted_thinking?.map((thinking, index) => (+ <RedactedThinkingBlock+ key={`redacted-${index}`}+ data={thinking.data}+ />+ ))}+ {children}+ {showToolCalls && (+ <ToolCallInvocationsView+ className={showThinking ? "mt-2" : undefined}+ message={message}+ toolCallNumbers={toolCallNumbers}+ renderResponse={renderToolResponse}+ />+ )}+ </>+ );+}diff --git a/web/src/features/traces/components/IOPreview/components/ChatMessageController.tsx b/web/src/features/traces/components/IOPreview/components/ChatMessageController.tsxnew file mode 100644index 0000000000..892fe24058--- /dev/null+++ b/web/src/features/traces/components/IOPreview/components/ChatMessageController.tsx@@ -0,0 +1,160 @@+import { useState } from "react";+import { type OpenAIOutputAudioType, stringify } from "@langfuse/shared";+import { ListChevronsDownUp, ListChevronsUpDown } from "@langfuse/icons";+import { type IOSectionAction } from "@/src/components/ui/IOSection";+import { copyTextToClipboard } from "@/src/utils/clipboard";+import {+ type ChatMlMessage,+ hasRenderableContent,+ hasAdditionalData,+ hasPassthroughJson,+ isPlaceholderMessage,+ isOnlyJsonMessage,+ parseToolCallsFromMessage,+ hasThinkingContent,+ hasRedactedThinkingContent,+ withoutUnsetFields,+} from "../../../fns/chatMessageUtils";+import { type IOPreviewContentMode } from "../IOPreview";++export interface ChatMessageBody {+ message: ChatMlMessage;+ toolCallNumbers?: number[];+ showThinking: boolean;+ showToolCalls: boolean;+}++type MessageData =+ | { kind: "collapsed" }+ | { kind: "tools" }+ | { kind: "data"; value: unknown; passthrough: boolean }+ | {+ kind: "message";+ title: string;+ content: unknown;+ originalContent: unknown;+ audio?: OpenAIOutputAudioType;+ includeMessageExtras: boolean;+ };++type RenderChatMessage = (state: {+ title: string;+ data: MessageData;+ body: ChatMessageBody;+ actions: IOSectionAction[];+ isSystemPrompt: boolean;+ collapsed: boolean;+ setCollapsed: (collapsed: boolean) => void;+ copy: () => void;+}) => React.ReactNode;++export function ChatMessageController({+ message,+ toolCallNumbers,+ isOutputMessage,+ contentMode = "all",+ defaultCollapsed,+ title,+ actions: extraActions,+ children,+}: {+ message: ChatMlMessage;+ toolCallNumbers?: number[];+ isOutputMessage?: boolean;+ contentMode?: IOPreviewContentMode;+ defaultCollapsed?: boolean;+ title: string;+ actions?: IOSectionAction[];+ children: RenderChatMessage;+}) {+ const [showPassthrough, setShowPassthrough] = useState(false);+ const [collapsed, setCollapsed] = useState(defaultCollapsed ?? false);+ const sectionTitle = title || (isOutputMessage ? "Output" : "Input");+ const showData = contentMode !== "conversation";++ const data = ((): MessageData | { kind: "empty" } => {+ // Avoid content parsing while the caller is rendering only the header.+ if (collapsed) return { kind: "collapsed" };+ if (isPlaceholderMessage(message)) {+ return {+ kind: "message",+ title: "Placeholder",+ content: message.name || "Unnamed placeholder",+ originalContent: message.name || "Unnamed placeholder",+ includeMessageExtras: false,+ };+ }+ if (isOnlyJsonMessage(message)) {+ return { kind: "data", value: message.json, passthrough: false };+ }+ if (showPassthrough) {+ return { kind: "data", value: message.json, passthrough: true };+ }+ if (+ hasRenderableContent(message) ||+ hasThinkingContent(message) ||+ hasRedactedThinkingContent(message)+ ) {+ return {+ kind: "message",+ title: sectionTitle,+ content: message.content || "",+ originalContent: message.content,+ audio: message.audio,+ includeMessageExtras: true,+ };+ }+ if (parseToolCallsFromMessage(message).length > 0) return { kind: "tools" };+ if (hasAdditionalData(message)) {+ return {+ kind: "data",+ value: withoutUnsetFields(message),+ passthrough: false,+ };+ }+ return { kind: "empty" };+ })();++ if (data.kind === "empty") return null;++ const passthroughAction: IOSectionAction | undefined =+ !collapsed && showData && hasPassthroughJson(message)+ ? {+ icon: showPassthrough ? ListChevronsDownUp : ListChevronsUpDown,+ label: showPassthrough+ ? "Show formatted view"+ : "Show passthrough JSON data",+ onClick: () => setShowPassthrough((value) => !value),+ active: showPassthrough,+ }+ : undefined;+ const includeMessageExtras =+ data.kind === "message" && data.includeMessageExtras;++ return children({+ title: data.kind === "message" ? data.title : sectionTitle,+ data,+ body: {+ message,+ toolCallNumbers,+ showThinking: includeMessageExtras,+ showToolCalls:+ data.kind === "tools" ||+ (includeMessageExtras &&+ showData &&+ parseToolCallsFromMessage(message).length > 0),+ },+ actions: collapsed+ ? []+ : [+ ...(passthroughAction ? [passthroughAction] : []),+ ...(extraActions ?? []),+ ],+ // Display titles may be names, so collapse eligibility uses the raw role.+ isSystemPrompt: includeMessageExtras && message.role === "system",+ collapsed,+ setCollapsed,+ // Decode escaped Unicode consistently with the rendered view.+ copy: () => copyTextToClipboard(stringify(message, undefined, 2)),+ });+}diff --git a/web/src/features/traces/components/IOPreview/components/SectionMedia.tsx b/web/src/features/traces/components/IOPreview/components/SectionMedia.tsxdeleted file mode 100644index 55ae656aac..0000000000--- a/web/src/features/traces/components/IOPreview/components/SectionMedia.tsx+++ /dev/null@@ -1,27 +0,0 @@-import { IOSection } from "@/src/components/ui/IOSection";-import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";-import { type MediaReturnType } from "@/src/features/media";--// SectionMedia props-export interface SectionMediaProps {- media: MediaReturnType[];-}--/**- * SectionMedia renders media attachments at the bottom of the message list.- */-export function SectionMedia({ media }: SectionMediaProps) {- return (- <IOSection title="Media" variant="media">- <div className="flex flex-wrap gap-2">- {media.map((m) => (- <LangfuseMediaView- mediaAPIReturnValue={m}- variant={m.contentType.startsWith("image") ? "inline" : "icon"}- key={m.mediaId}- />- ))}- </div>- </IOSection>- );-}diff --git a/web/src/features/traces/components/IOPreview/components/SectionSkills.stories.tsx b/web/src/features/traces/components/IOPreview/components/SectionSkills.stories.tsxdeleted file mode 100644index 0030f77bfc..0000000000--- a/web/src/features/traces/components/IOPreview/components/SectionSkills.stories.tsx+++ /dev/null@@ -1,356 +0,0 @@-import { expect, userEvent, within } from "storybook/test";--import preview from "../../../../../../.storybook/preview";-import { SectionSkills } from "./SectionSkills";--const meta = preview.meta({- component: SectionSkills,- args: { toolCallsByName: new Map() },-});--export const LoadRequested = meta.story({- args: {- projectId: "storybook-project",- skills: {- kind: "available",- items: [- {- skillName: "refund-policy",- langfuseSkillId: "refund",- skillVersion: 3,- },- {- skillName: "shipping-policy",- langfuseSkillId: "shipping",- skillVersion: 1,- },- { skillName: "account-security" },- ],- },- toolCallsByName: new Map([- [- "loadSkill",- [- {- name: "loadSkill",- invocationNumber: 1,- arguments: { name: "refund-policy", version: 3 },- },- ],- ],- [- "Read",- [- {- name: "Read",- invocationNumber: 2,- arguments: { file_path: "/skills/account-security/SKILL.md" },- },- ],- ],- [- "loadSkillResource",- [- {- name: "loadSkillResource",- invocationNumber: 3,- arguments: { name: "refund-policy", path: "references/refunds.md" },- },- {- name: "loadSkillResource",- invocationNumber: 4,- arguments: { name: "refund-policy", path: "references/refunds.md" },- },- ],- ],- ]),- },-});--export const Available = meta.story({- args: {- projectId: "storybook-project",- skills: {- kind: "available",- items: [- {- skillName: "refund-policy",- langfuseSkillId: "refund",- skillVersion: 3,- },- {- skillName: "shipping-policy",- langfuseSkillId: "shipping",- skillVersion: 1,- },- {- skillName: "subscription-support",- langfuseSkillId: "subscription",- skillVersion: 2,- },- { skillName: "account-security" },- { skillName: "billing-support" },- { skillName: "return-policy" },- { skillName: "order-tracking" },- { skillName: "customer-escalation" },- { skillName: "tone-of-voice" },- { skillName: "product-guide" },- ],- },- },-});--export const SingleLoaded = meta.story({- args: {- projectId: "storybook-project",- skills: {- kind: "loaded",- items: [- {- skillName: "refund-policy",- langfuseSkillId: "refund",- skillVersion: 3,- filePath: "SKILL.md",- },- {- skillName: "refund-policy",- langfuseSkillId: "refund",- skillVersion: 3,- filePath: "references/refunds.md",- },- {- skillName: "refund-policy",- langfuseSkillId: "refund",- skillVersion: 3,- filePath: "SKILL.md",- },- ],- },- },-});--export const SingleAvailable = meta.story({- args: {- projectId: "storybook-project",- skills: {- kind: "available",- items: [- {- skillName: "refund-policy",- langfuseSkillId: "refund",- skillVersion: 3,- },- ],- },- },-});--export const LongSkillAndFileNames = meta.story({- args: {- projectId: "storybook-project",- skills: {- kind: "loaded",- items: [- {- skillName:- "enterprise-customer-support-refund-policy-and-escalation-procedures",- filePath:- "references/international-shipping/customer-refund-and-escalation-procedures.md",- },- ],- },- },-});--export const SingleLoadedShowsFiles = meta.story({- name: "(Test) Single Loaded Shows Files",- args: SingleLoaded.input.args,- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await expect(canvas.getByText("references/refunds.md")).toBeVisible();- await expect(canvas.getAllByText("SKILL.md")).toHaveLength(1);- await expect(- canvas.queryByRole("button", { name: "Files loaded for refund-policy" }),- ).toBeNull();- await expect(- canvas.getByRole("link", { name: "refund-policy" }),- ).toHaveAttribute(- "href",- "/project/storybook-project/skills/refund-policy?version=3",- );- await userEvent.click(- canvas.getByRole("button", { name: "Collapse Loaded skill" }),- );- await userEvent.click(- canvas.getByRole("button", { name: "Expand Loaded skill" }),- );- await expect(canvas.getByText("references/refunds.md")).toBeVisible();- },-});--export const Loaded = meta.story({- name: "(Test) Loaded",- args: {- projectId: "storybook-project",- skills: {- kind: "loaded",- items: [- {- skillName: "refund-policy",- langfuseSkillId: "refund",- skillVersion: 3,- filePath: "SKILL.md",- },- {- skillName: "refund-policy",- langfuseSkillId: "refund",- skillVersion: 3,- filePath: "references/refunds.md",- },- {- skillName: "shipping-policy",- langfuseSkillId: "shipping",- skillVersion: 1,- filePath: "references/international-shipping.md",- },- { skillName: "local-customer-support", filePath: "SKILL.md" },- ],- },- },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- const summary = canvas.getByRole("button", {- name: "Collapse Loaded skills",- });-- await expect(summary).toHaveAttribute("aria-expanded", "true");- const refundFiles = canvas.getByRole("button", {- name: "Files loaded for refund-policy",- });- await userEvent.click(refundFiles);- await expect(canvas.getByText("references/refunds.md")).toBeVisible();-- await userEvent.click(summary);- await userEvent.click(summary);- await expect(canvas.getByText("references/refunds.md")).toBeVisible();-- await userEvent.click(- canvas.getByRole("button", { name: "Files loaded for shipping-policy" }),- );- await expect(- canvas.getByRole("button", { name: "Files loaded for refund-policy" }),- ).toHaveAttribute("aria-expanded", "false");- await expect(- canvas.getByText("references/international-shipping.md"),- ).toBeVisible();- },-});--export const LongListStartsCollapsed = meta.story({- name: "(Test) Long List Starts Collapsed",- args: {- ...Available.input.args,- toolCallsByName: LoadRequested.input.args.toolCallsByName,- },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- const summary = canvas.getByRole("button", { name: "Expand Skills" });- await expect(within(summary).getByText("10")).toBeVisible();- await expect(canvas.queryByRole("tab")).not.toBeInTheDocument();- await userEvent.click(summary);- await userEvent.click(- canvas.getByRole("tab", { name: /^Not requested\s*8$/ }),- );- await expect(canvas.getByText("product-guide")).toBeVisible();- await userEvent.click(- canvas.getByRole("button", { name: "Collapse Skills" }),- );- await expect(within(summary).getByText("10")).toBeVisible();- },-});--export const RequestedLoadsMatchAvailableRows = meta.story({- name: "(Test) Requested Loads Match Available Rows",- args: LoadRequested.input.args,- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await expect(- canvas.getByRole("tab", { name: /^Requested\s*2$/ }),- ).toHaveAttribute("aria-selected", "true");- await expect(- canvas.queryByRole("link", { name: "shipping-policy" }),- ).toBeNull();- await expect(- canvas.getByRole("link", { name: "refund-policy" }),- ).toHaveAttribute(- "href",- "/project/storybook-project/skills/refund-policy?version=3",- );- await userEvent.click(- canvas.getByRole("button", { name: "Files requested for refund-policy" }),- );- await expect(canvas.getByText("SKILL.md")).toBeVisible();- await expect(canvas.getAllByText("references/refunds.md")).toHaveLength(1);- await expect(canvas.getByText("2 files")).toBeVisible();- await userEvent.click(- canvas.getByRole("button", { name: "Collapse Skills" }),- );- await userEvent.click(- canvas.getByRole("button", { name: "Expand Skills" }),- );- await expect(canvas.getByText("references/refunds.md")).toBeVisible();- await userEvent.click(- canvas.getByRole("button", {- name: "Files requested for account-security",- }),- );- await expect(- canvas.getByText("/skills/account-security/SKILL.md"),- ).toBeVisible();- await expect(- canvas.getByRole("button", { name: "Files requested for refund-policy" }),- ).toHaveAttribute("aria-expanded", "false");- await userEvent.click(- canvas.getByRole("tab", { name: /^Not requested\s*1$/ }),- );- await expect(- canvas.getByRole("link", { name: "shipping-policy" }),- ).toBeVisible();- await expect(- canvas.queryByRole("link", { name: "refund-policy" }),- ).toBeNull();- await expect(- canvas.queryByRole("button", { name: /Files requested/ }),- ).toBeNull();- await userEvent.click(canvas.getByRole("tab", { name: /^Requested\s*2$/ }));- await expect(- canvas.getByRole("button", { name: "Files requested for refund-policy" }),- ).toHaveAttribute("aria-expanded", "false");- },-});--export const AllRequested = meta.story({- name: "(Test) All Requested",- args: {- ...LoadRequested.input.args,- skills: {- kind: "available",- items: [- {- skillName: "refund-policy",- langfuseSkillId: "refund",- skillVersion: 3,- },- ],- },- },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await expect(canvas.queryByRole("tab")).toBeNull();- await userEvent.click(- canvas.getByRole("button", { name: "Files requested for refund-policy" }),- );- await expect(canvas.getByText("SKILL.md")).toBeVisible();- await expect(canvas.getByText("references/refunds.md")).toBeVisible();- },-});diff --git a/web/src/features/traces/components/IOPreview/components/SectionSkills.tsx b/web/src/features/traces/components/IOPreview/components/SectionSkills.tsxdeleted file mode 100644index 9704bd83c6..0000000000--- a/web/src/features/traces/components/IOPreview/components/SectionSkills.tsx+++ /dev/null@@ -1,266 +0,0 @@-import { useState } from "react";-import {- type SkillsAvailable,- type SkillsResourceLoaded,-} from "@langfuse/shared";-import { FileCode2, FileText } from "@langfuse/icons";--import { Badge } from "@/src/components/design-system/Badge/Badge";-import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";-import { LinkBadge } from "@/src/components/design-system/LinkBadge/LinkBadge";-import {- Collapsible,- CollapsibleContent,- CollapsibleTrigger,-} from "@/src/components/ui/collapsible";-import { IOSection } from "@/src/components/ui/IOSection";-import { cn } from "@/src/utils/tailwind";-import { getSkillLoadRequests } from "../../../fns/getSkillLoadRequests";-import type { ToolCallInvocation } from "../../../hooks/useChatMLParser";--export function SectionSkills({- projectId,- skills,- toolCallsByName,-}: SectionSkillsProps) {- const [expandedSkillKey, setExpandedSkillKey] = useState("");- const [activeTab, setActiveTab] = useState("requested");- const groups = groupSkills(skills.items);- const [collapsed, setCollapsed] = useState(groups.length > 5);- const loadRequests = getSkillLoadRequests(- skills.kind === "available" ? groups.map((group) => group.skill) : [],- toolCallsByName,- );- const singleLoadedSkill =- skills.kind === "loaded" && groups.length === 1 ? groups[0] : undefined;- const title = skills.kind === "available" ? "Skills" : "Loaded skills";- const requestedGroups = groups.filter((group) =>- loadRequests.has(group.skill),- );- const notRequestedGroups = groups.filter(- (group) => !loadRequests.has(group.skill),- );- const hasSwitch = requestedGroups.length > 0 && notRequestedGroups.length > 0;- const tabGroups =- activeTab === "requested" ? requestedGroups : notRequestedGroups;- const visibleGroups = hasSwitch ? tabGroups : groups;-- return (- <IOSection- title={singleLoadedSkill ? "Loaded skill" : title}- count={- singleLoadedSkill || (hasSwitch && !collapsed)- ? undefined- : groups.length- }- variant="table"- collapsed={collapsed}- onCollapsedChange={setCollapsed}- tabs={- hasSwitch- ? {- value: activeTab,- onValueChange: (value) => {- setActiveTab(value);- setExpandedSkillKey("");- },- items: [- {- value: "requested",- label: "Requested",- count: requestedGroups.length,- },- {- value: "not-requested",- label: "Not requested",- count: notRequestedGroups.length,- },- ],- }- : undefined- }- info={- loadRequests.size > 0- ? {- label: "About skill load requests",- text: `${loadRequests.size} of ${groups.length} available skills requested by this generation's output tool calls. A request does not confirm that the skill was loaded successfully.`,- }- : undefined- }- >- {singleLoadedSkill ? (- <div className="min-w-0">- <div className="flex min-w-0 items-center gap-2 pb-1.5">- <FileCode2 size="base" color="muted" aria-hidden />- <SkillIdentity- projectId={projectId}- skill={singleLoadedSkill.skill}- />- </div>- <div className="border-border border-t py-3 pl-5.5">- <SkillFiles files={singleLoadedSkill.files} />- </div>- </div>- ) : (- <ul className="divide-border flex flex-col divide-y">- {visibleGroups.map((group, index) => (- <SkillRow- key={group.key}- projectId={projectId}- group={- skills.kind === "available"- ? {- ...group,- files: loadRequests.get(group.skill) ?? new Set<string>(),- }- : group- }- rowNumber={index + 1}- expanded={expandedSkillKey === group.key}- onExpandedChange={setExpandedSkillKey}- fileState={skills.kind === "available" ? "requested" : "loaded"}- />- ))}- </ul>- )}- </IOSection>- );-}--function SkillRow({- projectId,- group,- rowNumber,- expanded,- onExpandedChange,- fileState,-}: SkillRowProps) {- const { skill, files } = group;-- function handleOpenChange(open: boolean) {- onExpandedChange(open ? group.key : "");- }-- return (- <Collapsible asChild open={expanded} onOpenChange={handleOpenChange}>- <li className="group/skill-row min-w-0">- <div- className={cn(- "flex min-w-0 items-center gap-2 py-1.5 group-first/skill-row:pt-0",- !expanded && "group-last/skill-row:pb-0",- )}- >- {files.size > 0 ? (- <CollapsibleTrigger- className="hover:bg-muted/20 flex shrink-0 cursor-pointer items-center rounded-sm"- aria-label={`Files ${fileState} for ${skill.skillName}`}- >- <DropdownIndicator direction={expanded ? "down" : "right"} />- </CollapsibleTrigger>- ) : null}- <FileCode2 size="base" color="muted" aria-hidden />- <span className="text-foreground text-sm">{rowNumber}.</span>- <SkillIdentity projectId={projectId} skill={skill} />- {files.size > 0 ? (- <span className="text-muted-foreground shrink-0 text-xs">- {files.size} {files.size === 1 ? "file" : "files"}- </span>- ) : null}- </div>- {files.size > 0 ? (- <CollapsibleContent className="border-border border-t py-3 pl-11">- <SkillFiles files={files} />- </CollapsibleContent>- ) : null}- </li>- </Collapsible>- );-}--function SkillIdentity({- projectId,- skill,-}: {- projectId: string;- skill: SkillsAvailable[number];-}) {- return (- <div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1">- {skill.langfuseSkillId && skill.skillVersion != null ? (- <LinkBadge- href={`/project/${projectId}/skills/${encodeURIComponent(skill.skillName)}?version=${skill.skillVersion}`}- text={skill.skillName}- newTab- noCapture- />- ) : (- <span className="min-w-0 truncate text-sm" title={skill.skillName}>- {skill.skillName}- </span>- )}- {skill.skillVersion != null ? (- <Badge color="filled" size="sm" text={`v${skill.skillVersion}`} />- ) : null}- </div>- );-}--function SkillFiles({ files }: { files: Set<string> }) {- return (- <ul className="flex flex-col gap-2">- {Array.from(files, (filePath) => (- <li key={filePath} className="flex min-w-0 items-start gap-2">- <FileText- size="base"- color="muted"- __rawClassName="mt-0.5"- aria-hidden- />- <span className="min-w-0 font-mono text-xs leading-relaxed break-all">- {filePath}- </span>- </li>- ))}- </ul>- );-}--function groupSkills(- items: SectionSkillsProps["skills"]["items"],-): SkillGroup[] {- const groups = new Map<string, SkillGroup>();- for (const skill of items) {- const key = JSON.stringify([- skill.langfuseSkillId ?? null,- skill.skillName,- skill.skillVersion ?? null,- ]);- const group = groups.get(key) ?? { key, skill, files: new Set<string>() };- groups.set(key, group);- if ("filePath" in skill) group.files.add(skill.filePath);- }- return Array.from(groups.values());-}--export interface SectionSkillsProps {- projectId: string;- toolCallsByName: Map<string, ToolCallInvocation[]>;- skills:- | { kind: "available"; items: SkillsAvailable }- | { kind: "loaded"; items: SkillsResourceLoaded };-}--type SkillRowProps = {- projectId: string;- group: SkillGroup;- rowNumber: number;- expanded: boolean;- onExpandedChange: (key: string) => void;- fileState: "requested" | "loaded";-};--type SkillGroup = {- key: string;- skill: SkillsAvailable[number];- files: Set<string>;-};diff --git a/web/src/features/traces/components/IOPreview/components/SectionToolDefinitions.stories.tsx b/web/src/features/traces/components/IOPreview/components/SectionToolDefinitions.stories.tsxdeleted file mode 100644index eb793affe7..0000000000--- a/web/src/features/traces/components/IOPreview/components/SectionToolDefinitions.stories.tsx+++ /dev/null@@ -1,304 +0,0 @@-import { expect, userEvent, within } from "storybook/test";--import preview from "../../../../../../.storybook/preview";-import type { ToolDefinition } from "./ToolCallDefinitionCard";-import { SectionToolDefinitions } from "./SectionToolDefinitions";-import type { ToolCallInvocation } from "../../../hooks/useChatMLParser";--const baseTools: ToolDefinition[] = [- {- name: "search_docs",- description: "Searches product docs for relevant troubleshooting steps.",- parameters: {- type: "object",- properties: {- query: {- type: "string",- description: "What to search for",- },- limit: {- type: "number",- description: "Maximum number of results",- },- },- required: ["query"],- },- },-];--const baseToolCalls = new Map<string, ToolCallInvocation[]>([- [- "search_docs",- [- {- id: "call_01HXYZ123",- name: "search_docs",- invocationNumber: 1,- arguments: JSON.stringify({ query: "rate limits", limit: 3 }),- },- ],- ],-]);--const meta = preview.meta({- component: SectionToolDefinitions,-});--export const Default = meta.story({- args: {- tools: baseTools,- toolCallCounts: new Map([["search_docs", 0]]),- toolCallsByName: new Map(),- },-});--export const Called = meta.story({- args: {- tools: baseTools,- toolCallCounts: new Map([["search_docs", 1]]),- toolCallsByName: baseToolCalls,- },-});--export const MultipleTools = meta.story({- args: {- tools: [- ...baseTools,- {- name: "create_ticket",- description: "Creates a support escalation ticket.",- parameters: {- type: "object",- properties: {- title: { type: "string" },- priority: { type: "string", enum: ["low", "high"] },- },- required: ["title", "priority"],- },- },- {- name: "notify_team",- },- ],- toolCallCounts: new Map([- ["search_docs", 2],- ["create_ticket", 1],- ["notify_team", 0],- ]),- toolCallsByName: new Map<string, ToolCallInvocation[]>([- [- "search_docs",- [- {- id: "call_01HXYZ123",- name: "search_docs",- invocationNumber: 1,- arguments: JSON.stringify({ query: "rate limits", limit: 3 }),- },- {- id: "call_01HXYZ124",- name: "search_docs",- invocationNumber: 2,- arguments: JSON.stringify({ query: "retry policy" }),- },- ],- ],- [- "create_ticket",- [- {- id: "call_01HXYZ200",- name: "create_ticket",- invocationNumber: 1,- arguments: {- title: "API requests failing",- priority: "high",- },- },- ],- ],- ]),- },-});--export const WithLongToolNames = meta.story({- args: {- tools: [- {- name: "search_enterprise_customer_documentation_for_multistep_api_rate_limit_troubleshooting_and_backoff_recommendations",- description:- "Looks up long-form support guidance for enterprise API incidents.",- parameters: {- type: "object",- properties: {- query: { type: "string" },- },- required: ["query"],- },- },- {- name: "create_cross_functional_incident_escalation_ticket_with_customer_context_and_internal_follow_up_requirements",- description: "Creates a detailed incident escalation ticket.",- },- ],- toolCallCounts: new Map([- [- "search_enterprise_customer_documentation_for_multistep_api_rate_limit_troubleshooting_and_backoff_recommendations",- 1,- ],- [- "create_cross_functional_incident_escalation_ticket_with_customer_context_and_internal_follow_up_requirements",- 0,- ],- ]),- toolCallsByName: new Map<string, ToolCallInvocation[]>([- [- "search_enterprise_customer_documentation_for_multistep_api_rate_limit_troubleshooting_and_backoff_recommendations",- [- {- id: "call_long_01",- name: "search_enterprise_customer_documentation_for_multistep_api_rate_limit_troubleshooting_and_backoff_recommendations",- invocationNumber: 1,- arguments: JSON.stringify({ query: "429 retry guidance" }),- },- ],- ],- ]),- },-});--const manyToolNames = [- "langfuse_getPrompt",- "langfuse_getPromptUnresolved",- "langfuse_listPrompts",- "langfuse_listObservations",- "langfuse_getObservation",- "langfuse_getObservationFieldSchema",- "langfuse_getObservationFilterSchema",- "langfuse_getObservationFilterValues",- "langfuse_listAnnotationQueues",- "langfuse_getAnnotationQueue",- "langfuse_listAnnotationQueueItems",- "langfuse_createScoreConfigForProject",- "langfuse_searchLangfuseDocs",- "langfuse_proposeRedirect",- "langfuse_listDatasets",- "langfuse_getDataset",- "langfuse_listSessions",- "langfuse_getSession",-];-const calledNames = new Set(manyToolNames.slice(12));--/** Both sides have tools, so the header shows the Called / Not called switch. */-export const ManyTools = meta.story({- args: {- tools: manyToolNames.map((name) => ({ name })),- toolCallCounts: new Map(- manyToolNames.map((name) => [name, calledNames.has(name) ? 1 : 0]),- ),- toolCallsByName: new Map(),- defaultCollapsed: false,- },-});--/** Nothing called: no switch, one list. */-export const NoneCalled = meta.story({- args: {- tools: manyToolNames.map((name) => ({ name })),- toolCallCounts: new Map(manyToolNames.map((name) => [name, 0])),- toolCallsByName: new Map(),- defaultCollapsed: false,- },-});--/** Everything called: no switch, one list. */-export const AllCalled = meta.story({- args: {- tools: manyToolNames.map((name) => ({ name })),- toolCallCounts: new Map(manyToolNames.map((name) => [name, 1])),- toolCallsByName: new Map(),- defaultCollapsed: false,- },-});--const TOOLS_COLLAPSED_KEY = "toolsSectionCollapsed";-/** Stories start without a remembered collapse choice. */-const forgetCollapse = () => {- sessionStorage.removeItem(TOOLS_COLLAPSED_KEY);-};--export const NotCalledTab = meta.story({- name: "(Test) Not Called Tab",- beforeEach: forgetCollapse,- args: ManyTools.input.args,- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await expect(- canvas.getByRole("tab", { name: /^Called\s*6$/ }),- ).toHaveAttribute("aria-selected", "true");- await expect(- canvas.getByRole("button", {- name: /^1\.\s*langfuse_searchLangfuseDocs$/,- }),- ).toBeVisible();- await userEvent.click(- canvas.getByRole("tab", { name: /^Not called\s*12$/ }),- );- await expect(- canvas.getByRole("button", { name: /^1\.\s*langfuse_getPrompt$/ }),- ).toBeVisible();- await expect(canvas.queryByText("langfuse_getSession")).toBeNull();- },-});--/** One side empty: no switch, the whole list shows. */-export const NoSwitchWhenOneSideEmpty = meta.story({- name: "(Test) No Switch When One Side Empty",- beforeEach: forgetCollapse,- args: NoneCalled.input.args,- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await expect(canvas.queryByRole("tab")).toBeNull();- await expect(- canvas.getByRole("button", { name: /^18\.\s*langfuse_getSession$/ }),- ).toBeVisible();- },-});--export const RowTogglesDetails = meta.story({- name: "(Test) Row Toggles Details",- beforeEach: forgetCollapse,- args: Called.input.args,- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- const row = canvas.getByRole("button", { name: /^1\.\s*search_docs$/ });- await expect(row).toHaveAttribute("aria-expanded", "false");- await expect(canvas.queryByText("Description")).toBeNull();- await userEvent.click(row);- await expect(row).toHaveAttribute("aria-expanded", "true");- await expect(canvas.getByText("Description")).toBeVisible();- await userEvent.click(row);- await expect(row).toHaveAttribute("aria-expanded", "false");- },-});--/** More than five tools: collapsed to the header, switch hidden; opening it is remembered for the session. */-export const CollapsedByDefault = meta.story({- name: "(Test) Collapsed By Default",- beforeEach: forgetCollapse,- args: { ...ManyTools.input.args, defaultCollapsed: undefined },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- const header = canvas.getByRole("button", { name: "Expand Tools" });- await expect(header).toHaveAttribute("aria-expanded", "false");- await expect(canvas.queryByRole("tab")).toBeNull();-- await userEvent.click(header);- await expect(header).toHaveAttribute("aria-expanded", "true");- await expect(- canvas.getByRole("tab", { name: /^Called\s*6$/ }),- ).toBeVisible();- await expect(sessionStorage.getItem(TOOLS_COLLAPSED_KEY)).toBe("false");- sessionStorage.removeItem(TOOLS_COLLAPSED_KEY);- },-});diff --git a/web/src/features/traces/components/IOPreview/components/SectionToolDefinitions.tsx b/web/src/features/traces/components/IOPreview/components/SectionToolDefinitions.tsxdeleted file mode 100644index 30b65b51d1..0000000000--- a/web/src/features/traces/components/IOPreview/components/SectionToolDefinitions.tsx+++ /dev/null@@ -1,99 +0,0 @@-import { useMemo, useState } from "react";-import { IOSection } from "@/src/components/ui/IOSection";-import useSessionStorage from "@/src/components/useSessionStorage";-import {- ToolCallDefinitionCard,- type ToolDefinition,-} from "./ToolCallDefinitionCard";-import type { ToolCallInvocation } from "../../../hooks/useChatMLParser";--// SectionToolDefinitions props-export interface SectionToolDefinitionsProps {- tools: ToolDefinition[];- toolCallCounts: Map<string, number>;- toolCallsByName: Map<string, ToolCallInvocation[]>;- /** Initial state before the user toggles; by default long lists (more than five tools) start collapsed. */- defaultCollapsed?: boolean;-}--type ToolTab = "called" | "not-called";--/** Above this many tools the section starts collapsed. */-const TOOLS_COLLAPSE_THRESHOLD = 5;-/** The user's collapse choice lasts the session, across observations. */-const TOOLS_COLLAPSED_KEY = "toolsSectionCollapsed";--/**- * SectionToolDefinitions renders the Tools section at the top of IOPreview:- * an IOSection whose header carries a Called / Not called switch (only when- * both sides have tools) over the active tab's tools, numbered from 1.- */-export function SectionToolDefinitions({- tools,- toolCallCounts,- toolCallsByName,- defaultCollapsed,-}: SectionToolDefinitionsProps) {- const [activeTab, setActiveTab] = useState<ToolTab>("called");- const [storedCollapsed, setStoredCollapsed] = useSessionStorage<- boolean | null- >(TOOLS_COLLAPSED_KEY, null);-- const { calledTools, notCalledTools } = useMemo(- () =>- tools.reduce(- (groups, tool) => {- if ((toolCallCounts.get(tool.name) ?? 0) > 0) {- groups.calledTools.push(tool);- } else {- groups.notCalledTools.push(tool);- }- return groups;- },- {- calledTools: [] as ToolDefinition[],- notCalledTools: [] as ToolDefinition[],- },- ),- [tools, toolCallCounts],- );-- const hasSwitch = calledTools.length > 0 && notCalledTools.length > 0;- const tabTools = activeTab === "called" ? calledTools : notCalledTools;- const visibleTools = hasSwitch ? tabTools : tools;-- return (- <IOSection- title="Tools"- variant="table"- collapsed={- storedCollapsed ??- defaultCollapsed ??- tools.length > TOOLS_COLLAPSE_THRESHOLD- }- onCollapsedChange={setStoredCollapsed}- tabs={- hasSwitch- ? {- value: activeTab,- onValueChange: (value) => setActiveTab(value as ToolTab),- items: [- { value: "called", label: "Called", count: calledTools.length },- {- value: "not-called",- label: "Not called",- count: notCalledTools.length,- },- ],- }- : undefined- }- >- <ToolCallDefinitionCard- key={activeTab}- tools={visibleTools}- toolCallsByName={toolCallsByName}- />- </IOSection>- );-}diff --git a/web/src/features/traces/components/IOPreview/components/StatusMessageSection.stories.tsx b/web/src/features/traces/components/IOPreview/components/StatusMessageSection.stories.tsxdeleted file mode 100644index 7e82873961..0000000000--- a/web/src/features/traces/components/IOPreview/components/StatusMessageSection.stories.tsx+++ /dev/null@@ -1,52 +0,0 @@-import preview from "../../../../../../.storybook/preview";-import { StatusMessageSection } from "./StatusMessageSection";-import { expect } from "storybook/test";--const meta = preview.meta({- component: StatusMessageSection,-});--export const Default = meta.story({- args: {- currentView: "pretty",- status: {- level: "DEFAULT",- message: "The observation completed with additional status details.",- },- },-});--export const Debug = meta.story({- args: {- currentView: "pretty",- status: {- level: "DEBUG",- message: "Detailed diagnostic information for this observation.",- },- },-});--export const Warning = meta.story({- args: {- currentView: "pretty",- status: {- level: "WARNING",- message: "The observation completed with a recoverable warning.",- },- },-});--export const Error = meta.story({- name: "(Test) Renders Error Message",- args: {- currentView: "pretty",- status: {- level: "ERROR",- message: "Upstream model request timed out after 30 seconds.",- },- },- play: async ({ canvas, args }) => {- await expect(canvas.getByText("Error")).toBeVisible();- await expect(canvas.getByText(args.status.message)).toBeVisible();- },-});diff --git a/web/src/features/traces/components/IOPreview/components/StatusMessageSection.tsx b/web/src/features/traces/components/IOPreview/components/StatusMessageSection.tsxdeleted file mode 100644index e891b07334..0000000000--- a/web/src/features/traces/components/IOPreview/components/StatusMessageSection.tsx+++ /dev/null@@ -1,45 +0,0 @@-import { useMemo } from "react";-import { IOSection } from "@/src/components/ui/IOSection";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";-import { copyTextToClipboard } from "@/src/utils/clipboard";-import {- getStatusMessagePresentation,- parseStructuredStatusMessage,- type ObservationStatusMessage,-} from "./statusMessagePresentation";--export function StatusMessageSection({- status,- currentView,-}: {- status: ObservationStatusMessage;- currentView: "pretty" | "json";-}) {- const presentation = getStatusMessagePresentation(status.level);- const parsedStatusMessage = useMemo(- () => parseStructuredStatusMessage(status.message),- [status.message],- );-- if (parsedStatusMessage !== undefined) {- return (- <PrettyJsonView- title={presentation.title}- json={status.message}- parsedJson={parsedStatusMessage}- currentView={currentView}- tone={presentation.tone}- />- );- }-- return (- <IOSection- title={presentation.title}- onCopy={() => copyTextToClipboard(status.message)}- tone={presentation.tone}- >- {status.message}- </IOSection>- );-}diff --git a/web/src/features/traces/components/IOPreview/components/SystemPromptCollapseController.tsx b/web/src/features/traces/components/IOPreview/components/SystemPromptCollapseController.tsxnew file mode 100644index 0000000000..097a98709c--- /dev/null+++ b/web/src/features/traces/components/IOPreview/components/SystemPromptCollapseController.tsx@@ -0,0 +1,32 @@+import { useCollapsibleSystemPrompt } from "@/src/hooks/useCollapsibleSystemPrompt";++export function SystemPromptCollapseController({+ isSystemPrompt,+ text,+ collapsed,+ setCollapsed,+ children,+}: {+ isSystemPrompt: boolean;+ text: string;+ collapsed: boolean;+ setCollapsed: (collapsed: boolean) => void;+ children: (state: {+ collapsed: boolean;+ setCollapsed: (collapsed: boolean) => void;+ }) => React.ReactNode;+}) {+ const systemPrompt = useCollapsibleSystemPrompt({+ isSystemPrompt,+ content: text,+ });++ return children({+ collapsed: systemPrompt.shouldBeCollapsible+ ? systemPrompt.isCollapsed+ : collapsed,+ setCollapsed: systemPrompt.shouldBeCollapsible+ ? systemPrompt.toggleCollapsed+ : setCollapsed,+ });+}diff --git a/web/src/features/traces/components/IOPreview/components/ToolCallDefinitionCard.tsx b/web/src/features/traces/components/IOPreview/components/ToolCallDefinitionCard.tsxindex 6cee2ff0e9..e65d1e8ae1 100644--- a/web/src/features/traces/components/IOPreview/components/ToolCallDefinitionCard.tsx+++ b/web/src/features/traces/components/IOPreview/components/ToolCallDefinitionCard.tsx@@ -1,7 +1,9 @@/* eslint-disable @repo/no-style-props */++import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import { ChevronDown, ChevronRight, Wrench } from "@langfuse/icons";import { cn } from "@/src/utils/tailwind";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { Tabs } from "@/src/components/design-system/Tabs/Tabs";import useLocalStorage from "@/src/components/useLocalStorage";import { useState } from "react";@@ -76,7 +78,6 @@ function ToolCallArgumentsList({<PrettyJsonViewjson={parseToolCallArguments(toolCall.arguments)}currentView="pretty"- codeClassName="text-xs"/>) : (<div className="text-muted-foreground rounded-sm border px-2 py-1.5 text-xs">@@ -169,7 +170,6 @@ function ToolDefinitionRow({<PrettyJsonViewjson={tool.parameters}currentView={currentView === "json" ? "json" : "pretty"}- codeClassName="text-xs"/></div>)}@@ -200,7 +200,7 @@ function ToolDefinitionRow({/*** ToolCallDefinitionCard renders tools as expandable rows numbered from 1.* The section header, its collapse and the Called / Not called switch- * belong to the hosting IOSection (see SectionToolDefinitions).+ * belong to the hosting IOSection in IOPreviewPretty.*/export function ToolCallDefinitionCard({tools,diff --git a/web/src/features/traces/components/IOPreview/hooks/useStatusMessage.ts b/web/src/features/traces/components/IOPreview/hooks/useStatusMessage.tsnew file mode 100644index 0000000000..829213c52b--- /dev/null+++ b/web/src/features/traces/components/IOPreview/hooks/useStatusMessage.ts@@ -0,0 +1,19 @@+import { useMemo } from "react";+import {+ getStatusMessagePresentation,+ parseStructuredStatusMessage,+ type ObservationStatusMessage,+} from "../components/statusMessagePresentation";++export function useStatusMessage(status: ObservationStatusMessage | undefined) {+ const statusPresentation = status+ ? getStatusMessagePresentation(status.level)+ : undefined;+ const message = status?.message;+ const parsedStatusMessage = useMemo(() => {+ if (message === undefined) return undefined;+ return parseStructuredStatusMessage(message);+ }, [message]);++ return { statusPresentation, parsedStatusMessage };+}diff --git a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsxindex 1f5fdc7fd3..14974639b0 100644--- a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx+++ b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx@@ -66,7 +66,7 @@ import {import { useHasProjectAccess } from "@/src/features/rbac";import { useSession } from "next-auth/react";import { ObservationPreview } from "./ObservationPreview";-import type { SectionSkillsProps } from "../IOPreview/components/SectionSkills";+import type { IOPreviewPretty } from "../IOPreview/IOPreviewPretty";import {useInternalFeaturesEnabled,useIsFeatureEnabled,@@ -616,7 +616,7 @@ function getPreviewSkills({observationType,skillsAvailable,skillsResourceLoaded,-}: PreviewSkillsInput): SectionSkillsProps["skills"] | undefined {+}: PreviewSkillsInput): React.ComponentProps<typeof IOPreviewPretty>["skills"] {if (!skillManagementEnabled) return undefined;if (observationType === "GENERATION") {return { kind: "available", items: skillsAvailable ?? [] };diff --git a/web/src/features/traces/components/ToolCallInvocationsView.tsx b/web/src/features/traces/components/ToolCallInvocationsView.tsxindex d3ea094762..4d49ade91c 100644--- a/web/src/features/traces/components/ToolCallInvocationsView.tsx+++ b/web/src/features/traces/components/ToolCallInvocationsView.tsx@@ -112,11 +112,7 @@ export function ToolCallInvocationsView({Arguments</div>)}- <PrettyJsonView- json={parsedArguments}- currentView="pretty"- codeClassName="text-xs"- />+ <PrettyJsonView json={parsedArguments} currentView="pretty" /></div>{/* Response view: paired tool result. Only the normalized-parser@@ -135,7 +131,6 @@ export function ToolCallInvocationsView({<PrettyJsonViewjson={parseIfJsonString(response.output)}currentView="pretty"- codeClassName="text-xs"/>)}</div>diff --git a/web/src/features/traces/components/TraceLogView/LogViewExpandedContent.tsx b/web/src/features/traces/components/TraceLogView/LogViewExpandedContent.tsxindex f33acd5bd5..d7073cdd7a 100644--- a/web/src/features/traces/components/TraceLogView/LogViewExpandedContent.tsx+++ b/web/src/features/traces/components/TraceLogView/LogViewExpandedContent.tsx@@ -5,8 +5,9 @@* The header row is handled by JSONTableView.*/-import { memo, useMemo } from "react";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { memo, useMemo } from "react";+import { type TreeNode } from "@/src/features/traces/types/treeNode";import { useLogViewObservationIO } from "./useLogViewObservationIO";import { Spinner } from "@/src/components/design-system/Spinner/Spinner";@@ -70,7 +71,7 @@ export const LogViewExpandedContent = memo(function LogViewExpandedContent({}, [data]);return (- <div className="w-full">+ <div className="w-full [&_.border]:border-0 [&_.io-message-content]:p-0 [&_.rounded-sm]:rounded-none [&_td:first-child]:pl-6 [&_th]:h-6 [&_th]:text-xs [&_th:first-child]:pl-6">{isLoading && (<div className="flex items-center justify-center py-4"><Spinner size="sm" variant="muted" />@@ -90,12 +91,11 @@ export const LogViewExpandedContent = memo(function LogViewExpandedContent({currentView={toPrettyOrJsonView(currentView)}isLoading={false}showNullValues={false}- stickyTopLevelKey={false}- showObservationTypeBadge={true}- scrollable={true}externalExpansionState={externalExpansionState}onExternalExpansionChange={onExternalExpansionChange}- className="w-full [&_.border]:border-0 [&_.io-message-content]:p-0 [&_.rounded-sm]:rounded-none [&_td:first-child]:pl-6 [&_th]:h-6 [&_th]:text-xs [&_th:first-child]:pl-6"+ stickyTopLevelKey={false}+ showObservationTypeBadge+ scrollable/>)}diff --git a/web/src/features/traces/index.ts b/web/src/features/traces/index.tsindex 6208408d36..382f8bc8d2 100644--- a/web/src/features/traces/index.ts+++ b/web/src/features/traces/index.ts@@ -24,12 +24,11 @@ export {type IOPreviewContentMode,type ViewMode,} from "@/src/features/traces/components/IOPreview/IOPreview";-export { ChatMessageList } from "@/src/features/traces/components/ChatMessageList";export { ThinkingBlock } from "@/src/features/traces/components/ThinkingBlock";export {- getMessageTitle,hasRenderableConversationMessages,isOnlyJsonMessage,+ shouldRenderMessageForContentMode,} from "@/src/features/traces/fns/chatMessageUtils";export {useChatMLParser,diff --git a/web/src/components/ui/PrettyJsonView.clienttest.ts b/web/src/utils/decodeUnicodeInJson.clienttest.tssimilarity index 99%rename from web/src/components/ui/PrettyJsonView.clienttest.tsrename to web/src/utils/decodeUnicodeInJson.clienttest.tsindex 0bf283cf9a..ab55af0afc 100644--- a/web/src/components/ui/PrettyJsonView.clienttest.ts+++ b/web/src/utils/decodeUnicodeInJson.clienttest.ts@@ -4,7 +4,7 @@ import {decodeUnicodeInJson,DECODE_UNICODE_MAX_DEPTH,DECODE_UNICODE_MAX_NODES,-} from "@/src/components/ui/PrettyJsonView";+} from "./decodeUnicodeInJson";describe("decodeUnicodeInJson", () => {it("decodes \\uXXXX sequences in string values", () => {