🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(web): boxed, sticky I/O sections with a collapse caret (#18684)
Trang Nguyen60acb0e4d92a
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b761b1ec73..acb06c026a 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -583,7 +583,7 @@ The background color of the following component will be `hsl(var(--primary))` an| --find-match-selected-foreground | Foreground color for selected search matches | CodeMirrorEditor || --find-match-background | Background color for search matches | CodeMirrorEditor || --surface-sunken | Off-white panel behind detail content (99%, lighter than zinc-50) | Trace detail panel, nav sidebar |-| --surface-output | Background of output blocks in the trace preview (zinc-100) | IOPreview, MarkdownViewer, CodeView |+| --surface-section | Grey box behind every I/O section body in the trace preview | IOSection, IOPreview, CodeView || --line-dotted | Dotted connector lines; dimmed in dark | dotted-line-y, prompt timeline || --surface | Sticky table chrome fill; follows --surface-context | Table headers, footers || --observation-<type>-line | Observation type colour for stroked icons and borders | ItemTypeIcon, graph nodes |diff --git a/web/.storybook/docs/ThemeTokens/Color.tsx b/web/.storybook/docs/ThemeTokens/Color.tsxindex 6ddb0e36c0..d97657a21b 100644--- a/web/.storybook/docs/ThemeTokens/Color.tsx+++ b/web/.storybook/docs/ThemeTokens/Color.tsx@@ -86,7 +86,7 @@ const SECTION_MATCHERS: Array<{{id: "surfaces",test: (n) =>- /^--(?:background|foreground|foreground-secondary|foreground-tertiary|icon|muted|surface-code(?:-header)?|popover|card|modal|header)(?:-foreground)?$/.test(+ /^--(?:background|foreground|foreground-secondary|foreground-tertiary|icon|muted|surface-code(?:-header)?|surface-section|popover|card|modal|header)(?:-foreground)?$/.test(n,),},diff --git a/web/src/components/design-system/CodeSection/CodeSection.tsx b/web/src/components/design-system/CodeSection/CodeSection.tsxindex 590d28dcff..dd6105deac 100644--- a/web/src/components/design-system/CodeSection/CodeSection.tsx+++ b/web/src/components/design-system/CodeSection/CodeSection.tsx@@ -17,7 +17,7 @@ import { useCopyToClipboard } from "@/src/hooks/useCopyToClipboard";const bodyVariants = cva("relative flex min-w-0 max-w-full items-start", {variants: {variant: {- filled: "bg-surface-output rounded-md",+ filled: "bg-surface-section rounded-md",outline: "bg-background rounded-md border",plain: null,},diff --git a/web/src/components/design-system/StatusMessage/StatusMessage.tsx b/web/src/components/design-system/StatusMessage/StatusMessage.tsxindex 64f17e5702..39ce278147 100644--- a/web/src/components/design-system/StatusMessage/StatusMessage.tsx+++ b/web/src/components/design-system/StatusMessage/StatusMessage.tsx@@ -11,8 +11,8 @@ const statusMessageVariants = cva("dark:border-dark-red/20 dark:bg-light-red/35 border border-red-100 bg-red-50 text-red-900 dark:text-red-300",WARNING:"dark:border-dark-yellow/20 dark:bg-light-yellow/35 border border-yellow-100 bg-yellow-50 text-yellow-900 dark:text-yellow-300",- DEFAULT: "bg-surface-output text-foreground-secondary",- DEBUG: "bg-surface-output text-foreground-secondary",+ DEFAULT: "bg-surface-section text-foreground-secondary",+ DEBUG: "bg-surface-section text-foreground-secondary",} satisfies Record<ObservationLevelType, string>,},},diff --git a/web/src/components/design-system/table/columns/createIOTableColumn.stories.tsx b/web/src/components/design-system/table/columns/createIOTableColumn.stories.tsxindex 704cd5756b..d7d3191855 100644--- a/web/src/components/design-system/table/columns/createIOTableColumn.stories.tsx+++ b/web/src/components/design-system/table/columns/createIOTableColumn.stories.tsx@@ -309,9 +309,9 @@ export const TestLoadedCellBackgrounds = meta.story({const [inputCell, outputCell] = Array.from(row.cells);await expect(inputCell).toHaveClass("bg-muted/50");- await expect(outputCell).toHaveClass("bg-surface-output");+ await expect(outputCell).toHaveClass("bg-surface-section");await expect(inputCell?.querySelector('[class~="bg-muted/50"]')).toBeNull();- await expect(outputCell?.querySelector(".bg-surface-output")).toBeNull();+ await expect(outputCell?.querySelector(".bg-surface-section")).toBeNull();},});@@ -329,7 +329,7 @@ export const TestLoadingCellBackgrounds = meta.story({const [inputCell, outputCell] = Array.from(row.cells);await expect(inputCell).toHaveClass("bg-muted/50");- await expect(outputCell).toHaveClass("bg-surface-output");+ await expect(outputCell).toHaveClass("bg-surface-section");await expect(inputCell).toHaveClass("[&_[data-slot=skeleton]]:bg-muted-foreground/20",);diff --git a/web/src/components/design-system/table/components/IOTableCell/IOTableCell.stories.tsx b/web/src/components/design-system/table/components/IOTableCell/IOTableCell.stories.tsxindex f538e0eab6..0bce99e502 100644--- a/web/src/components/design-system/table/components/IOTableCell/IOTableCell.stories.tsx+++ b/web/src/components/design-system/table/components/IOTableCell/IOTableCell.stories.tsx@@ -140,7 +140,7 @@ export const TestOutputVariant = meta.story({},play: async ({ canvasElement }) => {await expect(- canvasElement.querySelector(".bg-surface-output"),+ canvasElement.querySelector(".bg-surface-section"),).toBeInTheDocument();},});diff --git a/web/src/components/design-system/table/components/IOTableCell/IOTableCell.tsx b/web/src/components/design-system/table/components/IOTableCell/IOTableCell.tsxindex 9c03bfda01..dda7b218dc 100644--- a/web/src/components/design-system/table/components/IOTableCell/IOTableCell.tsx+++ b/web/src/components/design-system/table/components/IOTableCell/IOTableCell.tsx@@ -31,7 +31,7 @@ export type IOTableCellMediaRenderer = (const ioTableCellVariantClassNames: Record<IOTableCellVariant, string> = {default: "",input: "bg-muted/50",- output: "bg-surface-output",+ output: "bg-surface-section",};const ioTableCellPaddingClassNames: Record<IOTableCellSize, string> = {diff --git a/web/src/components/editor/CodeMirrorEditor.tsx b/web/src/components/editor/CodeMirrorEditor.tsxindex 35c2e48cc2..7c99620f73 100644--- a/web/src/components/editor/CodeMirrorEditor.tsx+++ b/web/src/components/editor/CodeMirrorEditor.tsx@@ -13,6 +13,7 @@ import {RangeSetBuilder,StateEffect,StateField,+ Prec,} from "@codemirror/state";import { SearchQuery, setSearchQuery } from "@codemirror/search";import { json, jsonParseLinter } from "@codemirror/lang-json";@@ -343,6 +344,16 @@ const gutterHiddenTheme = EditorView.theme({".cm-gutters": { display: "none" },});+// Flat editors sit in a host box: no fill of their own, on any layer.+const flatTheme = Prec.highest(+ EditorView.theme({+ "&": { backgroundColor: "transparent" },+ ".cm-gutters": { backgroundColor: "transparent" },+ ".cm-scroller": { backgroundColor: "transparent" },+ ".cm-content": { backgroundColor: "transparent" },+ }),+);+const gutterBorderTheme = EditorView.theme({".cm-gutters": { borderRight: "1px solid" },});@@ -424,6 +435,7 @@ export function CodeMirrorEditor({enableSearchKeymap = true,onEditorMount,extensions: additionalExtensions,+ appearance = "bordered",}: {value: string;onChange?: (value: string) => void;@@ -442,6 +454,8 @@ export function CodeMirrorEditor({// Caller-provided CodeMirror extensions appended after the built-ins, e.g. a// media drop/paste handler. Memoize at the call site to avoid reconfiguring.extensions?: Extension[];+ /** `flat`: no border or fill of its own, for editors inside a host box. */+ appearance?: "bordered" | "flat";}) {const { resolvedTheme } = useTheme();const codeMirrorTheme = resolvedTheme === "dark" ? darkTheme : lightTheme;@@ -523,6 +537,7 @@ export function CodeMirrorEditor({...(editable && mode === "json" ? [createJsonMagicPasteExtension()] : []),...(mode === "prompt" ? [promptSupport, promptLinter] : []),...(lineWrapping ? [EditorView.lineWrapping] : []),+ ...(appearance === "flat" ? [flatTheme] : []),...(additionalExtensions ?? []),],[@@ -533,6 +548,7 @@ export function CodeMirrorEditor({mode,linterEnabled,lineWrapping,+ appearance,additionalExtensions,],);@@ -570,7 +586,8 @@ export function CodeMirrorEditor({onChange={handleChange}onBlur={onBlur}className={cn(- "ph-no-capture overflow-hidden overflow-y-auto rounded-md border text-xs",+ "ph-no-capture overflow-hidden overflow-y-auto rounded-md text-xs",+ appearance === "flat" ? "border-0 bg-transparent" : "border",className,)}editable={editable}diff --git a/web/src/components/table/DataTable.stories.tsx b/web/src/components/table/DataTable.stories.tsxindex 98d38af804..ed49132fd2 100644--- a/web/src/components/table/DataTable.stories.tsx+++ b/web/src/components/table/DataTable.stories.tsx@@ -1528,7 +1528,7 @@ export const TestManualIOCellBackground = meta.story({if (!row) throw new globalThis.Error("Row not found");await expect(row.cells[inputIndex]).toHaveClass("bg-muted/50");- await expect(row.cells[outputIndex]).toHaveClass("bg-surface-output");+ await expect(row.cells[outputIndex]).toHaveClass("bg-surface-section");},});diff --git a/web/src/components/table/ValueCell.tsx b/web/src/components/table/ValueCell.tsxindex f573b32415..feeb13cde4 100644--- a/web/src/components/table/ValueCell.tsx+++ b/web/src/components/table/ValueCell.tsx@@ -12,6 +12,7 @@ import { classifyMediaValue } from "@/src/components/ui/media/mediaUtils";import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";import { copyTextToClipboard } from "@/src/utils/clipboard";import { Button } from "@/src/components/ui/button";+import { Button as TextButton } from "@/src/components/design-system/Button/Button";import {DropdownMenuController,DropdownMenuItem,@@ -520,16 +521,15 @@ export const ValueCell = memo({content}</span>{needsTruncation && !row.original.hasChildren && (- <div- className="inline cursor-pointer opacity-50"- onClick={(e) => {- e.stopPropagation();- toggleCellExpansion(cellId);- }}- >- {isCellExpanded- ? "\n...collapse"- : `\n...expand (${getValueStringLength(value) - MAX_CELL_DISPLAY_CHARS} more characters)`}+ <div className="flex">+ <TextButton+ variant="text"+ text={isCellExpanded ? "Show less" : "Show more"}+ onClick={(e) => {+ e.stopPropagation();+ toggleCellExpansion(cellId);+ }}+ /></div>)}diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsxindex fc15cae62b..7b7aa74278 100644--- a/web/src/components/table/data-table.tsx+++ b/web/src/components/table/data-table.tsx@@ -251,7 +251,7 @@ const getCellPaddingClassName = (padding: DataTableCellPadding) => {const cellBackgroundClassNames = {gray: "bg-muted/50 [&_[data-slot=skeleton]]:bg-muted-foreground/20",- green: "bg-surface-output [&_[data-slot=skeleton]]:bg-muted-foreground/20",+ green: "bg-surface-section [&_[data-slot=skeleton]]:bg-muted-foreground/20",} satisfies Record<DataTableCellBackground, string>;const getCellBackgroundClassName = (background?: DataTableCellBackground) =>diff --git a/web/src/components/ui/CodeJsonViewer.tsx b/web/src/components/ui/CodeJsonViewer.tsxindex d2c0606fba..eaacb20cd7 100644--- a/web/src/components/ui/CodeJsonViewer.tsx+++ b/web/src/components/ui/CodeJsonViewer.tsx@@ -93,7 +93,7 @@ export function JSONView(props: {"io-message-content ph-no-capture flex max-w-full min-w-0 gap-2 text-xs wrap-break-word whitespace-pre-wrap",props.borderless ? "" : "p-2",props.title === "assistant" || props.title === "Output"- ? "bg-surface-output dark:border-border"+ ? "bg-surface-section dark:border-border": "",props.scrollable || props.borderless || props.title? ""diff --git a/web/src/components/ui/IOSection.stories.tsx b/web/src/components/ui/IOSection.stories.tsxnew file mode 100644index 0000000000..273effb44d--- /dev/null+++ b/web/src/components/ui/IOSection.stories.tsx@@ -0,0 +1,281 @@+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 { IOSection } from "./IOSection";+import { PrettyJsonView } from "./PrettyJsonView";+import { IO_STICKY_HEADERS_CLASS } from "@/src/features/traces/constants/ioSectionClasses";++const meta = preview.meta({+ component: IOSection,+ args: {+ onCopy: fn(),+ },+});++const USER_TEXT =+ "Hi — I was charged twice for my Pro subscription this month (invoices inv_20260701 and inv_20260701-2, $49 each). Can you refund the duplicate?";++const ASSISTANT_TEXT =+ "Context: pro plan customer (Maya Chen, Acme Robotics), two $49 invoices paid 5s apart on 2026-07-01, one prior ticket with the same pattern resolved by refund.";++const TOOL_INPUT = {+ customer_id: "cus_LqT4v8",+ period: "2026-07",+ amount_usd: 49,+};++const ERROR_OUTPUT = {+ error: {+ type: "upstream_error",+ code: 502,+ message: "Search backend unavailable, request not retried.",+ },+};++const LONG_TEXT = Array.from(+ { length: 40 },+ (_, i) =>+ `Turn ${i + 1}: the agent re-checked the invoice list, compared the payment intents and drafted the next step for the reply.`,+).join("\n\n");++const headerActions = [+ {+ icon: FoldVertical,+ label: "Collapse all rows",+ onClick: fn(),+ },+ {+ icon: Pencil,+ label: "Correct output",+ onClick: fn(),+ },+];++const info = {+ label: "About corrected outputs",+ text: "Corrected outputs allow you to save the expected output for a trace or observation.",+ docsHref: "https://langfuse.com/docs/observability/features/corrections",+};++const jsonToggle = {+ label: "JSON",+ checked: false,+ onCheckedChange: fn(),+};++export const Default = meta.story({+ args: {+ title: "user",+ children: <p className="text-sm">{USER_TEXT}</p>,+ },+});++export const VariantMatrix = meta.story({+ args: {+ title: "user",+ children: null,+ },+ render: (args) => (+ <div className="flex flex-col gap-8">+ <Example caption="Text body (default): chat message">+ <IOSection onCopy={args.onCopy} title="user">+ <p className="text-sm">{USER_TEXT}</p>+ </IOSection>+ </Example>++ <Example caption="Table body: PrettyJsonView owns the section (variant table, py-1)">+ <PrettyJsonView title="Input" json={TOOL_INPUT} currentView="pretty" />+ </Example>++ <Example caption="Media body: tiles sit 12px from every edge (variant media)">+ <IOSection onCopy={args.onCopy} title="Media" variant="media">+ <div className="flex flex-wrap gap-2">+ <Image+ src="/revenue-chart.svg"+ alt="Attached chart"+ width={160}+ height={96}+ unoptimized+ className="bg-background rounded-md border"+ />+ </div>+ </IOSection>+ </Example>++ <Example caption="Tone danger: error message text">+ <IOSection onCopy={args.onCopy} title="Error" tone="danger">+ Zendesk 502: upstream search unavailable+ </IOSection>+ </Example>++ <Example caption="Tone warning">+ <IOSection onCopy={args.onCopy} title="Warning" tone="warning">+ The observation completed with a recoverable warning.+ </IOSection>+ </Example>++ <Example caption="Tone muted: default status message">+ <IOSection onCopy={args.onCopy} title="Status" tone="muted">+ The observation completed with additional status details.+ </IOSection>+ </Example>++ <Example caption="Tone neutral">+ <IOSection onCopy={args.onCopy} title="Debug" tone="neutral">+ Detailed diagnostic information for this observation.+ </IOSection>+ </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"+ />+ </Example>++ <Example caption="Collapsed: header only, body not rendered">+ <IOSection onCopy={args.onCopy} title="system" defaultCollapsed>+ <p className="text-sm">{ASSISTANT_TEXT}</p>+ </IOSection>+ </Example>++ <Example caption="Header actions (hover the section): expand-all, pencil, copy">+ <IOSection onCopy={args.onCopy} title="Output" actions={headerActions}>+ <p className="text-sm">{ASSISTANT_TEXT}</p>+ </IOSection>+ </Example>++ <Example caption="Status saving + JSON toggle + info hover card (hover the section)">+ <IOSection+ title="Corrected output"+ info={info}+ status={{ kind: "saving", text: "Saving" }}+ toggle={jsonToggle}+ actions={headerActions}+ >+ <p className="text-sm">{ASSISTANT_TEXT}</p>+ </IOSection>+ </Example>++ <Example caption="Status saved">+ <IOSection+ title="Corrected output"+ info={info}+ status={{ kind: "saved", text: "Saved" }}+ toggle={jsonToggle}+ actions={headerActions}+ >+ <p className="text-sm">{ASSISTANT_TEXT}</p>+ </IOSection>+ </Example>++ <Example caption="Status error">+ <IOSection+ title="Corrected output"+ info={info}+ status={{ kind: "error", text: "Invalid JSON - fix to save" }}+ toggle={{ ...jsonToggle, checked: true }}+ >+ <p className="text-sm">{ASSISTANT_TEXT}</p>+ </IOSection>+ </Example>++ <Example caption="Count badge">+ <IOSection onCopy={args.onCopy} title="Skills" count={3}>+ <p className="text-sm">3 skills loaded for this run.</p>+ </IOSection>+ </Example>++ <Example caption="Title icon">+ <IOSection onCopy={args.onCopy} title="Tools" titleIcon={Wrench}>+ <p className="text-sm">+ 3 of 39 available tools were called in this generation.+ </p>+ </IOSection>+ </Example>++ <Example caption="Sticky header: long body inside a fixed-height scroll container">+ <div+ className={`h-64 overflow-y-auto rounded-md border p-3 ${IO_STICKY_HEADERS_CLASS}`}+ >+ <IOSection onCopy={args.onCopy} title="assistant">+ <p className="text-sm whitespace-pre-wrap">{LONG_TEXT}</p>+ </IOSection>+ </div>+ </Example>+ </div>+ ),+});++export const StickyHeader = meta.story({+ args: {+ title: "system",+ children: null,+ },+ render: (args) => (+ <div+ className={`h-72 overflow-y-auto rounded-md border p-3 ${IO_STICKY_HEADERS_CLASS}`}+ >+ <IOSection onCopy={args.onCopy} title="system">+ <p className="text-sm whitespace-pre-wrap">{LONG_TEXT}</p>+ </IOSection>+ <div className="pt-2">+ <IOSection onCopy={args.onCopy} title="user">+ <p className="text-sm">{USER_TEXT}</p>+ </IOSection>+ </div>+ </div>+ ),+});++export const HeaderRowToggles = meta.story({+ name: "(Test) Header Row Toggles",+ args: {+ title: "assistant",+ actions: headerActions,+ children: <p className="text-sm">{ASSISTANT_TEXT}</p>,+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ // Clicking the title text (not the caret) collapses the section.+ await userEvent.click(canvas.getByText("assistant"));+ await expect(canvas.queryByText(ASSISTANT_TEXT)).not.toBeInTheDocument();+ await expect(+ canvas.getByRole("button", { name: "Expand assistant" }),+ ).toHaveAttribute("aria-expanded", "false");++ await userEvent.click(+ canvas.getByRole("button", { name: "Expand assistant" }),+ );+ await expect(canvas.getByText(ASSISTANT_TEXT)).toBeVisible();++ // A header control runs its own action and leaves the section open.+ await userEvent.click(canvas.getByTitle("Copy to clipboard"));+ await expect(args.onCopy).toHaveBeenCalledTimes(1);+ await userEvent.click(canvas.getByTitle("Correct output"));+ await expect(canvas.getByText(ASSISTANT_TEXT)).toBeVisible();+ await expect(+ canvas.getByRole("button", { name: "Collapse assistant" }),+ ).toHaveAttribute("aria-expanded", "true");+ },+});++/** Caption + example, used by the variant matrix only. */+function Example({+ caption,+ children,+}: {+ caption: string;+ children: React.ReactNode;+}) {+ return (+ <div className="flex flex-col gap-2">+ <p className="text-muted-foreground text-xs">{caption}</p>+ {children}+ </div>+ );+}diff --git a/web/src/components/ui/IOSection.tsx b/web/src/components/ui/IOSection.tsxnew file mode 100644index 0000000000..a5d6e766dc--- /dev/null+++ b/web/src/components/ui/IOSection.tsx@@ -0,0 +1,357 @@+import { useState } from "react";+import {+ Check,+ ChevronDown,+ ChevronRight,+ Copy,+ Info,+ type IconComponent,+} from "@langfuse/icons";+import Link from "next/link";+import { Button } from "@/src/components/ui/button";+import { Badge } from "@/src/components/design-system/Badge/Badge";+import { HoverCard } from "@/src/components/design-system/HoverCard/HoverCard";+import { Spinner } from "@/src/components/design-system/Spinner/Spinner";+import { Switch } from "@/src/components/design-system/Switch/Switch";+import { cn } from "@/src/utils/tailwind";++/** An icon button in the section header. */+export type IOSectionAction = {+ icon: IconComponent;+ /** Tooltip and accessible name. */+ label: string;+ onClick: () => void;+ disabled?: boolean;+ /** Highlights the icon while the action's mode is on. */+ active?: boolean;+};++/** A short state label in the header, before the actions. */+export type IOSectionStatus = {+ kind: "saving" | "saved" | "error";+ text: string;+};++/** A labelled switch at the end of the header controls. */+export type IOSectionToggle = {+ label: string;+ checked: boolean;+ onCheckedChange: (checked: boolean) => void;+ disabled?: boolean;+};++/** An info hover card after the title. */+export type IOSectionInfo = {+ /** Accessible name of the info trigger. */+ label: string;+ text: string;+ /** Appends "Learn more in the documentation." linking here. */+ docsHref?: string;+};++export type IOSectionTone = "danger" | "warning" | "muted" | "neutral";++export type IOSectionProps = {+ title: string;+ titleIcon?: IconComponent;+ /** Count badge after the title. */+ count?: number;+ info?: IOSectionInfo;+ /** Header copy control; omitted when the section has nothing to copy. */+ onCopy?: (event?: React.MouseEvent<HTMLButtonElement>) => void;+ actions?: IOSectionAction[];+ status?: IOSectionStatus;+ toggle?: IOSectionToggle;+ /** Initial state of an uncontrolled section. */+ defaultCollapsed?: boolean;+ /** Controlled state; the header calls `onCollapsedChange`. */+ collapsed?: boolean;+ onCollapsedChange?: (collapsed: boolean) => void;+ /** Body box: `text` (default inset), `table` for rows that carry their own+ padding, `media` for tiles that want the same inset on every side. */+ variant?: "text" | "table" | "media";+ /** Level-coloured box (status messages, toned tables). */+ tone?: IOSectionTone;+ children: React.ReactNode;+};++const BODY_PADDING_CLASSES: Record<+ NonNullable<IOSectionProps["variant"]>,+ string+> = {+ text: "py-2",+ table: "py-1",+ media: "py-3",+};++/** Toned text boxes (status messages); same colours as StatusMessage. */+const TONE_TEXT_CLASSES: Record<IOSectionTone, string> = {+ danger:+ "border border-red-100 bg-red-50 text-red-900 dark:border-dark-red/20 dark:bg-light-red/35 dark:text-red-300",+ warning:+ "border border-yellow-100 bg-yellow-50 text-yellow-900 dark:border-dark-yellow/20 dark:bg-light-yellow/35 dark:text-yellow-300",+ muted: "bg-surface-section text-foreground-secondary",+ neutral: "bg-surface-section text-foreground-secondary",+};++/** Toned table boxes: the plain table box with the tone as its fill only. */+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",+ muted: "bg-surface-section",+ neutral: "bg-surface-section",+};++/** The body box: the section's grey fill, or a level-coloured frame. */+function boxClasses(+ variant: NonNullable<IOSectionProps["variant"]>,+ tone: IOSectionTone | undefined,+) {+ if (!tone) {+ return cn(+ "bg-surface-section overflow-hidden rounded-md px-3",+ BODY_PADDING_CLASSES[variant],+ );+ }+ if (variant === "table") {+ return cn(+ "overflow-hidden rounded-md px-3",+ BODY_PADDING_CLASSES.table,+ TONE_FILL_CLASSES[tone],+ );+ }+ return cn(+ "rounded-md px-3 py-2 text-sm wrap-break-word whitespace-pre-wrap",+ TONE_TEXT_CLASSES[tone],+ );+}++const HEADER_CONTROL_CLASSES =+ "text-muted-foreground hover:text-foreground hover:bg-transparent";++/**+ * One I/O section of the trace view: a header row (caret, title, hover+ * controls) over a boxed body. The header row toggles the body (its controls+ * do not); a collapsed section is just the header row and does not render+ * its children.+ */+export function IOSection({+ title,+ titleIcon: TitleIcon,+ count,+ info,+ onCopy,+ actions,+ status,+ toggle,+ defaultCollapsed = false,+ collapsed,+ onCollapsedChange,+ variant = "text",+ tone,+ children,+}: IOSectionProps) {+ const [internalCollapsed, setInternalCollapsed] = useState(defaultCollapsed);+ const isCollapsed = collapsed ?? internalCollapsed;+ const Caret = isCollapsed ? ChevronRight : ChevronDown;++ const toggleCollapsed = () => {+ const next = !isCollapsed;+ if (onCollapsedChange) {+ onCollapsedChange(next);+ } else {+ setInternalCollapsed(next);+ }+ };++ return (+ // overflow-clip (not hidden) so the sticky header can track the panel scroll.+ <div className="group/iosection flex flex-col overflow-clip">+ <div className="io-message-header flex h-8 flex-row items-center justify-between px-0 text-sm font-bold capitalize">+ {/* Masked from session recordings: the title can be a customer-provided+ message `name` (or tool name) rather than a fixed role string. */}+ <button+ type="button"+ className="ph-no-capture focus-visible:ring-ring flex h-full min-w-0 shrink cursor-pointer items-center gap-2 rounded-sm text-left capitalize focus-visible:ring-2 focus-visible:outline-hidden"+ aria-expanded={!isCollapsed}+ aria-label={`${isCollapsed ? "Expand" : "Collapse"} ${title}`}+ onClick={toggleCollapsed}+ >+ <Caret size="base" color="default" aria-hidden />+ {TitleIcon ? (+ <TitleIcon size="base" color="default" aria-hidden />+ ) : null}+ {title}+ {count !== undefined ? (+ <Badge color="filled" size="sm" text={String(count)} />+ ) : null}+ </button>+ {info ? (+ <div className="flex items-center pl-2">+ <IOSectionInfoButton info={info} />+ </div>+ ) : null}+ {/* The rest of the row toggles too; the title button carries the+ accessible name and state, so this hit area stays out of the tree. */}+ <button+ type="button"+ className="h-full min-w-0 flex-1 cursor-pointer"+ aria-hidden+ tabIndex={-1}+ onClick={toggleCollapsed}+ />+ <div+ className={cn(+ "mr-1 flex shrink-0 flex-row items-center gap-1",+ // pointer-coarse: touch devices have no hover, so the controls+ // stay visible there instead of being unreachable.+ "opacity-0 transition-opacity group-hover/iosection:opacity-100 focus-within:opacity-100 pointer-coarse:opacity-100",+ )}+ >+ {/* A collapsed section offers nothing to copy or act on. */}+ {!isCollapsed ? (+ <IOSectionControls+ status={status}+ actions={actions}+ toggle={toggle}+ onCopy={onCopy}+ />+ ) : null}+ </div>+ </div>+ {!isCollapsed && (+ <div className="io-message-content ph-no-capture pt-1">+ <div className={boxClasses(variant, tone)}>{children}</div>+ </div>+ )}+ </div>+ );+}++/** The header's right-hand controls, in order: status, actions, toggle, copy. */+function IOSectionControls({+ status,+ actions,+ toggle,+ onCopy,+}: Pick<IOSectionProps, "status" | "actions" | "toggle" | "onCopy">) {+ const [isCopied, setIsCopied] = useState(false);++ return (+ <>+ {status ? <StatusLabel status={status} /> : null}+ {actions?.map((action) => (+ <Button+ key={action.label}+ variant="ghost"+ size="icon-xs"+ type="button"+ title={action.label}+ aria-label={action.label}+ disabled={action.disabled}+ onClick={action.onClick}+ className={HEADER_CONTROL_CLASSES}+ >+ {action.active ? (+ <action.icon size="base" __rawClassName="text-primary" />+ ) : (+ <action.icon size="base" color="default" />+ )}+ </Button>+ ))}+ {toggle ? (+ <div className="flex items-center">+ <div className="mx-1">+ <Switch+ checked={toggle.checked}+ onCheckedChange={toggle.onCheckedChange}+ disabled={toggle.disabled}+ size="sm"+ />+ </div>+ <span className="text-muted-foreground text-xs">{toggle.label}</span>+ </div>+ ) : null}+ {onCopy ? (+ <Button+ title="Copy to clipboard"+ variant="ghost"+ size="icon-xs"+ type="button"+ onClick={(event) => {+ setIsCopied(true);+ onCopy(event);+ setTimeout(() => setIsCopied(false), 1000);+ }}+ className={HEADER_CONTROL_CLASSES}+ >+ {isCopied ? (+ <Check size="base" color="default" />+ ) : (+ <Copy size="base" color="default" />+ )}+ </Button>+ ) : null}+ </>+ );+}++/** Saving / saved / error label; `pr-2` keeps its gap to the actions. */+function StatusLabel({ status }: { status: IOSectionStatus }) {+ if (status.kind === "error") {+ return <span className="pr-2 text-xs text-red-500">{status.text}</span>;+ }+ return (+ <div className="flex items-center gap-1 pr-2">+ {status.kind === "saving" ? <Spinner size="xxs" /> : <Check size="sm" />}+ <span className="text-muted-foreground text-xs">{status.text}</span>+ </div>+ );+}++/** Info trigger with a hover card; sits outside the title toggle. */+function IOSectionInfoButton({ info }: { info: IOSectionInfo }) {+ return (+ <HoverCard+ placement="right"+ content={+ <div className="w-80 p-3 text-xs">+ <p>+ {info.text}+ {info.docsHref ? (+ <>+ {" "}+ Learn more in the{" "}+ <Link+ href={info.docsHref}+ target="_blank"+ rel="noreferrer"+ className="hover:text-foreground underline"+ >+ documentation+ </Link>+ .+ </>+ ) : null}+ </p>+ </div>+ }+ >+ {({ getTriggerProps }) => (+ <button+ type="button"+ aria-label={info.label}+ className="text-muted-foreground hover:text-foreground"+ {...getTriggerProps()}+ >+ <Info size="base" />+ </button>+ )}+ </HoverCard>+ );+}++// Hosts that draw their own header (the compact JSON Beta variant) reuse the+// section's control rendering.+IOSection.Controls = IOSectionControls;+IOSection.InfoButton = IOSectionInfoButton;diff --git a/web/src/components/ui/MarkdownJsonView.tsx b/web/src/components/ui/MarkdownJsonView.tsxindex 27b38bd196..5f7b948169 100644--- a/web/src/components/ui/MarkdownJsonView.tsx+++ b/web/src/components/ui/MarkdownJsonView.tsx@@ -8,7 +8,8 @@ import { Button } from "@/src/components/ui/button";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import { MarkdownView } from "@/src/components/ui/MarkdownViewer";import { type MediaReturnType } from "@/src/features/media";-import { Check, Copy } from "@langfuse/icons";+import { Check, Copy, type IconComponent } from "@langfuse/icons";+import { type IOSectionAction } from "@/src/components/ui/IOSection";import { useMemo, useState } from "react";import { type z } from "zod";import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";@@ -38,19 +39,13 @@ export function MarkdownJsonViewHeader({}: MarkdownJsonViewHeaderProps) {const [isCopied, setIsCopied] = useState(false);- const titleContent = (- <>- {titleIcon}- {title}- </>- );-return (- <div className="io-message-header flex flex-row items-center justify-between px-1 py-1 text-base font-bold capitalize">+ <div className="io-message-header flex h-8 flex-row items-center justify-between px-1 text-sm font-bold capitalize">{/* Masked from session recordings: the title can be a customer-providedmessage `name` (or tool name) rather than a fixed role string. */}<div className="ph-no-capture flex items-center gap-2">- {titleContent}+ {titleIcon}+ {title}</div><divclassName={cn(@@ -140,22 +135,34 @@ export function MarkdownJsonView({className,audio,media,- controlButtons,- afterHeader,+ actions,+ beforeContent,+ afterContent,isSystemPrompt,+ defaultCollapsed,+ collapsed,+ onCollapsedChange,}: {content?: unknown;title?: string;- titleIcon?: React.ReactNode;+ titleIcon?: IconComponent;className?: string;audio?: OpenAIOutputAudioType;media?: MediaReturnType[];- controlButtons?: React.ReactNode;- /** Content to render between header and main content (e.g., thinking blocks) */- afterHeader?: React.ReactNode;- /** Collapse long content to a preview (from raw `role === "system"`, since+ /** 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"`, sincethe 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@@ -175,9 +182,13 @@ export function MarkdownJsonView({titleIcon={titleIcon}audio={audio}media={media}- controlButtons={controlButtons}- afterHeader={afterHeader}+ actions={actions}+ beforeContent={beforeContent}+ afterContent={afterContent}isSystemPrompt={isSystemPrompt}+ defaultCollapsed={defaultCollapsed}+ collapsed={collapsed}+ onCollapsedChange={onCollapsedChange}/>) : (<PrettyJsonView@@ -187,9 +198,13 @@ export function MarkdownJsonView({className={className}media={media}currentView="pretty"- controlButtons={controlButtons}- afterHeader={afterHeader}+ actions={actions}+ beforeContent={beforeContent}+ afterContent={afterContent}isSystemPrompt={isSystemPrompt}+ defaultCollapsed={defaultCollapsed}+ collapsed={collapsed}+ onCollapsedChange={onCollapsedChange}/>);}diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsxindex e51636ef51..48fa6265c3 100644--- a/web/src/components/ui/MarkdownViewer.tsx+++ b/web/src/components/ui/MarkdownViewer.tsx@@ -20,7 +20,7 @@ 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 } from "@langfuse/icons";+import { ImageOff, Info, type IconComponent } from "@langfuse/icons";import { MentionBadge } from "@/src/features/comments/components/MentionBadge";import {OpenAIUrlImageUrl,@@ -38,12 +38,10 @@ import { ResizableImage } from "@/src/components/ui/resizable-image";import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";import { type MediaReturnType } from "@/src/features/media";import { JSONView } from "@/src/components/ui/CodeJsonViewer";-import { MarkdownJsonViewHeader } from "@/src/components/ui/MarkdownJsonView";-import { SystemPromptCollapseButton } from "@/src/components/ui/SystemPromptCollapseButton";+import { IOSection, type IOSectionAction } from "@/src/components/ui/IOSection";import { copyTextToClipboard } from "@/src/utils/clipboard";import { MENTION_USER_PREFIX } from "@/src/features/comments/lib/mentionParser";import { useCollapsibleSystemPrompt } from "@/src/hooks/useCollapsibleSystemPrompt";-import { Button } from "@/src/components/ui/button";import { getSafeImageUrl, getSafeLinkUrl } from "@/src/components/ui/safe-url";import { env } from "@/src/env.mjs";import {@@ -442,13 +440,13 @@ function MarkdownRenderer({if (tooLargeOrDeep) {return (- <div className={cn("space-y-2 overflow-x-auto text-base", className)}>+ <div className={cn("space-y-2 overflow-x-auto text-sm", className)}><div className="text-muted-foreground flex items-center gap-1 text-xs"><Info size="sm" />Content is too large or deeply nested to render as markdown.Displaying as plain text.</div>- <pre className="text-base break-words whitespace-pre-wrap">+ <pre className="text-sm break-words whitespace-pre-wrap">{markdown}</pre></div>@@ -462,7 +460,7 @@ function MarkdownRenderer({return (<divclassName={cn(- "space-y-2 overflow-x-auto text-base wrap-break-word",+ "space-y-2 overflow-x-auto text-sm wrap-break-word",className,)}>@@ -518,25 +516,37 @@ export function MarkdownView({audio,media,className,- controlButtons,- afterHeader,+ actions,+ beforeContent,+ afterContent,isSystemPrompt,+ defaultCollapsed,+ collapsed,+ onCollapsedChange,}: {/** The UNPARSED content shape — see `canRenderContentAsMarkdown`. Mediareference strings must still be strings when they reach the part guards. */markdown: string | z.input<typeof OpenAIContentSchema>;title?: string;- titleIcon?: React.ReactNode;+ titleIcon?: IconComponent;audio?: OpenAIOutputAudioType;media?: MediaReturnType[];className?: string;- controlButtons?: React.ReactNode;- /** Content to render between header and main content (e.g., thinking blocks) */- afterHeader?: React.ReactNode;- /** Collapse long content to a preview. Pass the raw message role check+ /** 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 therole. 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;@@ -546,11 +556,9 @@ export function MarkdownView({const standaloneMediaDescriptor: MediaDescriptor | null =typeof markdown === "string" ? classifyMediaValue(markdown) : null;- // Collapse preview is built from text parts only: media references, base64- // data URIs and audio parts neither survive the generic markdown renderer nor- // belong in a first-lines text preview — and media alone should not make a- // prompt collapsible.- const collapsibleContent =+ // 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")@@ -562,14 +570,9 @@ export function MarkdownView({.map((part) => part.text).join("\n");- const {- shouldBeCollapsible,- isCollapsed,- toggleCollapsed,- truncatedContent,- } = useCollapsibleSystemPrompt({- isSystemPrompt: isSystemPrompt ?? title === "system",- content: collapsibleContent,+ const systemPrompt = useCollapsibleSystemPrompt({+ isSystemPrompt: Boolean(title) && (isSystemPrompt ?? title === "system"),+ content: textContent,});const handleOnCopy = () => {@@ -585,117 +588,42 @@ export function MarkdownView({getRenderedInlineMediaIds({ markdown, audio }),);- const handleCollapseInline = () => toggleCollapsed("inline");- const handleCollapseHeader = () => toggleCollapsed("header");-- const collapseToggle = shouldBeCollapsible ? (- <Button- variant="ghost"- size="xs"- onClick={handleCollapseInline}- className="w-fit text-xs underline"- >- {isCollapsed ? "Expand system prompt" : "Collapse system prompt"}- </Button>- ) : null;-- const headerControlButtons =- shouldBeCollapsible && !isCollapsed ? (- <>- <SystemPromptCollapseButton onCollapse={handleCollapseHeader} />- {controlButtons}- </>- ) : (- controlButtons- );-- return (- <div className="group/iosection overflow-hidden" key={theme}>- {title ? (- <MarkdownJsonViewHeader- title={title}- titleIcon={titleIcon}- handleOnCopy={handleOnCopy}- hoverRevealControls- controlButtons={headerControlButtons}- />+ const body = (+ <div className="text-foreground-secondary grid grid-flow-row gap-2">+ {typeof markdown === "string" ? (+ // plain string+ standaloneMediaDescriptor?.kind === "s3" ? (+ <MediaReferenceTag descriptor={standaloneMediaDescriptor} />+ ) : inlineMediaReferenceStrings.length > 0 ? (+ inlineMediaReferenceStrings.map((referenceString, index) => (+ <LangfuseMediaView+ key={`${referenceString}-${index}`}+ mediaReferenceString={referenceString}+ />+ ))+ ) : (+ <MarkdownRenderer markdown={markdown} />+ )+ ) : (+ // content parts (multi-modal)+ (markdown ?? []).map(renderContentPart)+ )}+ {audio ? (+ <>+ <MarkdownRenderer+ markdown={audio.transcript ? "[Audio] \n" + audio.transcript : ""}+ />+ <LangfuseMediaView+ mediaReferenceString={audio.data.referenceString}+ />+ </>) : null}- {afterHeader}- <div- className={cn(- "io-message-content ph-no-capture text-foreground-secondary px-1 pt-1 pb-2",- className,- )}- >- <div- className={cn(- "grid grid-flow-row gap-2",- (title === "assistant" ||- title === "Output" ||- title === "Model") &&- "bg-surface-output overflow-hidden rounded-md px-3 py-2",- )}- >- {typeof markdown === "string" ? (- // plain string- standaloneMediaDescriptor?.kind === "s3" ? (- <MediaReferenceTag descriptor={standaloneMediaDescriptor} />- ) : inlineMediaReferenceStrings.length > 0 ? (- inlineMediaReferenceStrings.map((referenceString, index) => (- <LangfuseMediaView- key={`${referenceString}-${index}`}- mediaReferenceString={referenceString}- />- ))- ) : (- <>- <MarkdownRenderer- markdown={isCollapsed ? truncatedContent : markdown}- />- {collapseToggle}- </>- )- ) : (- // content parts (multi-modal); collapsing hides long TEXT only —- // attachments are not text, so media parts render either way. That- // also keeps the shared media strip's dedup honest: it assumes any- // inline-renderable media did render (LFE-14815).- <>- {isCollapsed ? (- <>- <MarkdownRenderer markdown={truncatedContent} />- {(markdown ?? []).map((content, index) =>- isOpenAITextContentPart(content)- ? null- : renderContentPart(content, index),- )}- </>- ) : (- (markdown ?? []).map(renderContentPart)- )}- {collapseToggle}- </>- )}- {audio ? (- <>- <MarkdownRenderer- markdown={- audio.transcript ? "[Audio] \n" + audio.transcript : ""- }- />- <LangfuseMediaView- mediaReferenceString={audio.data.referenceString}- />- </>- ) : null}- </div>- </div>{remainingMedia.length > 0 && (<>- <div className="text-muted-foreground mx-3 border-t px-2 py-1 text-xs">+ <div className="text-muted-foreground border-t py-1 text-xs">Media</div>- <div className="ph-no-capture mx-3 flex flex-wrap gap-2 px-2 pt-1 pb-4">+ <div className="flex flex-wrap gap-2">{remainingMedia.map((m) => (<LangfuseMediaViewmediaAPIReturnValue={m}@@ -709,6 +637,41 @@ 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/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsxindex a3444db578..21b72acaae 100644--- a/web/src/components/ui/PrettyJsonView.tsx+++ b/web/src/components/ui/PrettyJsonView.tsx@@ -14,18 +14,18 @@ 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 { MarkdownJsonViewHeader } from "@/src/components/ui/MarkdownJsonView";-import { SystemPromptCollapseButton } from "@/src/components/ui/SystemPromptCollapseButton";+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 { useCollapsibleSystemPrompt } from "@/src/hooks/useCollapsibleSystemPrompt";import {ChevronDown,ChevronRight,UnfoldVertical,FoldVertical,+ type IconComponent,} from "@langfuse/icons";import {useReactTable,@@ -82,40 +82,10 @@ const DEFAULT_MAX_ROWS_IF_ROOT = 100;const MAX_CELL_DISPLAY_CHARS = 2000;-const ASSISTANT_TITLES = ["assistant", "Output", "model"];-const PREVIEW_TEXT_CLASSES = "text-gray-500 dark:text-gray-400";type PrettyJsonViewTone = "danger" | "warning" | "muted" | "neutral";-const PRETTY_JSON_VIEW_TONE_CLASSES: Record<- PrettyJsonViewTone,- { container: string; row: string; cell: string }-> = {- danger: {- container:- "border-red-100 bg-red-50 text-red-900 dark:border-dark-red/20 dark:bg-light-red/35 dark:text-red-300",- row: "hover:bg-light-red/50 dark:hover:bg-light-red/35",- cell: "border-dark-red/20 dark:border-dark-red/15",- },- warning: {- container:- "border-yellow-100 bg-yellow-50 text-yellow-900 dark:border-dark-yellow/20 dark:bg-light-yellow/35 dark:text-yellow-300",- row: "hover:bg-light-yellow/50 dark:hover:bg-light-yellow/35",- cell: "border-dark-yellow/20 dark:border-dark-yellow/15",- },- muted: {- container: "border-transparent bg-surface-output text-foreground-secondary",- row: "hover:bg-muted",- cell: "border-border",- },- neutral: {- container: "border-transparent bg-surface-output text-foreground-secondary",- row: "hover:bg-muted",- cell: "border-border",- },-};-// 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.@@ -161,19 +131,17 @@ function getEmptyValueDisplay(value: unknown): string | null {return null;}+/** Borderless bodies sit inside a section box, which owns fill and inset. */function getContainerClasses(- title: string | undefined,scrollable: boolean | undefined,codeClassName: string | undefined,baseClasses = "whitespace-pre-wrap wrap-break-word p-3 text-xs",borderless = false,) {- const toned = ASSISTANT_TITLES.includes(title || "");return cn(baseClasses,- toned ? "bg-surface-output dark:border-border" : "",borderless- ? "rounded-md overflow-clip"+ ? "rounded-md overflow-clip p-0": scrollable? "": "rounded-sm border",@@ -336,7 +304,6 @@ interface JsonTableRowProps {expandedCells: Set<string>;toggleCellExpansion: (cellId: string) => void;stickyTopLevelKey: boolean;- toneClasses?: (typeof PRETTY_JSON_VIEW_TONE_CLASSES)[PrettyJsonViewTone];}const JsonTableRowComponent = memo(@@ -348,7 +315,6 @@ const JsonTableRowComponent = memo(expandedCells,toggleCellExpansion,stickyTopLevelKey,- toneClasses,}: JsonTableRowProps) => {// Hook is now at top level of this component ✅const isExpandable =@@ -382,7 +348,6 @@ const JsonTableRowComponent = memo(row.original.level === 0 && stickyTopLevelKey? "bg-background sticky top-0 z-10 shadow-xs": "",- toneClasses?.row,)}>{row.getVisibleCells().map((cell) => (@@ -392,7 +357,6 @@ const JsonTableRowComponent = memo("h-full border-b [:last-child_>_&]:border-b-0",CELL_CLASSES,cell.column.id === "value" && "[&>div]:wrap-anywhere",- toneClasses?.cell,)}style={{ width: `${cell.column.columnDef.size}%` }}>@@ -422,7 +386,6 @@ function JsonPrettyTable({showObservationTypeBadge = false,metadataActions,rowActions,- toneClasses,}: {data: JsonTableRow[];expandAllRef?: React.RefObject<(() => void) | null>;@@ -441,7 +404,6 @@ function JsonPrettyTable({showObservationTypeBadge?: boolean;metadataActions?: MetadataFilterActions;rowActions?: (row: Row<JsonTableRow>) => React.ReactNode;- toneClasses?: (typeof PRETTY_JSON_VIEW_TONE_CLASSES)[PrettyJsonViewTone];/** Drop the Path / Value header row. */}) {const topLevelRowRef = useRef<HTMLTableRowElement>(null);@@ -549,10 +511,11 @@ function JsonPrettyTable({const isLongValue = valueLength > MAX_CELL_DISPLAY_CHARS / 3; // already long if we don't truncateif (isLongValue) {- let topPosition = "0";- if (stickyTopLevelKey) {- topPosition =- row.original.level === 0 ? "0" : `${topLevelRowHeight}px`;+ // 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 (@@ -713,7 +676,6 @@ function JsonPrettyTable({expandedCells={expandedCells}toggleCellExpansion={toggleCellExpansion}stickyTopLevelKey={stickyTopLevelKey}- toneClasses={toneClasses}/>))}</tbody>@@ -726,7 +688,7 @@ export function PrettyJsonView(props: {json?: unknown;parsedJson?: unknown; // Pre-parsed data (optional, from useParsedObservation hook)title?: string;- titleIcon?: React.ReactNode;+ titleIcon?: IconComponent;/** Drop the Path / Value header row. */className?: string;isLoading?: boolean;@@ -735,7 +697,8 @@ export function PrettyJsonView(props: {collapseStringsAfterLength?: number | null;media?: MediaReturnType[];scrollable?: boolean;- controlButtons?: React.ReactNode;+ /** Section header actions, after the table's own. */+ actions?: IOSectionAction[];currentView?: "pretty" | "json";externalExpansionState?: Record<string, boolean> | boolean;onExternalExpansionChange?: (@@ -745,21 +708,25 @@ export function PrettyJsonView(props: {stickyTopLevelKey?: boolean;showObservationTypeBadge?: boolean;tone?: PrettyJsonViewTone;- /** Content to render between header and main content (e.g., thinking blocks) */- afterHeader?: React.ReactNode;+ /** 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;/** When set, rows show an actions menu with copy + add-to-filter shortcuts(metadata views only). */metadataActions?: MetadataFilterActions;/** Replaces the built-in row menu, for tables with their own actions. */rowActions?: (row: Row<JsonTableRow>) => React.ReactNode;- /** Collapse long string content to a preview (from raw `role === "system"`,+ /** Long system prompts start collapsed (from raw `role === "system"`,since the title can carry a message `name` instead of the role). */isSystemPrompt?: boolean;}) {- const toneClasses = props.tone- ? PRETTY_JSON_VIEW_TONE_CLASSES[props.tone]- : undefined;- const codeClassName = cn(props.codeClassName, toneClasses?.container);+ 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@@ -817,7 +784,8 @@ export function PrettyJsonView(props: {return decodeUnicodeInJson(result);}, [props.json, props.parsedJson, props.isParsing, largeStringValue]);- const tableBorderless = Boolean(props.title) && !props.tone;+ // 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@@ -1160,8 +1128,6 @@ export function PrettyJsonView(props: {[onExternalExpansionChange, actualExpansionState],);- const handleCollapseHeader = () => toggleSystemPromptCollapsed("header");-const handleOnCopy = (event?: React.MouseEvent<HTMLButtonElement>) => {if (event) {event.preventDefault();@@ -1197,14 +1163,12 @@ export function PrettyJsonView(props: {: [];const shouldRenderStandaloneMedia =isMarkdownMode && standaloneMediaReferenceStrings.length > 0;-- /** Collapse state for a nested MarkdownView that owns no header of its own. */- const {- shouldBeCollapsible: shouldCollapseSystemPrompt,- isCollapsed: isSystemPromptCollapsed,- toggleCollapsed: toggleSystemPromptCollapsed,- } = useCollapsibleSystemPrompt({- isSystemPrompt: Boolean(props.isSystemPrompt),+ const systemPrompt = useCollapsibleSystemPrompt({+ isSystemPrompt:+ Boolean(props.title) &&+ !!props.isSystemPrompt &&+ isMarkdownMode &&+ !shouldRenderStandaloneMedia,content: markdownContent ?? "",});const remainingMarkdownMedia = filterAlreadyRenderedMedia(@@ -1220,11 +1184,6 @@ export function PrettyJsonView(props: {!isMarkdown &&!emptyValueDisplay;- const getBackgroundColorClass = () =>- ASSISTANT_TITLES.includes(props.title || "")- ? "bg-surface-output rounded-md overflow-clip px-3 pt-1"- : "";-const body = (<>{largeStringValue !== null ? (@@ -1233,10 +1192,15 @@ export function PrettyJsonView(props: {<div className="io-message-content ph-no-capture"><divclassName={cn(- getContainerClasses(props.title, props.scrollable, codeClassName),+ getContainerClasses(+ props.scrollable,+ codeClassName,+ undefined,+ tableBorderless,+ ),)}>- <div className="space-y-2 p-3">+ <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" />@@ -1254,7 +1218,6 @@ export function PrettyJsonView(props: {className={cn("flex items-center",getContainerClasses(- props.title,props.scrollable,codeClassName,undefined,@@ -1280,7 +1243,7 @@ export function PrettyJsonView(props: {<MarkdownViewmarkdown={markdownContent || ""}media={props.media}- isSystemPrompt={props.isSystemPrompt}+ className={cn(props.title && "p-0")}/>)}</div>@@ -1294,7 +1257,6 @@ export function PrettyJsonView(props: {<divclassName={cn(getContainerClasses(- props.title,props.scrollable,codeClassName,"flex text-xs wrap-break-word whitespace-pre-wrap",@@ -1324,7 +1286,6 @@ export function PrettyJsonView(props: {showObservationTypeBadge={props.showObservationTypeBadge}metadataActions={props.metadataActions}rowActions={props.rowActions}- toneClasses={toneClasses}/>)}</div>@@ -1341,9 +1302,8 @@ export function PrettyJsonView(props: {// Pass a clone to avoid JSONView's internal deepParseJson// mutating the shared parsedJson / rawChildData tree.json={jsonViewInput}- title={props.title} // Title value used for background styling- hideTitle={true} // But hide the title, we display itclassName=""+ borderless={Boolean(props.title)}isLoading={props.isLoading}codeClassName={codeClassName}collapseStringsAfterLength={props.collapseStringsAfterLength}@@ -1393,93 +1353,75 @@ export function PrettyJsonView(props: {</>);- const expandCollapseButton = (- <>- {shouldUseTableView && hasExpandableRows && (- <Button- variant="ghost"- size="icon-xs"- onClick={() => expandAllRef.current?.()}- className="text-muted-foreground hover:text-foreground hover:bg-transparent"- title={allRowsExpanded ? "Collapse all rows" : "Expand all rows"}- >- {allRowsExpanded ? (- <FoldVertical size="base" color="default" />- ) : (- <UnfoldVertical size="base" color="default" />- )}- </Button>- )}- {!shouldUseTableView && !isMarkdownMode && !largeStringValue && (- <Button- variant="ghost"- size="icon-xs"- onClick={handleJsonToggleCollapse}- className="text-muted-foreground hover:text-foreground hover:bg-transparent"- title={jsonIsCollapsed ? "Expand all" : "Collapse all"}- >- {jsonIsCollapsed ? (- <UnfoldVertical size="base" color="default" />- ) : (- <FoldVertical size="base" color="default" />- )}- </Button>+ 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",)}- </>+ >+ <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 (<divclassName={cn("flex max-h-full min-h-0 flex-col",- "group/iosection",props.className,props.scrollable ? "overflow-hidden" : "",)}>- {props.title ? (- <MarkdownJsonViewHeader- title={props.title}- titleIcon={props.titleIcon}- handleOnCopy={handleOnCopy}- hoverRevealControls- controlButtons={- <>- {/* Expanded only, and only when the nested MarkdownView that owns- the inline control is the thing being rendered. */}- {shouldCollapseSystemPrompt &&- !isSystemPromptCollapsed &&- isMarkdownMode &&- !shouldRenderStandaloneMedia ? (- <SystemPromptCollapseButton onCollapse={handleCollapseHeader} />- ) : null}- {expandCollapseButton}- {props.controlButtons}- </>- }- />- ) : null}- {props.afterHeader}- {props.scrollable ? (- <div- className={cn(- "flex h-full min-h-0 overflow-hidden",- isMarkdownMode- ? getBackgroundColorClass()- : shouldUseTableView && tableBorderless- ? ""- : "rounded-sm border",- )}- >- <div className="max-h-full min-h-0 w-full overflow-y-auto">- {body}- </div>- </div>- ) : isMarkdownMode ? (- <div className={getBackgroundColorClass()}>{body}</div>- ) : (- body- )}+ <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>);}diff --git a/web/src/components/ui/SystemPromptCollapseButton.tsx b/web/src/components/ui/SystemPromptCollapseButton.tsxdeleted file mode 100644index a2bdec1365..0000000000--- a/web/src/components/ui/SystemPromptCollapseButton.tsx+++ /dev/null@@ -1,22 +0,0 @@-import { Button } from "@/src/components/ui/button";--/** Header collapse control for long system prompts; rendered only while expanded. */-export function SystemPromptCollapseButton({- onCollapse,-}: {- onCollapse: () => void;-}) {- return (- <Button- variant="ghost"- size="xs"- type="button"- onClick={onCollapse}- aria-label="Collapse system prompt"- title="Collapse system prompt"- className="text-muted-foreground hover:bg-border w-fit text-xs"- >- Collapse- </Button>- );-}diff --git a/web/src/features/corrections/contexts/CorrectionCacheProvider.tsx b/web/src/features/corrections/contexts/CorrectionCacheProvider.tsxindex 554a0f1b64..1691ff05c2 100644--- a/web/src/features/corrections/contexts/CorrectionCacheProvider.tsx+++ b/web/src/features/corrections/contexts/CorrectionCacheProvider.tsx@@ -192,3 +192,8 @@ export function useCorrectionCache() {}return context;}++/** The cache when a provider is mounted, else null (read-only hosts). */+export function useCorrectionCacheOptional() {+ return useContext(CorrectionCacheContext);+}diff --git a/web/src/features/corrections/index.ts b/web/src/features/corrections/index.tsindex ee650a6cb7..33542c3b09 100644--- a/web/src/features/corrections/index.ts+++ b/web/src/features/corrections/index.ts@@ -3,5 +3,6 @@export {CorrectionCacheProvider,useCorrectionCache,+ useCorrectionCacheOptional,} from "@/src/features/corrections/contexts/CorrectionCacheProvider";export { getMostRecentCorrection } from "@/src/features/corrections/utils/getMostRecentCorrection";diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsxindex ae923d88dc..d5ae31f833 100644--- a/web/src/features/prompts/components/prompt-detail.tsx+++ b/web/src/features/prompts/components/prompt-detail.tsx@@ -12,7 +12,6 @@ import { ChatMessageList } from "@/src/features/traces";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";-import { IO_SECTIONS_FLUSH_CLASS } from "@/src/features/traces/constants/ioSectionClasses";import { DetailViewHeaderShell } from "@/src/features/traces/components/DetailViewHeaderShell";import { JSONView } from "@/src/components/ui/CodeJsonViewer";import { CodeSection } from "@/src/components/design-system/CodeSection/CodeSection";@@ -700,12 +699,7 @@ export const PromptDetail = ({</div></Tabs.Content><Tabs.Content value="prompt" layout="fill">- <div- className={cn(- "mb-2 flex max-h-full min-h-0 w-full flex-col gap-3 overflow-y-auto px-4 pt-3",- IO_SECTIONS_FLUSH_CLASS,- )}- >+ <div className="mb-2 flex max-h-full min-h-0 w-full flex-col gap-3 overflow-y-auto px-4 pt-3">{promptGraph.data?.graph && (<div className="flex items-center justify-end py-2"><Tabsdiff --git a/web/src/features/traces/components/ChatMessageList.clienttest.tsx b/web/src/features/traces/components/ChatMessageList.clienttest.tsxindex 302b7c6f27..ee77928ca3 100644--- a/web/src/features/traces/components/ChatMessageList.clienttest.tsx+++ b/web/src/features/traces/components/ChatMessageList.clienttest.tsx@@ -1,12 +1,24 @@-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";import { vi } from "vitest";-// The dedup under test lives in ChatMessageList; stub the per-message renderer-// and the media strip to observe only which media survive the filter.+// 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: () => null,+ ChatMessage: ({+ message,+ defaultCollapsed,+ }: {+ message: { role: string };+ defaultCollapsed?: boolean;+ }) => (+ <div+ data-testid="chat-message"+ data-role={message.role}+ data-collapsed={String(defaultCollapsed)}+ />+ ),}),);vi.mock(@@ -44,6 +56,134 @@ const renderList = (message: ChatMlMessage, mediaIds: string[]) =>/>,);+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()}+ />,+ );++ // 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()}+ />,+ );++ 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()}+ 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, [diff --git a/web/src/features/traces/components/ChatMessageList.tsx b/web/src/features/traces/components/ChatMessageList.tsxindex 94b4dfb8cf..6445cac632 100644--- a/web/src/features/traces/components/ChatMessageList.tsx+++ b/web/src/features/traces/components/ChatMessageList.tsx@@ -1,5 +1,5 @@-import { useMemo, useState } from "react";-import { Button } from "@/src/components/design-system/Button/Button";+import { Fragment, useMemo, useState } from "react";+import { ChevronDown, ChevronRight } from "@langfuse/icons";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import {filterAlreadyRenderedMedia,@@ -19,8 +19,17 @@ import {} 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";-const COLLAPSE_THRESHOLD = 3;+/** 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 propsexport interface ChatMessageListProps {@@ -36,14 +45,18 @@ export interface ChatMessageListProps {showSystemPrompt?: boolean;/** Title messages Input / Output by side instead of by role. */titleBySide?: boolean;+ /** Header actions for the last output-side message (e.g. Correct output). */+ outputActions?: IOSectionAction[];}/**- * ChatMessageList renders a list of ChatML messages with collapse/expand.+ * ChatMessageList renders a list of ChatML messages, one section each.** Features:* - Filters out empty messages- * - Collapses long history (shows first + last N 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*/@@ -59,6 +72,7 @@ export function ChatMessageList({contentMode = "all",showSystemPrompt,titleBySide = false,+ outputActions,}: ChatMessageListProps) {// Filter messages to only those with renderable contentconst messagesToRender = useMemo(@@ -75,22 +89,24 @@ export function ChatMessageList({[contentMode, messages, showSystemPrompt],);- // Initialize collapsed state based on message count- const [isCollapsed, setCollapsed] = useState<boolean | null>(- collapseLongHistory && messagesToRender.length > COLLAPSE_THRESHOLD- ? true- : null,- );+ // 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;- const visibleMessages = useMemo(- () =>- messagesToRender.filter(- (_, filteredIndex) =>- !isCollapsed ||- filteredIndex === 0 ||- filteredIndex > messagesToRender.length - COLLAPSE_THRESHOLD,- ),- [isCollapsed, messagesToRender],+ // 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();@@ -102,7 +118,7 @@ export function ChatMessageList({const renderedMediaIds = new Set<string>();- visibleMessages.forEach(({ message }) => {+ messagesToRender.forEach(({ message }) => {const content = message.content || "";// Only content that ChatMessage renders through MarkdownView shows its@@ -117,43 +133,50 @@ export function ChatMessageList({});return filterAlreadyRenderedMedia(media, renderedMediaIds);- }, [media, shouldRenderMarkdown, visibleMessages, characterLimit]);+ }, [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-3">- <div className="flex flex-col gap-3">- {visibleMessages.map(({ message, originalIndex }) => {+ <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 sideTitle = isOutputMessage ? "Output" : "Input";- return (- <div className="flex flex-col" key={originalIndex}>- <ChatMessage- message={message}- title={titleBySide ? sideTitle : getMessageTitle(message)}- shouldRenderMarkdown={shouldRenderMarkdown}- currentView={currentView}- toolCallNumbers={messageToToolCallNumbers.get(originalIndex)}- isOutputMessage={isOutputMessage}- contentMode={contentMode}- />- {/* Show collapse/expand button after first message */}- {isCollapsed !== null &&- originalIndex === messagesToRender[0]?.originalIndex && (- <div className="mt-1 mb-2 flex">- <Button- variant="text"- onClick={() => setCollapsed((v) => !v)}- text={- isCollapsed- ? `Show ${messagesToRender.length - COLLAPSE_THRESHOLD} more`- : "Hide history"- }- />- </div>- )}- </div>+ 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={titleBySide ? sideTitle : getMessageTitle(message)}+ 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>@@ -172,3 +195,29 @@ export function ChatMessageList({</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.tsx b/web/src/features/traces/components/DetailAttributesTab.tsxindex ab3c4995db..51194db304 100644--- a/web/src/features/traces/components/DetailAttributesTab.tsx+++ b/web/src/features/traces/components/DetailAttributesTab.tsx@@ -4,8 +4,9 @@ import { useMemo } from "react";import { type MediaReturnType } from "@/src/features/media";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { IOSection } from "@/src/components/ui/IOSection";import { cn } from "@/src/utils/tailwind";-import { IO_SECTIONS_FLUSH_CLASS } from "@/src/features/traces/constants/ioSectionClasses";+import { IO_STICKY_HEADERS_CLASS } from "@/src/features/traces/constants/ioSectionClasses";import { type MetadataFilterActions } from "@/src/components/table/ValueCell";import { AttributeRowActions } from "./ObservationDetailView/AttributeRowActions";import { LargeJsonFieldFallback } from "@/src/features/traces/components/IOPreview/components/LargeJsonFieldFallback";@@ -59,8 +60,13 @@ export function DetailAttributesTab({const metadataTooLarge = metadataProbe.size > JSON_VIEW_RENDER_CHAR_LIMIT;return (- <div className="flex min-h-0 w-full flex-1 flex-col overflow-auto px-4 pb-4">- <div className={cn("space-y-3 pt-3", IO_SECTIONS_FLUSH_CLASS)}>+ <div+ className={cn(+ "flex min-h-0 w-full flex-1 flex-col overflow-auto px-4 pb-4",+ IO_STICKY_HEADERS_CLASS,+ )}+ >+ <div className="space-y-2 pt-3">{observation && hasAttributes ? (<PrettyJsonViewtitle="Attributes"@@ -87,13 +93,16 @@ export function DetailAttributesTab({{hasMetadata ? (<div>{metadataTooLarge ? (- <LargeJsonFieldFallback- title="Metadata"- serialized={metadataProbe.serialized}- isString={metadataProbe.isString}- charCount={metadataProbe.size}- downloadFileBase={`metadata-${objectId}`}- />+ <IOSection title="Metadata">+ <LargeJsonFieldFallback+ title="Metadata"+ hideTitle+ serialized={metadataProbe.serialized}+ isString={metadataProbe.isString}+ charCount={metadataProbe.size}+ downloadFileBase={`metadata-${objectId}`}+ />+ </IOSection>) : (<PrettyJsonViewtitle="Metadata"diff --git a/web/src/features/traces/components/IOPreview/IOPreviewJSON.tsx b/web/src/features/traces/components/IOPreview/IOPreviewJSON.tsxindex 4b2130a732..dfaa08a095 100644--- a/web/src/features/traces/components/IOPreview/IOPreviewJSON.tsx+++ b/web/src/features/traces/components/IOPreview/IOPreviewJSON.tsx@@ -53,7 +53,7 @@ function statusMessageBackgroundColor(return isDark ? "var(--light-red)" : "oklch(97.1% 0.013 17.38)";if (level === "WARNING")return isDark ? "var(--light-yellow)" : "oklch(98.7% 0.026 102.212)";- return "hsl(var(--surface-output))";+ return "hsl(var(--surface-section))";}/**@@ -163,7 +163,7 @@ function IOPreviewJSONInner({const { inputBgColor, outputBgColor, metadataBgColor } = useMemo(() => ({inputBgColor: isDark ? "rgb(15, 23, 42)" : "rgb(249, 252, 255)", // Dark slate vs light blue- outputBgColor: "hsl(var(--surface-output))",+ outputBgColor: "hsl(var(--surface-section))",metadataBgColor: isDark ? "rgb(30, 20, 40)" : "rgb(253, 251, 254)", // Dark purple vs light purple}),[isDark],diff --git a/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.clienttest.tsx b/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.clienttest.tsxindex 5351b57488..178b1fe046 100644--- a/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.clienttest.tsx+++ b/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.clienttest.tsx@@ -16,6 +16,11 @@ vi.mock("@/src/components/ui/PrettyJsonView", () => ({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", () => ({diff --git a/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.tsx b/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.tsxindex 023315daed..56cb4c5765 100644--- a/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.tsx+++ b/web/src/features/traces/components/IOPreview/IOPreviewJSONSimple.tsx@@ -1,8 +1,13 @@-import { useMemo } from "react";+import { useMemo, useState } from "react";import { type Prisma, type ScoreDomain, deepParseJson } from "@langfuse/shared";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import { type MediaReturnType } from "@/src/features/media";-import { CorrectedOutputField } from "./components/CorrectedOutputField";+import {+ CorrectedOutputField,+ useCorrectOutputAction,+} from "./components/CorrectedOutputField";+import { useCorrectionData } from "./hooks/useCorrectionData";+import { IOSection } from "@/src/components/ui/IOSection";import { LargeJsonFieldFallback } from "./components/LargeJsonFieldFallback";import {JSON_VIEW_RENDER_CHAR_LIMIT,@@ -10,8 +15,6 @@ import {} from "./fns/jsonViewSizeGate";import { StatusMessageSection } from "./components/StatusMessageSection";import type { ObservationStatusMessage } from "./components/statusMessagePresentation";-import { IO_SECTIONS_FLUSH_CLASS } from "../../constants/ioSectionClasses";-import { cn } from "@/src/utils/tailwind";export interface IOPreviewJSONSimpleProps {input?: Prisma.JsonValue;@@ -136,20 +139,45 @@ export function IOPreviewJSONSimple({const downloadName = observationId ?? traceId;+ // The "Correct output" pencil lives in the Output header; the field below+ // opens into its editor from there.+ const [correctionOpen, setCorrectionOpen] = useState(false);+ const correctOutputAction = useCorrectOutputAction({+ projectId,+ onOpen: () => setCorrectionOpen(true),+ });+ const { effectiveCorrection } = useCorrectionData(+ outputCorrection,+ observationId,+ traceId,+ );+ const correctionTrigger = showOutput ? "header" : "inline";+ // In header mode the field mounts only while open or with a correction.+ const showCorrectionField =+ showCorrections &&+ (correctionTrigger === "inline" || correctionOpen || !!effectiveCorrection);+ const outputActions =+ showCorrections && showOutput && !correctionOpen && !effectiveCorrection+ ? [correctOutputAction]+ : undefined;+return (- <div className={cn("pt-3", IO_SECTIONS_FLUSH_CLASS)}>+ <div className="space-y-2 pt-3">{status ? (<StatusMessageSection status={status} currentView="json" />) : null}{showInput &&(inputTooLarge ? (- <LargeJsonFieldFallback- title="Input"- serialized={inputProbe.serialized}- isString={inputProbe.isString}- charCount={inputProbe.size}- downloadFileBase={`input-${downloadName}`}- />+ <IOSection title="Input">+ <LargeJsonFieldFallback+ title="Input"+ hideTitle+ serialized={inputProbe.serialized}+ isString={inputProbe.isString}+ charCount={inputProbe.size}+ downloadFileBase={`input-${downloadName}`}+ />+ </IOSection>) : (<PrettyJsonViewtitle="Input"@@ -170,13 +198,16 @@ export function IOPreviewJSONSimple({))}{showOutput &&(outputTooLarge ? (- <LargeJsonFieldFallback- title="Output"- serialized={outputProbe.serialized}- isString={outputProbe.isString}- charCount={outputProbe.size}- downloadFileBase={`output-${downloadName}`}- />+ <IOSection title="Output" actions={outputActions}>+ <LargeJsonFieldFallback+ title="Output"+ hideTitle+ serialized={outputProbe.serialized}+ isString={outputProbe.isString}+ charCount={outputProbe.size}+ downloadFileBase={`output-${downloadName}`}+ />+ </IOSection>) : (<PrettyJsonViewtitle="Output"@@ -186,6 +217,7 @@ export function IOPreviewJSONSimple({isParsing={isParsing}media={media?.filter((m) => m.field === "output") ?? []}currentView="json"+ actions={outputActions}externalExpansionState={outputExpanded}onExternalExpansionChange={onOutputExpandedChange as (@@ -199,7 +231,7 @@ export function IOPreviewJSONSimple({against — an acceptable degradation for payloads too large to render.We flag it as too-large so the diff dialog says so, rather thanreporting "no original output". */}- {showCorrections && (+ {showCorrectionField && (<CorrectedOutputFieldactualOutput={effectiveOutput}actualOutputTooLarge={outputTooLarge}@@ -208,17 +240,23 @@ export function IOPreviewJSONSimple({projectId={projectId}traceId={traceId}environment={environment}+ trigger={correctionTrigger}+ startEditing={correctionOpen && !effectiveCorrection}+ onClosed={() => setCorrectionOpen(false)}/>)}{showMetadata &&(metadataTooLarge ? (- <LargeJsonFieldFallback- title="Metadata"- serialized={metadataProbe.serialized}- isString={metadataProbe.isString}- charCount={metadataProbe.size}- downloadFileBase={`metadata-${downloadName}`}- />+ <IOSection title="Metadata">+ <LargeJsonFieldFallback+ title="Metadata"+ hideTitle+ serialized={metadataProbe.serialized}+ isString={metadataProbe.isString}+ charCount={metadataProbe.size}+ downloadFileBase={`metadata-${downloadName}`}+ />+ </IOSection>) : (<PrettyJsonViewtitle="Metadata"diff --git a/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsx b/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsxindex 76a5935d8b..6c7fb9840f 100644--- a/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsx+++ b/web/src/features/traces/components/IOPreview/IOPreviewPretty.tsx@@ -1,6 +1,5 @@/* eslint-disable no-nested-ternary */-import { useEffect, useMemo, useRef } from "react";-import { cn } from "@/src/utils/tailwind";+import { useEffect, useMemo, useRef, useState } from "react";import {type ObservationType,type Prisma,@@ -8,6 +7,7 @@ import {deepParseJson,} from "@langfuse/shared";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { type IOSectionAction } from "@/src/components/ui/IOSection";import { useMarkdownRenderCharacterLimit } from "@/src/hooks/useMarkdownRenderCharacterLimit";import { type MediaReturnType } from "@/src/features/media";import { type ChatMLParserResult } from "../../hooks/useChatMLParser";@@ -26,10 +26,14 @@ import {type ExpansionStateProps,type IOPreviewContentMode,} from "./IOPreview";-import { CorrectedOutputField } from "./components/CorrectedOutputField";+import {+ CorrectedOutputField,+ useCorrectOutputAction,+} from "./components/CorrectedOutputField";+import { useCorrectionData } from "./hooks/useCorrectionData";+import { shouldRenderMessageForContentMode } from "@/src/features/traces/fns/chatMessageUtils";import { StatusMessageSection } from "./components/StatusMessageSection";import type { ObservationStatusMessage } from "./components/statusMessagePresentation";-import { IO_SECTIONS_FLUSH_CLASS } from "../../constants/ioSectionClasses";interface JsonInputOutputViewProps {parsedInput: unknown;@@ -48,6 +52,8 @@ interface JsonInputOutputViewProps {onOutputExpansionChange?: (expansion: Record<string, boolean> | boolean,) => void;+ /** Extra header controls on the Output section. */+ outputActions?: IOSectionAction[];}function JsonInputOutputView({@@ -63,6 +69,7 @@ function JsonInputOutputView({outputExpansionState,onInputExpansionChange,onOutputExpansionChange,+ outputActions,}: JsonInputOutputViewProps) {const showInput = !hideInput && !(hideIfNull && !parsedInput);const showOutput = !hideOutput && !(hideIfNull && !parsedOutput);@@ -89,6 +96,7 @@ function JsonInputOutputView({isParsing={isParsing}media={media?.filter((m) => m.field === "output") ?? []}currentView="pretty"+ actions={outputActions}externalExpansionState={outputExpansionState}onExternalExpansionChange={onOutputExpansionChange}/>@@ -280,6 +288,55 @@ export function IOPreviewPretty({};const showData = contentMode !== "conversation";+ // The "Correct output" pencil lives in the Output header; the field below+ // opens into its editor from there. Without an Output header (no output+ // message rendered) the field keeps its own inline trigger.+ const [correctionOpen, setCorrectionOpen] = useState(false);+ const correctOutputAction = useCorrectOutputAction({+ projectId,+ onOpen: () => setCorrectionOpen(true),+ });+ const { effectiveCorrection } = useCorrectionData(+ outputCorrection,+ observationId,+ traceId,+ );+ const hasOutputHeader = shouldRenderMessages+ ? allMessages.some(+ (message, index) =>+ index >= (inputMessageCount ?? 0) &&+ shouldRenderMessageForContentMode(+ message,+ contentMode,+ showSystemPrompt,+ ),+ )+ : !hideOutput && !(hideIfNull && !parsedOutput);+ const correctionTrigger = hasOutputHeader ? "header" : "inline";+ const outputActions =+ showCorrections &&+ hasOutputHeader &&+ !correctionOpen &&+ !effectiveCorrection+ ? [correctOutputAction]+ : undefined;+ // In header mode the field mounts only while open or with a correction.+ const showCorrectionField =+ showCorrections &&+ (correctionTrigger === "inline" || correctionOpen || !!effectiveCorrection);+ const correctedOutputField = showCorrectionField ? (+ <CorrectedOutputField+ actualOutput={parsedOutput}+ existingCorrection={outputCorrection}+ observationId={observationId}+ projectId={projectId}+ traceId={traceId}+ environment={environment}+ trigger={correctionTrigger}+ startEditing={correctionOpen && !effectiveCorrection}+ onClosed={() => setCorrectionOpen(false)}+ />+ ) : null;// Only generations hold a conversation; tools, spans, agents and the rest// are titled Input / Output rather than by role. (`isGenerationLike` is// wider: it also covers TOOL and AGENT, which carry model usage, not chat.)@@ -287,7 +344,7 @@ export function IOPreviewPretty({observationType !== undefined && observationType !== "GENERATION";return (- <div className={cn("space-y-3 pt-3", IO_SECTIONS_FLUSH_CLASS)}>+ <div className="space-y-2 pt-3">{showData && status ? (<StatusMessageSection status={status} currentView="pretty" />) : null}@@ -317,31 +374,17 @@ export function IOPreviewPretty({contentMode={contentMode}showSystemPrompt={showSystemPrompt}titleBySide={titleBySide}+ outputActions={outputActions}/>- {showCorrections && (- <CorrectedOutputField- actualOutput={parsedOutput}- existingCorrection={outputCorrection}- observationId={observationId}- projectId={projectId}- traceId={traceId}- environment={environment}- />- )}+ {correctedOutputField}</div>) : showData ? (<div>- <JsonInputOutputView {...jsonViewProps} />- {showCorrections && (- <CorrectedOutputField- actualOutput={parsedOutput}- existingCorrection={outputCorrection}- observationId={observationId}- projectId={projectId}- traceId={traceId}- environment={environment}- />- )}+ <JsonInputOutputView+ {...jsonViewProps}+ outputActions={outputActions}+ />+ {correctedOutputField}</div>) : null}</div>diff --git a/web/src/features/traces/components/IOPreview/components/ChatMessage.clienttest.tsx b/web/src/features/traces/components/IOPreview/components/ChatMessage.clienttest.tsxindex 69bd501221..12da928e29 100644--- a/web/src/features/traces/components/IOPreview/components/ChatMessage.clienttest.tsx+++ b/web/src/features/traces/components/IOPreview/components/ChatMessage.clienttest.tsx@@ -1,4 +1,5 @@import { fireEvent, render, screen } from "@testing-library/react";+import { Pencil } from "@langfuse/icons";import { vi } from "vitest";const { copyTextToClipboard } = vi.hoisted(() => ({@@ -74,9 +75,11 @@ function renderChatMessage({shouldRenderMarkdown = true,contentMode = "all",+ defaultCollapsed,}: {shouldRenderMarkdown?: boolean;contentMode?: IOPreviewContentMode;+ defaultCollapsed?: boolean;} = {},) {return render(@@ -86,6 +89,7 @@ function renderChatMessage(shouldRenderMarkdown={shouldRenderMarkdown}currentView="pretty"contentMode={contentMode}+ defaultCollapsed={defaultCollapsed}/>,);}@@ -120,20 +124,138 @@ describe("ChatMessage content modes", () => {// 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 prompt/i });+ screen.queryAllByRole("button", { name: /^expand system/i });const collapseButtons = () =>- screen.queryAllByRole("button", { name: /collapse system prompt/i });+ screen.queryAllByRole("button", { name: /^collapse system/i });const expandButton = () => expandButtons()[0] ?? null;const collapseButton = () => collapseButtons()[0] ?? null;-// An expanded prompt offers one control at each end of the message: the header-// (reachable without scrolling) and the inline one after the body.-const isInHeader = (el: HTMLElement) =>- el.closest(".io-message-header") !== null;-const headerCollapseButtons = () => collapseButtons().filter(isInHeader);-const inlineCollapseButtons = () =>- collapseButtons().filter((el) => !isInHeader(el));+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(() => {@@ -147,10 +269,10 @@ describe("ChatMessage system prompt collapse", () => {content: longSystemPrompt,} as ChatMlMessage);- // One control only, and it sits with the prompt body rather than being- // duplicated into the message header.+ // One caret in the section header; the body is not rendered.expect(expandButtons()).toHaveLength(1);- expect(expandButtons()[0].closest(".io-message-header")).toBeNull();+ 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", () => {@@ -162,7 +284,9 @@ describe("ChatMessage system prompt collapse", () => {content: longSystemPrompt,} as ChatMlMessage);- expect(expandButton()).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /^expand planner-instructions/i }),+ ).toBeInTheDocument();});it("collapses a long system message on the json/pretty path (markdown off)", () => {@@ -171,10 +295,9 @@ describe("ChatMessage system prompt collapse", () => {{ shouldRenderMarkdown: false },);- // Same collapsed-state guarantee as the markdown path: exactly one control,- // and it sits with the prompt body rather than in the message header.+ // The caret in the section header is the one collapse control here too.expect(expandButtons()).toHaveLength(1);- expect(expandButtons()[0].closest(".io-message-header")).toBeNull();+ expect(expandButtons()[0].closest(".io-message-header")).not.toBeNull();});it("expands on click and persists the expanded preference", () => {@@ -186,6 +309,9 @@ describe("ChatMessage system prompt collapse", () => {fireEvent.click(expandButton()!);expect(collapseButton()).toBeInTheDocument();+ expect(screen.getAllByText(/system-prompt-line-1 /).length).toBeGreaterThan(+ 0,+ );expect(localStorage.getItem("collapseSystemPrompt")).toBe("false");});@@ -197,41 +323,17 @@ describe("ChatMessage system prompt collapse", () => {content: longSystemPrompt,} as ChatMlMessage);- // rendered expanded, with one collapse control at each end of the message:- // an expanded prompt is too tall for the inline one to be reachable.+ // rendered expanded, with the caret offering to collapseexpect(expandButtons()).toHaveLength(0);- expect(collapseButtons()).toHaveLength(2);- expect(headerCollapseButtons()).toHaveLength(1);- expect(inlineCollapseButtons()).toHaveLength(1);+ expect(collapseButtons()).toHaveLength(1);- // Click the INLINE control — the header test below covers the header path.- fireEvent.click(inlineCollapseButtons()[0]!);+ fireEvent.click(collapseButton()!);expect(expandButtons().length).toBeGreaterThan(0);expect(localStorage.getItem("collapseSystemPrompt")).toBe("true");});- it("collapses from the header control without scrolling to the body", () => {- localStorage.setItem("collapseSystemPrompt", "false");-- renderChatMessage({- role: "system",- content: longSystemPrompt,- } as ChatMlMessage);-- fireEvent.click(headerCollapseButtons()[0]);-- // back to the collapsed shape: one control, inline only- expect(expandButtons()).toHaveLength(1);- expect(expandButtons()[0].closest(".io-message-header")).toBeNull();- expect(collapseButtons()).toHaveLength(0);- expect(localStorage.getItem("collapseSystemPrompt")).toBe("true");- });-- it("offers a header collapse control on the json/pretty path too", () => {- // PrettyJsonView delegates the body to a title-less MarkdownView, which- // renders no header of its own — so a fix confined to MarkdownViewer would- // leave this path collapsible only from the bottom.+ it("collapses a long system prompt from the header on the json/pretty path", () => {localStorage.setItem("collapseSystemPrompt", "false");renderChatMessage(@@ -239,14 +341,11 @@ describe("ChatMessage system prompt collapse", () => {{ shouldRenderMarkdown: false },);- expect(collapseButtons()).toHaveLength(2);- expect(headerCollapseButtons()).toHaveLength(1);- expect(inlineCollapseButtons()).toHaveLength(1);+ expect(collapseButtons()).toHaveLength(1);- fireEvent.click(headerCollapseButtons()[0]);+ fireEvent.click(collapseButton()!);expect(expandButtons()).toHaveLength(1);- expect(expandButtons()[0].closest(".io-message-header")).toBeNull();expect(localStorage.getItem("collapseSystemPrompt")).toBe("true");});@@ -278,9 +377,9 @@ describe("ChatMessage system prompt collapse", () => {expect(collapseButton()).toBeInTheDocument();});- it("does not collapse when only media parts push a system prompt over the threshold", () => {+ 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 collapse threshold (and must never appear in a preview)+ // toward the long-prompt thresholdrenderChatMessage({role: "system",content: [@@ -293,12 +392,11 @@ describe("ChatMessage system prompt collapse", () => {} as unknown as ChatMlMessage);expect(expandButton()).not.toBeInTheDocument();- expect(collapseButton()).not.toBeInTheDocument();+ expect(collapseButton()).toBeInTheDocument();});- it("offers no toggle when the preview would hide nothing", () => {- // above the char threshold, but fits within 4 lines / 500 chars, so- // collapsing would not hide anything — a toggle would be dead+ it("starts open when the prompt is short enough to read at a glance", () => {+ // above the char threshold, but fits within 4 lines / 500 charsconst content = Array.from({ length: 3 },(_, i) => `line-${i + 1} ${"x".repeat(90)}`,@@ -307,7 +405,7 @@ describe("ChatMessage system prompt collapse", () => {renderChatMessage({ role: "system", content } as ChatMlMessage);expect(expandButton()).not.toBeInTheDocument();- expect(collapseButton()).not.toBeInTheDocument();+ expect(collapseButton()).toBeInTheDocument();});it("keeps the toggle functional in-session when localStorage is blocked", () => {@@ -367,7 +465,7 @@ describe("ChatMessage system prompt collapse", () => {} as ChatMlMessage);expect(expandButton()).not.toBeInTheDocument();- expect(collapseButton()).not.toBeInTheDocument();+ expect(collapseButton()).toBeInTheDocument();});});@@ -486,9 +584,9 @@ describe("ChatMessage media content parts", () => {expect(screen.queryByText("tool_call_id")).not.toBeInTheDocument();});- // The media strip dedupes against what rendered inline, so a collapsed- // system prompt must not swallow its attachments.- it("keeps media parts visible while a long system prompt is collapsed", () => {+ // 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: [@@ -497,7 +595,10 @@ describe("ChatMessage media content parts", () => {],} as unknown as ChatMlMessage);- expect(expandButton()).toBeInTheDocument();+ 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.tsxindex 3577f034d0..c42ba11d1b 100644--- a/web/src/features/traces/components/IOPreview/components/ChatMessage.tsx+++ b/web/src/features/traces/components/IOPreview/components/ChatMessage.tsx@@ -1,11 +1,8 @@/* eslint-disable @repo/no-null-render */import { useState } from "react";-import { Button } from "@/src/components/ui/button";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";-import {- MarkdownJsonView,- MarkdownJsonViewHeader,-} from "@/src/components/ui/MarkdownJsonView";+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";@@ -37,8 +34,12 @@ export interface ChatMessageProps {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[];}/**@@ -57,9 +58,16 @@ export function ChatMessage({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@@ -78,25 +86,39 @@ export function ChatMessage({const isSystemPrompt = message.role === "system";const showData = contentMode !== "conversation";- // Toggle button for passthrough JSON- const passthroughToggleButton =- showData && hasPassthroughJson(message) ? (- <Button- variant="ghost"- size="icon-xs"- onClick={() => setShowTableView((v) => !v)}- title={- showTableView ? "Show formatted view" : "Show passthrough JSON data"+ // 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,}- className="hover:bg-border -mr-2"- >- {showTableView ? (- <ListChevronsDownUp size="sm" __rawClassName="text-primary" />- ) : (- <ListChevronsUpDown size="sm" color="default" />- )}- </Button>- ) : undefined;+ : 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 messageif (isPlaceholderMessage(message)) {@@ -106,6 +128,9 @@ export function ChatMessage({<MarkdownJsonViewtitle="Placeholder"content={message.name || "Unnamed placeholder"}+ actions={actions}+ collapsed={collapsed}+ onCollapsedChange={setCollapsed}/></div><div style={{ display: shouldRenderMarkdown ? "none" : "block" }}>@@ -113,6 +138,9 @@ export function ChatMessage({title="Placeholder"json={message.name || "Unnamed placeholder"}currentView={currentView}+ actions={actions}+ collapsed={collapsed}+ onCollapsedChange={setCollapsed}/></div></div>@@ -124,9 +152,12 @@ export function ChatMessage({return (<div className="transition-colors"><PrettyJsonView- title={title || (isOutputMessage ? "Output" : "Input")}+ title={sectionTitle}json={message.json}currentView={currentView}+ actions={actions}+ collapsed={collapsed}+ onCollapsedChange={setCollapsed}/></div>);@@ -137,10 +168,12 @@ export function ChatMessage({return (<div className="transition-colors"><PrettyJsonView- title={title}+ title={sectionTitle}json={message.json}currentView="pretty"- controlButtons={passthroughToggleButton}+ actions={actions}+ collapsed={collapsed}+ onCollapsedChange={setCollapsed}/></div>);@@ -154,25 +187,25 @@ export function ChatMessage({toolCalls.length > 0) {return (- <div className="group/iosection transition-colors">- <MarkdownJsonViewHeader- title={title}- hoverRevealControls- handleOnCopy={() => {- // Shared stringify (not raw JSON.stringify) so \uXXXX escapes in- // string fields are copied as real characters, like the rendered- // view shows them.- const rawText = stringify(message, undefined, 2);- copyTextToClipboard(rawText);- }}- controlButtons={passthroughToggleButton}- />+ <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}+ ><ToolCallInvocationsViewmessage={message}toolCallNumbers={toolCallNumbers}renderResponse={renderToolResponse}/>- </div>+ </IOSection>);}@@ -182,7 +215,7 @@ export function ChatMessage({hasThinkingContent(message) ||hasRedactedThinkingContent(message)) {- // Thinking blocks to render after header+ // Thinking blocks render at the top of the section boxconst thinkingBlocks = (<>{hasThinkingContent(message) &&@@ -200,48 +233,47 @@ export function ChatMessage({</>);+ // 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={title}+ title={sectionTitle}content={message.content || ""}audio={message.audio}- controlButtons={passthroughToggleButton}- afterHeader={thinkingBlocks}+ actions={actions}+ beforeContent={thinkingBlocks}+ afterContent={toolCallsView}isSystemPrompt={isSystemPrompt}+ collapsed={collapsed}+ onCollapsedChange={setCollapsed}/>- {showData && toolCalls.length > 0 && (- <div className="mt-2">- <ToolCallInvocationsView- message={message}- toolCallNumbers={toolCallNumbers}- renderResponse={renderToolResponse}- />- </div>- )}</div>{/* JSON view */}<div style={{ display: shouldRenderMarkdown ? "none" : "block" }}><PrettyJsonView- title={title}+ title={sectionTitle}json={message.content}currentView={currentView}- controlButtons={passthroughToggleButton}- afterHeader={thinkingBlocks}+ actions={actions}+ beforeContent={thinkingBlocks}+ afterContent={toolCallsView}isSystemPrompt={isSystemPrompt}+ collapsed={collapsed}+ onCollapsedChange={setCollapsed}/>- {showData && toolCalls.length > 0 && (- <div className="mt-2">- <ToolCallInvocationsView- message={message}- toolCallNumbers={toolCallNumbers}- renderResponse={renderToolResponse}- />- </div>- )}</div></div>);@@ -252,9 +284,12 @@ export function ChatMessage({return (<div className="transition-colors"><PrettyJsonView- title={title || (isOutputMessage ? "Output" : "Input")}+ title={sectionTitle}json={withoutUnsetFields(message)}currentView={currentView}+ actions={actions}+ collapsed={collapsed}+ onCollapsedChange={setCollapsed}/></div>);diff --git a/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.clienttest.tsx b/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.clienttest.tsxindex 6fcedc0e45..a718ad5db0 100644--- a/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.clienttest.tsx+++ b/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.clienttest.tsx@@ -16,19 +16,28 @@ vi.mock("../hooks/useCorrectionMutations", () => ({}),}));+const editorHook = vi.hoisted(() => ({+ spy: vi.fn(),+ handleEdit: vi.fn(),+}));+const access = vi.hoisted(() => ({ hasAccess: true }));+vi.mock("../hooks/useCorrectionEditor", () => ({- useCorrectionEditor: ({ correctionValue }: { correctionValue: string }) => ({- isEditing: false,- setIsEditing: vi.fn(),- value: correctionValue,- isValidJson: true,- handleEdit: vi.fn(),- handleChange: vi.fn(),- }),+ useCorrectionEditor: (params: { correctionValue: string }) => {+ editorHook.spy(params);+ return {+ isEditing: false,+ setIsEditing: vi.fn(),+ value: params.correctionValue,+ isValidJson: true,+ handleEdit: editorHook.handleEdit,+ handleChange: vi.fn(),+ };+ },}));vi.mock("@/src/features/rbac", () => ({- useHasProjectAccess: () => true,+ useHasProjectAccess: () => access.hasAccess,}));vi.mock("@/src/features/posthog-analytics", () => ({@@ -68,6 +77,51 @@ const baseProps = {};describe("CorrectedOutputField visibility", () => {+ beforeEach(() => {+ access.hasAccess = true;+ editorHook.spy.mockClear();+ editorHook.handleEdit.mockClear();+ });++ it("does not open the editor for readers without scores:save", () => {+ access.hasAccess = false;+ render(+ <CorrectedOutputField+ {...baseProps}+ existingCorrection={null}+ trigger="header"+ startEditing+ />,+ );++ expect(editorHook.spy).toHaveBeenLastCalledWith(+ expect.objectContaining({ initialEditing: false }),+ );+ expect(+ screen.getByRole("button", { name: "Click to add corrected output" }),+ ).toBeDisabled();+ });++ it("opens the inline link without entering edit mode for readers", () => {+ access.hasAccess = false;+ render(<CorrectedOutputField {...baseProps} existingCorrection={null} />);++ fireEvent.click(screen.getByRole("button", { name: "Correct output" }));++ expect(editorHook.handleEdit).not.toHaveBeenCalled();+ expect(+ screen.getByRole("button", { name: "Click to add corrected output" }),+ ).toBeDisabled();+ });++ it("opens the inline link straight into edit mode with access", () => {+ render(<CorrectedOutputField {...baseProps} existingCorrection={null} />);++ fireEvent.click(screen.getByRole("button", { name: "Correct output" }));++ expect(editorHook.handleEdit).toHaveBeenCalledTimes(1);+ });+it("shows an existing correction without requiring a click", () => {render(<CorrectedOutputField@@ -102,7 +156,7 @@ describe("CorrectedOutputField visibility", () => {/>,);- expect(screen.getByText("Corrected Output")).toBeInTheDocument();+ expect(screen.getByText("Corrected output")).toBeInTheDocument();expect(screen.queryByRole("button", { name: "Correct output" }),).not.toBeInTheDocument();@@ -131,7 +185,23 @@ describe("CorrectedOutputField visibility", () => {expect(screen.getByRole("button", { name: "Correct output" }),).toBeInTheDocument();- expect(screen.queryByText("Corrected Output")).not.toBeInTheDocument();+ expect(screen.queryByText("Corrected output")).not.toBeInTheDocument();+ });++ it("in header mode shows the section without its own link", () => {+ render(+ <CorrectedOutputField+ {...baseProps}+ existingCorrection={null}+ trigger="header"+ startEditing+ />,+ );++ expect(screen.getByText("Corrected output")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Correct output" }),+ ).not.toBeInTheDocument();});it("keeps the section collapsed when no correction exists", () => {diff --git a/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.tsx b/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.tsxindex 15da790578..f8e88b637b 100644--- a/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.tsx+++ b/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.tsx@@ -1,21 +1,22 @@-/* eslint-disable no-nested-ternary */-import { Pencil, Trash, FileDiff, Check, Info } from "@langfuse/icons";-import { cn } from "@/src/utils/tailwind";-import { Button } from "@/src/components/ui/button";+import { Pencil, Trash, FileDiff } from "@langfuse/icons";+import {+ IOSection,+ type IOSectionAction,+ type IOSectionInfo,+ type IOSectionStatus,+ type IOSectionToggle,+} from "@/src/components/ui/IOSection";import { type ScoreDomain } from "@langfuse/shared";import { useCorrectionData } from "../hooks/useCorrectionData";import { useCorrectionMutations } from "../hooks/useCorrectionMutations";import { useCorrectionEditor } from "../hooks/useCorrectionEditor";-import { useMemo, useState } from "react";+import { useCallback, useMemo, useRef, useState } from "react";+import { type ReactCodeMirrorRef } from "@uiw/react-codemirror";import { CodeMirrorEditor } from "@/src/components/editor/CodeMirrorEditor";import { useHasProjectAccess } from "@/src/features/rbac";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";-import { Switch } from "@/src/components/design-system/Switch/Switch";import useLocalStorage from "@/src/components/useLocalStorage";import { CorrectedOutputDiffDialog } from "./CorrectedOutputDiffDialog";-import { HoverCard } from "@/src/components/design-system/HoverCard/HoverCard";-import Link from "next/link";-import { Spinner } from "@/src/components/design-system/Spinner/Spinner";interface CorrectedOutputFieldProps {projectId: string;@@ -31,6 +32,39 @@ interface CorrectedOutputFieldProps {existingCorrection?: ScoreDomain | null;observationId?: string;compact?: boolean; // Use smaller font size for JSON Beta view+ /** `header`: the host renders `CorrectOutputButton` in the Output header+ and mounts this field only while open or when a correction exists, so+ the field has no trigger of its own. */+ trigger?: "inline" | "header";+ /** Mount straight into the editor (header mode, no correction yet). */+ startEditing?: boolean;+ /** Called when the section closes again (correction deleted). */+ onClosed?: () => void;+}++/** The Output header's pencil: opens the correction editor. Disabled without+ `scores:save`, like the section's own edit and delete actions. */+export function useCorrectOutputAction({+ projectId,+ onOpen,+}: {+ projectId: string;+ onOpen: () => void;+}): IOSectionAction {+ const capture = usePostHogClientCapture();+ const hasAccess = useHasProjectAccess({ projectId, scope: "scores:save" });+ return {+ icon: Pencil,+ label: "Correct output",+ disabled: !hasAccess,+ onClick: () => {+ capture("trace_detail:io_section_collapse_toggle", {+ section: "corrected_output",+ collapsed: false,+ });+ onOpen();+ },+ };}export function CorrectedOutputField({@@ -42,6 +76,9 @@ export function CorrectedOutputField({traceId,environment = "default",compact = false,+ trigger = "inline",+ startEditing = false,+ onClosed,}: CorrectedOutputFieldProps) {const hasAccess = useHasProjectAccess({ projectId, scope: "scores:save" });const capture = usePostHogClientCapture();@@ -55,8 +92,15 @@ export function CorrectedOutputField({// Diff dialog stateconst [isDiffDialogOpen, setIsDiffDialogOpen] = useState(false);- // When no correction exists, keep the section collapsed until it is opened.- const [isExpanded, setIsExpanded] = useState(false);+ // Inline mode: no correction keeps the section behind its link until opened.+ // Header mode: the host mounts this field only when it should show.+ const [internalExpanded, setIsExpanded] = useState(false);+ const isExpanded = trigger === "header" || internalExpanded;+ const editorRef = useRef<ReactCodeMirrorRef | null>(null);+ // Stable so CodeMirrorEditor's ref callback fires it once per mount.+ const focusEditor = useCallback(() => {+ requestAnimationFrame(() => editorRef.current?.view?.focus());+ }, []);// Merge cache + server dataconst { effectiveCorrection, correctionValue } = useCorrectionData(@@ -89,6 +133,7 @@ export function CorrectedOutputField({onSave: handleSave,setSaveStatus,strictJsonMode,+ initialEditing: startEditing && hasAccess,});// When not editing, use correctionValue (source of truth from cache/server)@@ -156,6 +201,7 @@ export function CorrectedOutputField({handleDelete();setIsEditing(false);setIsExpanded(false);+ onClosed?.();};if (!isExpanded && !effectiveCorrection) {@@ -168,7 +214,10 @@ export function CorrectedOutputField({section: "corrected_output",collapsed: false,});+ // One click: open the section straight into the editor (readers+ // without scores:save get the disabled placeholder).setIsExpanded(true);+ if (hasAccess) handleEdit();}}className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs hover:underline">@@ -179,6 +228,67 @@ export function CorrectedOutputField({);}+ const status = getStatus({+ isEditing,+ hasContent,+ isValidJson,+ saveStatus,+ strictJsonMode,+ });++ const actions: IOSectionAction[] = hasContent+ ? [+ {+ icon: FileDiff,+ label: "View diff between original and corrected output",+ onClick: () => setIsDiffDialogOpen(true),+ },+ ...(!isEditing+ ? [+ {+ icon: Pencil,+ label: "Edit corrected output",+ onClick: handleEdit,+ disabled: !hasAccess,+ },+ ]+ : []),+ {+ icon: Trash,+ label: "Delete corrected output",+ onClick: handleDeleteWithExitEdit,+ disabled: !hasAccess,+ },+ ]+ : [];++ const jsonToggle: IOSectionToggle = {+ label: "JSON",+ checked: strictJsonMode,+ onCheckedChange: handleStrictJsonModeChange,+ disabled: !isEditing,+ };++ const info: IOSectionInfo = {+ label: "About corrected outputs",+ text: "Corrected outputs allow you to save the expected output for a trace or observation.",+ docsHref: "https://langfuse.com/docs/observability/features/corrections",+ };++ const body = (+ <CorrectionBody+ hasContent={hasContent}+ isEditing={isEditing}+ hasAccess={hasAccess}+ displayValue={displayValue}+ strictJsonMode={strictJsonMode}+ editorRef={editorRef}+ onEdit={handleEdit}+ onChange={handleEditorChange}+ onEditorMount={focusEditor}+ />+ );+return (<><CorrectedOutputDiffDialog@@ -189,146 +299,120 @@ export function CorrectedOutputField({correctedOutput={value}strictJsonMode={strictJsonMode}/>- <div className="pt-3">- <div className="group relative rounded-md">+ {compact ? (+ // The JSON Beta section renders its own title; only controls + body here.+ <div className="group pt-2"><div className="flex items-center justify-between py-1.5">- <div className="flex items-center gap-1">- <span- className={cn("font-bold", compact ? "text-xs" : "text-base")}- >- {compact ? "" : "Corrected Output"}- </span>- <HoverCard- placement="right"- content={- <div className="w-80 p-3 text-xs">- <p>- Corrected outputs allow you to save the expected output- for a trace or observation. Learn more in the{" "}- <Link- href="https://langfuse.com/docs/observability/features/corrections"- target="_blank"- rel="noreferrer"- className="hover:text-foreground underline"- >- documentation- </Link>- .- </p>- </div>- }- >- {({ getTriggerProps }) => (- <button- type="button"- aria-label="About corrected outputs"- className="text-muted-foreground hover:text-foreground"- {...getTriggerProps()}- >- <Info size="base" />- </button>- )}- </HoverCard>- </div>- <div className="flex items-center">- <div className="flex items-center -space-x-1 opacity-0 transition-opacity group-hover:opacity-100">- {!isValidJson && isEditing && hasContent && (- <span className="mr-2 text-xs text-red-500">- {strictJsonMode- ? "Invalid JSON - fix to save"- : "Cannot save empty content"}- </span>- )}- {isValidJson && saveStatus === "saving" && (- <div className="mr-2 flex items-center gap-1">- <Spinner size="xxs" />- <span className="text-muted-foreground text-xs">- Saving- </span>- </div>- )}- {isValidJson && saveStatus === "saved" && (- <div className="mr-2 flex items-center gap-1">- <Check size="sm" />- <span className="text-muted-foreground text-xs">Saved</span>- </div>- )}- {hasContent && (- <>- <Button- size="icon-xs"- variant="ghost"- onClick={() => setIsDiffDialogOpen(true)}- className="hover:bg-border"- title="View diff between original and corrected output"- >- <FileDiff size="sm" color="default" />- </Button>- {!isEditing && (- <Button- size="icon-xs"- variant="ghost"- onClick={handleEdit}- disabled={!hasAccess}- className="hover:bg-border"- title="Edit corrected output"- >- <Pencil size="sm" color="default" />- </Button>- )}- <Button- size="icon-xs"- variant="ghost"- onClick={handleDeleteWithExitEdit}- disabled={!hasAccess}- className="hover:bg-border"- title="Delete corrected output"- >- <Trash size="sm" color="default" />- </Button>- </>- )}- </div>- <div className="flex items-center">- <div className="mx-1">- <Switch- checked={strictJsonMode}- onCheckedChange={handleStrictJsonModeChange}- disabled={!isEditing}- size="sm"- />- </div>- <span className="text-muted-foreground text-xs">JSON</span>- </div>+ <IOSection.InfoButton info={info} />+ <div className="flex items-center -space-x-1 opacity-0 transition-opacity group-hover:opacity-100">+ <IOSection.Controls+ status={status}+ actions={actions}+ toggle={jsonToggle}+ /></div></div>-- {!hasContent && !isEditing ? (- <button- onClick={handleEdit}- disabled={!hasAccess}- className="text-muted-foreground hover:bg-muted/50 w-full cursor-pointer rounded-md border px-3 py-4 text-center text-xs transition-colors"- >- Click to add corrected output- </button>- ) : isEditing ? (- <CodeMirrorEditor- value={displayValue}- onChange={handleEditorChange}- mode={strictJsonMode ? "json" : "text"}- minHeight={200}- placeholder="Enter corrected output..."- />- ) : (- <CodeMirrorEditor- value={displayValue}- mode={strictJsonMode ? "json" : "text"}- editable={false}- className="bg-surface-output [&_.cm-gutters]:bg-transparent! [&_.cm-scroller]:bg-transparent!"- />- )}+ {body}</div>- </div>+ ) : (+ <div className="pt-2">+ <IOSection+ title="Corrected output"+ info={info}+ status={status}+ actions={actions.length > 0 ? actions : undefined}+ toggle={jsonToggle}+ >+ {body}+ </IOSection>+ </div>+ )}</>);}++function getStatus({+ isEditing,+ hasContent,+ isValidJson,+ saveStatus,+ strictJsonMode,+}: {+ isEditing: boolean;+ hasContent: boolean;+ isValidJson: boolean;+ saveStatus: "idle" | "saving" | "saved";+ strictJsonMode: boolean;+}): IOSectionStatus | undefined {+ if (!isValidJson) {+ if (!isEditing || !hasContent) return undefined;+ return {+ kind: "error",+ text: strictJsonMode+ ? "Invalid JSON - fix to save"+ : "Cannot save empty content",+ };+ }+ if (saveStatus === "saving") return { kind: "saving", text: "Saving" };+ if (saveStatus === "saved") return { kind: "saved", text: "Saved" };+ return undefined;+}++/** Placeholder, editor, or read-only view of the correction. */+function CorrectionBody({+ hasContent,+ isEditing,+ hasAccess,+ displayValue,+ strictJsonMode,+ editorRef,+ onEdit,+ onChange,+ onEditorMount,+}: {+ hasContent: boolean;+ isEditing: boolean;+ hasAccess: boolean;+ displayValue: string;+ strictJsonMode: boolean;+ editorRef: React.RefObject<ReactCodeMirrorRef | null>;+ onEdit: () => void;+ onChange: (value: string) => void;+ onEditorMount: () => void;+}) {+ if (!hasContent && !isEditing) {+ return (+ <button+ type="button"+ onClick={onEdit}+ disabled={!hasAccess}+ className="text-muted-foreground hover:text-foreground w-full cursor-pointer text-left text-sm disabled:cursor-not-allowed"+ >+ Click to add corrected output+ </button>+ );+ }+ if (isEditing) {+ return (+ <CodeMirrorEditor+ value={displayValue}+ onChange={onChange}+ mode={strictJsonMode ? "json" : "text"}+ minHeight={200}+ placeholder="Enter corrected output..."+ editorRef={editorRef}+ onEditorMount={onEditorMount}+ appearance="flat"+ className="focus-within:ring-ring focus-within:ring-2"+ />+ );+ }+ return (+ <CodeMirrorEditor+ value={displayValue}+ mode={strictJsonMode ? "json" : "text"}+ editable={false}+ appearance="flat"+ />+ );+}diff --git a/web/src/features/traces/components/IOPreview/components/SectionMedia.tsx b/web/src/features/traces/components/IOPreview/components/SectionMedia.tsxindex 8389be8b71..55ae656aac 100644--- a/web/src/features/traces/components/IOPreview/components/SectionMedia.tsx+++ b/web/src/features/traces/components/IOPreview/components/SectionMedia.tsx@@ -1,3 +1,4 @@+import { IOSection } from "@/src/components/ui/IOSection";import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";import { type MediaReturnType } from "@/src/features/media";@@ -11,11 +12,8 @@ export interface SectionMediaProps {*/export function SectionMedia({ media }: SectionMediaProps) {return (- <>- <div className="io-message-header px-1 py-1 text-base font-bold">- Media- </div>- <div className="ph-no-capture flex flex-wrap gap-2 pb-4">+ <IOSection title="Media" variant="media">+ <div className="flex flex-wrap gap-2">{media.map((m) => (<LangfuseMediaViewmediaAPIReturnValue={m}@@ -24,6 +22,6 @@ export function SectionMedia({ media }: SectionMediaProps) {/>))}</div>- </>+ </IOSection>);}diff --git a/web/src/features/traces/components/IOPreview/components/SectionSkills.tsx b/web/src/features/traces/components/IOPreview/components/SectionSkills.tsxindex 34257eda88..94bdf4e3b5 100644--- a/web/src/features/traces/components/IOPreview/components/SectionSkills.tsx+++ b/web/src/features/traces/components/IOPreview/components/SectionSkills.tsx@@ -13,6 +13,7 @@ import {CollapsibleContent,CollapsibleTrigger,} from "@/src/components/ui/collapsible";+import { IOSection } from "@/src/components/ui/IOSection";export function SectionSkills({ projectId, skills }: SectionSkillsProps) {const [isGroupExpanded, setGroupExpanded] = useState(false);@@ -29,15 +30,7 @@ export function SectionSkills({ projectId, skills }: SectionSkillsProps) {}return (- <section- className="ph-no-capture border-border border-b pb-4"- aria-label="Skills"- >- <div className="flex items-center gap-2 px-1 py-1">- <h3 className="io-message-header text-base font-bold">Skills</h3>- <Badge color="filled" size="sm" text={String(groups.length)} />- <Badge text="Beta" color="blue" size="sm" />- </div>+ <IOSection title="Skills" count={groups.length}><Collapsibleopen={isGroupExpanded}onOpenChange={handleGroupChange}@@ -72,7 +65,7 @@ export function SectionSkills({ projectId, skills }: SectionSkillsProps) {</ul></CollapsibleContent></Collapsible>- </section>+ </IOSection>);}diff --git a/web/src/features/traces/components/IOPreview/components/SectionToolDefinitions.tsx b/web/src/features/traces/components/IOPreview/components/SectionToolDefinitions.tsxindex 336ec125ff..dfa9080b77 100644--- a/web/src/features/traces/components/IOPreview/components/SectionToolDefinitions.tsx+++ b/web/src/features/traces/components/IOPreview/components/SectionToolDefinitions.tsx@@ -1,3 +1,4 @@+import { IOSection } from "@/src/components/ui/IOSection";import {ToolCallDefinitionCard,type ToolDefinition,@@ -20,12 +21,12 @@ export function SectionToolDefinitions({toolCallsByName,}: SectionToolDefinitionsProps) {return (- <div className="mb-4 pb-4">+ <IOSection title="Tools"><ToolCallDefinitionCardtools={tools}toolCallCounts={toolCallCounts}toolCallsByName={toolCallsByName}/>- </div>+ </IOSection>);}diff --git a/web/src/features/traces/components/IOPreview/components/StatusMessageSection.tsx b/web/src/features/traces/components/IOPreview/components/StatusMessageSection.tsxindex 349a3a77c7..e891b07334 100644--- a/web/src/features/traces/components/IOPreview/components/StatusMessageSection.tsx+++ b/web/src/features/traces/components/IOPreview/components/StatusMessageSection.tsx@@ -1,7 +1,6 @@import { useMemo } from "react";-import { MarkdownJsonViewHeader } from "@/src/components/ui/MarkdownJsonView";+import { IOSection } from "@/src/components/ui/IOSection";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";-import { StatusMessage } from "@/src/components/design-system/StatusMessage/StatusMessage";import { copyTextToClipboard } from "@/src/utils/clipboard";import {getStatusMessagePresentation,@@ -35,17 +34,12 @@ export function StatusMessageSection({}return (- <div className="group/iosection">- <MarkdownJsonViewHeader- title={presentation.title}- handleOnCopy={() => copyTextToClipboard(status.message)}- hoverRevealControls- />- <StatusMessage- level={status.level}- message={status.message}- size="default"- />- </div>+ <IOSection+ title={presentation.title}+ onCopy={() => copyTextToClipboard(status.message)}+ tone={presentation.tone}+ >+ {status.message}+ </IOSection>);}diff --git a/web/src/features/traces/components/IOPreview/hooks/useCorrectionData.ts b/web/src/features/traces/components/IOPreview/hooks/useCorrectionData.tsindex a79ac1415c..7c2a35c4cb 100644--- a/web/src/features/traces/components/IOPreview/hooks/useCorrectionData.ts+++ b/web/src/features/traces/components/IOPreview/hooks/useCorrectionData.ts@@ -1,5 +1,5 @@import { useMemo } from "react";-import { useCorrectionCache } from "@/src/features/corrections";+import { useCorrectionCacheOptional } from "@/src/features/corrections";import { type ScoreDomain } from "@langfuse/shared";/**@@ -12,11 +12,13 @@ export function useCorrectionData(observationId: string | undefined,traceId: string,) {- const correctionCache = useCorrectionCache();+ // Without a provider (read-only hosts) the server correction is the truth.+ const correctionCache = useCorrectionCacheOptional();// Get cached correction - for observation or trace level// NOTE: getForObservation/getForTrace filter out deleted itemsconst cachedMeta = useMemo(() => {+ if (!correctionCache) return null;if (observationId) {return correctionCache.getForObservation(traceId, observationId);}@@ -38,7 +40,7 @@ export function useCorrectionData(// 2. If server correction is marked as deleted, return nullif (existingCorrection?.id &&- correctionCache.isDeleted(existingCorrection.id)+ correctionCache?.isDeleted(existingCorrection.id)) {return null;}@@ -50,7 +52,7 @@ export function useCorrectionData(// Check if deleted - check server correction ID since that's what we deleteconst isDeleted = useMemo(() => {return existingCorrection?.id- ? correctionCache.isDeleted(existingCorrection.id)+ ? (correctionCache?.isDeleted(existingCorrection.id) ?? false): false;}, [existingCorrection?.id, correctionCache]);diff --git a/web/src/features/traces/components/IOPreview/hooks/useCorrectionEditor.clienttest.tsx b/web/src/features/traces/components/IOPreview/hooks/useCorrectionEditor.clienttest.tsxnew file mode 100644index 0000000000..6dbb78b80d--- /dev/null+++ b/web/src/features/traces/components/IOPreview/hooks/useCorrectionEditor.clienttest.tsx@@ -0,0 +1,52 @@+import { act, renderHook } from "@testing-library/react";+import { useCorrectionEditor } from "./useCorrectionEditor";++describe("useCorrectionEditor", () => {+ const actualOutput = { answer: "original" };++ it("prefills from the actual output on edit without saving", () => {+ const onSave = vi.fn();+ const setSaveStatus = vi.fn();+ const { result } = renderHook(() =>+ useCorrectionEditor({+ correctionValue: "",+ actualOutput,+ onSave,+ setSaveStatus,+ }),+ );++ act(() => result.current.handleEdit());++ expect(result.current.isEditing).toBe(true);+ expect(result.current.value).toBe(JSON.stringify(actualOutput));+ expect(onSave).not.toHaveBeenCalled();+ expect(setSaveStatus).not.toHaveBeenCalled();+ });++ it("mounts in edit mode prefilled, saving only once the user types", () => {+ vi.useFakeTimers();+ const onSave = vi.fn();+ const { result } = renderHook(() =>+ useCorrectionEditor({+ correctionValue: "",+ actualOutput,+ onSave,+ setSaveStatus: vi.fn(),+ initialEditing: true,+ }),+ );++ expect(result.current.isEditing).toBe(true);+ expect(result.current.value).toBe(JSON.stringify(actualOutput));+ expect(onSave).not.toHaveBeenCalled();++ act(() => result.current.handleChange('{"answer":"fixed"}'));+ act(() => {+ vi.runAllTimers();+ });++ expect(onSave).toHaveBeenCalledWith('{"answer":"fixed"}');+ vi.useRealTimers();+ });+});diff --git a/web/src/features/traces/components/IOPreview/hooks/useCorrectionEditor.ts b/web/src/features/traces/components/IOPreview/hooks/useCorrectionEditor.tsindex e0e8d40335..9e0db1cb53 100644--- a/web/src/features/traces/components/IOPreview/hooks/useCorrectionEditor.ts+++ b/web/src/features/traces/components/IOPreview/hooks/useCorrectionEditor.ts@@ -7,6 +7,31 @@ interface UseCorrectionEditorParams {setSaveStatus: (status: "idle" | "saving" | "saved") => void;debounceMs?: number;strictJsonMode?: boolean;+ /** Mount in edit mode, prefilled from `actualOutput` when there is no+ correction yet; nothing is saved until the user types. */+ initialEditing?: boolean;+}++/** The actual output as the editor's starting text. */+function serializeActualOutput(actualOutput: unknown): string {+ try {+ return typeof actualOutput === "string"+ ? actualOutput+ : JSON.stringify(actualOutput);+ } catch {+ return String(actualOutput);+ }+}++function isValidValue(value: string, strictJsonMode: boolean): boolean {+ if (!strictJsonMode) return value.trim().length > 0;+ try {+ if (!value.trim()) return false;+ JSON.parse(value);+ return true;+ } catch {+ return false;+ }}/**@@ -19,16 +44,26 @@ export function useCorrectionEditor({setSaveStatus,debounceMs = 500,strictJsonMode = false,+ initialEditing = false,}: UseCorrectionEditorParams) {- const [isEditing, setIsEditing] = useState(false);- const [value, setValue] = useState(correctionValue);- const [isValidJson, setIsValidJson] = useState(true);+ const [isEditing, setIsEditing] = useState(initialEditing);+ const [value, setValue] = useState(() =>+ initialEditing && !correctionValue && actualOutput+ ? serializeActualOutput(actualOutput)+ : correctionValue,+ );+ const [isValidJson, setIsValidJson] = useState(() =>+ initialEditing ? isValidValue(value, strictJsonMode) : true,+ );const timeoutRef = useRef<NodeJS.Timeout | null>(null);const textareaRef = useRef<HTMLTextAreaElement>(null);// Sync local value with correctionValue from cache/server// This includes handling deletions (correctionValue becomes empty string)+ const syncedCorrectionValue = useRef(correctionValue);useEffect(() => {+ if (syncedCorrectionValue.current === correctionValue) return;+ syncedCorrectionValue.current = correctionValue;setValue(correctionValue);}, [correctionValue]);@@ -51,53 +86,18 @@ export function useCorrectionEditor({// eslint-disable-next-line react-hooks/exhaustive-deps}, [strictJsonMode]);+ // Enter edit mode. With no correction yet the editor is prefilled from+ // the actual output; nothing is saved until the user types.const handleEdit = useCallback(() => {setIsEditing(true);- // Prepopulate with actual output if no existing correctionif (!value && actualOutput) {- try {- // Store as JSON string (not stringified string)- const jsonValue =- typeof actualOutput === "string"- ? actualOutput- : JSON.stringify(actualOutput);- setValue(jsonValue);-- // Validate the prefilled value- let valid = false;- if (strictJsonMode) {- try {- if (jsonValue.trim()) {- JSON.parse(jsonValue);- valid = true;- }- } catch {- valid = false;- }- } else {- valid = jsonValue.trim().length > 0;- }- setIsValidJson(valid);-- // Auto-save prefilled value if valid- if (valid) {- setSaveStatus("saving");- onSave(jsonValue);- }- } catch {- const stringValue = String(actualOutput);- setValue(stringValue);- const valid = stringValue.trim().length > 0;- setIsValidJson(valid);- if (valid) {- setSaveStatus("saving");- onSave(stringValue);- }- }+ const prefill = serializeActualOutput(actualOutput);+ setValue(prefill);+ setIsValidJson(isValidValue(prefill, strictJsonMode));}// Focus textarea after it renderssetTimeout(() => textareaRef.current?.focus(), 0);- }, [value, actualOutput, strictJsonMode, onSave, setSaveStatus]);+ }, [value, actualOutput, strictJsonMode]);const handleChange = useCallback((newValue: string) => {diff --git a/web/src/features/traces/components/ObservationDetailView/ObservationPreview.tsx b/web/src/features/traces/components/ObservationDetailView/ObservationPreview.tsxindex 2eaddf381c..2e6fb252d7 100644--- a/web/src/features/traces/components/ObservationDetailView/ObservationPreview.tsx+++ b/web/src/features/traces/components/ObservationDetailView/ObservationPreview.tsx@@ -2,6 +2,7 @@ import { useState, type ComponentProps, type Key } from "react";import { IOPreview } from "@/src/features/traces/components/IOPreview/IOPreview";import { cn } from "@/src/utils/tailwind";+import { IO_STICKY_HEADERS_CLASS } from "@/src/features/traces/constants/ioSectionClasses";export interface ObservationPreviewProps {currentView?: ComponentProps<typeof IOPreview>["currentView"];@@ -27,7 +28,7 @@ export function ObservationPreview({"flex min-h-0 w-full flex-1 flex-col",currentView === "json-beta" && isJSONBetaVirtualized? "overflow-hidden"- : "overflow-auto pb-4",+ : cn("overflow-auto pb-4", IO_STICKY_HEADERS_CLASS),// The JSON beta viewer runs edge to edge with its own toolbar.currentView !== "json-beta" && "px-4",)}diff --git a/web/src/features/traces/components/ThinkingBlock.tsx b/web/src/features/traces/components/ThinkingBlock.tsxindex e531d877e4..05334aa1fe 100644--- a/web/src/features/traces/components/ThinkingBlock.tsx+++ b/web/src/features/traces/components/ThinkingBlock.tsx@@ -18,7 +18,7 @@ export function ThinkingBlock({const displayContent = summary || content;return (- <div className="my-2 px-1">+ <div className="my-2"><buttontype="button"className="text-muted-foreground hover:text-foreground flex w-full cursor-pointer items-start gap-1 text-left"@@ -63,7 +63,7 @@ export function RedactedThinkingBlock({const [expanded, setExpanded] = useState(defaultExpanded);return (- <div className="my-2 px-1">+ <div className="my-2"><buttontype="button"className="text-muted-foreground hover:text-foreground flex w-full cursor-pointer items-start gap-1 text-left"diff --git a/web/src/features/traces/components/ToolCallInvocationsView.tsx b/web/src/features/traces/components/ToolCallInvocationsView.tsxindex b95de6eea0..d3ea094762 100644--- a/web/src/features/traces/components/ToolCallInvocationsView.tsx+++ b/web/src/features/traces/components/ToolCallInvocationsView.tsx@@ -56,7 +56,8 @@ export function ToolCallInvocationsView({}return (- <div className={cn("flex flex-col gap-1", className)}>+ // pb-1 + the box's py-2 = the box's horizontal inset below the last table.+ <div className={cn("flex flex-col gap-3 pb-1", className)}>{toolCalls.map((toolCall, index) => {const invocationNumber = toolCallNumbers?.[index];// Without a paired result the arguments are the whole card and need no label.@@ -77,12 +78,10 @@ export function ToolCallInvocationsView({<divkey={`${toolCall.id}-${index}`}className={cn(- "py-2",- message.role === "assistant" ||- message.name === "Output" ||- message.name === "Model"- ? "bg-surface-output rounded-md px-3"- : "w-full border-t",+ message.role !== "assistant" &&+ message.name !== "Output" &&+ message.name !== "Model" &&+ "w-full border-t pt-2",)}>{/* Card header */}@@ -107,7 +106,7 @@ export function ToolCallInvocationsView({</div>{/* Arguments view */}- <div className="py-2 [&_.io-message-content]:px-0">+ <div className="pt-1 [&_.io-message-content]:px-0">{hasResponse && (<div className="text-muted-foreground mb-1.5 text-xs font-bold">Arguments@@ -124,7 +123,7 @@ export function ToolCallInvocationsView({projection sets `response`, so this section is beta-only bydata presence — legacy messages never carry the field. */}{response && (- <div className="py-2 [&_.io-message-content]:px-0">+ <div className="pt-2 [&_.io-message-content]:px-0"><div className="text-muted-foreground mb-1.5 text-xs font-bold">Response{response.isError && (diff --git a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsxindex 8dfd967666..7230df6105 100644--- a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx+++ b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx@@ -10,6 +10,7 @@ import { Switch } from "@/src/components/design-system/Switch/Switch";import { Skeleton } from "@/src/components/ui/skeleton";import { useCallback, useMemo, useState } from "react";import { cn } from "@/src/utils/tailwind";+import { IO_STICKY_HEADERS_CLASS } from "@/src/features/traces/constants/ioSectionClasses";import {CommentDrawerController,getCommentDrawerInitialStateFromUrl,@@ -417,7 +418,7 @@ function LoadedTraceDetailView({"flex min-h-0 w-full flex-1 flex-col",currentView === "json-beta" && isJSONBetaVirtualized? "overflow-hidden"- : "overflow-auto pb-4",+ : cn("overflow-auto pb-4", IO_STICKY_HEADERS_CLASS),// The JSON beta viewer runs edge to edge with its own toolbar.currentView !== "json-beta" && "px-4",)}diff --git a/web/src/features/traces/constants/ioSectionClasses.ts b/web/src/features/traces/constants/ioSectionClasses.tsindex f470f297b5..35580388ac 100644--- a/web/src/features/traces/constants/ioSectionClasses.ts+++ b/web/src/features/traces/constants/ioSectionClasses.ts@@ -1,3 +1,3 @@-/** IO sections render flush; the hosting panel owns the horizontal inset. */-export const IO_SECTIONS_FLUSH_CLASS =- "[&_.io-message-content]:px-0 [&_.io-message-header]:px-0";+/** Scroll containers that pin each section header to their top edge. */+export const IO_STICKY_HEADERS_CLASS =+ "[--io-header-h:calc(var(--spacing)*8)] [&_.io-message-header]:bg-surface [&_.io-message-header]:sticky [&_.io-message-header]:top-0 [&_.io-message-header]:z-10";diff --git a/web/src/features/traces/contexts/ViewPreferencesContext.tsx b/web/src/features/traces/contexts/ViewPreferencesContext.tsxindex 7e46bfceb2..1844614ccf 100644--- a/web/src/features/traces/contexts/ViewPreferencesContext.tsx+++ b/web/src/features/traces/contexts/ViewPreferencesContext.tsx@@ -68,7 +68,7 @@ interface ViewPreferencesContextValue {/** Whether JSON Beta (advanced viewer) is enabled */jsonBetaEnabled: boolean;setJsonBetaEnabled: (value: boolean) => void;- /** Whether long system prompts render collapsed to a first-lines preview */+ /** Whether long system prompts render with their section collapsed */collapseSystemPrompt: boolean;setCollapseSystemPrompt: (value: boolean) => void;}@@ -144,7 +144,7 @@ export function ViewPreferencesProvider({typeof window !== "undefined" &&localStorage.getItem(JSON_VIEW_PREFERENCE_STORAGE_KEY) === '"json-beta"',);- // Shared with the inline expand/collapse toggle on system prompt messages;+ // Shared with the section caret on system prompt messages;// instances sync via useLocalStorage's localStorageChange events.const [collapseSystemPrompt, setCollapseSystemPrompt] =useCollapseSystemPromptPreference();diff --git a/web/src/hooks/useCollapsibleSystemPrompt.ts b/web/src/hooks/useCollapsibleSystemPrompt.tsindex ee62f6eaaf..4a8772a609 100644--- a/web/src/hooks/useCollapsibleSystemPrompt.ts+++ b/web/src/hooks/useCollapsibleSystemPrompt.ts@@ -1,11 +1,11 @@import { useMemo, useSyncExternalStore } from "react";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";+// A prompt counts as long when it exceeds the char threshold and would not+// fit a short first-lines preview anyway.const COLLAPSE_CHAR_THRESHOLD = 250;-const DEFAULT_PREVIEW_LINES = 4;-// Matches JSONView's collapseStringsAfterLength default; generous enough that-// the first N lines usually survive intact instead of being cut mid-line.-const DEFAULT_PREVIEW_CHAR_LIMIT = 500;+const PREVIEW_LINES = 4;+const PREVIEW_CHAR_LIMIT = 500;const STORAGE_KEY = "collapseSystemPrompt";const LEGACY_STORAGE_KEY = "traceSystemPrompt:collapsed";@@ -67,8 +67,8 @@ function writeCollapsePreference(value: boolean): void {/*** Persisted default for whether long system prompts render collapsed.- * Shared by the inline expand/collapse toggle and the trace view preferences- * (ViewPreferencesContext). Backed by useSyncExternalStore rather than+ * Shared by the section caret on system prompt messages and the trace view+ * preferences (ViewPreferencesContext). Backed by useSyncExternalStore rather than* per-instance state: many instances of this hook mount at once (one per* message), and a state-updater-based sync would setState across components* mid-render.@@ -90,86 +90,67 @@ interface UseCollapsibleSystemPromptOptions {message that carries a `name` is titled by that name. */isSystemPrompt: boolean;content: string;- /** Number of lines shown while collapsed. */- previewLines?: number;- /** Character cap applied to the collapsed preview. */- previewCharLimit?: number;}-type SystemPromptCollapseSource = "inline" | "header";-interface UseCollapsibleSystemPromptReturn {+ /** True for long system prompts: their section follows the persisted+ preference instead of the default open state. */shouldBeCollapsible: boolean;isCollapsed: boolean;- toggleCollapsed: (source?: SystemPromptCollapseSource) => void;- truncatedContent: string;+ toggleCollapsed: () => void;}/**- * Collapses long system prompts to a first-N-lines preview by default.- * Toggling flips the persisted preference, so an explicit "expanded" choice- * sticks across messages and navigation instead of being force-collapsed.+ * Long system prompts start collapsed by default. Toggling flips the+ * persisted preference, so an explicit "expanded" choice sticks across+ * messages and navigation instead of being force-collapsed.*/export function useCollapsibleSystemPrompt({isSystemPrompt,content,- previewLines = DEFAULT_PREVIEW_LINES,- previewCharLimit = DEFAULT_PREVIEW_CHAR_LIMIT,}: UseCollapsibleSystemPromptOptions): UseCollapsibleSystemPromptReturn {const capture = usePostHogClientCapture();const [collapsePreference, setCollapsePreference] =useCollapseSystemPromptPreference();- // null = collapsing would hide nothing, so no toggle is offered. Deriving- // collapsibility from the actual truncation result (instead of a bare char- // threshold) avoids a dead toggle for content that clears the threshold but- // fits entirely within the preview.- const preview = useMemo(() => {+ const shouldBeCollapsible = useMemo(() => {if (!isSystemPrompt ||typeof content !== "string" ||content.length <= COLLAPSE_CHAR_THRESHOLD) {- return null;+ return false;}// Split only a bounded prefix. A full split("\n") over a multi-MB string// is the main-thread cost PrettyJsonView's large-string gate exists to- // avoid; the preview never needs more than the first few lines anyway.- const scanLimit = Math.max(previewCharLimit, 8_192);+ // avoid.+ const scanLimit = Math.max(PREVIEW_CHAR_LIMIT, 8_192);const scanText =content.length > scanLimit ? content.slice(0, scanLimit) : content;const lines = scanText.split("\n");- const previewText = lines.slice(0, previewLines).join("\n");+ const previewText = lines.slice(0, PREVIEW_LINES).join("\n");- if (previewText.length > previewCharLimit) {- return previewText.slice(0, previewCharLimit) + "...";- }- if (lines.length > previewLines || content.length > scanText.length) {- return previewText + "\n...";- }- return null;- }, [isSystemPrompt, content, previewLines, previewCharLimit]);+ return (+ previewText.length > PREVIEW_CHAR_LIMIT ||+ lines.length > PREVIEW_LINES ||+ content.length > scanText.length+ );+ }, [isSystemPrompt, content]);- const shouldBeCollapsible = preview !== null;const isCollapsed = shouldBeCollapsible && collapsePreference;- const toggleCollapsed = (source: SystemPromptCollapseSource = "inline") => {+ const toggleCollapsed = () => {const next = !collapsePreference;// No trace analytics dimensions here on purpose: this fires from shared// components that also render outside trace contexts (e.g. session view),// and the event must keep one shape across sources.capture("trace_detail:system_prompt_collapse_toggle", {collapsed: next,- source,+ source: "header",});setCollapsePreference(next);};- return {- shouldBeCollapsible,- isCollapsed,- toggleCollapsed,- truncatedContent: preview ?? content,- };+ return { shouldBeCollapsible, isCollapsed, toggleCollapsed };}diff --git a/web/src/styles/globals.css b/web/src/styles/globals.cssindex b472ba0e84..3844ebcccc 100644--- a/web/src/styles/globals.css+++ b/web/src/styles/globals.css@@ -77,7 +77,7 @@--color-surface-code: hsl(var(--surface-code));--color-surface-code-header: hsl(var(--surface-code-header));--color-surface-sunken: hsl(var(--surface-sunken));- --color-surface-output: hsl(var(--surface-output));+ --color-surface-section: hsl(var(--surface-section));/* Sticky table chrome; hosts on another surface set --surface-context. */--color-surface: var(--surface-context, hsl(var(--background)));--color-muted-magenta: hsl(var(--muted-magenta));@@ -353,7 +353,7 @@--surface-code: 0 0% 92%;--surface-code-header: 0 0% 86%;--surface-sunken: 0 0% 99%; /* between white and zinc-50 */- --surface-output: 240 4.8% 95.9%; /* zinc-100 */+ --surface-section: 240 4.8% 96.5%; /* a hair lighter than zinc-100 */--popover: 0 0% 100%;--popover-foreground: var(--foreground);@@ -591,7 +591,7 @@--surface-code: 0 0% 2.3%;--surface-code-header: 0 0% 8.2%;--surface-sunken: 0 0% 8%; /* one step below the modal */- --surface-output: var(--popover);+ --surface-section: 0 0% 11%; /* a hair quieter than the popover */--popover: 0 0% 12%;--popover-foreground: var(--foreground);