🪢 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
feat(advanced-json-viewer): fully virtualized JSON Beta view with search and media attachments (#11253)
Michael Fröhlich99ff3073b602
diff --git a/packages/shared/scripts/seeder/seed-media.ts b/packages/shared/scripts/seeder/seed-media.tsnew file mode 100644index 0000000000..3b1be2a60c--- /dev/null+++ b/packages/shared/scripts/seeder/seed-media.ts@@ -0,0 +1,285 @@+/**+ * Media Seeding Utilities+ *+ * Seeds test traces with media attachments (images, PDFs, audio) for testing+ * the JSON Beta view's media rendering capabilities.+ *+ * Integrated into the seeder flow - runs automatically during `dx` or `db:seed:examples`.+ */++import crypto from "crypto";+import fs from "fs";+import path from "path";+import { Readable } from "stream";++import { prisma } from "../../src/db";+import { env } from "../../src/env";+import { logger, StorageServiceFactory } from "../../src/server";++// Test file paths (relative to monorepo root)+const TEST_FILES_DIR = path.join(+ __dirname,+ "../../../../web/src/__tests__/static",+);++interface MediaFile {+ name: string;+ contentType: string;+ filePath: string;+}++const MEDIA_FILES: Record<string, MediaFile> = {+ image: {+ name: "langfuse-logo.png",+ contentType: "image/png",+ filePath: path.join(TEST_FILES_DIR, "langfuse-logo.png"),+ },+ pdf: {+ name: "bitcoin.pdf",+ contentType: "application/pdf",+ filePath: path.join(TEST_FILES_DIR, "bitcoin.pdf"),+ },+ audio: {+ name: "sounds-of-mars.wav",+ contentType: "audio/wav",+ filePath: path.join(+ TEST_FILES_DIR,+ "sounds-of-mars-one-small-step-earth.wav",+ ),+ },+};++// Deterministic trace IDs for media test traces+export const MEDIA_TEST_TRACE_IDS = {+ imageOnly: "seed-media-image-only",+ allTypes: "seed-media-all-types",+ allTypesChatML: "seed-media-all-types-chatml",+} as const;++/**+ * Derive media ID from SHA256 hash (first 22 chars, URL-safe)+ */+function getMediaIdFromHash(sha256Hash: string): string {+ const urlSafeHash = sha256Hash.replaceAll("+", "-").replaceAll("/", "_");+ return urlSafeHash.slice(0, 22);+}++/**+ * Get bucket path for a media file+ */+function getBucketPath(+ projectId: string,+ mediaId: string,+ contentType: string,+): string {+ const extensionMap: Record<string, string> = {+ "image/png": "png",+ "image/jpeg": "jpg",+ "application/pdf": "pdf",+ "audio/wav": "wav",+ "audio/mpeg": "mp3",+ };+ const extension = extensionMap[contentType] || "bin";+ const prefix = env.LANGFUSE_S3_MEDIA_UPLOAD_PREFIX || "";+ return `${prefix}${projectId}/${mediaId}.${extension}`;+}++/**+ * Upload a media file to storage and create database records+ */+async function uploadAndCreateMediaRecord(+ projectId: string,+ traceId: string,+ field: "input" | "output" | "metadata",+ mediaFile: MediaFile,+): Promise<void> {+ // Check if bucket is configured+ if (!env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET) {+ logger.warn(+ "[seed-media] LANGFUSE_S3_MEDIA_UPLOAD_BUCKET not configured, skipping media seeding",+ );+ return;+ }++ // Check if file exists+ if (!fs.existsSync(mediaFile.filePath)) {+ logger.warn(+ `[seed-media] Test file not found: ${mediaFile.filePath}, skipping`,+ );+ return;+ }++ const fileBytes = fs.readFileSync(mediaFile.filePath);+ const sha256Hash = crypto+ .createHash("sha256")+ .update(fileBytes)+ .digest("base64");+ const mediaId = getMediaIdFromHash(sha256Hash);+ const bucketPath = getBucketPath(projectId, mediaId, mediaFile.contentType);++ // Check if media already exists+ const existingMedia = await prisma.media.findUnique({+ where: {+ projectId_sha256Hash: {+ projectId,+ sha256Hash,+ },+ },+ });++ if (existingMedia && existingMedia.uploadHttpStatus === 200) {+ logger.debug(+ `[seed-media] Media already exists for ${mediaFile.name}, creating TraceMedia link only`,+ );++ // Just create the TraceMedia link+ await prisma.$queryRaw`+ INSERT INTO "trace_media" ("id", "project_id", "trace_id", "media_id", "field")+ VALUES (${crypto.randomUUID()}, ${projectId}, ${traceId}, ${existingMedia.id}, ${field})+ ON CONFLICT DO NOTHING;+ `;+ return;+ }++ // Upload to storage+ try {+ const storageClient = StorageServiceFactory.getInstance({+ bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,+ accessKeyId: env.LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID,+ secretAccessKey: env.LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY,+ endpoint: env.LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT,+ region: env.LANGFUSE_S3_MEDIA_UPLOAD_REGION,+ forcePathStyle: env.LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE === "true",+ awsSse: env.LANGFUSE_S3_MEDIA_UPLOAD_SSE,+ awsSseKmsKeyId: env.LANGFUSE_S3_MEDIA_UPLOAD_SSE_KMS_KEY_ID,+ });++ await storageClient.uploadFile({+ fileName: bucketPath,+ fileType: mediaFile.contentType,+ data: Readable.from(fileBytes),+ });++ logger.debug(`[seed-media] Uploaded ${mediaFile.name} to ${bucketPath}`);+ } catch (error) {+ logger.error(`[seed-media] Failed to upload ${mediaFile.name}:`, error);+ return;+ }++ // Create Media record+ await prisma.$queryRaw`+ INSERT INTO "media" (+ "id",+ "project_id",+ "sha_256_hash",+ "bucket_path",+ "bucket_name",+ "content_type",+ "content_length",+ "uploaded_at",+ "upload_http_status"+ )+ VALUES (+ ${mediaId},+ ${projectId},+ ${sha256Hash},+ ${bucketPath},+ ${env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET},+ ${mediaFile.contentType},+ ${BigInt(fileBytes.length)},+ ${new Date()},+ ${200}+ )+ ON CONFLICT ("project_id", "sha_256_hash")+ DO UPDATE SET+ "bucket_name" = ${env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET},+ "bucket_path" = ${bucketPath},+ "content_type" = ${mediaFile.contentType},+ "content_length" = ${BigInt(fileBytes.length)},+ "uploaded_at" = ${new Date()},+ "upload_http_status" = ${200}+ `;++ // Create TraceMedia link+ await prisma.$queryRaw`+ INSERT INTO "trace_media" ("id", "project_id", "trace_id", "media_id", "field")+ VALUES (${crypto.randomUUID()}, ${projectId}, ${traceId}, ${mediaId}, ${field})+ ON CONFLICT DO NOTHING;+ `;++ logger.info(+ `[seed-media] Created media record for ${mediaFile.name} -> ${field}`,+ );+}++/**+ * Seed media test traces for a project+ *+ * Creates two test traces with media attachments:+ * 1. Image only (in input)+ * 2. All types (image in input, PDF in output, audio in metadata)+ */+export async function seedMediaTraces(projectId: string): Promise<void> {+ logger.info(`[seed-media] Seeding media traces for project ${projectId}`);++ // Check if bucket is configured+ if (!env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET) {+ logger.warn(+ "[seed-media] LANGFUSE_S3_MEDIA_UPLOAD_BUCKET not configured, skipping media seeding",+ );+ return;+ }++ // Trace 1: Image only (input)+ const trace1Id = MEDIA_TEST_TRACE_IDS.imageOnly;+ await uploadAndCreateMediaRecord(+ projectId,+ trace1Id,+ "input",+ MEDIA_FILES.image,+ );++ // Trace 2: All media types+ const trace2Id = MEDIA_TEST_TRACE_IDS.allTypes;+ await uploadAndCreateMediaRecord(+ projectId,+ trace2Id,+ "input",+ MEDIA_FILES.image,+ );+ await uploadAndCreateMediaRecord(+ projectId,+ trace2Id,+ "output",+ MEDIA_FILES.pdf,+ );+ await uploadAndCreateMediaRecord(+ projectId,+ trace2Id,+ "metadata",+ MEDIA_FILES.audio,+ );++ // Trace 3: All media types with ChatML format (pretty-rendered)+ const trace3Id = MEDIA_TEST_TRACE_IDS.allTypesChatML;+ await uploadAndCreateMediaRecord(+ projectId,+ trace3Id,+ "input",+ MEDIA_FILES.image,+ );+ await uploadAndCreateMediaRecord(+ projectId,+ trace3Id,+ "output",+ MEDIA_FILES.pdf,+ );+ await uploadAndCreateMediaRecord(+ projectId,+ trace3Id,+ "metadata",+ MEDIA_FILES.audio,+ );++ logger.info("[seed-media] Media seeding completed");+}diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.tsindex 60c4b6e488..0517341052 100644--- a/packages/shared/scripts/seeder/seed-postgres.ts+++ b/packages/shared/scripts/seeder/seed-postgres.ts@@ -31,6 +31,7 @@ import {generateEvalTraceId,} from "./utils/seed-helpers";import { seedDatasetVersions } from "./seed-dataset-versions";+import { seedMediaTraces } from "./seed-media";const options = {environment: { type: "string" },@@ -350,6 +351,9 @@ async function main() {await createDashboardsAndWidgets([project1, project2]);await seedDatasetVersions(prisma, [project1.id, project2.id]);+ // Seed media test traces (uploads to MinIO + creates Media/TraceMedia records)+ await seedMediaTraces(project1.id);+await prisma.llmSchema.createMany({data: [{diff --git a/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts b/packages/shared/scripts/seeder/utils/seeder-orchestrator.tsindex ee0b14f382..fdeb277270 100644--- a/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts+++ b/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts@@ -7,8 +7,10 @@ import { DataGenerator } from "./data-generators";import { ClickHouseQueryBuilder } from "./clickhouse-builder";import { FrameworkTraceLoader } from "./framework-traces/framework-trace-loader";import { EVAL_TRACE_COUNT, SEED_DATASETS } from "./postgres-seed-constants";+import { MEDIA_TEST_TRACE_IDS } from "../seed-media";import {clickhouseClient,+ createTrace,DatasetRunItemRecordInsertType,logger,ObservationRecordInsertType,@@ -338,6 +340,9 @@ export class SeederOrchestrator {// create traces from real examples for each framework sourceawait this.createFrameworkTraces(projectIds);+ // Create traces for media attachment testing+ await this.createMediaTestTraces(projectIds);+// Log completion statistics (commented out to reduce terminal noise)await this.logStatistics();@@ -448,4 +453,106 @@ export class SeederOrchestrator {}}}++ /**+ * Creates test traces for media attachment testing (JSON Beta view).+ * Use for: Testing media rendering in the trace detail view.+ */+ async createMediaTestTraces(projectIds: string[]): Promise<void> {+ logger.info(+ `Creating media test traces for ${projectIds.length} projects.`,+ );++ const now = Date.now();++ for (const projectId of projectIds) {+ logger.info(`Processing media test traces for project ${projectId}`);++ const traces: TraceRecordInsertType[] = [+ // Trace 1: Image only (in input)+ createTrace({+ id: MEDIA_TEST_TRACE_IDS.imageOnly,+ project_id: projectId,+ name: "Media Test: Image Only",+ timestamp: now,+ input: JSON.stringify({+ message: "This trace has an image attachment in input",+ description: "Used for testing media rendering in JSON Beta view",+ }),+ output: JSON.stringify({ status: "success" }),+ metadata: { test_type: "media", media_types: "image" },+ tags: ["media-test", "image"],+ environment: "default",+ }),+ // Trace 2: All media types+ createTrace({+ id: MEDIA_TEST_TRACE_IDS.allTypes,+ project_id: projectId,+ name: "Media Test: All Types",+ timestamp: now + 1000,+ input: JSON.stringify({+ message: "This trace has an image in input",+ description: "Testing image attachment",+ }),+ output: JSON.stringify({+ message: "This trace has a PDF in output",+ description: "Testing PDF attachment",+ }),+ metadata: {+ message: "This trace has audio in metadata",+ description: "Testing audio attachment",+ test_type: "media",+ media_types: "image,pdf,audio",+ },+ tags: ["media-test", "all-types"],+ environment: "default",+ }),+ // Trace 3: All media types with ChatML format (pretty-rendered)+ createTrace({+ id: MEDIA_TEST_TRACE_IDS.allTypesChatML,+ project_id: projectId,+ name: "Media Test: All Types (ChatML)",+ timestamp: now + 2000,+ input: JSON.stringify([+ {+ role: "system",+ content:+ "You are a helpful assistant that can analyze images, documents, and audio files.",+ },+ {+ role: "user",+ content:+ "Please analyze the attached image and describe what you see.",+ },+ ]),+ output: JSON.stringify([+ {+ role: "assistant",+ content:+ "I can see the Langfuse logo in the image. It appears to be a modern, clean design with distinctive branding elements. The attached PDF contains additional documentation about the Bitcoin whitepaper.",+ },+ ]),+ metadata: {+ message: "This trace has audio in metadata",+ description: "Testing audio attachment with ChatML format",+ test_type: "media",+ media_types: "image,pdf,audio",+ format: "chatml",+ },+ tags: ["media-test", "all-types", "chatml"],+ environment: "default",+ }),+ ];++ try {+ await this.queryBuilder.executeTracesInsert(traces);+ logger.info(+ `✓ Created ${traces.length} media test traces for project ${projectId}`,+ );+ } catch (error) {+ logger.error(`✗ Media test traces insert failed:`, error);+ throw error;+ }+ }+ }}diff --git a/web/src/__tests__/static/sounds-of-mars-one-small-step-earth.wav b/web/src/__tests__/static/sounds-of-mars-one-small-step-earth.wavnew file mode 100644index 0000000000..bc781411e6Binary files /dev/null and b/web/src/__tests__/static/sounds-of-mars-one-small-step-earth.wav differdiff --git a/web/src/components/trace2/components/IOPreview/IOPreview.tsx b/web/src/components/trace2/components/IOPreview/IOPreview.tsxindex e0f41f9b6b..8a370e1e05 100644--- a/web/src/components/trace2/components/IOPreview/IOPreview.tsx+++ b/web/src/components/trace2/components/IOPreview/IOPreview.tsx@@ -49,6 +49,8 @@ export interface IOPreviewProps extends ExpansionStateProps {// Whether to show metadata section in pretty view (default: false)// JSON view always shows metadatashowMetadata?: boolean;+ // Callback to inform parent if virtualization is being used (for scroll handling)+ onVirtualizationChange?: (isVirtualized: boolean) => void;}/**@@ -85,6 +87,7 @@ export function IOPreview({onOutputExpansionChange,setIsPrettyViewAvailable,showMetadata = false,+ onVirtualizationChange,}: IOPreviewProps) {const capture = usePostHogClientCapture();const [dismissedTraceViewNotifications, setDismissedTraceViewNotifications] =@@ -167,7 +170,21 @@ export function IOPreview({* but this eliminates UI freeze with large observations.*/}{selectedView === "json-beta" ? (- <IOPreviewJSON {...sharedProps} />+ <IOPreviewJSON+ parsedInput={parsedInput}+ parsedOutput={parsedOutput}+ parsedMetadata={parsedMetadata}+ isParsing={isParsing}+ hideIfNull={hideIfNull}+ hideInput={hideInput}+ hideOutput={hideOutput}+ media={media}+ inputExpansionState={inputExpansionState}+ outputExpansionState={outputExpansionState}+ onInputExpansionChange={onInputExpansionChange}+ onOutputExpansionChange={onOutputExpansionChange}+ onVirtualizationChange={onVirtualizationChange}+ />) : selectedView === "json" ? (<IOPreviewJSONSimple {...sharedProps} />) : (diff --git a/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsx b/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsxindex 7a15c53181..6ccdc18cf6 100644--- a/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsx+++ b/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsx@@ -1,27 +1,37 @@-import { useState, useEffect, useCallback } from "react";+import { useState, useEffect, useCallback, useMemo, useRef } from "react";import { useTheme } from "next-themes";-import { type Prisma } from "@langfuse/shared";-import { AdvancedJsonSection } from "@/src/components/ui/AdvancedJsonSection/AdvancedJsonSection";-import { type MediaReturnType } from "@/src/features/media/validation";import { type ExpansionStateProps } from "./IOPreview";+import { countJsonRows } from "@/src/components/ui/AdvancedJsonViewer/utils/rowCount";+import {+ MultiSectionJsonViewer,+ type MultiSectionJsonViewerHandle,+} from "@/src/components/ui/AdvancedJsonViewer/MultiSectionJsonViewer";+import { Command, CommandInput } from "@/src/components/ui/command";+import { Button } from "@/src/components/ui/button";+import { ChevronUp, ChevronDown, WrapText, Minus, Copy } from "lucide-react";+import { useJsonViewPreferences } from "@/src/components/ui/AdvancedJsonViewer/hooks/useJsonViewPreferences";+import { type MediaReturnType } from "@/src/features/media/validation";+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+} from "@/src/components/ui/hover-card";-const SECTION_PREFERENCE_KEY = "langfuse:io-section-preference";-type SectionType = "input" | "output" | "metadata";+const VIRTUALIZATION_THRESHOLD = 3333;export interface IOPreviewJSONProps extends ExpansionStateProps {- input?: Prisma.JsonValue;- output?: Prisma.JsonValue;- metadata?: Prisma.JsonValue;- // Pre-parsed data (optional, from useParsedObservation hook for performance)+ // Pre-parsed data (from useParsedObservation hook)parsedInput?: unknown;parsedOutput?: unknown;parsedMetadata?: unknown;- isLoading?: boolean;isParsing?: boolean;hideIfNull?: boolean;- media?: MediaReturnType[];hideOutput?: boolean;hideInput?: boolean;+ // Media attachments+ media?: MediaReturnType[];+ // Callback to inform parent if virtualization is being used (for scroll handling)+ onVirtualizationChange?: (isVirtualized: boolean) => void;}/**@@ -37,194 +47,343 @@ export interface IOPreviewJSONProps extends ExpansionStateProps {* because it skips all ChatML processing.*/export function IOPreviewJSON({- input,- output,- metadata,parsedInput,parsedOutput,parsedMetadata,- isLoading = false,isParsing = false,hideIfNull = false,hideOutput = false,hideInput = false,media,+ onVirtualizationChange,}: IOPreviewJSONProps) {const { resolvedTheme } = useTheme();const isDark = resolvedTheme === "dark";- // Background colors that adapt to theme- const inputBgColor = isDark ? "rgb(15, 23, 42)" : "rgb(249, 252, 255)"; // Dark slate vs light blue- const outputBgColor = isDark ? "rgb(20, 30, 41)" : "rgb(248, 253, 250)"; // Dark blue-gray vs light green- const metadataBgColor = isDark ? "rgb(30, 20, 40)" : "rgb(253, 251, 254)"; // Dark purple vs light purple-- const showInput = !hideInput && !(hideIfNull && !parsedInput && !input);- const showOutput = !hideOutput && !(hideIfNull && !parsedOutput && !output);- const showMetadata = !(hideIfNull && !parsedMetadata && !metadata);-- // Helper to check if data has content (renders rows in JSON viewer)- // null/undefined = 0 rows, everything else (including {} and []) = 1+ rows- const hasContent = (data: unknown): boolean => {- if (data === null || data === undefined) return false;- if (typeof data === "string") return data.trim().length > 0;- // Arrays and objects always count as content (even if empty)- // because they render as at least 1 row in the JSON viewer- return true;- };-- // Check for non-empty content (prefer parsed data if available)- const outputHasContent = hasContent(parsedOutput ?? output);- const inputHasContent = hasContent(parsedInput ?? input);- const metadataHasContent = hasContent(parsedMetadata ?? metadata);-- // Get user's preferred section from session storage- const getUserPreference = (): SectionType | null => {- if (typeof window === "undefined") return null;- const stored = sessionStorage.getItem(SECTION_PREFERENCE_KEY);- if (stored === "input" || stored === "output" || stored === "metadata") {- return stored;- }- return null;- };-- // Check if user's preferred section is visible and has content- const userPreference = getUserPreference();- const userPreferenceIsVisible =- userPreference === "output"- ? showOutput- : userPreference === "input"- ? showInput- : userPreference === "metadata"- ? showMetadata- : false;- const userPreferenceHasContent =- userPreference === "output"- ? showOutput && outputHasContent- : userPreference === "input"- ? showInput && inputHasContent- : userPreference === "metadata"- ? showMetadata && metadataHasContent- : false;-- // Accordion state: only one section can be expanded at a time- // Default expansion priority:- // 1. User preference (if visible AND has content)- // 2. Output > Input > Metadata (first with content)- // 3. User preference (if visible, even without content)- // 4. Output > Input > Metadata (first visible)- const defaultExpanded = userPreferenceHasContent- ? userPreference- : showOutput && outputHasContent- ? "output"- : showInput && inputHasContent- ? "input"- : showMetadata && metadataHasContent- ? "metadata"- : userPreferenceIsVisible- ? userPreference- : showOutput- ? "output"- : showInput- ? "input"- : showMetadata- ? "metadata"- : null;- const [expandedSection, setExpandedSection] = useState<- "input" | "output" | "metadata" | null- >(defaultExpanded);-- // Handle user manually selecting a section (stores preference)- const handleUserToggle = useCallback(- (section: SectionType) => {- const isExpanding = expandedSection !== section;- setExpandedSection(isExpanding ? section : null);-- // Only store preference when user manually expands a section- if (isExpanding && typeof window !== "undefined") {- sessionStorage.setItem(SECTION_PREFERENCE_KEY, section);- }- },- [expandedSection],+ // Background colors that adapt to theme (memoized to prevent tree rebuilds)+ const { inputBgColor, outputBgColor, metadataBgColor } = useMemo(+ () => ({+ inputBgColor: isDark ? "rgb(15, 23, 42)" : "rgb(249, 252, 255)", // Dark slate vs light blue+ outputBgColor: isDark ? "rgb(20, 30, 41)" : "rgb(248, 253, 250)", // Dark blue-gray vs light green+ metadataBgColor: isDark ? "rgb(30, 20, 40)" : "rgb(253, 251, 254)", // Dark purple vs light purple+ }),+ [isDark],);- // Ensure expandedSection is always valid (if current is hidden, switch to first visible)- // Priority: output > input > metadata+ const showInput = !hideInput && !(hideIfNull && parsedInput === undefined);+ const showOutput = !hideOutput && !(hideIfNull && parsedOutput === undefined);+ const showMetadata = !(hideIfNull && parsedMetadata === undefined);++ // Count rows for each section to determine if virtualization is needed+ const rowCounts = useMemo(() => {+ return {+ input: countJsonRows(parsedInput),+ output: countJsonRows(parsedOutput),+ metadata: countJsonRows(parsedMetadata),+ };+ }, [parsedInput, parsedOutput, parsedMetadata]);++ // Determine if virtualization is needed based on threshold+ const needsVirtualization = useMemo(() => {+ return (+ rowCounts.input > VIRTUALIZATION_THRESHOLD ||+ rowCounts.output > VIRTUALIZATION_THRESHOLD ||+ rowCounts.metadata > VIRTUALIZATION_THRESHOLD+ );+ }, [rowCounts]);++ // Hooks for multi-section viewer (Path B) - must be called unconditionally+ const { stringWrapMode, setStringWrapMode } = useJsonViewPreferences();+ const [searchQuery, setSearchQuery] = useState("");+ const [debouncedSearchQuery, setDebouncedSearchQuery] = useState("");+ const [currentMatchIndex, setCurrentMatchIndex] = useState(0);+ const [searchMatchCount, setSearchMatchCount] = useState(0);+ const scrollContainerRef = useRef<HTMLDivElement>(null);+ const viewerRef = useRef<MultiSectionJsonViewerHandle>(null);++ // Debounce search query (applies to both virtualized and non-virtualized modes)useEffect(() => {- if (expandedSection === "output" && !showOutput) {- setExpandedSection(- showInput ? "input" : showMetadata ? "metadata" : null,- );- } else if (expandedSection === "input" && !showInput) {- setExpandedSection(- showOutput ? "output" : showMetadata ? "metadata" : null,- );- } else if (expandedSection === "metadata" && !showMetadata) {- setExpandedSection(showOutput ? "output" : showInput ? "input" : null);+ const timer = setTimeout(() => {+ setDebouncedSearchQuery(searchQuery);+ setCurrentMatchIndex(0);+ }, 300);+ return () => clearTimeout(timer);+ }, [searchQuery]);++ // No longer using accordion mode - MultiSectionJsonViewer shows all sections with collapsible headers++ // Notify parent about virtualization state+ useEffect(() => {+ onVirtualizationChange?.(needsVirtualization);+ }, [needsVirtualization, onVirtualizationChange]);++ // Search navigation callbacks+ const handleNextMatch = useCallback(() => {+ if (searchMatchCount === 0) return;+ setCurrentMatchIndex((prev) => (prev + 1) % searchMatchCount);+ }, [searchMatchCount]);++ const handlePreviousMatch = useCallback(() => {+ if (searchMatchCount === 0) return;+ setCurrentMatchIndex((prev) =>+ prev === 0 ? searchMatchCount - 1 : prev - 1,+ );+ }, [searchMatchCount]);++ const handleClearSearch = useCallback(() => {+ setSearchQuery("");+ setDebouncedSearchQuery("");+ setCurrentMatchIndex(0);+ }, []);++ // Handle string wrap mode cycling for Path B+ const handleCycleWrapMode = useCallback(() => {+ if (stringWrapMode === "truncate") {+ setStringWrapMode("wrap");+ } else if (stringWrapMode === "wrap") {+ setStringWrapMode("nowrap");+ } else {+ setStringWrapMode("truncate");}- }, [showInput, showOutput, showMetadata, expandedSection]);+ }, [stringWrapMode, setStringWrapMode]);++ // Handle copy for Path B+ // Handle scrolling to a specific section+ const handleScrollToSection = useCallback((sectionKey: string) => {+ viewerRef.current?.scrollToSection(sectionKey);+ }, []);++ const handleCopy = useCallback(() => {+ const dataObj: Record<string, unknown> = {};+ if (showInput) dataObj.input = parsedInput;+ if (showOutput) dataObj.output = parsedOutput;+ if (showMetadata) dataObj.metadata = parsedMetadata;+ const jsonString = JSON.stringify(dataObj, null, 2);+ void navigator.clipboard.writeText(jsonString);+ }, [+ showInput,+ showOutput,+ showMetadata,+ parsedInput,+ parsedOutput,+ parsedMetadata,+ ]);++ const wrapIcon = useMemo(+ () =>+ stringWrapMode === "truncate" ? (+ <Minus size={14} />+ ) : stringWrapMode === "wrap" ? (+ <WrapText size={14} />+ ) : (+ <ChevronDown size={14} className="rotate-[-90deg]" />+ ),+ [stringWrapMode],+ );++ // Build sections - memoized to prevent re-creation+ // Must be defined before any conditional returns (React hooks rules)+ const sections = useMemo(() => {+ const result = [];+ if (showInput) {+ result.push({+ key: "input",+ title: "Input",+ data: parsedInput,+ backgroundColor: inputBgColor,+ minHeight: "200px",+ });+ }+ if (showOutput) {+ result.push({+ key: "output",+ title: "Output",+ data: parsedOutput,+ backgroundColor: outputBgColor,+ minHeight: "200px",+ });+ }+ if (showMetadata) {+ result.push({+ key: "metadata",+ title: "Metadata",+ data: parsedMetadata,+ backgroundColor: metadataBgColor,+ minHeight: "200px",+ });+ }+ return result;+ }, [+ showInput,+ showOutput,+ showMetadata,+ parsedInput,+ parsedOutput,+ parsedMetadata,+ inputBgColor,+ outputBgColor,+ metadataBgColor,+ ]);++ // Wait for parsing to complete before rendering to avoid flicker+ // isParsing is true when we have raw data but parsed data hasn't arrived yet+ // This check happens AFTER all hooks to comply with React hooks rules+ if (isParsing) {+ return (+ <div className="flex min-h-0 flex-1 flex-col border-b border-t">+ <div className="flex h-full items-center justify-center">+ <div className="text-sm text-muted-foreground">Parsing data...</div>+ </div>+ </div>+ );+ }return (- <div className="flex min-h-0 flex-1 flex-col">- {showInput && (- <AdvancedJsonSection- title="Input"- field="input"- data={input}- parsedData={parsedInput}- collapsed={expandedSection !== "input"}- onToggleCollapse={() => handleUserToggle("input")}- isLoading={isLoading || isParsing}- media={media?.filter((m) => m.field === "input")}- enableSearch={true}- searchPlaceholder="Search input"- hideIfNull={hideIfNull}- truncateStringsAt={100}- enableCopy={true}- backgroundColor={inputBgColor}- headerBackgroundColor={inputBgColor}- className={expandedSection === "input" ? "min-h-0 flex-1" : ""}- />- )}- {showOutput && (- <AdvancedJsonSection- title="Output"- field="output"- data={output}- parsedData={parsedOutput}- collapsed={expandedSection !== "output"}- onToggleCollapse={() => handleUserToggle("output")}- isLoading={isLoading || isParsing}- media={media?.filter((m) => m.field === "output")}- enableSearch={true}- searchPlaceholder="Search output"- hideIfNull={hideIfNull}- truncateStringsAt={100}- enableCopy={true}- backgroundColor={outputBgColor}- headerBackgroundColor={outputBgColor}- className={expandedSection === "output" ? "min-h-0 flex-1" : ""}- />- )}- {showMetadata && (- <AdvancedJsonSection- title="Metadata"- field="metadata"- data={metadata}- parsedData={parsedMetadata}- collapsed={expandedSection !== "metadata"}- onToggleCollapse={() => handleUserToggle("metadata")}- isLoading={isLoading || isParsing}- media={media?.filter((m) => m.field === "metadata")}- enableSearch={true}- searchPlaceholder="Search metadata"- hideIfNull={hideIfNull}- truncateStringsAt={100}+ <div className="flex min-h-0 flex-1 flex-col border-b border-t">+ {/* Header - matches LogViewToolbar styling */}+ <div className="flex h-9 flex-shrink-0 items-center gap-1.5 border-b bg-background px-2">+ {/* Search input - expands to fill available width */}+ <Command className="flex-1 rounded-none border-0 bg-transparent">+ <CommandInput+ showBorder={false}+ placeholder="Search across all sections..."+ className="h-7 border-0 focus:ring-0"+ value={searchQuery}+ onValueChange={setSearchQuery}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ if (e.shiftKey) {+ handlePreviousMatch();+ } else {+ handleNextMatch();+ }+ } else if (e.key === "Escape") {+ handleClearSearch();+ }+ }}+ />+ </Command>++ {/* Match counter - inline text (only when searching) */}+ {searchQuery && (+ <span className="whitespace-nowrap text-xs text-muted-foreground">+ {searchMatchCount > 0+ ? `${currentMatchIndex + 1} of ${searchMatchCount}`+ : "No matches"}+ </span>+ )}++ {/* Navigation buttons (only when matches exist) */}+ {searchQuery && searchMatchCount > 0 && (+ <>+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7"+ onClick={handlePreviousMatch}+ title="Previous match (Shift+Enter)"+ >+ <ChevronUp className="h-3.5 w-3.5" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7"+ onClick={handleNextMatch}+ title="Next match (Enter)"+ >+ <ChevronDown className="h-3.5 w-3.5" />+ </Button>+ </>+ )}++ {/* Wrap mode toggle */}+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7"+ onClick={handleCycleWrapMode}+ title={`String wrap mode: ${stringWrapMode}`}+ >+ {wrapIcon}+ </Button>++ {/* Copy button */}+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7"+ onClick={handleCopy}+ title="Copy to clipboard"+ >+ <Copy className="h-3.5 w-3.5" />+ </Button>+ </div>++ {/* Section navigation hint bar */}+ <div className="flex h-6 flex-shrink-0 items-center gap-1.5 border-b bg-background px-2">+ <span className="text-xs text-muted-foreground">Jump to:</span>+ {sections.map((section, index) => (+ <span key={section.key} className="flex items-center">+ <button+ onClick={() => handleScrollToSection(section.key)}+ className="cursor-pointer text-xs text-primary hover:underline"+ >+ {section.title}+ </button>+ {index < sections.length - 1 && (+ <span className="text-xs text-muted-foreground">, </span>+ )}+ </span>+ ))}+ {needsVirtualization && (+ <HoverCard>+ <HoverCardTrigger asChild>+ <span className="ml-auto cursor-help rounded bg-muted px-1.5 py-px text-[10px] font-medium text-muted-foreground">+ Virtualized+ </span>+ </HoverCardTrigger>+ <HoverCardContent className="w-80" side="bottom" align="end">+ <div className="space-y-2">+ <p className="text-sm font-medium">Virtualized View</p>+ <p className="text-xs text-muted-foreground">+ This view is using virtualization due to a large number of+ keys ({rowCounts.input.toLocaleString()} input,{" "}+ {rowCounts.output.toLocaleString()} output,{" "}+ {rowCounts.metadata.toLocaleString()} metadata). Only visible+ rows are rendered for optimal performance.+ </p>+ </div>+ </HoverCardContent>+ </HoverCard>+ )}+ </div>++ {/* Body with MultiSectionJsonViewer */}+ <div className="min-h-0 flex-1 overflow-auto" ref={scrollContainerRef}>+ <MultiSectionJsonViewer+ ref={viewerRef}+ sections={sections}+ virtualized={needsVirtualization}+ showLineNumbers={true}enableCopy={true}- backgroundColor={metadataBgColor}- headerBackgroundColor={metadataBgColor}- className={expandedSection === "metadata" ? "min-h-0 flex-1" : ""}+ stringWrapMode={stringWrapMode}+ truncateStringsAt={stringWrapMode === "truncate" ? 100 : null}+ searchQuery={debouncedSearchQuery}+ currentMatchIndex={currentMatchIndex}+ onSearchResults={setSearchMatchCount}+ scrollContainerRef={+ scrollContainerRef as React.RefObject<HTMLDivElement>+ }+ media={media}+ theme={{+ fontSize: "0.7rem",+ lineHeight: 14,+ indentSize: 12,+ }}/>- )}+ </div></div>);}diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsxindex c72d991443..88adda342f 100644--- a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx@@ -74,6 +74,7 @@ export function ObservationDetailView({const currentView = jsonViewPreference;const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(true);+ const [isJSONBetaVirtualized, setIsJSONBetaVirtualized] = useState(false);// Get comments, scores, and expansion state from contextsconst { comments, scores } = useTraceData();@@ -91,7 +92,7 @@ export function ObservationDetailView({parsedOutput,parsedMetadata,isLoadingObservation,- isParsing,+ isWaitingForParsing,} = useParsedObservation({observationId: observation.id,traceId: traceId,@@ -179,7 +180,9 @@ export function ObservationDetailView({><divclassName={`flex min-h-0 w-full flex-1 flex-col ${- currentView === "json-beta" ? "overflow-hidden" : "overflow-auto"+ currentView === "json-beta" && isJSONBetaVirtualized+ ? "overflow-hidden"+ : "overflow-auto pb-4"}`}><IOPreview@@ -192,7 +195,7 @@ export function ObservationDetailView({parsedOutput={parsedOutput}parsedMetadata={parsedMetadata}isLoading={observationWithIOCompat.isLoading}- isParsing={isParsing}+ isParsing={isWaitingForParsing}media={observationMedia.data}currentView={currentView}setIsPrettyViewAvailable={setIsPrettyViewAvailable}@@ -203,6 +206,7 @@ export function ObservationDetailView({setFieldExpansion("output", exp)}showMetadata+ onVirtualizationChange={setIsJSONBetaVirtualized}/>{currentView !== "json-beta" && (<div className="h-4 w-full flex-shrink-0" />diff --git a/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsxindex 6d5e18fb44..e50d3c7aa3 100644--- a/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx+++ b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx@@ -63,6 +63,7 @@ export function TraceDetailView({// Tab and view state from URL (via SelectionContext)const { selectedTab, setSelectedTab } = useSelection();const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(true);+ const [isJSONBetaVirtualized, setIsJSONBetaVirtualized] = useState(false);// Get jsonViewPreference directly from ViewPreferencesContext for "json-beta" supportconst { jsonViewPreference, setJsonViewPreference } = useViewPreferences();@@ -249,7 +250,7 @@ export function TraceDetailView({><divclassName={`flex min-h-0 w-full flex-1 flex-col ${- currentView === "json-beta"+ currentView === "json-beta" && isJSONBetaVirtualized? "overflow-hidden": "overflow-auto pb-4"}`}@@ -290,6 +291,7 @@ export function TraceDetailView({setFieldExpansion("output", exp)}showMetadata+ onVirtualizationChange={setIsJSONBetaVirtualized}/></div></TabsBarContent>diff --git a/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSection.tsx b/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSection.tsxindex 0f4c430c33..fe04aad394 100644--- a/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSection.tsx+++ b/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSection.tsx@@ -82,6 +82,9 @@ export interface AdvancedJsonSectionProps {/** Additional control buttons in header */controlButtons?: React.ReactNode;++ /** Force virtualization on/off (overrides auto-detection) */+ virtualized?: boolean;}export function AdvancedJsonSection({@@ -103,6 +106,7 @@ export function AdvancedJsonSection({isLoading = false,media: _media, // TODO: Implement media attachment supportcontrolButtons,+ virtualized,}: AdvancedJsonSectionProps) {// String wrap mode state (persisted in localStorage)const { stringWrapMode, setStringWrapMode } = useJsonViewPreferences();@@ -115,7 +119,13 @@ export function AdvancedJsonSection({? controlledCollapsed: internalCollapsed;+ // When virtualized=false (continuous scroll mode), ignore collapse state - always expanded+ const effectiveCollapsed = virtualized === false ? false : sectionCollapsed;+const handleToggleSectionCollapse = () => {+ // Don't allow toggling in non-virtualized mode+ if (virtualized === false) return;+if (isCollapseControlled) {onToggleCollapse();} else {@@ -260,7 +270,7 @@ export function AdvancedJsonSection({return (<div- className={`flex flex-col border-b border-t ${sectionCollapsed ? "" : "min-h-0 overflow-hidden"} ${className || ""}`}+ className={`flex flex-col border-b border-t ${effectiveCollapsed ? "" : virtualized !== false ? "min-h-0 overflow-hidden" : ""} ${className || ""}`}style={{backgroundColor: headerBackgroundColor || backgroundColor,}}@@ -285,11 +295,11 @@ export function AdvancedJsonSection({handleOnCopy={handleCopy}backgroundColor={headerBackgroundColor}onToggleCollapse={handleToggleSectionCollapse}- sectionCollapsed={sectionCollapsed}+ sectionCollapsed={effectiveCollapsed}controlButtons={<>{/* Search */}- {!sectionCollapsed && enableSearch && (+ {!effectiveCollapsed && enableSearch && (<div className="flex items-center gap-1"><div className="relative"><Input@@ -349,10 +359,10 @@ export function AdvancedJsonSection({)}{/* Custom control buttons */}- {!sectionCollapsed && controlButtons}+ {!effectiveCollapsed && controlButtons}{/* String wrap mode toggle */}- {!sectionCollapsed && (+ {!effectiveCollapsed && (<Buttonvariant="ghost"size="icon-xs"@@ -399,10 +409,14 @@ export function AdvancedJsonSection({</div>{/* Body */}- {!sectionCollapsed && (+ {!effectiveCollapsed && (<divref={scrollContainerRef}- className="min-h-0 flex-1 overflow-auto"+ className={+ virtualized !== false+ ? "min-h-0 flex-1 overflow-auto"+ : "min-h-48 overflow-x-auto"+ }style={{backgroundColor: headerBackgroundColor || backgroundColor,}}@@ -427,7 +441,8 @@ export function AdvancedJsonSection({truncateStringsAt={truncateStringsAt}isLoading={isLoading}scrollContainerRef={scrollContainerRef}- className="h-full"+ virtualized={virtualized} // Pass through virtualized prop+ className={virtualized !== false ? "h-full" : ""}/>)}</div>diff --git a/web/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer.tsxindex d9bef394b0..25aba207a5 100644--- a/web/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer.tsx+++ b/web/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer.tsx@@ -262,7 +262,11 @@ export function AdvancedJsonViewer({return (<divclassName={className}- style={{ display: "flex", flexDirection: "column", height: "100%" }}+ style={{+ display: "flex",+ flexDirection: "column",+ ...(shouldUseVirtualization && { height: "100%" }),+ }}>{/* Search bar */}{enableSearch && (diff --git a/web/src/components/ui/AdvancedJsonViewer/MultiSectionJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/MultiSectionJsonViewer.tsxnew file mode 100644index 0000000000..c12bec71b6--- /dev/null+++ b/web/src/components/ui/AdvancedJsonViewer/MultiSectionJsonViewer.tsx@@ -0,0 +1,236 @@+import {+ useMemo,+ useEffect,+ useRef,+ useImperativeHandle,+ forwardRef,+ type RefObject,+} from "react";+import type {+ JsonSection,+ PartialJSONTheme,+ StringWrapMode,+ SectionContext,+} from "./types";+import { useMultiSectionTreeState } from "./hooks/useMultiSectionTreeState";+import { useJsonTheme } from "./hooks/useJsonTheme";+import {+ VirtualizedMultiSectionViewer,+ type VirtualizedMultiSectionViewerHandle,+} from "./VirtualizedMultiSectionViewer";+import {+ SimpleMultiSectionViewer,+ type SimpleMultiSectionViewerHandle,+} from "./SimpleMultiSectionViewer";+import { SectionContextProvider } from "./contexts/SectionContext";+import { searchInTree, getMatchCountsPerNode } from "./utils/searchJson";+import { type MediaReturnType } from "@/src/features/media/validation";++export interface MultiSectionJsonViewerHandle {+ scrollToSection: (sectionKey: string) => void;+}++export interface MultiSectionJsonViewerProps {+ /** Section definitions (key, data, header, footer, backgroundColor) */+ sections: JsonSection[];++ /** Force virtualization on/off (overrides auto-detection) */+ virtualized?: boolean;++ /** Theme customization */+ theme?: PartialJSONTheme;++ /** Default header renderer (used when section.renderHeader is not provided) */+ defaultRenderHeader?: (+ context: SectionContext & { title: string },+ ) => React.ReactNode;++ /** Controlled search */+ searchQuery?: string;+ onSearchQueryChange?: (query: string) => void;+ currentMatchIndex?: number;+ onCurrentMatchIndexChange?: (index: number) => void;+ onSearchResults?: (matchCount: number) => void;++ /** Display options */+ showLineNumbers?: boolean;+ enableCopy?: boolean;+ stringWrapMode?: StringWrapMode;+ truncateStringsAt?: number | null;++ /** Styling */+ className?: string;++ /** Scroll container ref (for virtualization) */+ scrollContainerRef?: RefObject<HTMLDivElement>;++ /** Media attachments (will be filtered by section field) */+ media?: MediaReturnType[];+}++/**+ * Multi-section JSON viewer with collapsible sections+ *+ * Features:+ * - Multiple JSON roots in one viewer+ * - Sticky section headers+ * - Search across all sections with auto-expand+ * - Line numbering resets per section+ * - Context API for header/footer components+ * - Maintains JIT O(log n) performance+ */+export const MultiSectionJsonViewer = forwardRef<+ MultiSectionJsonViewerHandle,+ MultiSectionJsonViewerProps+>(function MultiSectionJsonViewer(+ {+ sections,+ virtualized: virtualizedProp,+ theme: userTheme,+ defaultRenderHeader,+ searchQuery,+ onSearchQueryChange: _onSearchQueryChange,+ currentMatchIndex,+ onCurrentMatchIndexChange: _onCurrentMatchIndexChange,+ onSearchResults,+ showLineNumbers = true,+ enableCopy = true,+ stringWrapMode = "wrap",+ truncateStringsAt = 100,+ className,+ scrollContainerRef,+ media,+ },+ ref,+) {+ // Ref for child viewer (either virtualized or simple)+ const viewerRef = useRef<+ VirtualizedMultiSectionViewerHandle | SimpleMultiSectionViewerHandle+ >(null);++ // Resolve theme+ const theme = useJsonTheme(userTheme);++ // Extract data configs for tree building (pure data, no presentation)+ const sectionConfigs = useMemo(+ () =>+ sections.map((s) => ({+ key: s.key,+ data: s.data,+ backgroundColor: s.backgroundColor,+ minHeight: s.minHeight,+ })),+ [sections],+ );++ // Build and manage multi-section tree (pure data structure)+ const {+ tree,+ expansionVersion,+ handleToggleExpansion,+ handleToggleSectionExpansion,+ } = useMultiSectionTreeState({+ sectionConfigs,+ searchQuery,+ indentSizePx: theme.indentSize,+ });++ // Compute search matches+ const searchMatches = useMemo(() => {+ if (!searchQuery || !tree) return [];+ return searchInTree(tree, searchQuery, { caseSensitive: false });+ }, [tree, searchQuery]);++ // Calculate match counts for collapsed nodes and multi-match badges+ const matchCounts = useMemo(() => {+ return tree && searchMatches.length > 0+ ? getMatchCountsPerNode(tree, searchMatches)+ : undefined;+ }, [tree, searchMatches]);++ // Notify parent of search result count+ useEffect(() => {+ if (onSearchResults) {+ onSearchResults(searchMatches.length);+ }+ }, [searchMatches, onSearchResults]);++ // Expose scrollToSection method via ref (forwards to child viewer)+ useImperativeHandle(+ ref,+ () => ({+ scrollToSection: (sectionKey: string) => {+ viewerRef.current?.scrollToSection(sectionKey);+ },+ }),+ [],+ );++ // Determine virtualization (auto-detect based on total nodes)+ const shouldVirtualize = useMemo(() => {+ if (virtualizedProp !== undefined) return virtualizedProp;+ if (!tree) return false;+ return tree.totalNodeCount > 500;+ }, [virtualizedProp, tree]);++ // Common viewer props (includes both data tree and presentation sections)+ const viewerProps = useMemo(+ () => ({+ tree,+ sections,+ expansionVersion,+ theme,+ defaultRenderHeader,+ searchQuery,+ currentMatchIndex,+ matchCounts,+ showLineNumbers,+ enableCopy,+ stringWrapMode,+ truncateStringsAt,+ onToggleExpansion: handleToggleExpansion,+ scrollContainerRef,+ media,+ }),+ [+ tree,+ sections,+ expansionVersion,+ theme,+ defaultRenderHeader,+ searchQuery,+ currentMatchIndex,+ matchCounts,+ showLineNumbers,+ enableCopy,+ stringWrapMode,+ truncateStringsAt,+ handleToggleExpansion,+ scrollContainerRef,+ media,+ ],+ );++ if (!tree) {+ return <div className={className}>Building tree...</div>;+ }++ return (+ <SectionContextProvider tree={tree} onToggle={handleToggleSectionExpansion}>+ <div+ className={className}+ style={{+ display: "flex",+ flexDirection: "column",+ ...(shouldVirtualize && { height: "100%" }),+ }}+ >+ {shouldVirtualize ? (+ <VirtualizedMultiSectionViewer ref={viewerRef} {...viewerProps} />+ ) : (+ <SimpleMultiSectionViewer ref={viewerRef} {...viewerProps} />+ )}+ </div>+ </SectionContextProvider>+ );+});diff --git a/web/src/components/ui/AdvancedJsonViewer/SimpleJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/SimpleJsonViewer.tsxindex 771cdb7465..2a25fc02d0 100644--- a/web/src/components/ui/AdvancedJsonViewer/SimpleJsonViewer.tsx+++ b/web/src/components/ui/AdvancedJsonViewer/SimpleJsonViewer.tsx@@ -114,7 +114,6 @@ export const SimpleJsonViewer = memo(function SimpleJsonViewer({ref={containerRef}className={className}style={{- height: "100%",width: stringWrapMode === "wrap" ? "100%" : "fit-content",minWidth: "100%",backgroundColor: theme.background,@@ -162,12 +161,16 @@ export const SimpleJsonViewer = memo(function SimpleJsonViewer({maxLineNumberDigits={maxLineNumberDigits}searchMatch={searchMatch}isCurrentMatch={isCurrentMatch}+ matchCount={matchCount}+ currentMatchIndexInRow={+ isCurrentMatch ? currentMatchIndexInRow : undefined+ }onToggleExpansion={onToggleExpansion}stringWrapMode={stringWrapMode}/></div>- {/* Scrollable column (indent + key + value + badges + copy) */}+ {/* Scrollable column (indent + key + value + copy) */}<divstyle={{width: "fit-content",@@ -184,10 +187,6 @@ export const SimpleJsonViewer = memo(function SimpleJsonViewer({theme={theme}stringWrapMode={stringWrapMode}truncateStringsAt={truncateStringsAt}- matchCount={matchCount}- currentMatchIndexInRow={- isCurrentMatch ? currentMatchIndexInRow : undefined- }enableCopy={enableCopy}searchMatch={searchMatch}isCurrentMatch={isCurrentMatch}diff --git a/web/src/components/ui/AdvancedJsonViewer/SimpleMultiSectionViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/SimpleMultiSectionViewer.tsxnew file mode 100644index 0000000000..cd328dacf2--- /dev/null+++ b/web/src/components/ui/AdvancedJsonViewer/SimpleMultiSectionViewer.tsx@@ -0,0 +1,412 @@+import {+ useRef,+ useMemo,+ memo,+ useEffect,+ useState,+ useLayoutEffect,+ useImperativeHandle,+ forwardRef,+ type RefObject,+} from "react";+import type {+ JSONTheme,+ StringWrapMode,+ JsonSection,+ SectionContext,+} from "./types";+import { MultiSectionJsonViewerHeader } from "./components/MultiSectionJsonViewerHeader";+import type { TreeState } from "./utils/treeStructure";+import { getAllVisibleNodes, treeNodeToFlatRow } from "./utils/treeNavigation";+import { JsonRowFixed } from "./components/JsonRowFixed";+import { JsonRowScrollable } from "./components/JsonRowScrollable";+import { useJsonSearch } from "./hooks/useJsonSearch";+import { useJsonViewerLayout } from "./hooks/useJsonViewerLayout";+import { searchInTree } from "./utils/searchJson";+import { type MediaReturnType } from "@/src/features/media/validation";++export interface SimpleMultiSectionViewerHandle {+ scrollToSection: (sectionKey: string) => void;+}++export interface SimpleMultiSectionViewerProps {+ tree: TreeState;+ sections: JsonSection[];+ expansionVersion: number;+ theme: JSONTheme;+ defaultRenderHeader?: (+ context: SectionContext & { title: string },+ ) => React.ReactNode;+ searchQuery?: string;+ currentMatchIndex?: number;+ matchCounts?: Map<string, number>;+ showLineNumbers?: boolean;+ enableCopy?: boolean;+ stringWrapMode?: StringWrapMode;+ truncateStringsAt?: number | null;+ onToggleExpansion?: (nodeId: string) => void;+ scrollContainerRef?: RefObject<HTMLDivElement>;+ media?: MediaReturnType[];+}++export const SimpleMultiSectionViewer = memo(+ forwardRef<SimpleMultiSectionViewerHandle, SimpleMultiSectionViewerProps>(+ function SimpleMultiSectionViewer(+ {+ tree,+ sections,+ expansionVersion,+ theme,+ defaultRenderHeader,+ searchQuery,+ currentMatchIndex = 0,+ matchCounts,+ showLineNumbers = true,+ enableCopy = false,+ stringWrapMode = "wrap",+ truncateStringsAt = 100,+ onToggleExpansion,+ scrollContainerRef,+ media,+ },+ ref,+ ) {+ const containerRef = useRef<HTMLDivElement>(null);+ const [containerWidth, setContainerWidth] = useState<number | null>(null);++ // Build sections map for O(1) lookup+ const sectionsMap = useMemo(() => {+ return new Map(sections.map((s) => [s.key, s]));+ }, [sections]);++ // Measure scroll container width for sticky headers+ useLayoutEffect(() => {+ const container = scrollContainerRef?.current;+ if (!container) return;++ const updateWidth = () => {+ setContainerWidth(container.clientWidth);+ };++ updateWidth(); // Initial measurement++ if (+ typeof window !== "undefined" &&+ typeof ResizeObserver !== "undefined"+ ) {+ const resizeObserver = new ResizeObserver(updateWidth);+ resizeObserver.observe(container);+ return () => resizeObserver.disconnect();+ }+ }); // Remove dependency array - run on every render++ // Get all visible nodes+ const allNodes = useMemo(() => {+ if (!tree) return [];+ return getAllVisibleNodes(tree.rootNode);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [tree, expansionVersion]);++ // Filter out meta-root (depth: -1)+ const visibleNodes = useMemo(() => {+ return allNodes.filter((node) => node.depth >= 0);+ }, [allNodes]);++ // Layout calculations+ const {+ maxLineNumberDigits,+ fixedColumnWidth,+ scrollableMinWidth,+ scrollableMaxWidth,+ } = useJsonViewerLayout({+ tree,+ expansionVersion,+ theme,+ showLineNumbers,+ totalLineCount: tree?.totalNodeCount,+ stringWrapMode,+ truncateStringsAt,+ });++ // Search matches+ const searchMatches = useMemo(() => {+ if (!searchQuery || !tree) return [];+ return searchInTree(tree, searchQuery);+ }, [tree, searchQuery]);++ const { matchMap, currentMatch, currentMatchIndexInRow } = useJsonSearch(+ searchMatches,+ currentMatchIndex,+ );++ // Store refs to row elements for scroll-to-match+ const rowRefs = useRef<Map<string, HTMLDivElement>>(new Map());++ // Scroll to current match when it changes+ useEffect(() => {+ if (!currentMatch) return;+ const element = rowRefs.current.get(currentMatch.rowId);+ if (element) {+ element.scrollIntoView({ block: "center", behavior: "smooth" });+ }+ }, [currentMatch]);++ // Expose scrollToSection method via ref+ useImperativeHandle(+ ref,+ () => ({+ scrollToSection: (sectionKey: string) => {+ const container = scrollContainerRef?.current;+ if (!container) return;++ // Find section by data-section-key attribute+ const sectionElement = container.querySelector(+ `[data-section-key="${sectionKey}"]`,+ );+ if (sectionElement) {+ sectionElement.scrollIntoView({+ behavior: "smooth",+ block: "start",+ });+ }+ },+ }),+ [scrollContainerRef],+ );++ // Group nodes by section for rendering+ const sectionGroups = useMemo(() => {+ interface SectionGroup {+ header: (typeof visibleNodes)[0];+ content: typeof visibleNodes;+ spacer: (typeof visibleNodes)[0] | null;+ footer: (typeof visibleNodes)[0] | null;+ }++ const result: SectionGroup[] = [];+ let currentSection: SectionGroup | null = null;++ visibleNodes.forEach((node) => {+ if (node.nodeType === "section-header") {+ currentSection = {+ header: node,+ content: [],+ spacer: null,+ footer: null,+ };+ result.push(currentSection);+ } else if (node.nodeType === "section-spacer") {+ if (currentSection) {+ currentSection.spacer = node;+ }+ } else if (node.nodeType === "section-footer") {+ if (currentSection) {+ currentSection.footer = node;+ }+ } else if (node.nodeType === "json") {+ if (currentSection) {+ currentSection.content.push(node);+ }+ }+ });++ return result;+ }, [visibleNodes]);++ const renderJsonRow = (node: (typeof visibleNodes)[0], index: number) => {+ const searchMatch = matchMap.get(node.id);+ const isCurrentMatch = currentMatch?.rowId === node.id;+ const row = treeNodeToFlatRow(node, index);+ const matchCount = matchCounts?.get(node.id);++ return (+ <div+ key={node.id}+ ref={(el) => {+ if (el) {+ rowRefs.current.set(node.id, el);+ } else {+ rowRefs.current.delete(node.id);+ }+ }}+ style={{+ display: "grid",+ gridTemplateColumns: `${fixedColumnWidth}px auto`,+ width: stringWrapMode === "nowrap" ? undefined : "100%",+ backgroundColor: node.backgroundColor || theme.background,+ }}+ >+ {/* Fixed column */}+ <div+ style={{+ position: "sticky",+ left: 0,+ zIndex: 1,+ width: `${fixedColumnWidth}px`,+ backgroundColor: node.backgroundColor || theme.background,+ }}+ >+ <JsonRowFixed+ row={row}+ theme={theme}+ showLineNumber={showLineNumbers}+ lineNumber={node.sectionLineNumber ?? index + 1}+ maxLineNumberDigits={maxLineNumberDigits}+ searchMatch={searchMatch}+ isCurrentMatch={isCurrentMatch}+ matchCount={matchCount}+ currentMatchIndexInRow={+ isCurrentMatch ? currentMatchIndexInRow : undefined+ }+ onToggleExpansion={onToggleExpansion}+ stringWrapMode={stringWrapMode}+ />+ </div>++ {/* Scrollable column */}+ <div+ style={{+ width: "fit-content",+ minWidth: scrollableMinWidth ? `${scrollableMinWidth}px` : 0,+ maxWidth: scrollableMaxWidth+ ? `${scrollableMaxWidth}px`+ : undefined,+ overflow: stringWrapMode === "nowrap" ? undefined : "hidden",+ }}+ >+ <JsonRowScrollable+ row={row}+ theme={theme}+ searchMatch={searchMatch}+ isCurrentMatch={isCurrentMatch}+ enableCopy={enableCopy}+ stringWrapMode={stringWrapMode}+ truncateStringsAt={truncateStringsAt}+ />+ </div>+ </div>+ );+ };++ return (+ <div+ ref={containerRef}+ style={{+ width: stringWrapMode === "wrap" ? "100%" : "fit-content",+ minWidth: "100%",+ backgroundColor: theme.background,+ color: theme.foreground,+ fontFamily: "monospace",+ }}+ >+ <div style={{ position: "relative" }}>+ {sectionGroups.map((sectionGroup) => {+ // Look up JsonSection for render functions+ const sectionKey = sectionGroup.header.sectionKey;+ const jsonSection = sectionKey+ ? sectionsMap.get(sectionKey)+ : null;++ // Get section context (using hook requires component wrapper)+ const sectionContext = {+ sectionKey: sectionKey || "",+ rowCount:+ sectionGroup.header.totalDescendantCount ??+ sectionGroup.content.length,+ isExpanded: sectionGroup.header.isExpanded,+ setExpanded: (_expanded: boolean) => {+ if (onToggleExpansion) {+ onToggleExpansion(sectionGroup.header.id);+ }+ },+ };++ // Derive title from section config or capitalize key+ const title =+ jsonSection?.title ||+ (sectionKey+ ? sectionKey.charAt(0).toUpperCase() + sectionKey.slice(1)+ : "");++ // Filter media for this section+ const sectionMedia = media?.filter((m) => m.field === sectionKey);++ // Render header with fallback chain+ let headerContent;+ if (jsonSection?.renderHeader) {+ headerContent = jsonSection.renderHeader(sectionContext);+ } else if (defaultRenderHeader) {+ headerContent = defaultRenderHeader({+ ...sectionContext,+ title,+ });+ } else {+ headerContent = (+ <MultiSectionJsonViewerHeader+ title={title}+ context={sectionContext}+ media={sectionMedia}+ />+ );+ }++ return (+ <div+ key={sectionGroup.header.id}+ data-section-key={sectionKey}+ style={{+ width: stringWrapMode === "wrap" ? "100%" : "fit-content",+ backgroundColor:+ sectionGroup.header.backgroundColor || theme.background,+ }}+ >+ {/* Render section header */}+ <div+ style={{+ position: "sticky",+ top: 0,+ left: 0,+ width: containerWidth ? `${containerWidth}px` : "100%",+ zIndex: 10,+ backgroundColor:+ sectionGroup.header.backgroundColor || theme.background,+ borderBottom: "1px solid",+ borderColor: theme.punctuationColor || "#e5e7eb",+ }}+ >+ {headerContent}+ </div>++ {/* Render section content */}+ <div+ style={{+ width: stringWrapMode === "wrap" ? "100%" : "max-content",+ }}+ >+ {sectionGroup.content.map((node, index) =>+ renderJsonRow(node, index),+ )}+ </div>++ {/* Render spacer if exists */}+ {sectionGroup.spacer && (+ <div+ style={{+ height: `${sectionGroup.spacer.spacerHeight}px`,+ }}+ />+ )}++ {/* Render section footer if exists */}+ {jsonSection?.renderFooter && (+ <div>{jsonSection.renderFooter(sectionContext)}</div>+ )}+ </div>+ );+ })}+ </div>+ </div>+ );+ },+ ),+);diff --git a/web/src/components/ui/AdvancedJsonViewer/VirtualizedJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/VirtualizedJsonViewer.tsxindex 7488d377f6..38fc31bc4f 100644--- a/web/src/components/ui/AdvancedJsonViewer/VirtualizedJsonViewer.tsx+++ b/web/src/components/ui/AdvancedJsonViewer/VirtualizedJsonViewer.tsx@@ -14,6 +14,7 @@ import { JsonRowFixed } from "./components/JsonRowFixed";import { JsonRowScrollable } from "./components/JsonRowScrollable";import { useJsonSearch } from "./hooks/useJsonSearch";import { useJsonViewerLayout } from "./hooks/useJsonViewerLayout";+import { useMonospaceCharWidth } from "./hooks/useMonospaceCharWidth";interface VirtualizedJsonViewerProps {tree: TreeState | null;@@ -52,6 +53,9 @@ export const VirtualizedJsonViewer = memo(function VirtualizedJsonViewer({}: VirtualizedJsonViewerProps) {const parentRef = useRef<HTMLDivElement>(null);+ // Measure actual monospace character width for accurate height estimation+ const charWidth = useMonospaceCharWidth();+// Determine row count// NOTE: Must recalculate when expansionVersion changes because tree is mutated in placeconst rowCount = tree ? 1 + tree.rootNode.visibleDescendantCount : 0;@@ -71,6 +75,7 @@ export const VirtualizedJsonViewer = memo(function VirtualizedJsonViewer({totalLineCount,stringWrapMode,truncateStringsAt,+ charWidth,});// Search-related calculations@@ -200,12 +205,16 @@ export const VirtualizedJsonViewer = memo(function VirtualizedJsonViewer({maxLineNumberDigits={maxLineNumberDigits}searchMatch={searchMatch}isCurrentMatch={isCurrentMatch}+ matchCount={matchCount}+ currentMatchIndexInRow={+ isCurrentMatch ? currentMatchIndexInRow : undefined+ }onToggleExpansion={finalHandleToggleExpansion}stringWrapMode={stringWrapMode}/></div>- {/* Scrollable column (indent + key + value + badges + copy) */}+ {/* Scrollable column (indent + key + value + copy) */}<divstyle={{width: "fit-content",@@ -222,10 +231,6 @@ export const VirtualizedJsonViewer = memo(function VirtualizedJsonViewer({theme={theme}stringWrapMode={stringWrapMode}truncateStringsAt={truncateStringsAt}- matchCount={matchCount}- currentMatchIndexInRow={- isCurrentMatch ? currentMatchIndexInRow : undefined- }enableCopy={enableCopy}searchMatch={searchMatch}isCurrentMatch={isCurrentMatch}diff --git a/web/src/components/ui/AdvancedJsonViewer/VirtualizedMultiSectionViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/VirtualizedMultiSectionViewer.tsxnew file mode 100644index 0000000000..edf3b40bb6--- /dev/null+++ b/web/src/components/ui/AdvancedJsonViewer/VirtualizedMultiSectionViewer.tsx@@ -0,0 +1,492 @@+import {+ useEffect,+ useMemo,+ memo,+ useRef,+ useLayoutEffect,+ useState,+ useImperativeHandle,+ forwardRef,+ type RefObject,+} from "react";+import { useVirtualizer } from "@tanstack/react-virtual";+import type {+ JSONTheme,+ StringWrapMode,+ JsonSection,+ SectionContext,+} from "./types";+import { MultiSectionJsonViewerHeader } from "./components/MultiSectionJsonViewerHeader";+import type { TreeState } from "./utils/treeStructure";+import {+ getNodeByIndex,+ treeNodeToFlatRow,+ findNodeIndex,+ findSectionHeaderIndex,+} from "./utils/treeNavigation";+import { JsonRowFixed } from "./components/JsonRowFixed";+import { JsonRowScrollable } from "./components/JsonRowScrollable";+import { useJsonSearch } from "./hooks/useJsonSearch";+import { useJsonViewerLayout } from "./hooks/useJsonViewerLayout";+import { searchInTree } from "./utils/searchJson";+import { useMonospaceCharWidth } from "./hooks/useMonospaceCharWidth";+import { type MediaReturnType } from "@/src/features/media/validation";++export interface VirtualizedMultiSectionViewerHandle {+ scrollToSection: (sectionKey: string) => void;+}++export interface VirtualizedMultiSectionViewerProps {+ tree: TreeState;+ sections: JsonSection[];+ expansionVersion: number;+ theme: JSONTheme;+ defaultRenderHeader?: (+ context: SectionContext & { title: string },+ ) => React.ReactNode;+ searchQuery?: string;+ currentMatchIndex?: number;+ matchCounts?: Map<string, number>;+ showLineNumbers?: boolean;+ enableCopy?: boolean;+ stringWrapMode?: StringWrapMode;+ truncateStringsAt?: number | null;+ onToggleExpansion?: (nodeId: string) => void;+ scrollContainerRef?: RefObject<HTMLDivElement>;+ media?: MediaReturnType[];+}++export const VirtualizedMultiSectionViewer = memo(+ forwardRef<+ VirtualizedMultiSectionViewerHandle,+ VirtualizedMultiSectionViewerProps+ >(function VirtualizedMultiSectionViewer(+ {+ tree,+ sections,+ expansionVersion,+ theme,+ defaultRenderHeader,+ searchQuery,+ currentMatchIndex = 0,+ matchCounts,+ showLineNumbers = true,+ enableCopy = false,+ stringWrapMode = "wrap",+ truncateStringsAt = 100,+ onToggleExpansion,+ scrollContainerRef,+ media,+ },+ ref,+ ) {+ const parentRef = useRef<HTMLDivElement>(null);+ const [containerWidth, setContainerWidth] = useState<number | null>(null);++ // Measure actual monospace character width for accurate height estimation+ const charWidth = useMonospaceCharWidth();++ // Build sections map for O(1) lookup+ const sectionsMap = useMemo(() => {+ return new Map(sections.map((s) => [s.key, s]));+ }, [sections]);++ // Measure scroll container width for sticky headers+ useLayoutEffect(() => {+ const container = scrollContainerRef?.current;+ if (!container) {+ return;+ }++ const updateWidth = () => {+ const width = container.clientWidth;+ setContainerWidth(width);+ };++ updateWidth(); // Initial measurement++ if (+ typeof window !== "undefined" &&+ typeof ResizeObserver !== "undefined"+ ) {+ const resizeObserver = new ResizeObserver(updateWidth);+ resizeObserver.observe(container);+ return () => {+ resizeObserver.disconnect();+ };+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [scrollContainerRef?.current]);++ // Row count (includes meta-root, but we skip it in rendering)+ const rowCount = tree ? 1 + tree.rootNode.visibleDescendantCount : 0;++ // Layout calculations+ const {+ maxLineNumberDigits,+ fixedColumnWidth,+ scrollableMinWidth,+ scrollableMaxWidth,+ estimateSize,+ } = useJsonViewerLayout({+ tree,+ expansionVersion,+ theme,+ showLineNumbers,+ totalLineCount: tree?.totalNodeCount,+ stringWrapMode,+ truncateStringsAt,+ charWidth,+ });++ // Calculate total content width (stable, memoized)+ const totalContentWidth = useMemo(() => {+ if (!tree) return undefined;++ if (stringWrapMode === "nowrap") {+ return fixedColumnWidth + tree.maxContentWidth;+ }++ if (scrollableMaxWidth) {+ return fixedColumnWidth + scrollableMaxWidth;+ }++ return undefined;+ }, [tree, fixedColumnWidth, stringWrapMode, scrollableMaxWidth]);++ // Calculate effective row width (takes max of content width and container width)+ const effectiveRowWidth = useMemo(() => {+ if (!totalContentWidth && !containerWidth) return undefined;+ if (!totalContentWidth) return containerWidth;+ if (!containerWidth) return totalContentWidth;+ return Math.max(totalContentWidth, containerWidth);+ }, [totalContentWidth, containerWidth]);++ // Search matches+ const searchMatches = useMemo(() => {+ if (!searchQuery || !tree) return [];+ return searchInTree(tree, searchQuery);+ }, [tree, searchQuery]);++ const { matchMap, currentMatch, currentMatchIndexInRow } = useJsonSearch(+ searchMatches,+ currentMatchIndex,+ );++ // Virtualizer with custom estimateSize for different node types+ const rowVirtualizer = useVirtualizer({+ count: rowCount,+ getScrollElement: () => scrollContainerRef?.current || parentRef.current,+ estimateSize: (index) => {+ if (!tree) return 16;+ const node = getNodeByIndex(tree.rootNode, index);++ if (!node) return 16;++ // Meta-root should have 0 height (it's never rendered)+ if (node.nodeType === "meta") return 0;++ // Custom heights for different node types+ if (node.nodeType === "section-header") return 32;+ if (node.nodeType === "section-footer") return 40;+ if (node.nodeType === "section-spacer") return node.spacerHeight || 0;++ // Regular JSON rows+ return estimateSize(index);+ },+ overscan: 100,+ measureElement:+ typeof window !== "undefined"+ ? (element) => element.getBoundingClientRect().height+ : undefined,+ getItemKey: (index) => {+ if (!tree) return index;+ const node = getNodeByIndex(tree.rootNode, index);+ return node ? node.id : index;+ },+ });++ // Scroll to current search match+ useEffect(() => {+ if (!currentMatch || !tree) return;++ const index = findNodeIndex(tree.rootNode, currentMatch.rowId);++ if (index !== -1) {+ rowVirtualizer.scrollToIndex(index, { align: "center" });+ }+ }, [currentMatch, tree, rowVirtualizer]);++ // Expose scrollToSection method via ref+ useImperativeHandle(+ ref,+ () => ({+ scrollToSection: (sectionKey: string) => {+ if (!tree) return;++ const index = findSectionHeaderIndex(tree.rootNode, sectionKey);++ if (index !== -1) {+ rowVirtualizer.scrollToIndex(index, {+ align: "start",+ behavior: "auto",+ });+ }+ },+ }),+ [tree, rowVirtualizer],+ );++ const virtualItems = rowVirtualizer.getVirtualItems();++ return (+ <div+ ref={parentRef}+ id="virtualized-multi-section-parent"+ style={{+ height: "100%",+ width: stringWrapMode === "nowrap" ? "fit-content" : "100%",+ minWidth: "100%",+ backgroundColor: theme.background,+ }}+ >+ <div+ id="virtualized-multi-section-content"+ style={{+ height: `${rowVirtualizer.getTotalSize()}px`,+ minWidth: totalContentWidth ? `${totalContentWidth}px` : "100%",+ width: "max-content",+ position: "relative",+ }}+ >+ {virtualItems.map((virtualRow) => {+ const node = getNodeByIndex(tree.rootNode, virtualRow.index);++ if (!node) return null;++ // Skip meta-root (depth: -1)+ if (node.depth < 0) return null;++ const searchMatch = matchMap.get(node.id);+ const isCurrentMatch = currentMatch?.rowId === node.id;++ // Render based on node type+ if (node.nodeType === "section-header") {+ const jsonSection = node.sectionKey+ ? sectionsMap.get(node.sectionKey)+ : null;+ const sectionContext = {+ sectionKey: node.sectionKey || "",+ rowCount:+ node.totalDescendantCount ?? node.visibleDescendantCount,+ isExpanded: node.isExpanded,+ setExpanded: (_expanded: boolean) => {+ if (onToggleExpansion) {+ onToggleExpansion(node.id);+ }+ },+ };++ // Derive title from section config or capitalize key+ const title =+ jsonSection?.title ||+ (node.sectionKey+ ? node.sectionKey.charAt(0).toUpperCase() ++ node.sectionKey.slice(1)+ : "");++ // Filter media for this section+ const sectionMedia = media?.filter(+ (m) => m.field === node.sectionKey,+ );++ // Render header with fallback chain+ let headerContent;+ if (jsonSection?.renderHeader) {+ headerContent = jsonSection.renderHeader(sectionContext);+ } else if (defaultRenderHeader) {+ headerContent = defaultRenderHeader({+ ...sectionContext,+ title,+ });+ } else {+ headerContent = (+ <MultiSectionJsonViewerHeader+ title={title}+ context={sectionContext}+ media={sectionMedia}+ />+ );+ }++ return (+ <div+ key={virtualRow.key}+ data-index={virtualRow.index}+ data-section-key={node.sectionKey}+ ref={rowVirtualizer.measureElement}+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ minWidth: effectiveRowWidth+ ? `${effectiveRowWidth}px`+ : "100%",+ width: "max-content",+ transform: `translateY(${virtualRow.start}px)`,+ }}+ >+ <div+ style={{+ position: "sticky",+ left: 0,+ width: containerWidth ? `${containerWidth}px` : "100%",+ zIndex: 2,+ backgroundColor: node.backgroundColor || theme.background,+ borderBottom: "1px solid",+ borderColor: theme.punctuationColor || "#e5e7eb",+ }}+ >+ {headerContent}+ </div>+ </div>+ );+ }++ if (node.nodeType === "section-footer") {+ const jsonSection = node.sectionKey+ ? sectionsMap.get(node.sectionKey)+ : null;+ const sectionContext = {+ sectionKey: node.sectionKey || "",+ rowCount: 0, // Footer doesn't track row count+ isExpanded: true, // Footers are always shown+ setExpanded: () => {}, // No-op+ };++ return (+ <div+ key={virtualRow.key}+ data-index={virtualRow.index}+ ref={rowVirtualizer.measureElement}+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ minWidth: effectiveRowWidth+ ? `${effectiveRowWidth}px`+ : "100%",+ width: "max-content",+ transform: `translateY(${virtualRow.start}px)`,+ backgroundColor: node.backgroundColor || theme.background,+ }}+ >+ {jsonSection?.renderFooter?.(sectionContext)}+ </div>+ );+ }++ if (node.nodeType === "section-spacer") {+ return (+ <div+ key={virtualRow.key}+ data-index={virtualRow.index}+ ref={rowVirtualizer.measureElement}+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ minWidth: effectiveRowWidth+ ? `${effectiveRowWidth}px`+ : "100%",+ width: "max-content",+ transform: `translateY(${virtualRow.start}px)`,+ height: `${node.spacerHeight}px`,+ backgroundColor: node.backgroundColor || theme.background,+ }}+ />+ );+ }++ // Regular JSON row+ const row = treeNodeToFlatRow(node, virtualRow.index);+ const matchCount = matchCounts?.get(row.id);++ return (+ <div+ key={virtualRow.key}+ data-index={virtualRow.index}+ ref={rowVirtualizer.measureElement}+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ minWidth: effectiveRowWidth+ ? `${effectiveRowWidth}px`+ : "100%",+ width: "max-content",+ transform: `translateY(${virtualRow.start}px)`,+ display: "grid",+ gridTemplateColumns: `${fixedColumnWidth}px auto`,+ backgroundColor: node.backgroundColor || theme.background,+ }}+ >+ {/* Fixed column (line numbers + expand buttons) */}+ <div+ style={{+ position: "sticky",+ left: 0,+ zIndex: 1,+ width: `${fixedColumnWidth}px`,+ backgroundColor: node.backgroundColor || theme.background,+ }}+ >+ <JsonRowFixed+ row={row}+ theme={theme}+ showLineNumber={showLineNumbers}+ lineNumber={node.sectionLineNumber ?? virtualRow.index + 1}+ maxLineNumberDigits={maxLineNumberDigits}+ searchMatch={searchMatch}+ isCurrentMatch={isCurrentMatch}+ matchCount={matchCount}+ currentMatchIndexInRow={+ isCurrentMatch ? currentMatchIndexInRow : undefined+ }+ onToggleExpansion={onToggleExpansion}+ stringWrapMode={stringWrapMode}+ />+ </div>++ {/* Scrollable column (JSON content) */}+ <div+ style={{+ width: "fit-content",+ minWidth: scrollableMinWidth+ ? `${scrollableMinWidth}px`+ : 0,+ maxWidth: scrollableMaxWidth+ ? `${scrollableMaxWidth}px`+ : undefined,+ overflow:+ stringWrapMode === "nowrap" ? undefined : "hidden",+ }}+ >+ <JsonRowScrollable+ row={row}+ theme={theme}+ searchMatch={searchMatch}+ isCurrentMatch={isCurrentMatch}+ enableCopy={enableCopy}+ stringWrapMode={stringWrapMode}+ truncateStringsAt={truncateStringsAt}+ />+ </div>+ </div>+ );+ })}+ </div>+ </div>+ );+ }),+);diff --git a/web/src/components/ui/AdvancedJsonViewer/components/JsonRowFixed.tsx b/web/src/components/ui/AdvancedJsonViewer/components/JsonRowFixed.tsxindex 402a51de02..3ec174c3b5 100644--- a/web/src/components/ui/AdvancedJsonViewer/components/JsonRowFixed.tsx+++ b/web/src/components/ui/AdvancedJsonViewer/components/JsonRowFixed.tsx@@ -17,6 +17,8 @@ export interface JsonRowFixedProps {maxLineNumberDigits?: number;searchMatch?: SearchMatch;isCurrentMatch?: boolean;+ matchCount?: number;+ currentMatchIndexInRow?: number;onToggleExpansion?: (rowId: string) => void;stringWrapMode?: "nowrap" | "truncate" | "wrap";className?: string;@@ -31,6 +33,8 @@ export function JsonRowFixed({maxLineNumberDigits,searchMatch,isCurrentMatch = false,+ matchCount,+ currentMatchIndexInRow,onToggleExpansion,stringWrapMode = "wrap",className,@@ -47,6 +51,7 @@ export function JsonRowFixed({<divclassName={className}style={{+ position: "relative",display: "flex",alignItems: stringWrapMode === "wrap" ? "start" : "center",minHeight: `${theme.lineHeight}px`,@@ -76,6 +81,41 @@ export function JsonRowFixed({theme={theme}isToggling={isToggling}/>++ {/* Match count badge (positioned absolutely in top-right corner) */}+ {matchCount !== undefined &&+ matchCount > 1 &&+ ((row.isExpandable && !row.isExpanded) || !row.isExpandable) && (+ <span+ style={{+ position: "absolute",+ top: "2px",+ right: "2px",+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ padding: "0 4px",+ minWidth: "16px",+ height: "14px",+ fontSize: "9px",+ fontWeight: 600,+ borderRadius: "7px",+ backgroundColor: theme.searchMatchBackground,+ color: theme.foreground,+ border: `1px solid ${theme.searchCurrentBackground}`,+ pointerEvents: "none", // Don't interfere with clicks+ }}+ title={+ row.isExpandable+ ? `${matchCount} match${matchCount === 1 ? "" : "es"} in this section`+ : `${matchCount} match${matchCount === 1 ? "" : "es"} in this value`+ }+ >+ {currentMatchIndexInRow !== undefined+ ? `${currentMatchIndexInRow}/${matchCount}`+ : matchCount}+ </span>+ )}</div>);}diff --git a/web/src/components/ui/AdvancedJsonViewer/components/JsonRowScrollable.tsx b/web/src/components/ui/AdvancedJsonViewer/components/JsonRowScrollable.tsxindex 0457d030bd..a69e81a0fc 100644--- a/web/src/components/ui/AdvancedJsonViewer/components/JsonRowScrollable.tsx+++ b/web/src/components/ui/AdvancedJsonViewer/components/JsonRowScrollable.tsx@@ -15,8 +15,6 @@ export interface JsonRowScrollableProps {theme: JSONTheme;stringWrapMode?: "nowrap" | "truncate" | "wrap";truncateStringsAt?: number | null;- matchCount?: number;- currentMatchIndexInRow?: number;enableCopy?: boolean;searchMatch?: SearchMatch;isCurrentMatch?: boolean;@@ -28,8 +26,6 @@ export function JsonRowScrollable({theme,stringWrapMode = "wrap",truncateStringsAt = null,- matchCount,- currentMatchIndexInRow,enableCopy = false,searchMatch,isCurrentMatch = false,@@ -95,39 +91,6 @@ export function JsonRowScrollable({highlightEnd={isValue ? searchMatch?.highlightEnd : undefined}/>- {/* Match count badge (for collapsed rows or leaf nodes with multiple matches) */}- {matchCount !== undefined &&- matchCount > 1 &&- ((row.isExpandable && !row.isExpanded) || !row.isExpandable) && (- <span- style={{- display: "inline-flex",- alignItems: "center",- justifyContent: "center",- marginLeft: "6px",- padding: "0 4px",- minWidth: "16px",- height: "14px",- fontSize: "9px",- fontWeight: 600,- borderRadius: "7px",- backgroundColor: theme.searchMatchBackground,- color: theme.foreground,- border: `1px solid ${theme.searchCurrentBackground}`,- flexShrink: 0,- }}- title={- row.isExpandable- ? `${matchCount} match${matchCount === 1 ? "" : "es"} in this section`- : `${matchCount} match${matchCount === 1 ? "" : "es"} in this value`- }- >- {currentMatchIndexInRow !== undefined- ? `${currentMatchIndexInRow}/${matchCount}`- : matchCount}- </span>- )}-{/* Copy button (optional, on hover) */}{enableCopy && (<CopyButton value={row.value} theme={theme} className="mt-0.5" />diff --git a/web/src/components/ui/AdvancedJsonViewer/components/MediaButtonGroup.tsx b/web/src/components/ui/AdvancedJsonViewer/components/MediaButtonGroup.tsxnew file mode 100644index 0000000000..67563e385d--- /dev/null+++ b/web/src/components/ui/AdvancedJsonViewer/components/MediaButtonGroup.tsx@@ -0,0 +1,296 @@+import { useMemo, useState, useRef } from "react";+import { type MediaReturnType } from "@/src/features/media/validation";+import { File, Image as ImageIcon, Volume2, Video } from "lucide-react";+import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import { api } from "@/src/utils/api";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";++export interface MediaButtonGroupProps {+ media: MediaReturnType[];+}++type MediaCategory = "image" | "audio" | "video" | "document";++interface GroupedMedia {+ category: MediaCategory;+ items: MediaReturnType[];+ icon: typeof ImageIcon;+}++/**+ * AudioPlayer - Renders HTML5 audio player with controls+ */+function AudioPlayer({ src }: { src?: string }) {+ if (!src) return null;++ return (+ <audio controls className="w-full" preload="metadata">+ <source src={src} />+ Your browser does not support the audio element.+ </audio>+ );+}++/**+ * VideoPlayer - Renders HTML5 video player with controls+ */+function VideoPlayer({ src }: { src?: string }) {+ if (!src) return null;++ return (+ <video controls className="w-full" preload="metadata" playsInline>+ <source src={src} />+ Your browser does not support the video element.+ </video>+ );+}++/**+ * ImagePreview - Renders 96x96px image that opens in new tab when clicked+ */+function ImagePreview({ src }: { src?: string }) {+ if (!src) return null;++ const openInNewTab = () => {+ window.open(src, "_blank", "noopener,noreferrer");+ };++ return (+ <button+ onClick={openInNewTab}+ className="h-24 w-24 overflow-hidden rounded-md border bg-muted transition-opacity hover:opacity-80"+ aria-label="Open image in new tab"+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={src}+ alt="Media preview"+ className="h-full w-full object-cover"+ />+ </button>+ );+}++/**+ * MediaPreview - Renders media preview based on content type+ */+function MediaPreview({ mediaItem }: { mediaItem: MediaReturnType }) {+ const projectId = useProjectIdFromURL();++ const { data } = api.media.getById.useQuery(+ {+ mediaId: mediaItem.mediaId,+ projectId: projectId as string,+ },+ {+ enabled: Boolean(projectId),+ refetchOnWindowFocus: false,+ refetchOnMount: false,+ refetchOnReconnect: false,+ staleTime: 55 * 60 * 1000, // 55 minutes, s3 links expire after 1 hour+ },+ );++ const mediaUrl = data?.url;++ if (!mediaUrl) return null;++ const contentType = mediaItem.contentType;++ if (contentType.startsWith("image")) {+ return <ImagePreview src={mediaUrl} />;+ } else if (contentType.startsWith("audio")) {+ return <AudioPlayer src={mediaUrl} />;+ } else if (contentType.startsWith("video")) {+ return <VideoPlayer src={mediaUrl} />;+ } else {+ // Documents: use file icon view+ return (+ <LangfuseMediaView mediaAPIReturnValue={mediaItem} asFileIcon={true} />+ );+ }+}++/**+ * MediaButtonGroup - Displays media attachment buttons grouped by type+ *+ * Shown in section headers to indicate presence of media attachments.+ * Groups media by category (image/audio/video/document) and shows count badges.+ * Shows popover on hover; click to keep it open.+ */+export function MediaButtonGroup({ media }: MediaButtonGroupProps) {+ const [openCategory, setOpenCategory] = useState<MediaCategory | null>(null);+ const [clickedCategory, setClickedCategory] = useState<MediaCategory | null>(+ null,+ );+ const justClickedRef = useRef<MediaCategory | null>(null);+ const closeTimeoutRef = useRef<NodeJS.Timeout | null>(null);++ // Group media by category+ const groupedMedia = useMemo(() => {+ const groups: GroupedMedia[] = [];++ const imageMedia = media.filter((m) => m.contentType.startsWith("image"));+ const audioMedia = media.filter((m) => m.contentType.startsWith("audio"));+ const videoMedia = media.filter((m) => m.contentType.startsWith("video"));+ const documentMedia = media.filter(+ (m) =>+ !m.contentType.startsWith("image") &&+ !m.contentType.startsWith("audio") &&+ !m.contentType.startsWith("video"),+ );++ if (imageMedia.length > 0) {+ groups.push({+ category: "image",+ items: imageMedia,+ icon: ImageIcon,+ });+ }+ if (audioMedia.length > 0) {+ groups.push({+ category: "audio",+ items: audioMedia,+ icon: Volume2,+ });+ }+ if (videoMedia.length > 0) {+ groups.push({+ category: "video",+ items: videoMedia,+ icon: Video,+ });+ }+ if (documentMedia.length > 0) {+ groups.push({+ category: "document",+ items: documentMedia,+ icon: File,+ });+ }++ return groups;+ }, [media]);++ if (groupedMedia.length === 0) {+ return null;+ }++ return (+ <div+ className="flex items-center gap-1"+ onClick={(e) => e.stopPropagation()} // Prevent header click+ >+ {groupedMedia.map((group) => (+ <Popover+ key={group.category}+ open={openCategory === group.category}+ onOpenChange={(open) => {+ setOpenCategory(open ? group.category : null);+ if (!open) {+ setClickedCategory(null);+ }+ }}+ >+ <PopoverTrigger asChild>+ <button+ className="relative flex h-6 w-6 items-center justify-center rounded hover:bg-accent"+ title={`${group.items.length} ${group.category} file${+ group.items.length > 1 ? "s" : ""+ }`}+ onMouseEnter={() => {+ // Clear any pending close timeout+ if (closeTimeoutRef.current) {+ clearTimeout(closeTimeoutRef.current);+ closeTimeoutRef.current = null;+ }+ // Always open on hover, even if something else is pinned+ setOpenCategory(group.category);+ }}+ onMouseLeave={() => {+ // Ignore mouse leave if we just clicked (prevents race condition)+ if (justClickedRef.current === group.category) {+ return;+ }+ // Only close on mouse leave if not clicked - with delay+ if (clickedCategory !== group.category) {+ closeTimeoutRef.current = setTimeout(() => {+ setOpenCategory(null);+ }, 300); // 300ms delay to allow moving mouse to popover+ }+ }}+ onPointerDown={(e) => {+ e.stopPropagation();+ // If already pinned, unpin and close+ if (clickedCategory === group.category) {+ setClickedCategory(null);+ setOpenCategory(null);+ justClickedRef.current = null;+ } else {+ // Pin it open (first click)+ setClickedCategory(group.category);+ setOpenCategory(group.category);+ justClickedRef.current = group.category;+ // Clear the ref after a short delay+ setTimeout(() => {+ justClickedRef.current = null;+ }, 200);+ }+ }}+ onClick={(e) => {+ // Prevent default click behavior+ e.stopPropagation();+ e.preventDefault();+ }}+ >+ <group.icon className="h-3.5 w-3.5" />+ {group.items.length > 1 && (+ <span className="absolute -right-1 -top-1 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-primary text-[9px] font-medium text-primary-foreground">+ {group.items.length}+ </span>+ )}+ </button>+ </PopoverTrigger>+ <PopoverContent+ className="w-auto max-w-md p-2"+ align="end"+ side="bottom"+ onMouseEnter={() => {+ // Clear any pending close timeout+ if (closeTimeoutRef.current) {+ clearTimeout(closeTimeoutRef.current);+ closeTimeoutRef.current = null;+ }+ // Keep it open when hovering over content+ if (+ clickedCategory === null ||+ clickedCategory === group.category+ ) {+ setOpenCategory(group.category);+ }+ }}+ onMouseLeave={() => {+ // Only close on mouse leave if not clicked - with delay+ if (clickedCategory !== group.category) {+ closeTimeoutRef.current = setTimeout(() => {+ setOpenCategory(null);+ }, 300); // 300ms delay+ }+ }}+ >+ <div className="flex flex-wrap gap-2">+ {group.items.map((mediaItem) => (+ <MediaPreview key={mediaItem.mediaId} mediaItem={mediaItem} />+ ))}+ </div>+ </PopoverContent>+ </Popover>+ ))}+ </div>+ );+}diff --git a/web/src/components/ui/AdvancedJsonViewer/components/MultiSectionJsonViewerHeader.tsx b/web/src/components/ui/AdvancedJsonViewer/components/MultiSectionJsonViewerHeader.tsxnew file mode 100644index 0000000000..63071afbe9--- /dev/null+++ b/web/src/components/ui/AdvancedJsonViewer/components/MultiSectionJsonViewerHeader.tsx@@ -0,0 +1,71 @@+import { ChevronRight, ChevronDown } from "lucide-react";+import type { SectionContext } from "../types";+import { type MediaReturnType } from "@/src/features/media/validation";+import { MediaButtonGroup } from "./MediaButtonGroup";++export interface MultiSectionJsonViewerHeaderProps {+ /** Display title for the section */+ title: string;+ /** Section context (expansion state, row count, toggle function) */+ context: SectionContext;+ /** Media attachments for this section (optional) */+ media?: MediaReturnType[];+}++/**+ * Default section header for MultiSectionJsonViewer+ *+ * Shows: [ChevronRight/ChevronDown] Title (N rows)+ *+ * This is the fallback header used when no custom renderHeader is provided+ */+export function MultiSectionJsonViewerHeader({+ title,+ context,+ media,+}: MultiSectionJsonViewerHeaderProps) {+ return (+ <div+ style={{+ display: "flex",+ alignItems: "center",+ padding: "6px 8px",+ cursor: "pointer",+ userSelect: "none",+ fontWeight: 500,+ }}+ onClick={() => context.setExpanded(!context.isExpanded)}+ >+ <span+ style={{+ marginRight: "8px",+ width: "16px",+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ opacity: 0.5,+ }}+ >+ {context.isExpanded ? (+ <ChevronDown size={14} />+ ) : (+ <ChevronRight size={14} />+ )}+ </span>+ <span className="text-xs font-medium">{title}</span>+ <span+ style={{+ marginLeft: "8px",+ color: "#6b7280",+ fontWeight: 400,+ fontSize: "0.65rem",+ }}+ >+ {context.rowCount.toLocaleString()} keys+ </span>+ <div style={{ marginLeft: "auto" }}>+ {media && media.length > 0 && <MediaButtonGroup media={media} />}+ </div>+ </div>+ );+}diff --git a/web/src/components/ui/AdvancedJsonViewer/components/SimpleSectionHeader.tsx b/web/src/components/ui/AdvancedJsonViewer/components/SimpleSectionHeader.tsxnew file mode 100644index 0000000000..2244abc162--- /dev/null+++ b/web/src/components/ui/AdvancedJsonViewer/components/SimpleSectionHeader.tsx@@ -0,0 +1,57 @@+import { ChevronRight, ChevronDown } from "lucide-react";+import { useSectionContext } from "../contexts/SectionContext";++export interface SimpleSectionHeaderProps {+ title: string;+ sectionKey: string;+}++/**+ * Simple collapsible section header+ *+ * Shows: [ChevronRight/ChevronDown] Title (N rows)+ *+ * Uses useSectionContext to access section state and toggle function+ */+export function SimpleSectionHeader({+ title,+ sectionKey,+}: SimpleSectionHeaderProps) {+ const context = useSectionContext(sectionKey);++ return (+ <div+ style={{+ display: "flex",+ alignItems: "center",+ padding: "6px 8px",+ cursor: "pointer",+ userSelect: "none",+ fontSize: "0.875rem",+ fontWeight: 500,+ }}+ onClick={() => context.setExpanded(!context.isExpanded)}+ >+ <span+ style={{+ marginRight: "8px",+ width: "16px",+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ opacity: 0.5,+ }}+ >+ {context.isExpanded ? (+ <ChevronDown size={14} />+ ) : (+ <ChevronRight size={14} />+ )}+ </span>+ <span>{title}</span>+ <span style={{ marginLeft: "8px", color: "#6b7280", fontWeight: 400 }}>+ {context.rowCount} rows+ </span>+ </div>+ );+}diff --git a/web/src/components/ui/AdvancedJsonViewer/contexts/SectionContext.tsx b/web/src/components/ui/AdvancedJsonViewer/contexts/SectionContext.tsxnew file mode 100644index 0000000000..dca48093c2--- /dev/null+++ b/web/src/components/ui/AdvancedJsonViewer/contexts/SectionContext.tsx@@ -0,0 +1,84 @@+import { createContext, useContext, useMemo } from "react";+import type { SectionContext } from "../types";+import type { TreeState } from "../utils/treeStructure";+import { getSectionContext, getSectionKeys } from "../utils/multiSectionTree";++/**+ * Map of section contexts by sectionKey+ */+interface SectionContextMap {+ [sectionKey: string]: SectionContext;+}++const SectionContextMapContext = createContext<SectionContextMap>({});++export interface SectionContextProviderProps {+ tree: TreeState;+ onToggle: (sectionKey: string) => void;+ children: React.ReactNode;+}++/**+ * Provides section context to header/footer components+ */+export function SectionContextProvider({+ tree,+ onToggle,+ children,+}: SectionContextProviderProps) {+ const contextMap = useMemo(() => {+ const map: SectionContextMap = {};+ const sectionKeys = getSectionKeys(tree);++ sectionKeys.forEach((sectionKey) => {+ const context = getSectionContext(tree, sectionKey);++ map[sectionKey] = {+ sectionKey,+ rowCount: context.rowCount,+ isExpanded: context.isExpanded,+ setExpanded: (expanded: boolean) => {+ if (expanded !== context.isExpanded) {+ onToggle(sectionKey);+ }+ },+ };+ });++ return map;+ }, [tree, onToggle]);++ return (+ <SectionContextMapContext.Provider value={contextMap}>+ {children}+ </SectionContextMapContext.Provider>+ );+}++/**+ * Hook for header/footer components to access section context+ *+ * Usage in header component:+ * const context = useSectionContext('input');+ * <div onClick={() => context.setExpanded(!context.isExpanded)}>+ * {context.isExpanded ? '▼' : '▶'} Input ({context.rowCount} rows)+ * </div>+ */+export function useSectionContext(sectionKey: string): SectionContext {+ const map = useContext(SectionContextMapContext);++ const context = map[sectionKey];++ if (!context) {+ // Default context if not found+ console.warn(`Section context not found for key: ${sectionKey}`);+ return {+ sectionKey,+ rowCount: 0,+ isExpanded: false,+ setExpanded: () => {},+ };+ }++ return context;+}diff --git a/web/src/components/ui/AdvancedJsonViewer/hooks/useJsonViewerLayout.ts b/web/src/components/ui/AdvancedJsonViewer/hooks/useJsonViewerLayout.tsindex f5ab8e7b0c..9b00cca1ce 100644--- a/web/src/components/ui/AdvancedJsonViewer/hooks/useJsonViewerLayout.ts+++ b/web/src/components/ui/AdvancedJsonViewer/hooks/useJsonViewerLayout.ts@@ -28,6 +28,7 @@ interface UseJsonViewerLayoutParams {totalLineCount?: number;stringWrapMode: StringWrapMode;truncateStringsAt: number | null;+ charWidth?: number; // Measured character width for accurate height estimation}export function useJsonViewerLayout({@@ -38,6 +39,7 @@ export function useJsonViewerLayout({totalLineCount,stringWrapMode,truncateStringsAt,+ charWidth,}: UseJsonViewerLayoutParams) {// Calculate visible row count from treeconst visibleRowCount = tree ? 1 + tree.rootNode.visibleDescendantCount : 0;@@ -134,6 +136,27 @@ export function useJsonViewerLayout({const threshold = truncateStringsAt ?? 100;if (str.length > threshold) {+ // Use measured character width for accurate line calculation+ if (charWidth && scrollableMaxWidth) {+ const indentWidth = node.depth * theme.indentSize;+ const keyWidth = String(row.key).length * charWidth;+ const colonWidth = 2 * charWidth; // ": "+ // For wrapped strings with white-space: pre-wrap, ALL lines (including continuations)+ // start at the same position - after the opening quote of the value+ const leftIndent = indentWidth + keyWidth + colonWidth + charWidth; // +charWidth for opening quote position+ const availableWidth = scrollableMaxWidth - leftIndent;++ if (availableWidth > 0) {+ const charsPerLine = Math.max(+ 40,+ Math.floor(availableWidth / charWidth),+ );+ const lines = Math.ceil(str.length / charsPerLine);+ return theme.lineHeight * Math.min(lines, 10);+ }+ }++ // Fallback to original estimate if charWidth not available or calc failsconst lines = Math.ceil(str.length / 80);return theme.lineHeight * Math.min(lines, 10);}@@ -141,7 +164,15 @@ export function useJsonViewerLayout({return theme.lineHeight;},- [tree, theme.lineHeight, stringWrapMode, truncateStringsAt],+ [+ tree,+ theme.lineHeight,+ theme.indentSize,+ stringWrapMode,+ truncateStringsAt,+ charWidth,+ scrollableMaxWidth,+ ],);return {diff --git a/web/src/components/ui/AdvancedJsonViewer/hooks/useMonospaceCharWidth.ts b/web/src/components/ui/AdvancedJsonViewer/hooks/useMonospaceCharWidth.tsnew file mode 100644index 0000000000..cd95f3d141--- /dev/null+++ b/web/src/components/ui/AdvancedJsonViewer/hooks/useMonospaceCharWidth.ts@@ -0,0 +1,103 @@+import { useState, useEffect } from "react";++const STORAGE_KEY = "monospace-char-width-0.7rem";+const DEFAULT_CHAR_WIDTH = 6.2; // Fallback for SSR or measurement failure++/**+ * Hook to measure and cache the actual rendered width of monospace characters+ *+ * Measures the width of '0' character in the current browser's monospace font+ * at 0.7rem font size. Caches result in sessionStorage to avoid re-measuring.+ *+ * This provides accurate width estimation regardless of which monospace font+ * the browser uses (Menlo, Consolas, Monaco, DejaVu Sans Mono, etc.)+ *+ * @param fontSize - Font size to measure (default: "0.7rem")+ * @returns Measured character width in pixels+ */+export function useMonospaceCharWidth(fontSize = "0.7rem"): number {+ const [charWidth, setCharWidth] = useState<number>(() => {+ // SSR guard+ if (typeof window === "undefined") {+ return DEFAULT_CHAR_WIDTH;+ }++ // Check sessionStorage first+ try {+ const stored = sessionStorage.getItem(STORAGE_KEY);+ if (stored) {+ const parsed = parseFloat(stored);+ if (!isNaN(parsed) && parsed > 0) {+ return parsed;+ }+ }+ } catch (error) {+ console.warn(+ "[useMonospaceCharWidth] Failed to read from sessionStorage:",+ error,+ );+ }++ return DEFAULT_CHAR_WIDTH;+ });++ useEffect(() => {+ // Skip if we already have a cached value+ if (charWidth !== DEFAULT_CHAR_WIDTH) {+ return;+ }++ // Skip on server+ if (typeof window === "undefined") {+ return;+ }++ // Measure actual character width+ try {+ // Create invisible measurement element+ const measureEl = document.createElement("span");+ measureEl.style.fontFamily = "monospace";+ measureEl.style.fontSize = fontSize;+ measureEl.style.visibility = "hidden";+ measureEl.style.position = "absolute";+ measureEl.style.whiteSpace = "nowrap";+ measureEl.textContent = "0";++ document.body.appendChild(measureEl);++ // Get actual rendered width+ const rect = measureEl.getBoundingClientRect();+ const measuredWidth = rect.width;++ // Clean up+ document.body.removeChild(measureEl);++ // Validate measurement+ if (!isNaN(measuredWidth) && measuredWidth > 0) {+ // Store in sessionStorage+ try {+ sessionStorage.setItem(STORAGE_KEY, measuredWidth.toString());+ } catch (error) {+ console.warn(+ "[useMonospaceCharWidth] Failed to write to sessionStorage:",+ error,+ );+ }++ // Update state+ setCharWidth(measuredWidth);+ } else {+ console.warn(+ "[useMonospaceCharWidth] Invalid measurement:",+ measuredWidth,+ "- using default",+ );+ }+ } catch (error) {+ console.error("[useMonospaceCharWidth] Measurement failed:", error);+ // Keep default value+ }+ }, [fontSize, charWidth]);++ return charWidth;+}diff --git a/web/src/components/ui/AdvancedJsonViewer/hooks/useMultiSectionTreeState.ts b/web/src/components/ui/AdvancedJsonViewer/hooks/useMultiSectionTreeState.tsnew file mode 100644index 0000000000..b63d421588--- /dev/null+++ b/web/src/components/ui/AdvancedJsonViewer/hooks/useMultiSectionTreeState.ts@@ -0,0 +1,117 @@+import { useState, useMemo, useCallback, useEffect } from "react";+import {+ buildMultiSectionTree,+ updateSpacerHeights,+ type SectionConfig,+} from "../utils/multiSectionTree";+import { toggleNodeExpansion } from "../utils/treeExpansion";+import { searchInTree } from "../utils/searchJson";+import { useMonospaceCharWidth } from "./useMonospaceCharWidth";++export interface UseMultiSectionTreeStateProps {+ /** Data configurations (no presentation logic) */+ sectionConfigs: SectionConfig[];+ searchQuery?: string;+ /** Indent size in pixels (default: 12) */+ indentSizePx?: number;+}++/**+ * Hook for managing multi-section tree state+ *+ * Manages pure data structure (TreeState) separated from presentation.+ * The tree contains no React elements - only structural/semantic data.+ *+ * Features:+ * - Builds tree on mount (memoized)+ * - Tracks expansion version for re-renders+ * - Handles node toggle (JSON nodes)+ * - Handles section toggle (section headers)+ * - Auto-expands sections with search matches+ */+export function useMultiSectionTreeState({+ sectionConfigs,+ searchQuery,+ indentSizePx = 12,+}: UseMultiSectionTreeStateProps) {+ // Measure actual monospace character width for accurate width estimation+ const charWidth = useMonospaceCharWidth();++ // Build tree from data configs (memoized, pure data structure)+ const initialTree = useMemo(() => {+ const tree = buildMultiSectionTree(sectionConfigs, {+ widthConfig: {+ charWidthPx: charWidth,+ indentSizePx,+ extraBufferPx: 50,+ },+ });++ return tree;+ }, [sectionConfigs, charWidth, indentSizePx]);++ // Track expansion version (triggers re-render after toggle)+ // Tree is mutated in place (JIT approach), so we need version for React+ const [expansionVersion, setExpansionVersion] = useState(0);++ // Tree reference (mutated in place)+ const tree = initialTree;++ // Toggle expansion of any node (JSON nodes within sections)+ const handleToggleExpansion = useCallback(+ (nodeId: string) => {+ toggleNodeExpansion(tree, nodeId);+ updateSpacerHeights(tree, 14); // Update spacer heights after toggle+ setExpansionVersion((v) => v + 1);+ },+ [tree],+ );++ // Toggle section expansion (section headers)+ const handleToggleSectionExpansion = useCallback(+ (sectionKey: string) => {+ const headerNodeId = `${sectionKey}__header`;+ toggleNodeExpansion(tree, headerNodeId);+ updateSpacerHeights(tree, 14); // Update spacer heights after toggle+ setExpansionVersion((v) => v + 1);+ },+ [tree],+ );++ // Auto-expand sections with search matches+ useEffect(() => {+ if (!searchQuery || searchQuery.trim() === "") return;++ const matches = searchInTree(tree, searchQuery);+ const sectionsWithMatches = new Set<string>();++ matches.forEach((match) => {+ const node = tree.nodeMap.get(match.rowId);+ if (node?.sectionKey) {+ sectionsWithMatches.add(node.sectionKey);+ }+ });++ // Expand sections that have matches but are collapsed+ let needsUpdate = false;+ sectionsWithMatches.forEach((sectionKey) => {+ const headerNode = tree.nodeMap.get(`${sectionKey}__header`);+ if (headerNode && !headerNode.isExpanded) {+ toggleNodeExpansion(tree, headerNode.id);+ needsUpdate = true;+ }+ });++ if (needsUpdate) {+ updateSpacerHeights(tree, 14); // Update spacer heights after auto-expand+ setExpansionVersion((v) => v + 1);+ }+ }, [tree, searchQuery]);++ return {+ tree,+ expansionVersion,+ handleToggleExpansion,+ handleToggleSectionExpansion,+ };+}diff --git a/web/src/components/ui/AdvancedJsonViewer/hooks/useTreeState.ts b/web/src/components/ui/AdvancedJsonViewer/hooks/useTreeState.tsindex c8aae93690..74cafcca29 100644--- a/web/src/components/ui/AdvancedJsonViewer/hooks/useTreeState.ts+++ b/web/src/components/ui/AdvancedJsonViewer/hooks/useTreeState.ts@@ -30,6 +30,7 @@ import {writeExpansionToStorage,} from "@/src/components/trace2/contexts/JsonExpansionContext";import { useDebounce } from "@/src/hooks/useDebounce";+import { useMonospaceCharWidth } from "./useMonospaceCharWidth";/*** Configuration for tree building@@ -138,6 +139,9 @@ export function useTreeState(): UseTreeStateReturn {const { rootKey = "root", expandDepth, indentSizePx = 16 } = config;+ // Measure actual monospace character width for accurate width estimation+ const charWidth = useMonospaceCharWidth();+// Estimate data size onceconst dataSize = useMemo(() => estimateNodeCount(data), [data]);@@ -167,7 +171,7 @@ export function useTreeState(initialExpansion: expansionFromStorage,expandDepth,widthEstimator: {- charWidthPx: 6.2,+ charWidthPx: charWidth,indentSizePx,extraBufferPx: 50,},@@ -186,6 +190,7 @@ export function useTreeState(expandDepth,expansionFromStorage,indentSizePx,+ charWidth,]);// For large datasets, use React Query + Web Worker@@ -197,6 +202,7 @@ export function useTreeState(expandDepth,expansionFromStorage,indentSizePx,+ charWidth,],queryFn: () =>buildTreeInWorker(@@ -206,7 +212,7 @@ export function useTreeState(initialExpansion: expansionFromStorage,expandDepth,widthEstimator: {- charWidthPx: 6.2,+ charWidthPx: charWidth,indentSizePx,extraBufferPx: 50,},diff --git a/web/src/components/ui/AdvancedJsonViewer/types.ts b/web/src/components/ui/AdvancedJsonViewer/types.tsindex 9ac3c43bb6..740ac0152a 100644--- a/web/src/components/ui/AdvancedJsonViewer/types.ts+++ b/web/src/components/ui/AdvancedJsonViewer/types.ts@@ -403,3 +403,61 @@ export interface RowHeightEstimate {/** Whether height is dynamic (might change on render) */isDynamic: boolean;}++// ============================================================================+// Multi-Section Support+// ============================================================================++/**+ * Node type discriminator for multi-section trees+ */+export type TreeNodeType =+ | "meta"+ | "section-header"+ | "section-footer"+ | "section-spacer"+ | "json";++/**+ * Section definition for MultiSectionJsonViewer+ */+export interface JsonSection {+ /** Unique identifier (for expansion state) */+ key: string;++ /** JSON data to display */+ data: unknown;++ /** Display title (shown in header). If not provided, derived from key */+ title?: string;++ /** Optional header render function (receives section context) */+ renderHeader?: (context: SectionContext) => React.ReactNode;++ /** Optional footer render function (receives section context) */+ renderFooter?: (context: SectionContext) => React.ReactNode;++ /** Section background color */+ backgroundColor?: string;++ /** Minimum height for section content (CSS value, e.g., "200px", "50vh") */+ minHeight?: string;+}++/**+ * Context passed to header/footer components+ * Access via useSectionContext(sectionKey)+ */+export interface SectionContext {+ /** Section identifier */+ sectionKey: string;++ /** Number of visible JSON rows in this section */+ rowCount: number;++ /** Is section expanded? */+ isExpanded: boolean;++ /** Toggle section expansion */+ setExpanded: (expanded: boolean) => void;+}diff --git a/web/src/components/ui/AdvancedJsonViewer/utils/multiSectionTree.ts b/web/src/components/ui/AdvancedJsonViewer/utils/multiSectionTree.tsnew file mode 100644index 0000000000..00094198c4--- /dev/null+++ b/web/src/components/ui/AdvancedJsonViewer/utils/multiSectionTree.ts@@ -0,0 +1,321 @@+/**+ * Multi-Section Tree Building Utilities+ *+ * Builds a tree with multiple JSON roots, each with optional header/footer.+ * Maintains JIT O(log n) performance by treating sections as TreeNodes.+ *+ * Tree Structure:+ * __meta_root__ (depth: -1, never rendered, always expanded)+ * ├─ section1_header (depth: 0, nodeType: 'section-header')+ * │ └─ section1_json_root (depth: 1, nodeType: 'json')+ * ├─ section2_header (depth: 0, nodeType: 'section-header')+ * │ ├─ section2_json_root (depth: 1, nodeType: 'json')+ * │ └─ section2_footer (depth: 0, nodeType: 'section-footer')+ * └─ ...+ */++import type { TreeNode, TreeState } from "./treeStructure";+import { buildTreeFromJSON } from "./treeStructure";+import { type WidthEstimatorConfig } from "./calculateWidth";++/**+ * Section configuration for tree building (data only, no presentation)+ */+export interface SectionConfig {+ /** Unique identifier (for expansion state) */+ key: string;+ /** JSON data to display */+ data: unknown;+ /** Section background color */+ backgroundColor?: string;+ /** Minimum height for section content (CSS value) */+ minHeight?: string;+}++/**+ * Get expansion state from sessionStorage+ */+function getStoredExpansion(key: string): boolean | undefined {+ if (typeof window === "undefined") return undefined;++ try {+ const stored = sessionStorage.getItem(`json-expansion:${key}`);+ if (stored === null) return undefined;+ return JSON.parse(stored) as boolean;+ } catch {+ return undefined;+ }+}++/**+ * Recompute childOffsets and visibleDescendantCount for a node+ */+function recomputeNodeOffsets(node: TreeNode): void {+ if (!node.isExpanded || node.children.length === 0) {+ node.childOffsets = [];+ node.visibleDescendantCount = 0;+ return;+ }++ const offsets: number[] = [];+ let cumulative = 0;++ node.children.forEach((child) => {+ cumulative += 1 + child.visibleDescendantCount;+ offsets.push(cumulative);+ });++ node.childOffsets = offsets;+ node.visibleDescendantCount = cumulative;+}++/**+ * Build multi-section tree with synthetic meta-root+ *+ * Each section becomes:+ * - section-header node (collapsible)+ * - JSON tree (children of header)+ * - section-footer node (optional, but not created here - headers/footers are rendered separately)+ *+ * @param sections - Array of section data configurations (no presentation logic)+ * @param config - Optional configuration+ * @returns TreeState with meta-root (pure data structure)+ */+export function buildMultiSectionTree(+ sections: SectionConfig[],+ config?: {+ initialExpansion?: boolean;+ widthConfig?: WidthEstimatorConfig;+ },+): TreeState {+ // 1. Create synthetic meta-root (never rendered)+ const metaRoot: TreeNode = {+ id: "__meta_root__",+ key: "__meta_root__",+ pathArray: ["__meta_root__"],+ value: null,+ type: "object",+ depth: -1, // Negative depth = not rendered+ parentNode: null,+ children: [],+ childCount: 0,+ isExpandable: false, // Can't collapse meta-root+ isExpanded: true, // Always expanded+ userExpand: undefined,+ childOffsets: [],+ visibleDescendantCount: 0,+ absoluteLineNumber: 0,+ indexInParent: 0,+ isLastChild: false,+ nodeType: "meta",+ };++ const allNodes: TreeNode[] = [metaRoot];+ const nodeMap = new Map<string, TreeNode>();+ nodeMap.set(metaRoot.id, metaRoot);++ let absoluteLineNumber = 1;+ let maxDepth = 0;+ let maxContentWidth = 0;++ // 2. Build each section+ sections.forEach((section) => {+ // 2a. Create section header node+ const headerNode: TreeNode = {+ id: `${section.key}__header`,+ key: `${section.key}__header`,+ pathArray: ["__meta_root__", `${section.key}__header`],+ value: null,+ type: "object",+ depth: 0,+ parentNode: metaRoot,+ children: [],+ childCount: 0,+ isExpandable: true, // Sections can collapse+ isExpanded: getStoredExpansion(`${section.key}__header`) ?? true,+ userExpand: undefined,+ childOffsets: [],+ visibleDescendantCount: 0,+ absoluteLineNumber: absoluteLineNumber++,+ indexInParent: metaRoot.children.length,+ isLastChild: false, // Will update later+ nodeType: "section-header",+ sectionKey: section.key,+ backgroundColor: section.backgroundColor,+ minHeight: section.minHeight,+ sectionLineNumber: undefined, // Headers don't have line numbers+ };++ allNodes.push(headerNode);+ nodeMap.set(headerNode.id, headerNode);+ metaRoot.children.push(headerNode);++ // 2b. Build JSON tree for this section+ const jsonTree = buildTreeFromJSON(section.data, {+ rootKey: section.key,+ initialExpansion: getStoredExpansion(section.key) ?? true,+ widthEstimator: config?.widthConfig,+ });++ // Track max content width from this section+ maxContentWidth = Math.max(maxContentWidth, jsonTree.maxContentWidth);++ // 2c. Re-parent JSON tree under header node and update properties+ let sectionLineNumber = 1;+ const stack: { node: TreeNode; newDepth: number }[] = [+ { node: jsonTree.rootNode, newDepth: 0 },+ ];++ while (stack.length > 0) {+ const { node, newDepth } = stack.pop()!;++ // Update node properties for multi-section+ node.depth = newDepth;+ node.sectionKey = section.key;+ node.backgroundColor = section.backgroundColor;+ node.minHeight = section.minHeight;+ node.nodeType = "json";++ // Set section line number (stable, assigned once during tree building)+ node.sectionLineNumber = sectionLineNumber++;++ // Update absolute line number+ node.absoluteLineNumber = absoluteLineNumber++;++ // Track max depth+ maxDepth = Math.max(maxDepth, node.depth);++ // Add to collections+ allNodes.push(node);+ nodeMap.set(node.id, node);++ // Process children in reverse order (for correct stack ordering)+ for (let i = node.children.length - 1; i >= 0; i--) {+ stack.push({ node: node.children[i]!, newDepth: newDepth + 1 });+ }+ }++ // Link JSON root to header+ jsonTree.rootNode.parentNode = headerNode;+ jsonTree.rootNode.indexInParent = 0;+ headerNode.children.push(jsonTree.rootNode);+ headerNode.childCount = 1;++ // Set total descendant count (for row count display, independent of expansion)+ headerNode.totalDescendantCount = jsonTree.totalNodeCount;++ // 2c. Create spacer node if minHeight is set and content is shorter+ if (section.minHeight) {+ const minHeightPx = parseFloat(section.minHeight);+ const contentHeight = headerNode.visibleDescendantCount * 14; // lineHeight constant+ const spacerHeight = Math.max(0, minHeightPx - contentHeight);++ if (spacerHeight > 0) {+ const spacerNode: TreeNode = {+ id: `${section.key}__spacer`,+ key: `${section.key}__spacer`,+ pathArray: ["__meta_root__", `${section.key}__spacer`],+ value: null,+ type: "object",+ depth: 0,+ parentNode: headerNode,+ children: [],+ childCount: 0,+ isExpandable: false,+ isExpanded: true,+ userExpand: undefined,+ childOffsets: [],+ visibleDescendantCount: 0,+ absoluteLineNumber: absoluteLineNumber++,+ indexInParent: headerNode.children.length,+ isLastChild: false,+ nodeType: "section-spacer",+ sectionKey: section.key,+ backgroundColor: section.backgroundColor,+ spacerHeight: spacerHeight,+ };++ allNodes.push(spacerNode);+ nodeMap.set(spacerNode.id, spacerNode);+ headerNode.children.push(spacerNode);+ headerNode.childCount += 1;+ }+ }++ // Recompute header offsets after adding JSON tree and spacer+ recomputeNodeOffsets(headerNode);+ });++ // 3. Update isLastChild flags+ metaRoot.children.forEach((child, index) => {+ child.isLastChild = index === metaRoot.children.length - 1;+ });++ // 4. Compute meta-root offsets+ metaRoot.childCount = metaRoot.children.length;+ recomputeNodeOffsets(metaRoot);++ return {+ rootNode: metaRoot,+ nodeMap,+ allNodes,+ totalNodeCount: allNodes.length,+ maxDepth,+ maxContentWidth,+ };+}++/**+ * Get section context data for a section key+ */+export function getSectionContext(+ tree: TreeState,+ sectionKey: string,+): { rowCount: number; isExpanded: boolean } {+ const headerNode = tree.nodeMap.get(`${sectionKey}__header`);++ if (!headerNode) {+ return { rowCount: 0, isExpanded: false };+ }++ // rowCount = number of visible JSON rows in section+ // = visibleDescendantCount of header node (excludes header itself)+ return {+ rowCount: headerNode.visibleDescendantCount,+ isExpanded: headerNode.isExpanded,+ };+}++/**+ * Get all section keys from tree+ */+export function getSectionKeys(tree: TreeState): string[] {+ return tree.rootNode.children+ .filter((child) => child.nodeType === "section-header")+ .map((child) => child.sectionKey!)+ .filter(Boolean);+}++/**+ * Update spacer heights after expansion changes+ * Call this after toggleNodeExpansion to recalculate spacer sizes+ */+export function updateSpacerHeights(tree: TreeState, lineHeight: number): void {+ tree.rootNode.children.forEach((headerNode) => {+ if (headerNode.nodeType !== "section-header" || !headerNode.minHeight) {+ return;+ }++ // Find spacer node (if it exists)+ const spacerNode = headerNode.children.find(+ (n) => n.nodeType === "section-spacer",+ );++ if (!spacerNode) return;++ // Recalculate spacer height based on current content+ const minHeightPx = parseFloat(headerNode.minHeight);+ const contentHeight = headerNode.visibleDescendantCount * lineHeight;+ spacerNode.spacerHeight = Math.max(0, minHeightPx - contentHeight);+ });+}diff --git a/web/src/components/ui/AdvancedJsonViewer/utils/rowCount.ts b/web/src/components/ui/AdvancedJsonViewer/utils/rowCount.tsnew file mode 100644index 0000000000..cd2a4a1373--- /dev/null+++ b/web/src/components/ui/AdvancedJsonViewer/utils/rowCount.ts@@ -0,0 +1,74 @@+/**+ * Row Counting Utility for JSON Data+ *+ * Lightweight utility to count how many rows would be displayed when JSON is fully expanded.+ * Does not build the full tree structure - just counts nodes recursively.+ *+ * Used to determine if virtualization threshold is met without expensive tree building.+ */++/**+ * Count total rows that would be displayed when JSON is fully expanded+ *+ * @param data - Any JSON-serializable value+ * @returns Number of rows (nodes) in the JSON structure+ *+ * @example+ * countJsonRows(null) // 0+ * countJsonRows("hello") // 1+ * countJsonRows({ a: 1, b: 2 }) // 3 (object + 2 properties)+ * countJsonRows([1, 2, 3]) // 4 (array + 3 elements)+ * countJsonRows({ a: { b: { c: 1 } } }) // 4 (3 objects + 1 number)+ */+export function countJsonRows(data: unknown): number {+ // null/undefined → no rows+ if (data === null || data === undefined) {+ return 0;+ }++ // Primitives (string, number, boolean) → 1 row+ const type = typeof data;+ if (type === "string" || type === "number" || type === "boolean") {+ return 1;+ }++ // Arrays+ if (Array.isArray(data)) {+ // 1 for array itself + sum of all elements+ let count = 1;+ for (const element of data) {+ count += countJsonRows(element);+ }+ return count;+ }++ // Objects+ if (type === "object" && data !== null) {+ // 1 for object itself + sum of all properties+ let count = 1;+ const obj = data as Record<string, unknown>;+ for (const key in obj) {+ if (Object.prototype.hasOwnProperty.call(obj, key)) {+ count += countJsonRows(obj[key]);+ }+ }+ return count;+ }++ // Fallback for other types (functions, symbols, etc.) → 1 row+ return 1;+}++/**+ * Check if JSON data exceeds a row count threshold+ *+ * @param data - Any JSON-serializable value+ * @param threshold - Maximum allowed row count+ * @returns true if row count exceeds threshold+ *+ * @example+ * exceedsRowThreshold(largeObject, 2500) // true if >2500 rows+ */+export function exceedsRowThreshold(data: unknown, threshold: number): boolean {+ return countJsonRows(data) > threshold;+}diff --git a/web/src/components/ui/AdvancedJsonViewer/utils/treeNavigation.ts b/web/src/components/ui/AdvancedJsonViewer/utils/treeNavigation.tsindex 90df4e17f2..d76f935a55 100644--- a/web/src/components/ui/AdvancedJsonViewer/utils/treeNavigation.ts+++ b/web/src/components/ui/AdvancedJsonViewer/utils/treeNavigation.ts@@ -183,6 +183,52 @@ export function findNodeIndex(rootNode: TreeNode, targetId: string): number {return -1; // Not found}+/**+ * Find index of section header node by sectionKey+ *+ * Searches for a node with nodeType === "section-header" and matching sectionKey.+ * Used for scroll-to-section functionality in multi-section viewers.+ *+ * @param rootNode - Root of the tree (typically meta-root)+ * @param sectionKey - Section key to find (e.g., "input", "output")+ * @returns 0-based index in visible rows, or -1 if not found/not visible+ */+export function findSectionHeaderIndex(+ rootNode: TreeNode,+ sectionKey: string,+): number {+ // Iterative pre-order traversal+ const stack: Array<{ node: TreeNode; index: number }> = [+ { node: rootNode, index: 0 },+ ];++ while (stack.length > 0) {+ const current = stack.pop()!;+ const { node, index } = current;++ // Check if this is a section header with matching key+ if (node.nodeType === "section-header" && node.sectionKey === sectionKey) {+ return index;+ }++ // If expanded, traverse children+ if (node.isExpanded && node.children.length > 0) {+ // Push children in REVERSE order (LIFO stack)+ for (let i = node.children.length - 1; i >= 0; i--) {+ const child = node.children[i]!;+ const previousChildOffset = i > 0 ? node.childOffsets[i - 1]! : 0;++ stack.push({+ node: child,+ index: index + (i === 0 ? 1 : previousChildOffset + 1),+ });+ }+ }+ }++ return -1; // Not found+}+/*** Get all visible nodes in tree (for debugging/testing)*diff --git a/web/src/components/ui/AdvancedJsonViewer/utils/treeStructure.ts b/web/src/components/ui/AdvancedJsonViewer/utils/treeStructure.tsindex 07ea778771..4b953652dc 100644--- a/web/src/components/ui/AdvancedJsonViewer/utils/treeStructure.ts+++ b/web/src/components/ui/AdvancedJsonViewer/utils/treeStructure.ts@@ -60,11 +60,25 @@ export interface TreeNode {// NavigationchildOffsets: number[]; // Cumulative visible descendant counts for binary searchvisibleDescendantCount: number; // Total visible descendants when expanded (0 if collapsed)+ totalDescendantCount?: number; // Total descendants regardless of expansion (for section row counts)// PositionabsoluteLineNumber: number; // 1-indexed line number in fully expanded treeindexInParent: number; // Index within parent's children arrayisLastChild: boolean; // Is this the last child of parent?++ // Multi-section support (optional, only for multi-root trees)+ nodeType?:+ | "meta"+ | "section-header"+ | "section-footer"+ | "section-spacer"+ | "json"; // Type discriminator+ sectionKey?: string; // Which section this belongs to+ backgroundColor?: string; // Section background color+ sectionLineNumber?: number; // Line number within section (resets per section)+ minHeight?: string; // Minimum height for section content (CSS value)+ spacerHeight?: number; // For section-spacer nodes: height in pixels}/**diff --git a/web/src/hooks/useParsedObservation.ts b/web/src/hooks/useParsedObservation.tsindex ad77b44078..cee8ea8f83 100644--- a/web/src/hooks/useParsedObservation.ts+++ b/web/src/hooks/useParsedObservation.ts@@ -197,6 +197,10 @@ export function useParsedObservation({!observationQuery.isLoading &&!parseQuery.isLoading &&parseQuery.data !== undefined,+ // True when we have raw data but parsing hasn't completed yet+ isWaitingForParsing:+ !!observationQuery.data &&+ (parseQuery.isLoading || parseQuery.data === undefined),// Debug infoparseTime: parseQuery.data?.parseTime,