Skip to content

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

feat(json-viewer): async virtualized lazy JSON renderer (LFE-11080) (#15265)

Nikita Kabardina4bee59b63f9
diff --git a/web/src/components/ui/AdvancedJsonViewer/LAZY_TREE_DESIGN.md b/web/src/components/ui/AdvancedJsonViewer/LAZY_TREE_DESIGN.md
new file mode 100644
index 0000000000..263502cecd
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/LAZY_TREE_DESIGN.md
@@ -0,0 +1,82 @@
+# Lazy JSON viewer β€” design (LFE-11080/82, under LFE-10847/LFE-10152)
+
+## Problem
+
+The JSON Beta viewer virtualizes the DOM (only visible rows paint) but builds the
+**entire** node tree up front, on the main thread, before any paint. A ~20 MB
+structured payload is ~1M nodes β†’ the build freezes the tab; `JSON.parse` itself
+blows heap 5–8.5Γ— and hard-walls at the ~512 MB JS-string cap. Interim stopgap: a
+node-count gate (LFE-10847, PR #15230). This is the real fix: **never build,
+parse, or hold more than what is expanded/visible.**
+
+## Architecture (validated by the LFE-11079 spike + Fable review)
+
+Bytes in, lazy index, materialize on demand β€” **one engine, one model, one
+renderer**:
+
+```
+raw UTF-8 bytes ──▢ ByteJsonIndexEngine ──▢ AsyncJsonSource ──▢ TreeRowModel ──▢ (renderer)
+ (streamed or byteJsonIndex.ts asyncJsonSource.ts treeRowModel.ts
+ stringified) cached offset index nodeId-keyed async flatten/expand/paginate
+```
+
+- **`byteJsonIndex.ts`** β€” our own UTF-8 byte indexer (never a JS string of the
+ whole doc, never a whole-doc `JSON.parse`). Scans a container **once** and
+ caches a columnar child-offset table, so pages after the first are O(page)
+ (measured ~5000Γ— faster than re-walking). Values materialized by slicing +
+ `TextDecoder`; precision preserved (bigint / raw string) for leaves; a
+ `ByteScanner` seam lets a WASM hot-loop drop in later.
+- **`asyncJsonSource.ts`** β€” the async, nodeId-keyed child-source seam
+ (`root` / `childrenPage` / `getValue`). `createInProcessSource(bytes)` wraps the
+ engine on the main thread; a Worker source implements the same interface for the
+ ~1 GB streamed path. **`sourceFromValue(value)`** is the in-memory entry:
+ `JSON.stringify β†’ UTF-8 β†’ engine` β€” so in-memory data uses the SAME engine, not
+ a second tree (per the spike's "unify on the byte engine" decision).
+- **`treeRowModel.ts`** β€” the ONE flatten/expand/paginate implementation over a
+ source. Only expanded levels are fetched; wide containers page with a "load
+ more" row; the flattened visible list rebuilds iteratively (deep-tree safe) on
+ structural change. Hardened per the review: a **revision** counter stamped onto
+ every `getRows` window (stale-read detection for async/worker responses), a
+ **`getValue` error envelope** (never throws), and truncation/byteLength
+ passthrough.
+- **`rowModel.ts`** β€” the renderer-facing contract the renderer is built against
+ exactly once.
+- **`react/`** β€” the async virtualized renderer over the seam (see
+ `react/README.md`). A per-mount vanilla Zustand store (`rowModelStore.ts`) owns
+ the model lifecycle and all async actions; `LazyJsonList` only positions row
+ shells and reports the visible range back; `LazyJsonRow` is view-only.
+ `LazyJsonViewer` is the in-memory entry (gate-render on the model, one
+ integration-boundary effect). The identical renderer will run over the Worker
+ source unchanged.
+
+## Key design constraint (from prod experience)
+
+The prior viewers taught us that **the Worker itself is a cost**: always parsing
+in a Worker made *fast trace-flipping on small JSON* noticeably slower. So "use
+the byte engine" and "use a Worker" are **independent** decisions. Because
+`load()` is O(1) and each container is scanned once only on expand, the
+**main-thread** byte-engine path has near-zero upfront cost and handles the common
+large case (a base64 image = one giant string leaf, never materialized) with **no
+Worker**. The Worker is reserved for genuinely-huge *structured* payloads (rare),
+chosen at the `buildModel` seam by a size threshold. Virtualization also breaks
+browser Ctrl+F, so the viewer owns an in-viewer find.
+
+## Status / next (phased)
+
+- **P0 β€” interim gate (LFE-10847, #15230): MERGED.** Stops the crash today.
+- **P1 β€” byte engine + async seam + renderer: done** (#15265). Covered by store
+ client tests + verified in the integrated trace view. Materialization +
+ wide-container pagination (LFE-11082) are built inside the engine; the
+ streaming backend (LFE-11081, #15239) is merged.
+- **P2 β€” integrate into IOPreview, MAIN-THREAD, no Worker (LFE-11084): NEXT.**
+ Replace the eager JSON Beta path with the lazy renderer; add in-viewer find
+ (Ctrl+F replacement, LFE-11083 main-thread slice); retire the gate for this
+ path; Sentry-instrument genuine failures + a rate-limited "default miscalibrated"
+ signal; size thresholds calibrated to an M1 MacBook Air 2020.
+- **P3 β€” Worker source + GB tail:** wire a Worker `AsyncJsonSource` (byte engine
+ off-thread) consuming #15239, behind the size threshold. Renderer unchanged.
+ Byte-engine stream blockers first (non-JSON/raw root, empty-doc, strict
+ truncation β€” stream-only; in-memory bytes from `JSON.stringify` are always valid
+ JSON). Seam needs dispose/cancel + a progress signal for this.
+- **P4 β€” chDB source:** when ClickHouse returns parsed JSON on demand (Valeriy),
+ swap the source behind `AsyncJsonSource`; renderer + RowModel unchanged.
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/asyncJsonSource.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/asyncJsonSource.ts
new file mode 100644
index 0000000000..ad7b95e732
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/asyncJsonSource.ts
@@ -0,0 +1,84 @@
+/**
+ * AsyncJsonSource β€” the child-source seam under the RowModel (LFE-11080/82).
+ *
+ * A source answers three async, nodeId-keyed questions: what's the root, page
+ * this container's immediate children, materialize this node's value. This is
+ * exactly the byte-indexer's surface, made async so ONE model
+ * (`TreeRowModel`) works over either:
+ * - `createInProcessSource(bytes)` β€” the byte engine on the main thread
+ * (resolves immediately). The in-memory case routes through here too, via
+ * `sourceFromValue` (stringify β†’ UTF-8 bytes β†’ engine), so there is a single
+ * tree/preview/precision implementation, not two.
+ * - a Worker source (future, LFE-11081/82) β€” the engine behind postMessage,
+ * for the ~1 GB streamed path. Same interface, genuinely async.
+ */
+
+import {
+ ByteJsonIndexEngine,
+ type ChildrenPage,
+ type GetValueResult,
+ type NodeDescriptor,
+} from "./byteJsonIndex";
+
+export interface AsyncJsonSource {
+ /** Root descriptor (available once the source is constructed). */
+ readonly root: NodeDescriptor;
+ /** Immediate children of `nodeId` in the window `[offset, offset+limit)`. */
+ childrenPage(
+ nodeId: number,
+ offset: number,
+ limit: number,
+ ): Promise<ChildrenPage>;
+ /** Materialize a single node's full value (bounded by the engine's cap). */
+ getValue(nodeId: number, maxBytes?: number): Promise<GetValueResult>;
+ /** Re-describe a node (e.g. a container after its child count is known). */
+ describe(nodeId: number): NodeDescriptor;
+}
+
+/**
+ * Wrap the synchronous byte engine as an AsyncJsonSource. Suitable for the main
+ * thread; every call resolves immediately. The same class is what a Worker host
+ * would drive, exposing the identical interface across `postMessage`.
+ */
+export function createInProcessSource(bytes: Uint8Array): AsyncJsonSource {
+ const engine = new ByteJsonIndexEngine();
+ const root = engine.load(bytes);
+ return {
+ root,
+ childrenPage(nodeId, offset, limit) {
+ return Promise.resolve(engine.childrenPage(nodeId, offset, limit));
+ },
+ getValue(nodeId, maxBytes) {
+ return Promise.resolve(engine.getValue(nodeId, maxBytes));
+ },
+ describe(nodeId) {
+ return engine.describeNode(nodeId);
+ },
+ };
+}
+
+const encoder = new TextEncoder();
+
+/**
+ * In-memory entry point: an AsyncJsonSource over an already-parsed JS value.
+ * Per the spike's "unify on the byte engine" decision, we do NOT keep a second
+ * in-memory tree engine β€” we serialize the value to UTF-8 bytes and feed the
+ * same byte indexer. In-memory payloads are bounded (v3/parsed IO is well under
+ * the streamed-GB regime), so `JSON.stringify` here is cheap, and any numeric
+ * precision was already resolved upstream when the value was parsed.
+ */
+export function sourceFromValue(value: unknown): AsyncJsonSource {
+ // `JSON.stringify(undefined)` is `undefined`; normalize to a valid document.
+ const json = value === undefined ? "null" : (JSON.stringify(value) ?? "null");
+ return createInProcessSource(encoder.encode(json));
+}
+
+/**
+ * In-memory entry when the caller ALREADY has the value's JSON serialization
+ * (e.g. a size probe serialized it for a download). Skips a redundant second
+ * `JSON.stringify` of a large value β€” feed the existing string straight to the
+ * engine. The string must be valid JSON (it is, for a structured field).
+ */
+export function sourceFromSerialized(json: string): AsyncJsonSource {
+ return createInProcessSource(encoder.encode(json.length > 0 ? json : "null"));
+}
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/benchByteJsonIndex.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/benchByteJsonIndex.ts
new file mode 100644
index 0000000000..3ab16dedcc
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/benchByteJsonIndex.ts
@@ -0,0 +1,430 @@
+/**
+ * Node bench for the lazy UTF-8 JSON byte indexer (LFE-11082).
+ *
+ * Run with a recent Node (>= 22.6, native TS type-stripping). `web` is a
+ * CommonJS package, so Node prints a one-line "reparsing as ES module" notice
+ * and runs it as ESM β€” harmless for a dev script:
+ *
+ * SCRATCH=/tmp/lfe-11082 node \
+ * web/src/components/ui/AdvancedJsonViewer/lazy/benchByteJsonIndex.ts
+ *
+ * (It is a .ts, not .mts, only because this repo's concurrent ESLint crashes
+ * on function-type annotations in .mts files; the engine itself is unaffected.)
+ *
+ * It generates two payloads in SCRATCH (a ~200MB structured array and a ~2M
+ * element wide array), then proves the core property: the FIRST childrenPage
+ * on a container pays a one-time O(container) scan, but the 2nd and 3rd pages
+ * are O(page) because the child-offset table is cached β€” unlike big-json-viewer
+ * which re-walks the container (~470ms) on every page. It also reports peak RSS
+ * vs a JSON.parse baseline.
+ *
+ * Each scenario runs in its own child process so peak RSS is measured cleanly
+ * (no cross-contamination between the indexer and the JSON.parse baseline).
+ */
+
+import { spawnSync } from "node:child_process";
+import {
+ closeSync,
+ openSync,
+ readFileSync,
+ statSync,
+ writeSync,
+} from "node:fs";
+import { existsSync, mkdirSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+// Type-only import (erased at runtime); the value import is the computed
+// dynamic import() below so Node can type-strip the .ts target at load time.
+import type { ByteJsonIndexEngine } from "./byteJsonIndex";
+
+type Mod = { ByteJsonIndexEngine: typeof ByteJsonIndexEngine };
+
+const SCRATCH = process.env.SCRATCH ?? join(tmpdir(), "lfe-11082-bench");
+
+const STRUCTURED_TARGET_BYTES = Number(
+ process.env.STRUCTURED_BYTES ?? 200 * 1024 * 1024,
+);
+const WIDE_COUNT = Number(process.env.WIDE_COUNT ?? 2_000_000);
+const BLOB_BYTES = 4 * 1024 * 1024; // large-value target inside record 0
+
+const structuredPath = join(SCRATCH, "structured-200mb.json");
+const widePath = join(SCRATCH, "wide-2m.json");
+
+const MB = 1024 * 1024;
+const fmtMB = (n: number) => `${(n / MB).toFixed(1)}MB`;
+const fmtMs = (n: number) => `${n.toFixed(3)}ms`;
+
+async function loadModule(): Promise<Mod> {
+ const url = new URL("./byteJsonIndex.ts", import.meta.url).href;
+ // Computed specifier => TS types this as any; cast back to the module type.
+ return (await import(url)) as Mod;
+}
+
+// ---------------------------------------------------------------------------
+// Payload generation (streamed to disk; never builds the whole doc in memory)
+// ---------------------------------------------------------------------------
+
+function generateStructured(path: string, targetBytes: number): void {
+ if (existsSync(path) && statSync(path).size >= targetBytes * 0.98) return;
+ const fd = openSync(path, "w");
+ try {
+ let written = 0;
+ const write = (s: string) => {
+ written += writeSync(fd, s);
+ };
+ write("[");
+ let buf = "";
+ let i = 0;
+ let first = true;
+ while (written + buf.length < targetBytes) {
+ const prefix = first ? "" : ",";
+ first = false;
+ const blob = i === 0 ? `,"blob":"${"x".repeat(BLOB_BYTES)}"` : "";
+ buf +=
+ `${prefix}{"id":${i},"uuid":"0f1e2d3c4b5a69788796a5b4c3d2e1f0",` +
+ `"name":"user_${i}","email":"user${i}@example.com","active":${
+ i % 2 === 0
+ },"score":0.12345678901234567890123,"balance":9007199254740993,` +
+ `"tags":["alpha","beta","gamma"],"profile":{"age":${
+ 20 + (i % 60)
+ },"city":"Springfield","prefs":{"theme":"dark","lang":"en"}},` +
+ `"note":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt."${blob}}`;
+ i++;
+ if (buf.length >= 4 * MB) {
+ write(buf);
+ buf = "";
+ }
+ }
+ if (buf.length) write(buf);
+ write("]");
+ } finally {
+ closeSync(fd);
+ }
+}
+
+function generateWide(path: string, count: number): void {
+ if (existsSync(path)) return;
+ const fd = openSync(path, "w");
+ try {
+ writeSync(fd, "[");
+ let buf = "";
+ for (let i = 0; i < count; i++) {
+ buf += i === 0 ? String(i) : "," + i;
+ if (buf.length >= 4 * MB) {
+ writeSync(fd, buf);
+ buf = "";
+ }
+ }
+ if (buf.length) writeSync(fd, buf);
+ writeSync(fd, "]");
+ } finally {
+ closeSync(fd);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Peak-RSS sampler
+// ---------------------------------------------------------------------------
+
+function startRssSampler(): () => number {
+ let peak = process.memoryUsage().rss;
+ const timer = setInterval(() => {
+ const rss = process.memoryUsage().rss;
+ if (rss > peak) peak = rss;
+ }, 10);
+ timer.unref();
+ return () => {
+ clearInterval(timer);
+ const rss = process.memoryUsage().rss;
+ return Math.max(peak, rss);
+ };
+}
+
+function time<T>(fn: () => T): { ms: number; value: T } {
+ const t0 = performance.now();
+ const value = fn();
+ return { ms: performance.now() - t0, value };
+}
+
+// ---------------------------------------------------------------------------
+// Child roles (one scenario per process => clean peak RSS)
+// ---------------------------------------------------------------------------
+
+interface RoleResult {
+ role: string;
+ fileBytes: number;
+ peakRssBytes: number;
+ metrics: Record<string, unknown>;
+ error?: string;
+}
+
+async function runIndexerRole(
+ path: string,
+ wide: boolean,
+): Promise<RoleResult> {
+ const stopSampler = startRssSampler();
+ const fileBytes = statSync(path).size;
+ const mod = await loadModule();
+ // Alias the Buffer's ArrayBuffer (no copy) so RSS stays ~1x the file.
+ const buf = readFileSync(path);
+ const bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
+
+ const metrics: Record<string, unknown> = {};
+
+ const engine = new mod.ByteJsonIndexEngine();
+ const loaded = time(() => engine.load(bytes));
+ metrics.loadMs = loaded.ms;
+ metrics.rootType = loaded.value.type;
+
+ // The whole point: 3 consecutive childrenPage(root, 0, 100). Page 1 scans &
+ // caches the container; pages 2 and 3 slice the cached table.
+ const root = loaded.value;
+ const pageTimings: number[] = [];
+ let firstPage: ReturnType<typeof engine.childrenPage> | null = null;
+ for (let k = 0; k < 3; k++) {
+ const p = time(() => engine.childrenPage(root.nodeId, 0, 100));
+ pageTimings.push(p.ms);
+ if (k === 0) firstPage = p.value;
+ }
+ metrics.childrenPage_x3_ms = pageTimings;
+ metrics.total = firstPage!.total;
+ metrics.rootChildCount = engine.describeNode(root.nodeId).childCount;
+
+ if (wide) {
+ const total = firstPage!.total;
+ const mid = time(() =>
+ engine.childrenPage(root.nodeId, Math.floor(total / 2), 100),
+ );
+ const last = time(() =>
+ engine.childrenPage(root.nodeId, Math.max(0, total - 100), 100),
+ );
+ metrics.midPageMs = mid.ms;
+ metrics.lastPageMs = last.ms;
+ metrics.midFirstIndex = mid.value.children[0]?.index;
+ metrics.lastFirstIndex = last.value.children[0]?.index;
+ // Prove random access lands on the right element.
+ const midNode = mid.value.children[0];
+ metrics.midValue = engine.getValue(midNode.nodeId).value;
+
+ // getValue on a small leaf.
+ const small = time(() => engine.getValue(firstPage!.children[0].nodeId));
+ metrics.smallValue = small.value.value;
+ metrics.getValueSmallMs = small.ms;
+ } else {
+ // Structured: descend into record 0 and read a small leaf + a large value.
+ const rec0 = firstPage!.children[0];
+ const rec0Page = engine.childrenPage(rec0.nodeId, 0, 100);
+ const idNode = rec0Page.children.find((c) => c.key === "id");
+ const blobNode = rec0Page.children.find((c) => c.key === "blob");
+ const balanceNode = rec0Page.children.find((c) => c.key === "balance");
+ const scoreNode = rec0Page.children.find((c) => c.key === "score");
+
+ if (idNode) {
+ const small = time(() => engine.getValue(idNode.nodeId));
+ metrics.smallValue = small.value.value;
+ metrics.getValueSmallMs = small.ms;
+ }
+ // Precision proofs on real generated data.
+ if (balanceNode) {
+ const r = engine.getValue(balanceNode.nodeId);
+ metrics.balance = String(r.value);
+ metrics.balanceIsBigInt = typeof r.value === "bigint";
+ metrics.balanceLossy = r.lossyNumber;
+ }
+ if (scoreNode) {
+ const r = engine.getValue(scoreNode.nodeId);
+ metrics.score = r.value;
+ metrics.scoreLossy = r.lossyNumber;
+ }
+ // Large value: decode a ~4MB string via TextDecoder (must not throw).
+ if (blobNode) {
+ const large = time(() =>
+ engine.getValue(blobNode.nodeId, 16 * 1024 * 1024),
+ );
+ metrics.largeValueBytes = large.value.byteLength;
+ metrics.largeValueLen = (large.value.value as string).length;
+ metrics.largeValueTruncated = large.value.truncated;
+ metrics.getValueLargeMs = large.ms;
+ }
+ // Demonstrate the maxBytes safety cap on the whole-doc root (no OOM).
+ const capped = engine.getValue(root.nodeId, 1 * MB);
+ metrics.rootCappedTruncated = capped.truncated;
+ metrics.rootCappedReturnedLen = (capped.value as string).length;
+ }
+
+ return {
+ role: wide ? "indexer:wide" : "indexer:structured",
+ fileBytes,
+ peakRssBytes: stopSampler(),
+ metrics,
+ };
+}
+
+function runJsonParseRole(path: string): RoleResult {
+ const stopSampler = startRssSampler();
+ const fileBytes = statSync(path).size;
+ const metrics: Record<string, unknown> = {};
+ try {
+ const buf = readFileSync(path);
+ const bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
+ const decoded = time(() => new TextDecoder().decode(bytes));
+ metrics.decodeMs = decoded.ms;
+ const parsed = time(() => JSON.parse(decoded.value) as unknown);
+ metrics.parseMs = parsed.ms;
+ metrics.isArray = Array.isArray(parsed.value);
+ } catch (e) {
+ return {
+ role: "json.parse",
+ fileBytes,
+ peakRssBytes: stopSampler(),
+ metrics,
+ error: e instanceof Error ? `${e.name}: ${e.message}` : String(e),
+ };
+ }
+ return {
+ role: "json.parse",
+ fileBytes,
+ peakRssBytes: stopSampler(),
+ metrics,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Dispatch
+// ---------------------------------------------------------------------------
+
+async function runRole(role: string, path: string): Promise<void> {
+ let result: RoleResult;
+ if (role === "indexer:structured") result = await runIndexerRole(path, false);
+ else if (role === "indexer:wide") result = await runIndexerRole(path, true);
+ else if (role === "json.parse") result = runJsonParseRole(path);
+ else throw new Error(`Unknown role: ${role}`);
+ process.stdout.write("RESULT" + JSON.stringify(result) + "\n");
+}
+
+function spawnRole(
+ role: string,
+ path: string,
+ maxOldSpaceMb: number,
+): RoleResult {
+ const self = fileURLToPath(import.meta.url);
+ const proc = spawnSync(
+ process.execPath,
+ [
+ `--max-old-space-size=${maxOldSpaceMb}`,
+ self,
+ `--role=${role}`,
+ `--file=${path}`,
+ ],
+ { encoding: "utf8", maxBuffer: 64 * MB },
+ );
+ const out = proc.stdout ?? "";
+ const marker = out.indexOf("RESULT");
+ if (marker === -1) {
+ return {
+ role,
+ fileBytes: existsSync(path) ? statSync(path).size : 0,
+ peakRssBytes: 0,
+ metrics: {},
+ error:
+ `child produced no result (exit ${proc.status}, signal ${proc.signal}). ` +
+ `stderr: ${(proc.stderr ?? "").slice(-400)}`,
+ };
+ }
+ const json = out.slice(marker + "RESULT".length).split("\n")[0];
+ return JSON.parse(json) as RoleResult;
+}
+
+function report(title: string, r: RoleResult): void {
+ console.log(`\n=== ${title} ===`);
+ if (r.error) {
+ console.log(` ERROR: ${r.error}`);
+ console.log(` peak RSS: ${fmtMB(r.peakRssBytes)} (before failure)`);
+ return;
+ }
+ const ratio = r.fileBytes ? r.peakRssBytes / r.fileBytes : 0;
+ console.log(` file size : ${fmtMB(r.fileBytes)}`);
+ console.log(
+ ` peak RSS : ${fmtMB(r.peakRssBytes)} (${ratio.toFixed(2)}x file)`,
+ );
+ for (const [k, v] of Object.entries(r.metrics)) {
+ if (k === "childrenPage_x3_ms" && Array.isArray(v)) {
+ const [a, b, c] = v as number[];
+ console.log(
+ ` childrenPage(root,0,100) x3: [${fmtMs(a)}, ${fmtMs(b)}, ${fmtMs(
+ c,
+ )}] -> page1/page3 = ${(a / Math.max(c, 1e-6)).toFixed(0)}x`,
+ );
+ } else if (typeof v === "number" && k.endsWith("Ms")) {
+ console.log(` ${k}: ${fmtMs(v)}`);
+ } else {
+ const s =
+ typeof v === "string" && v.length > 60 ? `${v.slice(0, 60)}…` : v;
+ console.log(` ${k}: ${s}`);
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Entry
+// ---------------------------------------------------------------------------
+
+function argOf(name: string): string | undefined {
+ const p = process.argv.find((a) => a.startsWith(`--${name}=`));
+ return p ? p.slice(name.length + 3) : undefined;
+}
+
+async function main(): Promise<void> {
+ const role = argOf("role");
+ if (role) {
+ await runRole(role, argOf("file")!);
+ return;
+ }
+
+ // Orchestrator.
+ if (!existsSync(SCRATCH)) mkdirSync(SCRATCH, { recursive: true });
+ console.log("Generating payloads (idempotent) in", SCRATCH);
+ const genStruct = time(() =>
+ generateStructured(structuredPath, STRUCTURED_TARGET_BYTES),
+ );
+ const genWide = time(() => generateWide(widePath, WIDE_COUNT));
+ console.log(
+ ` structured: ${fmtMB(statSync(structuredPath).size)} (gen ${fmtMs(
+ genStruct.ms,
+ )})`,
+ );
+ console.log(
+ ` wide : ${fmtMB(statSync(widePath).size)}, ${WIDE_COUNT} elems (gen ${fmtMs(
+ genWide.ms,
+ )})`,
+ );
+
+ report(
+ "OUR INDEXER β€” structured ~200MB",
+ spawnRole("indexer:structured", structuredPath, 512),
+ );
+ report(
+ "JSON.parse baseline β€” structured ~200MB",
+ spawnRole("json.parse", structuredPath, 8192),
+ );
+ report(
+ "OUR INDEXER β€” wide 2M array",
+ spawnRole("indexer:wide", widePath, 256),
+ );
+ report(
+ "JSON.parse baseline β€” wide 2M array",
+ spawnRole("json.parse", widePath, 8192),
+ );
+
+ console.log(
+ "\nNote: the indexer children run with a tight --max-old-space-size to " +
+ "demonstrate it survives on a small JS heap (bytes live in an ArrayBuffer, " +
+ "off the V8 heap); the JSON.parse baseline gets 8GB and still balloons.",
+ );
+}
+
+main().catch((e: unknown) => {
+ console.error(e);
+ process.exitCode = 1;
+});
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/byteJsonIndex.clienttest.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/byteJsonIndex.clienttest.ts
new file mode 100644
index 0000000000..56e410f2fe
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/byteJsonIndex.clienttest.ts
@@ -0,0 +1,295 @@
+import {
+ ByteJsonIndexEngine,
+ loadByteJsonIndex,
+ parseNumberPreservePrecision,
+} from "@/src/components/ui/AdvancedJsonViewer/lazy/byteJsonIndex";
+
+const enc = new TextEncoder();
+const bytes = (s: string) => enc.encode(s);
+
+describe("byteJsonIndex", () => {
+ describe("load", () => {
+ it("describes an object root", () => {
+ const { root } = loadByteJsonIndex(bytes(`{"a":1,"b":2}`));
+ expect(root.nodeId).toBe(0);
+ expect(root.type).toBe("object");
+ expect(root.expandable).toBe(true);
+ // childCount is unknown until the container is scanned.
+ expect(root.childCount).toBeUndefined();
+ });
+
+ it("describes an array root", () => {
+ const { root } = loadByteJsonIndex(bytes(`[1,2,3]`));
+ expect(root.type).toBe("array");
+ expect(root.expandable).toBe(true);
+ });
+
+ it("describes a primitive root as non-expandable", () => {
+ const { root } = loadByteJsonIndex(bytes(`"hello"`));
+ expect(root.type).toBe("string");
+ expect(root.expandable).toBe(false);
+ });
+
+ it("ignores leading/trailing whitespace around the root", () => {
+ const { root } = loadByteJsonIndex(bytes(` \n\t {"a":1} \n`));
+ expect(root.type).toBe("object");
+ });
+ });
+
+ describe("childrenPage", () => {
+ it("returns object members with keys, types and order", () => {
+ const engine = new ByteJsonIndexEngine();
+ const root = engine.load(
+ bytes(`{"s":"x","n":42,"b":true,"z":null,"o":{},"a":[1]}`),
+ );
+ const page = engine.childrenPage(root.nodeId, 0, 100);
+ expect(page.total).toBe(6);
+ expect(page.hasMore).toBe(false);
+ expect(page.children.map((c) => c.key)).toEqual([
+ "s",
+ "n",
+ "b",
+ "z",
+ "o",
+ "a",
+ ]);
+ expect(page.children.map((c) => c.type)).toEqual([
+ "string",
+ "number",
+ "boolean",
+ "null",
+ "object",
+ "array",
+ ]);
+ expect(page.children.map((c) => c.expandable)).toEqual([
+ false,
+ false,
+ false,
+ false,
+ true,
+ true,
+ ]);
+ });
+
+ it("returns array elements with indices", () => {
+ const engine = new ByteJsonIndexEngine();
+ const root = engine.load(bytes(`[10,20,30]`));
+ const page = engine.childrenPage(root.nodeId, 0, 100);
+ expect(page.children.map((c) => c.index)).toEqual([0, 1, 2]);
+ expect(page.children.every((c) => c.key === undefined)).toBe(true);
+ });
+
+ it("handles empty containers", () => {
+ const engine = new ByteJsonIndexEngine();
+ const rootObj = engine.load(bytes(`{}`));
+ expect(engine.childrenPage(rootObj.nodeId, 0, 10)).toMatchObject({
+ total: 0,
+ hasMore: false,
+ });
+ const rootArr = engine.load(bytes(`[]`));
+ expect(engine.childrenPage(rootArr.nodeId, 0, 10).total).toBe(0);
+ });
+
+ it("paginates with offset/limit and reports hasMore", () => {
+ const engine = new ByteJsonIndexEngine();
+ const arr = `[${Array.from({ length: 250 }, (_, i) => i).join(",")}]`;
+ const root = engine.load(bytes(arr));
+
+ const p0 = engine.childrenPage(root.nodeId, 0, 100);
+ expect(p0.total).toBe(250);
+ expect(p0.children).toHaveLength(100);
+ expect(p0.children[0].index).toBe(0);
+ expect(p0.hasMore).toBe(true);
+
+ const p2 = engine.childrenPage(root.nodeId, 200, 100);
+ expect(p2.children).toHaveLength(50);
+ expect(p2.children[0].index).toBe(200);
+ expect(p2.children.at(-1)!.index).toBe(249);
+ expect(p2.hasMore).toBe(false);
+ });
+
+ it("random-accesses a middle page correctly (offset table)", () => {
+ const engine = new ByteJsonIndexEngine();
+ const arr = `[${Array.from({ length: 1000 }, (_, i) => `"v${i}"`).join(",")}]`;
+ const root = engine.load(bytes(arr));
+ const page = engine.childrenPage(root.nodeId, 500, 3);
+ expect(page.children.map((c) => c.index)).toEqual([500, 501, 502]);
+ // materialize the middle element to confirm the offsets point at it
+ expect(engine.getValue(page.children[1].nodeId).value).toBe("v501");
+ });
+
+ it("assigns stable nodeIds across repeated pages (caching)", () => {
+ const engine = new ByteJsonIndexEngine();
+ const root = engine.load(bytes(`[1,2,3,4,5]`));
+ const first = engine
+ .childrenPage(root.nodeId, 0, 5)
+ .children.map((c) => c.nodeId);
+ const second = engine
+ .childrenPage(root.nodeId, 0, 5)
+ .children.map((c) => c.nodeId);
+ expect(second).toEqual(first);
+ // and the container now reports its childCount
+ expect(engine.describeNode(root.nodeId).childCount).toBe(5);
+ });
+
+ it("exposes childCount only after a nested container is expanded", () => {
+ const engine = new ByteJsonIndexEngine();
+ const root = engine.load(bytes(`{"outer":{"a":1,"b":2,"c":3}}`));
+ const [outer] = engine.childrenPage(root.nodeId, 0, 10).children;
+ expect(outer.type).toBe("object");
+ expect(outer.childCount).toBeUndefined(); // not yet scanned
+ const inner = engine.childrenPage(outer.nodeId, 0, 10);
+ expect(inner.total).toBe(3);
+ expect(engine.describeNode(outer.nodeId).childCount).toBe(3);
+ });
+ });
+
+ describe("UTF-8 correctness", () => {
+ it("decodes multi-byte keys and values without misreading offsets", () => {
+ const engine = new ByteJsonIndexEngine();
+ // emoji + CJK are multi-byte in UTF-8; none of their bytes collide with
+ // ASCII structural bytes.
+ const root = engine.load(bytes(`{"πŸ”‘":"cafΓ© β˜•","ζΌ’ε­—":"ζ—₯本θͺž"}`));
+ const page = engine.childrenPage(root.nodeId, 0, 10);
+ expect(page.children.map((c) => c.key)).toEqual(["πŸ”‘", "ζΌ’ε­—"]);
+ expect(engine.getValue(page.children[0].nodeId).value).toBe("cafΓ© β˜•");
+ expect(engine.getValue(page.children[1].nodeId).value).toBe("ζ—₯本θͺž");
+ });
+
+ it("does not treat brackets/quotes inside strings as structure", () => {
+ const engine = new ByteJsonIndexEngine();
+ const root = engine.load(
+ bytes(`{"tricky":"} ] { [ \\" , : ","after":7}`),
+ );
+ const page = engine.childrenPage(root.nodeId, 0, 10);
+ expect(page.total).toBe(2);
+ expect(page.children.map((c) => c.key)).toEqual(["tricky", "after"]);
+ expect(engine.getValue(page.children[0].nodeId).value).toBe(
+ `} ] { [ " , : `,
+ );
+ expect(engine.getValue(page.children[1].nodeId).value).toBe(7);
+ });
+ });
+
+ describe("getValue precision", () => {
+ it("returns safe integers as numbers", () => {
+ const engine = new ByteJsonIndexEngine();
+ const root = engine.load(bytes(`[42]`));
+ const [n] = engine.childrenPage(root.nodeId, 0, 1).children;
+ const r = engine.getValue(n.nodeId);
+ expect(r.value).toBe(42);
+ expect(r.lossyNumber).toBe(false);
+ });
+
+ it("preserves out-of-safe-range integers as bigint", () => {
+ const engine = new ByteJsonIndexEngine();
+ // 2^53 + 1 is not representable as a JS number.
+ const root = engine.load(bytes(`[9007199254740993]`));
+ const [n] = engine.childrenPage(root.nodeId, 0, 1).children;
+ const r = engine.getValue(n.nodeId);
+ expect(typeof r.value).toBe("bigint");
+ expect(r.value).toBe(9007199254740993n);
+ expect(r.lossyNumber).toBe(true);
+ });
+
+ it("preserves long fractions as raw strings", () => {
+ const engine = new ByteJsonIndexEngine();
+ const lit = "0.12345678901234567890123456789";
+ const root = engine.load(bytes(`[${lit}]`));
+ const [n] = engine.childrenPage(root.nodeId, 0, 1).children;
+ const r = engine.getValue(n.nodeId);
+ expect(r.value).toBe(lit);
+ expect(r.lossyNumber).toBe(true);
+ });
+
+ it("keeps short decimals as numbers", () => {
+ const engine = new ByteJsonIndexEngine();
+ const root = engine.load(bytes(`[3.14,-2.5e3]`));
+ const page = engine.childrenPage(root.nodeId, 0, 2);
+ const a = engine.getValue(page.children[0].nodeId);
+ const b = engine.getValue(page.children[1].nodeId);
+ expect(a.value).toBe(3.14);
+ expect(a.lossyNumber).toBe(false);
+ expect(b.value).toBe(-2500);
+ expect(b.lossyNumber).toBe(false);
+ });
+
+ it("parseNumberPreservePrecision unit cases", () => {
+ expect(parseNumberPreservePrecision("42")).toEqual({
+ value: 42,
+ lossy: false,
+ });
+ expect(parseNumberPreservePrecision("9007199254740993")).toEqual({
+ value: 9007199254740993n,
+ lossy: true,
+ });
+ expect(parseNumberPreservePrecision("1e400")).toEqual({
+ value: "1e400",
+ lossy: true,
+ });
+ // Underflow: Number("1e-400") === 0, but the literal is non-zero β€” keep
+ // the exact text (lossy) rather than silently rendering 0.
+ expect(parseNumberPreservePrecision("1e-400")).toEqual({
+ value: "1e-400",
+ lossy: true,
+ });
+ // A genuine zero literal stays a number.
+ expect(parseNumberPreservePrecision("0.0")).toEqual({
+ value: 0,
+ lossy: false,
+ });
+ // A genuine zero in scientific notation is exactly 0: the nonzero digit
+ // lives in the exponent, not the mantissa, so it must NOT be flagged
+ // lossy (only the mantissa is inspected for underflow).
+ expect(parseNumberPreservePrecision("0e10")).toEqual({
+ value: 0,
+ lossy: false,
+ });
+ expect(parseNumberPreservePrecision("-0e100")).toEqual({
+ value: -0,
+ lossy: false,
+ });
+ expect(parseNumberPreservePrecision("0.0e12")).toEqual({
+ value: 0,
+ lossy: false,
+ });
+ });
+ });
+
+ describe("preview UTF-8 boundary", () => {
+ it("does not end a truncated multi-byte preview in a replacement char", () => {
+ const engine = new ByteJsonIndexEngine();
+ // 200+ three-byte CJK chars: the ~320-byte preview cut lands mid-codepoint
+ // unless aligned. The preview must not contain U+FFFD from a partial char.
+ const cjk = "ζ–‡".repeat(300);
+ const root = engine.load(bytes(`{"k":"${cjk}"}`));
+ const [k] = engine.childrenPage(root.nodeId, 0, 1).children;
+ expect(k.preview).not.toContain("οΏ½");
+ expect(k.truncatedPreview).toBe(true);
+ });
+ });
+
+ describe("getValue slicing", () => {
+ it("materializes objects and arrays via a bounded slice", () => {
+ const engine = new ByteJsonIndexEngine();
+ const root = engine.load(bytes(`{"inner":{"x":[1,2,3],"y":"z"}}`));
+ const [inner] = engine.childrenPage(root.nodeId, 0, 1).children;
+ const r = engine.getValue(inner.nodeId);
+ expect(r.type).toBe("object");
+ expect(r.value).toEqual({ x: [1, 2, 3], y: "z" });
+ expect(r.truncated).toBe(false);
+ });
+
+ it("truncates via maxBytes without throwing (TextDecoder path)", () => {
+ const engine = new ByteJsonIndexEngine();
+ const big = "x".repeat(5000);
+ const root = engine.load(bytes(`["${big}"]`));
+ const [s] = engine.childrenPage(root.nodeId, 0, 1).children;
+ const r = engine.getValue(s.nodeId, 100);
+ expect(r.truncated).toBe(true);
+ expect(r.byteLength).toBeGreaterThan(5000);
+ expect(typeof r.value).toBe("string");
+ expect((r.value as string).length).toBe(100); // raw prefix, unparsed
+ });
+ });
+});
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/byteJsonIndex.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/byteJsonIndex.ts
new file mode 100644
index 0000000000..fb27d20b05
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/byteJsonIndex.ts
@@ -0,0 +1,787 @@
+/**
+ * Lazy UTF-8 JSON byte indexer (LFE-11082, spike LFE-11079).
+ *
+ * ---------------------------------------------------------------------------
+ * WHY THIS EXISTS
+ * ---------------------------------------------------------------------------
+ * `JSON.parse` on a large document blows the V8 heap 5-8.5x the byte size and
+ * hard-walls at the ~512MB JS-string cap, so a 200MB trace payload simply
+ * cannot be viewed. The spike validated the "index the bytes, materialize on
+ * demand" architecture using `big-json-viewer`, but that library is the wrong
+ * dependency for two reasons:
+ * 1. it is UTF-16 only (it inflates the doc into a `Uint16Array`, doubling
+ * memory and misreading multi-byte UTF-8), and
+ * 2. it keeps NO cached child index, so every page re-walks the whole
+ * container (~470ms per page on a 200MB doc).
+ *
+ * This module is our own engine that fixes exactly those two problems:
+ * - it operates on the raw UTF-8 `Uint8Array` (never inflates to a JS string,
+ * never `JSON.parse`s the whole doc), keeping RSS ~1-1.5x the file, and
+ * - it scans each container exactly ONCE, caching a compact child-offset
+ * table in typed arrays, so pages after the first are O(page), not
+ * O(container).
+ *
+ * ---------------------------------------------------------------------------
+ * WORKER <-> MAIN CONTRACT
+ * ---------------------------------------------------------------------------
+ * This is the worker-side engine. No actual Worker is wired up here; the three
+ * public methods map 1:1 to the messages a wrapping Worker would handle:
+ * - `load(bytes)` -> root descriptor
+ * - `childrenPage(nodeId, offset, limit)` -> { children, total, hasMore }
+ * - `getValue(nodeId, maxBytes?)` -> decoded value (+ lossyNumber)
+ * `nodeId`s are stable numeric handles assigned by the engine (not paths), so
+ * the main thread can address any previously-seen node by a plain number.
+ *
+ * ---------------------------------------------------------------------------
+ * WASM SEAM
+ * ---------------------------------------------------------------------------
+ * The hot byte loops (skip whitespace / string / container, scan a token,
+ * build a child-offset table) live behind the {@link ByteScanner} interface and
+ * are implemented in pure TS by {@link JsByteScanner}. A future WASM module can
+ * implement the same interface and be swapped in without touching the engine,
+ * pagination, previews, or precision logic above it.
+ *
+ * Reference: the byte state machine is a UTF-8, cached-offset rewrite of
+ * big-json-viewer's `buffer-json-parser` scanner (see NOTES at bottom for what
+ * was reusable).
+ */
+
+// ============================================================================
+// Public types
+// ============================================================================
+
+export type JsonNodeType =
+ | "object"
+ | "array"
+ | "string"
+ | "number"
+ | "boolean"
+ | "null";
+
+export interface NodeDescriptor {
+ /** Stable numeric handle assigned by the engine. */
+ nodeId: number;
+ /** Object member key (present only for object children). */
+ key?: string;
+ /** Array element index (present only for array children). */
+ index?: number;
+ type: JsonNodeType;
+ /** Number of immediate children. Present once the node has been scanned. */
+ childCount?: number;
+ /** True for objects/arrays (i.e. has a `childrenPage`). */
+ expandable: boolean;
+ /** Short (~200 char) preview of the value. */
+ preview: string;
+ /** True if `preview` was cut short of the full value. */
+ truncatedPreview: boolean;
+}
+
+export interface ChildrenPage {
+ children: NodeDescriptor[];
+ /** Total number of immediate children in the container. */
+ total: number;
+ /** True if `offset + limit < total`. */
+ hasMore: boolean;
+}
+
+export interface GetValueResult {
+ nodeId: number;
+ type: JsonNodeType;
+ /**
+ * The decoded value. For containers this is the parsed subtree; for leaves
+ * the parsed primitive. Out-of-double-range integers come back as `bigint`,
+ * long-fraction numbers as their raw `string` (see `lossyNumber`). When
+ * `truncated` is true this is the raw (unparsed) decoded text prefix.
+ */
+ value: unknown;
+ /** True if the number could not be represented exactly as a JS `number`. */
+ lossyNumber: boolean;
+ /** True if `maxBytes` forced a partial slice (value not fully parsed). */
+ truncated: boolean;
+ /** Full byte length of the value (independent of `maxBytes`). */
+ byteLength: number;
+}
+
+// ============================================================================
+// Byte constants (JSON structural bytes are all ASCII => single UTF-8 bytes;
+// UTF-8 continuation/lead bytes are all >= 0x80 and can never collide with
+// these, so byte-wise scanning inside strings is safe).
+// ============================================================================
+
+const BRACE_OPEN = 0x7b; // {
+const BRACE_CLOSE = 0x7d; // }
+const BRACKET_OPEN = 0x5b; // [
+const BRACKET_CLOSE = 0x5d; // ]
+const COMMA = 0x2c; // ,
+const DQUOTE = 0x22; // "
+const BACKSLASH = 0x5c; // \
+const SPACE = 0x20;
+const TAB = 0x09;
+const LF = 0x0a;
+const CR = 0x0d;
+const MINUS = 0x2d; // -
+const PLUS = 0x2b; // +
+const DOT = 0x2e; // .
+const CHAR_e = 0x65;
+const CHAR_E = 0x45;
+const CHAR_t = 0x74; // true
+const CHAR_f = 0x66; // false
+const CHAR_n = 0x6e; // null
+const DIGIT_0 = 0x30;
+const DIGIT_9 = 0x39;
+
+// Compact numeric type tags stored in the columnar child tables.
+const T_OBJECT = 0;
+const T_ARRAY = 1;
+const T_STRING = 2;
+const T_NUMBER = 3;
+const T_BOOLEAN = 4;
+const T_NULL = 5;
+
+const TYPE_NAMES: JsonNodeType[] = [
+ "object",
+ "array",
+ "string",
+ "number",
+ "boolean",
+ "null",
+];
+
+// Preview / value caps.
+const PREVIEW_BYTE_CAP = 320; // bytes decoded to build a preview
+const PREVIEW_CHAR_CAP = 200; // final preview character budget
+const DEFAULT_MAX_VALUE_BYTES = 25 * 1024 * 1024; // getValue safety cap
+
+// Significant decimal digits a double reliably round-trips. Numbers with more
+// than this are treated as potentially lossy (conservative: we may preserve an
+// exactly-representable 16-digit value as a raw string, which is still exact
+// for display).
+const DOUBLE_SAFE_SIG_DIGITS = 15;
+
+// ============================================================================
+// WASM seam: low-level byte scanner
+// ============================================================================
+
+export interface ScanResult {
+ /** Exclusive end byte offset of the scanned value. */
+ end: number;
+ /** Compact type tag (T_*). */
+ type: number;
+}
+
+export interface ScannedContainer {
+ isObject: boolean;
+ /** Start byte offset of each child value (Uint32 => docs up to 4GB). */
+ starts: Uint32Array;
+ /** Exclusive end byte offset of each child value. */
+ ends: Uint32Array;
+ /** Compact type tag (T_*) of each child. */
+ types: Uint8Array;
+ /** Decoded keys, parallel to the arrays above (objects only; null for arrays). */
+ keys: string[] | null;
+}
+
+/**
+ * The hot loop, isolated so a WASM implementation can replace it wholesale.
+ * All methods take/return absolute byte offsets into the same backing buffer.
+ */
+export interface ByteScanner {
+ readonly bytes: Uint8Array;
+ /** First non-whitespace offset at or after `pos`. */
+ skipWhitespace(pos: number): number;
+ /**
+ * Scan the single value beginning at `pos` (first non-ws byte). Returns its
+ * exclusive end and type WITHOUT descending into / allocating children.
+ */
+ scanValue(pos: number): ScanResult;
+ /**
+ * Scan a container (`pos` at `{` or `[`) in one pass, producing the columnar
+ * offset table of its immediate children.
+ */
+ scanContainer(pos: number): ScannedContainer;
+}
+
+/** Growable Uint32Array (avoids boxing 2M+ offsets through a JS number[]). */
+class U32Builder {
+ private buf: Uint32Array;
+ private len = 0;
+ constructor(initialCapacity = 16) {
+ this.buf = new Uint32Array(initialCapacity);
+ }
+ push(v: number): void {
+ if (this.len === this.buf.length) {
+ const next = new Uint32Array(this.buf.length * 2);
+ next.set(this.buf);
+ this.buf = next;
+ }
+ this.buf[this.len++] = v;
+ }
+ finish(): Uint32Array {
+ // slice to the exact length so the steady-state footprint is tight.
+ return this.buf.slice(0, this.len);
+ }
+}
+
+/** Growable Uint8Array. */
+class U8Builder {
+ private buf: Uint8Array;
+ private len = 0;
+ constructor(initialCapacity = 16) {
+ this.buf = new Uint8Array(initialCapacity);
+ }
+ push(v: number): void {
+ if (this.len === this.buf.length) {
+ const next = new Uint8Array(this.buf.length * 2);
+ next.set(this.buf);
+ this.buf = next;
+ }
+ this.buf[this.len++] = v;
+ }
+ finish(): Uint8Array {
+ return this.buf.slice(0, this.len);
+ }
+}
+
+/**
+ * Pure-TS UTF-8 byte scanner. This is the piece a WASM module would replace.
+ */
+export class JsByteScanner implements ByteScanner {
+ readonly bytes: Uint8Array;
+ private readonly decoder = new TextDecoder();
+
+ constructor(bytes: Uint8Array) {
+ this.bytes = bytes;
+ }
+
+ skipWhitespace(pos: number): number {
+ const b = this.bytes;
+ const n = b.length;
+ let i = pos;
+ while (i < n) {
+ const c = b[i];
+ if (c === SPACE || c === TAB || c === LF || c === CR) {
+ i++;
+ continue;
+ }
+ break;
+ }
+ return i;
+ }
+
+ /** `pos` at opening quote; returns offset just past the closing quote. */
+ private skipString(pos: number): number {
+ const b = this.bytes;
+ const n = b.length;
+ let i = pos + 1;
+ while (i < n) {
+ const c = b[i];
+ if (c === BACKSLASH) {
+ // Skip the backslash and the escaped byte. For \uXXXX the four hex
+ // digits are ordinary bytes (never `"`/`\`), so this is correct.
+ i += 2;
+ continue;
+ }
+ if (c === DQUOTE) return i + 1;
+ i++;
+ }
+ return n; // unterminated (malformed / truncated input)
+ }
+
+ /**
+ * `pos` at `{` or `[`; depth-tracks to the matching close, skipping strings
+ * so brackets inside string literals are ignored. Single forward pass.
+ */
+ private skipContainer(pos: number): number {
+ const b = this.bytes;
+ const n = b.length;
+ let depth = 0;
+ let i = pos;
+ while (i < n) {
+ const c = b[i];
+ if (c === DQUOTE) {
+ i = this.skipString(i);
+ continue;
+ }
+ if (c === BRACE_OPEN || c === BRACKET_OPEN) {
+ depth++;
+ i++;
+ continue;
+ }
+ if (c === BRACE_CLOSE || c === BRACKET_CLOSE) {
+ depth--;
+ i++;
+ if (depth === 0) return i;
+ continue;
+ }
+ i++;
+ }
+ return n; // malformed / truncated
+ }
+
+ /** Scan number / true / false / null token to its end. Lenient by design. */
+ private skipNumber(pos: number): number {
+ const b = this.bytes;
+ const n = b.length;
+ let i = pos;
+ while (i < n) {
+ const c = b[i];
+ if (
+ (c >= DIGIT_0 && c <= DIGIT_9) ||
+ c === MINUS ||
+ c === PLUS ||
+ c === DOT ||
+ c === CHAR_e ||
+ c === CHAR_E
+ ) {
+ i++;
+ continue;
+ }
+ break;
+ }
+ return i;
+ }
+
+ scanValue(pos: number): ScanResult {
+ const c = this.bytes[pos];
+ switch (c) {
+ case DQUOTE:
+ return { end: this.skipString(pos), type: T_STRING };
+ case BRACE_OPEN:
+ return { end: this.skipContainer(pos), type: T_OBJECT };
+ case BRACKET_OPEN:
+ return { end: this.skipContainer(pos), type: T_ARRAY };
+ case CHAR_t:
+ return { end: pos + 4, type: T_BOOLEAN }; // true
+ case CHAR_f:
+ return { end: pos + 5, type: T_BOOLEAN }; // false
+ case CHAR_n:
+ return { end: pos + 4, type: T_NULL }; // null
+ default:
+ return { end: this.skipNumber(pos), type: T_NUMBER };
+ }
+ }
+
+ scanContainer(openPos: number): ScannedContainer {
+ const b = this.bytes;
+ const isObject = b[openPos] === BRACE_OPEN;
+ const closeByte = isObject ? BRACE_CLOSE : BRACKET_CLOSE;
+ const starts = new U32Builder();
+ const ends = new U32Builder();
+ const types = new U8Builder();
+ const keys: string[] | null = isObject ? [] : null;
+
+ let pos = this.skipWhitespace(openPos + 1);
+ if (b[pos] === closeByte) {
+ // Empty container.
+ return {
+ isObject,
+ starts: starts.finish(),
+ ends: ends.finish(),
+ types: types.finish(),
+ keys,
+ };
+ }
+
+ for (;;) {
+ if (isObject) {
+ // key: b[pos] is the opening quote of the key string.
+ const keyStart = pos;
+ const keyEnd = this.skipString(pos);
+ (keys as string[]).push(this.decodeStringSlice(keyStart, keyEnd));
+ pos = this.skipWhitespace(keyEnd); // -> ':'
+ pos = this.skipWhitespace(pos + 1); // past ':' -> value
+ }
+
+ const valStart = pos;
+ const sr = this.scanValue(pos);
+ starts.push(valStart);
+ ends.push(sr.end);
+ types.push(sr.type);
+
+ pos = this.skipWhitespace(sr.end);
+ const c = b[pos];
+ if (c === COMMA) {
+ pos = this.skipWhitespace(pos + 1);
+ continue;
+ }
+ break; // c === closeByte (or EOF on malformed input)
+ }
+
+ return {
+ isObject,
+ starts: starts.finish(),
+ ends: ends.finish(),
+ types: types.finish(),
+ keys,
+ };
+ }
+
+ /** Decode a `"..."` slice (quotes included) and unescape via JSON.parse. */
+ private decodeStringSlice(start: number, end: number): string {
+ const text = this.decoder.decode(this.bytes.subarray(start, end));
+ try {
+ return JSON.parse(text) as string;
+ } catch {
+ return text;
+ }
+ }
+}
+
+// ============================================================================
+// Internal node model
+// ============================================================================
+
+interface ChildTable {
+ isObject: boolean;
+ starts: Uint32Array;
+ ends: Uint32Array;
+ types: Uint8Array;
+ keys: string[] | null;
+ count: number;
+ /** Lazily-assigned child index -> nodeId (only for children ever addressed). */
+ ids: Map<number, number>;
+}
+
+interface NodeRecord {
+ id: number;
+ parentId: number | null;
+ key: string | null;
+ index: number | null;
+ type: number; // T_*
+ valueStart: number;
+ valueEnd: number;
+ /** Cached immediate-child offset table, built on first `childrenPage`. */
+ childTable: ChildTable | null;
+}
+
+// ============================================================================
+// Precision-preserving number parsing
+// ============================================================================
+
+function significantDigitCount(text: string): number {
+ let s = text.replace(/^[+-]/, "");
+ const eIdx = s.search(/[eE]/);
+ if (eIdx >= 0) s = s.slice(0, eIdx);
+ s = s.replace(".", "");
+ s = s.replace(/^0+/, ""); // leading zeros are not significant
+ s = s.replace(/0+$/, ""); // trailing zeros do not add precision pressure
+ return s.length;
+}
+
+/**
+ * Parse a JSON number literal without silently losing precision:
+ * - safe integers -> `number`
+ * - big integers -> `bigint` (lossy=true: JSON.parse would round it)
+ * - long fractions -> raw string (lossy=true)
+ * - everything else -> `number`
+ */
+export function parseNumberPreservePrecision(text: string): {
+ value: number | bigint | string;
+ lossy: boolean;
+} {
+ const t = text.trim();
+ if (/^-?\d+$/.test(t)) {
+ const n = Number(t);
+ if (Number.isSafeInteger(n)) return { value: n, lossy: false };
+ return { value: BigInt(t), lossy: true };
+ }
+ const n = Number(t);
+ if (!Number.isFinite(n)) {
+ // Overflows double range (e.g. 1e400) -> keep exact text.
+ return { value: t, lossy: true };
+ }
+ // Underflowed to 0 (e.g. 1e-400) but the literal is non-zero β€” rendering it
+ // as `0` would silently lose the value, so keep the exact text (lossy). Test
+ // only the mantissa (text before the exponent) for a nonzero digit: a genuine
+ // zero in scientific notation (e.g. "0e10", "-0e100") has a nonzero digit in
+ // its exponent but is exactly 0, and must stay a plain `0`.
+ if (n === 0 && /[1-9]/.test(t.split(/[eE]/)[0]!)) {
+ return { value: t, lossy: true };
+ }
+ const lossy = significantDigitCount(t) > DOUBLE_SAFE_SIG_DIGITS;
+ return { value: lossy ? t : n, lossy };
+}
+
+// ============================================================================
+// Engine
+// ============================================================================
+
+export class ByteJsonIndexEngine {
+ private bytes: Uint8Array = new Uint8Array(0);
+ private scanner: ByteScanner | null = null;
+ private nodes: NodeRecord[] = [];
+ private rootId = -1;
+ private readonly decoder = new TextDecoder();
+
+ /**
+ * Point the engine at a UTF-8 byte buffer and index the root value only.
+ * Cheap: it locates the root's bounds/type, it does NOT scan children.
+ */
+ load(bytes: Uint8Array): NodeDescriptor {
+ this.bytes = bytes;
+ this.scanner = new JsByteScanner(bytes);
+ this.nodes = [];
+ const start = this.scanner.skipWhitespace(0);
+ const first = bytes[start];
+ let type: number;
+ let valueEnd: number;
+ if (first === BRACE_OPEN || first === BRACKET_OPEN) {
+ // Root container: its end is the last non-whitespace byte of the doc, so
+ // we can find it without a full O(doc) scan. The real child scan is
+ // deferred to the first childrenPage. This keeps `load` cheap.
+ type = first === BRACE_OPEN ? T_OBJECT : T_ARRAY;
+ let e = bytes.length;
+ while (e > start) {
+ const c = bytes[e - 1];
+ if (c === SPACE || c === TAB || c === LF || c === CR) e--;
+ else break;
+ }
+ valueEnd = e;
+ } else {
+ const sr = this.scanner.scanValue(start);
+ type = sr.type;
+ valueEnd = sr.end;
+ }
+ this.rootId = this.pushNode({
+ parentId: null,
+ key: null,
+ index: null,
+ type,
+ valueStart: start,
+ valueEnd,
+ });
+ return this.describe(this.rootId);
+ }
+
+ /**
+ * Page through a container's immediate children. The FIRST call on a given
+ * node scans the container once and caches its offset table; subsequent calls
+ * (any offset) slice that cached table in O(limit).
+ */
+ childrenPage(nodeId: number, offset: number, limit: number): ChildrenPage {
+ const node = this.mustNode(nodeId);
+ if (node.type !== T_OBJECT && node.type !== T_ARRAY) {
+ return { children: [], total: 0, hasMore: false };
+ }
+ const table = this.ensureChildTable(node);
+ const total = table.count;
+ const startIdx = Math.min(Math.max(0, offset), total);
+ const endIdx = Math.min(total, startIdx + Math.max(0, limit));
+ const children: NodeDescriptor[] = [];
+ for (let i = startIdx; i < endIdx; i++) {
+ children.push(this.describe(this.childNodeId(node, table, i)));
+ }
+ return { children, total, hasMore: endIdx < total };
+ }
+
+ /**
+ * Materialize a single node's value on demand by slicing its bytes and
+ * decoding just that slice with TextDecoder (never `String.fromCharCode`,
+ * which throws on large slices).
+ */
+ getValue(
+ nodeId: number,
+ maxBytes: number = DEFAULT_MAX_VALUE_BYTES,
+ ): GetValueResult {
+ const node = this.mustNode(nodeId);
+ const type = TYPE_NAMES[node.type];
+ const byteLength = node.valueEnd - node.valueStart;
+ const cap = maxBytes ?? Number.POSITIVE_INFINITY;
+ const truncated = byteLength > cap;
+ const sliceEnd = truncated ? node.valueStart + cap : node.valueEnd;
+ const text = this.decoder.decode(
+ this.bytes.subarray(node.valueStart, sliceEnd),
+ );
+
+ if (truncated) {
+ // Cannot parse a partial slice; hand back the raw decoded prefix.
+ return {
+ nodeId,
+ type,
+ value: text,
+ lossyNumber: false,
+ truncated,
+ byteLength,
+ };
+ }
+
+ if (node.type === T_NUMBER) {
+ const parsed = parseNumberPreservePrecision(text);
+ return {
+ nodeId,
+ type,
+ value: parsed.value,
+ lossyNumber: parsed.lossy,
+ truncated: false,
+ byteLength,
+ };
+ }
+
+ // string / boolean / null / object / array: parse the (bounded) slice.
+ // NOTE: JSON.parse on a container subtree does not preserve big-number
+ // precision for numbers nested inside it (see NOTES/gaps).
+ const value = JSON.parse(text) as unknown;
+ return {
+ nodeId,
+ type,
+ value,
+ lossyNumber: false,
+ truncated: false,
+ byteLength,
+ };
+ }
+
+ /** Re-describe a known node (e.g. root after its children were scanned). */
+ describeNode(nodeId: number): NodeDescriptor {
+ return this.describe(nodeId);
+ }
+
+ // -- internals -----------------------------------------------------------
+
+ private ensureChildTable(node: NodeRecord): ChildTable {
+ if (node.childTable) return node.childTable;
+ // KNOWN LIMITATION (LFE-11082 follow-up): this scans the WHOLE container to
+ // build the offset table on the first `childrenPage`, so a container with
+ // millions of immediate children costs O(all children) up front even to
+ // show the first page. Bounded in practice by the size tiering (LFE-14418):
+ // payloads large enough to make this scan jank the main thread are routed to
+ // the Worker source. The real fix is a resumable, page-at-a-time scan.
+ const scanned = this.scanner!.scanContainer(node.valueStart);
+ node.childTable = {
+ isObject: scanned.isObject,
+ starts: scanned.starts,
+ ends: scanned.ends,
+ types: scanned.types,
+ keys: scanned.keys,
+ count: scanned.types.length,
+ ids: new Map(),
+ };
+ return node.childTable;
+ }
+
+ private childNodeId(
+ parent: NodeRecord,
+ table: ChildTable,
+ i: number,
+ ): number {
+ const existing = table.ids.get(i);
+ if (existing !== undefined) return existing;
+ const id = this.pushNode({
+ parentId: parent.id,
+ key: table.keys ? table.keys[i] : null,
+ index: table.keys ? null : i,
+ type: table.types[i],
+ valueStart: table.starts[i],
+ valueEnd: table.ends[i],
+ });
+ table.ids.set(i, id);
+ return id;
+ }
+
+ private pushNode(rec: Omit<NodeRecord, "id" | "childTable">): number {
+ const id = this.nodes.length;
+ this.nodes.push({ ...rec, id, childTable: null });
+ return id;
+ }
+
+ private mustNode(nodeId: number): NodeRecord {
+ const node = this.nodes[nodeId];
+ if (!node) throw new Error(`Unknown nodeId: ${nodeId}`);
+ return node;
+ }
+
+ private describe(id: number): NodeDescriptor {
+ const node = this.mustNode(id);
+ const typeName = TYPE_NAMES[node.type];
+ const expandable = node.type === T_OBJECT || node.type === T_ARRAY;
+ const { preview, truncated } = this.makePreview(node);
+ const d: NodeDescriptor = {
+ nodeId: id,
+ type: typeName,
+ expandable,
+ preview,
+ truncatedPreview: truncated,
+ };
+ if (node.key !== null) d.key = node.key;
+ if (node.index !== null) d.index = node.index;
+ if (node.childTable) d.childCount = node.childTable.count;
+ return d;
+ }
+
+ private makePreview(node: NodeRecord): {
+ preview: string;
+ truncated: boolean;
+ } {
+ // For an already-scanned container show a compact structural summary.
+ if (node.childTable) {
+ const label = node.type === T_ARRAY ? "Array" : "Object";
+ return {
+ preview: `${label}(${node.childTable.count})`,
+ truncated: false,
+ };
+ }
+ const total = node.valueEnd - node.valueStart;
+ let sliceEnd = Math.min(node.valueEnd, node.valueStart + PREVIEW_BYTE_CAP);
+ // If we're truncating, don't cut mid-codepoint: back the cut up off any
+ // UTF-8 continuation bytes (10xxxxxx) to the start of that codepoint, so a
+ // multi-byte char (e.g. CJK) at the boundary doesn't decode to a trailing οΏ½.
+ if (sliceEnd < node.valueEnd) {
+ while (
+ sliceEnd > node.valueStart &&
+ (this.bytes[sliceEnd]! & 0xc0) === 0x80
+ ) {
+ sliceEnd--;
+ }
+ }
+ let text = this.decoder.decode(
+ this.bytes.subarray(node.valueStart, sliceEnd),
+ );
+ text = text.replace(/\s+/g, " ").trim();
+ const bytesTruncated = total > sliceEnd - node.valueStart;
+ const truncated = bytesTruncated || text.length > PREVIEW_CHAR_CAP;
+ if (text.length > PREVIEW_CHAR_CAP) text = text.slice(0, PREVIEW_CHAR_CAP);
+ return { preview: text, truncated };
+ }
+}
+
+/** Convenience factory mirroring the worker `load(bytes)` entry point. */
+export function loadByteJsonIndex(bytes: Uint8Array): {
+ engine: ByteJsonIndexEngine;
+ root: NodeDescriptor;
+} {
+ const engine = new ByteJsonIndexEngine();
+ const root = engine.load(bytes);
+ return { engine, root };
+}
+
+/*
+ * ---------------------------------------------------------------------------
+ * NOTES
+ * ---------------------------------------------------------------------------
+ * What was reusable from big-json-viewer's `buffer-json-parser` (~200 lines):
+ * - The state-machine SHAPE only: the set of primitives (skipWhitespace,
+ * skipString-with-escape-flag, per-value dispatch, number/token scan) and
+ * the structural byte constants. That is the ~30% that transferred.
+ * - Everything else was rewritten:
+ * * UTF-8 Uint8Array bytes instead of a UTF-16 Uint16Array (their design
+ * inflates the whole doc; we never do),
+ * * container skipping via a single depth-tracking `skipContainer` pass
+ * (bracket matching) rather than recursive descent,
+ * * a CACHED columnar child-offset table (their scanner re-walks the
+ * container to locate the Nth child on every access; that is the
+ * ~470ms/page regression we exist to remove),
+ * * lazy numeric nodeIds + precision-preserving number handling, neither
+ * of which their scanner has.
+ *
+ * Gaps / not yet validated (spike-grade):
+ * - Browser Worker wiring + transferable ArrayBuffer hand-off is unproven
+ * (this module is only the engine; the bench drives it in-process).
+ * - Browser ArrayBuffer / typed-array size caps are not probed here.
+ * - `getValue` on a container uses JSON.parse on the slice, so big numbers
+ * NESTED inside a returned subtree are not precision-preserved (only leaf
+ * number nodes accessed directly are).
+ * - Malformed / truncated input is handled leniently (best-effort bounds),
+ * not validated; a production build should surface parse errors.
+ * - The float lossiness rule is conservative (>15 significant digits), so a
+ * few exactly-representable 16-digit values are preserved as raw strings.
+ */
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonList.tsx b/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonList.tsx
new file mode 100644
index 0000000000..f711bb9c3d
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonList.tsx
@@ -0,0 +1,168 @@
+/**
+ * LazyJsonList β€” the virtualized body of the lazy JSON viewer. It positions row
+ * shells and keeps the store's loaded window in sync with the visible range; it
+ * owns no document state. Row content comes from the store's per-revision cache
+ * (LFE-11080).
+ */
+
+import React, { useEffect, useRef } from "react";
+import { useStore } from "zustand";
+import { useVirtualizer } from "@tanstack/react-virtual";
+import { LazyJsonRow } from "./LazyJsonRow";
+import type { RowModelStore } from "./rowModelStore";
+
+/** Fixed single-line row height β€” JSON rows never wrap, so no live measurement. */
+const ROW_HEIGHT = 20;
+
+// How much of a leaf we're willing to materialize for a clipboard copy. Well
+// above the engine's preview-sized default, so a large string (e.g. a base64
+// image) copies WHOLE; a value beyond even this is too large for the clipboard.
+const COPY_MAX_BYTES = 64 * 1024 * 1024;
+
+async function copyFullValue(store: RowModelStore, nodeId: number) {
+ await store.getState().materialize(nodeId, COPY_MAX_BYTES);
+ const result = store.getState().values.get(nodeId);
+ if (!result || !result.ok) return;
+ const { value, truncated } = result.value;
+ // Honesty: if the value is STILL truncated at the copy cap, we do NOT have
+ // the whole value β€” writing the prefix would silently produce a corrupt copy
+ // (a half base64 image is useless) under a "Copy full value" label. Skip it;
+ // the field-level download is the escape hatch for values this large.
+ if (truncated) return;
+ // Out-of-double integers come back as bigint, which JSON.stringify can't
+ // serialize β€” handle strings and bigint before the object path.
+ const text =
+ typeof value === "string"
+ ? value
+ : typeof value === "bigint"
+ ? value.toString()
+ : safeStringify(value);
+ try {
+ await navigator.clipboard.writeText(text);
+ } catch {
+ // Clipboard denied (permissions / insecure context) β€” nothing to do here;
+ // a production caller would surface a toast.
+ }
+}
+
+function safeStringify(value: unknown): string {
+ try {
+ return JSON.stringify(
+ value,
+ (_k, v) => (typeof v === "bigint" ? v.toString() : v),
+ 2,
+ );
+ } catch {
+ return String(value);
+ }
+}
+
+export interface LazyJsonListProps {
+ store: RowModelStore;
+ className?: string;
+}
+
+export function LazyJsonList({ store, className }: LazyJsonListProps) {
+ const parentRef = useRef<HTMLDivElement>(null);
+
+ const totalVisible = useStore(store, (s) => s.totalVisible);
+ const rows = useStore(store, (s) => s.rows);
+ const pending = useStore(store, (s) => s.pending);
+ // Subscribe to revision so a structural change (which swaps `rows` for a new
+ // empty Map, then refills) reliably repaints even before the refill lands.
+ const revision = useStore(store, (s) => s.revision);
+
+ // Stable action bag β€” bound once to the store, so memoized rows never see a
+ // changed callback identity on scroll.
+ const actionsRef = useRef<{
+ toggle: (nodeId: number, expanded: boolean) => void;
+ loadMore: (nodeId: number) => void;
+ copyValue: (nodeId: number) => void;
+ } | null>(null);
+ if (actionsRef.current === null) {
+ actionsRef.current = {
+ toggle: (nodeId, expanded) => {
+ store.getState().toggle(nodeId, expanded);
+ },
+ loadMore: (nodeId) => {
+ store.getState().loadMore(nodeId);
+ },
+ copyValue: (nodeId) => {
+ copyFullValue(store, nodeId);
+ },
+ };
+ }
+ const actions = actionsRef.current;
+
+ const virtualizer = useVirtualizer({
+ count: totalVisible,
+ getScrollElement: () => parentRef.current,
+ estimateSize: () => ROW_HEIGHT,
+ overscan: 40,
+ });
+
+ const virtualItems = virtualizer.getVirtualItems();
+ const firstIndex = virtualItems.length > 0 ? virtualItems[0]!.index : 0;
+ const lastIndex =
+ virtualItems.length > 0 ? virtualItems[virtualItems.length - 1]!.index : 0;
+
+ // Keep the store's loaded window in sync with the virtualizer's visible range.
+ // This is the windowed-loading integration boundary: it must react both to
+ // SCROLL (virtual indices change) and to a structural change that GROWS the
+ // range in place (revision bumps, count grows, but no scroll/resize event
+ // fires β€” so the virtualizer's own onChange would miss it). Depending on the
+ // computed range + revision covers both. `ensureRange` no-ops when the range
+ // is already cached, so scroll ticks are cheap.
+ useEffect(() => {
+ if (totalVisible === 0) return;
+ store.getState().ensureRange(firstIndex, lastIndex - firstIndex + 1);
+ }, [store, firstIndex, lastIndex, revision, totalVisible]);
+
+ return (
+ <div
+ ref={parentRef}
+ className={className}
+ style={{ height: "100%", overflow: "auto" }}
+ >
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: "100%",
+ position: "relative",
+ }}
+ >
+ {virtualItems.map((virtualRow) => {
+ const row = rows.get(virtualRow.index);
+ return (
+ <div
+ key={virtualRow.key}
+ data-index={virtualRow.index}
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ height: `${virtualRow.size}px`,
+ transform: `translateY(${virtualRow.start}px)`,
+ }}
+ >
+ {row ? (
+ <LazyJsonRow
+ row={row}
+ pending={pending.has(row.nodeId)}
+ onToggle={actions.toggle}
+ onLoadMore={actions.loadMore}
+ onCopyValue={actions.copyValue}
+ />
+ ) : (
+ // Not yet fetched β€” reserve the shell; the row fills in when the
+ // window resolves and the store repaints.
+ <div className="h-full" aria-hidden />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonRow.tsx b/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonRow.tsx
new file mode 100644
index 0000000000..d7173af876
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonRow.tsx
@@ -0,0 +1,157 @@
+/**
+ * LazyJsonRow β€” a single visible line of the lazy JSON viewer. View-only: it
+ * receives one `JsonRow` plus stable callbacks and renders; it owns no state,
+ * runs no effects, and fetches nothing. All logic lives in the store
+ * (LFE-11080).
+ */
+
+import React from "react";
+import { ChevronRight, Copy, Loader2 } from "lucide-react";
+import { cn } from "@/src/utils/tailwind";
+import type { JsonNodeType, JsonRow } from "../rowModel";
+
+const INDENT_PX = 14;
+// Past this nesting level the indent stops growing, so a very deep chain stays
+// readable instead of pushing every value off the right edge (same failure mode
+// as the deep-trace layout collapse, LFE-10959). The tree is still conveyed by
+// the chevrons and keys; only the horizontal offset is capped.
+const MAX_VISUAL_DEPTH = 24;
+
+/** Tailwind text color per JSON scalar type (containers use the muted key color). */
+const TYPE_CLASS: Record<JsonNodeType, string> = {
+ string: "text-green-700 dark:text-green-400",
+ number: "text-blue-700 dark:text-blue-400",
+ boolean: "text-purple-700 dark:text-purple-400",
+ null: "text-muted-foreground",
+ object: "text-foreground",
+ array: "text-foreground",
+};
+
+export interface LazyJsonRowProps {
+ row: JsonRow;
+ /** True while this node has an in-flight expand/collapse/load-more. */
+ pending?: boolean;
+ onToggle: (nodeId: number, currentlyExpanded: boolean) => void;
+ onLoadMore: (loadMoreId: number) => void;
+ onCopyValue: (nodeId: number) => void;
+}
+
+function keyLabel(keyOrIndex: string | number | null): string | null {
+ if (keyOrIndex === null) return null;
+ return typeof keyOrIndex === "number" ? `${keyOrIndex}` : keyOrIndex;
+}
+
+function LazyJsonRowImpl({
+ row,
+ pending = false,
+ onToggle,
+ onLoadMore,
+ onCopyValue,
+}: LazyJsonRowProps) {
+ const paddingLeft = Math.min(row.depth, MAX_VISUAL_DEPTH) * INDENT_PX;
+
+ // Synthetic "reveal next page" row for a paginated wide container.
+ if (row.isLoadMore) {
+ return (
+ <div
+ className="flex h-full items-center gap-1 font-mono text-xs"
+ style={{ paddingLeft: paddingLeft + INDENT_PX }}
+ >
+ <button
+ type="button"
+ disabled={pending}
+ className="text-muted-foreground hover:text-foreground rounded px-1 underline decoration-dotted underline-offset-2 disabled:opacity-60"
+ onClick={() => onLoadMore(row.nodeId)}
+ >
+ {row.preview}
+ </button>
+ {pending ? <Loader2 className="h-3 w-3 animate-spin" /> : null}
+ </div>
+ );
+ }
+
+ const label = keyLabel(row.keyOrIndex);
+ const isContainer = row.expandable;
+
+ return (
+ <div
+ className="hover:bg-muted/50 group flex h-full items-center gap-1 font-mono text-xs"
+ style={{ paddingLeft }}
+ >
+ {/* Chevron gutter β€” reserved even for leaves so keys align by depth. */}
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center">
+ {isContainer ? (
+ pending ? (
+ <Loader2 className="text-muted-foreground h-3 w-3 animate-spin" />
+ ) : (
+ <button
+ type="button"
+ aria-label={row.expanded ? "Collapse" : "Expand"}
+ className="text-muted-foreground hover:text-foreground flex h-4 w-4 items-center justify-center"
+ onClick={() => onToggle(row.nodeId, row.expanded)}
+ >
+ <ChevronRight
+ className={cn(
+ "h-3 w-3 transition-transform",
+ row.expanded && "rotate-90",
+ )}
+ />
+ </button>
+ )
+ ) : null}
+ </span>
+
+ {label !== null ? (
+ <span className="text-muted-foreground shrink-0">
+ {label}
+ <span className="opacity-60">:</span>
+ </span>
+ ) : null}
+
+ {isContainer ? (
+ <span className="text-muted-foreground truncate" title={row.preview}>
+ {row.preview}
+ {typeof row.childCount === "number" ? (
+ <span className="ml-1 opacity-60">
+ {row.type === "array"
+ ? `[${row.childCount}]`
+ : `{${row.childCount}}`}
+ </span>
+ ) : null}
+ </span>
+ ) : (
+ <span
+ className={cn("truncate", TYPE_CLASS[row.type])}
+ title={row.preview}
+ >
+ {row.preview}
+ {row.truncatedPreview ? (
+ <span className="text-muted-foreground opacity-60">…</span>
+ ) : null}
+ </span>
+ )}
+
+ {/* Copy-full-value: for a truncated leaf the preview is not the whole
+ value, so offer to materialize + copy it on demand (never rendered
+ inline β€” that is the freeze we are avoiding). */}
+ {!isContainer && row.truncatedPreview ? (
+ <button
+ type="button"
+ aria-label="Copy full value"
+ title="Copy full value"
+ className="text-muted-foreground hover:text-foreground ml-1 shrink-0 opacity-0 group-hover:opacity-100"
+ onClick={() => onCopyValue(row.nodeId)}
+ >
+ <Copy className="h-3 w-3" />
+ </button>
+ ) : null}
+ </div>
+ );
+}
+
+/**
+ * Memoized: scrolling re-renders the virtualizer, but a row whose `row` object
+ * and callbacks are unchanged (guaranteed within a revision by the store) must
+ * not re-render. Callbacks are stable (bound to the store in the list).
+ */
+export const LazyJsonRow = React.memo(LazyJsonRowImpl);
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonViewer.tsx
new file mode 100644
index 0000000000..9afcaa9336
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonViewer.tsx
@@ -0,0 +1,95 @@
+/**
+ * LazyJsonViewer β€” the in-memory entry point to the lazy JSON renderer
+ * (LFE-11080).
+ *
+ * It owns the model lifecycle and gates render: build the async `RowModel` over
+ * the given value, show a fallback until it is ready, then mount the virtualized
+ * list. Everything below the seam (byte engine, tree flatten, pagination) is
+ * unchanged whether the value is a small parsed object here or a ~1 GB streamed
+ * payload behind a Worker later β€” the renderer is written once against the seam.
+ *
+ * The value β†’ model build is the single effect in this feature: it is an
+ * integration boundary (constructing and disposing an external async engine),
+ * with a cleanup, keyed on the document. All other work is store actions driven
+ * by user events, never effects.
+ */
+
+import React, { useEffect, useState } from "react";
+import { useStore } from "zustand";
+import Spinner from "@/src/components/design-system/Spinner/Spinner";
+import { cn } from "@/src/utils/tailwind";
+import { LazyJsonList } from "./LazyJsonList";
+import { createRowModelStore } from "./rowModelStore";
+import { TreeRowModel } from "../treeRowModel";
+import { sourceFromSerialized } from "../asyncJsonSource";
+
+export interface LazyJsonViewerProps {
+ /**
+ * The already-parsed JSON value to display. Must have a STABLE identity per
+ * document: re-init (rebuild + re-index) is keyed on `value` identity, so a
+ * caller that recreates it every render (inline `JSON.parse`, spread) would
+ * re-index on every parent render. Memoize it, or pass a stable reference.
+ * Provide EITHER `value` or `serialized`, and stick to one per mount.
+ */
+ value?: unknown;
+ /**
+ * The value's JSON serialization, when the caller already has it (e.g. a size
+ * probe serialized it for a download). Feeding it here skips a redundant
+ * second `JSON.stringify` of a large value. Same stable-identity contract.
+ */
+ serialized?: string;
+ className?: string;
+}
+
+export function LazyJsonViewer({
+ value,
+ serialized,
+ className,
+}: LazyJsonViewerProps) {
+ // Per-mount, view-scoped store (lazy init β€” created once, not per render).
+ // In `serialized` mode, build the engine from the existing JSON string; the
+ // document passed to init is that string (see below). `useState` reads props
+ // once on mount, which is fine: a given mount is one mode.
+ const usesSerialized = serialized !== undefined;
+ const [store] = useState(() =>
+ createRowModelStore(
+ usesSerialized
+ ? {
+ buildModel: (doc) =>
+ TreeRowModel.create(sourceFromSerialized(doc as string)),
+ }
+ : undefined,
+ ),
+ );
+
+ // The document identity re-init keys on: the serialized string, or the value.
+ const doc = usesSerialized ? serialized : value;
+
+ // Build the model over `doc`, and tear it down on unmount / doc change.
+ // This is the feature's only effect: an external-engine lifecycle boundary
+ // (construct + dispose an async engine, with cleanup), keyed on the document.
+ useEffect(() => {
+ store.getState().init(doc);
+ return () => store.getState().dispose();
+ // Re-run when the document identity changes; `store` is stable.
+ }, [store, doc]);
+
+ const status = useStore(store, (s) => s.status);
+ const error = useStore(store, (s) => s.error);
+
+ return (
+ <div className={cn("h-full w-full", className)}>
+ {status === "loading" ? (
+ <div className="flex h-full items-center justify-center">
+ <Spinner size="md" />
+ </div>
+ ) : status === "error" ? (
+ <div className="text-destructive flex h-full items-center justify-center p-4 text-sm">
+ Failed to read JSON: {error}
+ </div>
+ ) : (
+ <LazyJsonList store={store} />
+ )}
+ </div>
+ );
+}
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/react/README.md b/web/src/components/ui/AdvancedJsonViewer/lazy/react/README.md
new file mode 100644
index 0000000000..da752e061c
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/react/README.md
@@ -0,0 +1,32 @@
+# Lazy JSON renderer (`lazy/react/`)
+
+The React layer over the lazy JSON seam (`../rowModel.ts`). Built **once**
+against the async `RowModel`, so it renders an in-memory value today and a
+Worker-backed ~1 GB stream tomorrow with no change. See
+`../../LAZY_TREE_DESIGN.md` for the full engine→source→model→renderer picture.
+
+## Owner map
+
+| File | Role |
+| --- | --- |
+| `rowModelStore.ts` | Per-mount vanilla Zustand store. Owns the `RowModel` lifecycle and **all** async actions (`init`, `ensureRange`, `toggle`, `loadMore`, `materialize`, `dispose`). A generation token abandons work from a previous document or after teardown. This is where logic lives. |
+| `LazyJsonViewer.tsx` | Controller / in-memory entry. Creates the store, builds the model over `value` in the feature's **one** effect (an external-engine lifecycle boundary), and gates render (spinner β†’ list). |
+| `LazyJsonList.tsx` | Virtualized body (`@tanstack/react-virtual`). Positions row shells, reads rows from the store's per-revision cache, and reports the visible range back via the virtualizer's `onChange` β€” the external event that drives windowed loading. Owns no document state. |
+| `LazyJsonRow.tsx` | View-only row. Receives one `JsonRow` + stable callbacks; no state, no effects, no fetching. Memoized so scrolling never re-renders unchanged rows. |
+| `rowModelStore.clienttest.ts` | Pins the store contract: laziness, expand/collapse counts, pagination + load-more, revision bumps, materialize, async-race + error capture. |
+
+> No Storybook story: `LazyJsonViewer` is a full-height, value-driven viewer, so
+> it can't render "as it is" in a canvas without a layout decorator (which the
+> Storybook guide forbids), and a scale demo needs large fixtures (also
+> discouraged). Correctness is covered by the store client tests and the
+> integrated trace-view flow (JSON Beta over a large seeded trace).
+
+## Rules that keep it honest
+
+- The `RowModel` is the only thing the renderer knows; it never sees bytes/tree.
+- Cost is proportional to what is expanded/visible β€” never to total size. A row
+ carries only a bounded preview; the full value is fetched on demand.
+- Within one revision a visible row is immutable, so the store merges only
+ missing indices and scroll re-fetches never churn stable row objects.
+- Async responses are revision-stamped; a window resolved against a
+ since-mutated model is dropped.
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.clienttest.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.clienttest.ts
new file mode 100644
index 0000000000..390148fca9
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.clienttest.ts
@@ -0,0 +1,270 @@
+/**
+ * rowModelStore drives the async RowModel seam for the renderer. These tests
+ * pin the observable contract the virtualized list depends on: laziness (cost
+ * proportional to what's expanded, not to total size), expand/collapse row
+ * counts, wide-container pagination + load-more, revision bumps on structural
+ * change, and on-demand value materialization (LFE-11080).
+ */
+import { createRowModelStore } from "./rowModelStore";
+import { PAGE_SIZE } from "../treeRowModel";
+import type { JsonRow, RowModel, RowWindow } from "../rowModel";
+
+const visibleRows = (
+ store: ReturnType<typeof createRowModelStore>,
+): JsonRow[] => [...store.getState().rows.values()];
+
+const findRow = (
+ store: ReturnType<typeof createRowModelStore>,
+ keyOrIndex: string | number,
+): JsonRow | undefined =>
+ visibleRows(store).find((r) => r.keyOrIndex === keyOrIndex);
+
+describe("rowModelStore", () => {
+ it("becomes ready and shows the root expanded one level", async () => {
+ const store = createRowModelStore();
+ await store.getState().init({ a: 1, b: [10, 20, 30] });
+
+ expect(store.getState().status).toBe("ready");
+ // root object + its two members (b is a collapsed array).
+ expect(store.getState().totalVisible).toBe(3);
+
+ const b = findRow(store, "b");
+ expect(b?.type).toBe("array");
+ expect(b?.expandable).toBe(true);
+ expect(b?.expanded).toBe(false);
+ // Note: a collapsed nested container's childCount may be unknown until it
+ // is scanned (engine laziness), so we don't assert it here β€” see the
+ // expand test, where the expanded array's elements are all visible.
+ });
+
+ it("is lazy: a 5000-element array shows one page + a load-more row, not 5000", async () => {
+ const store = createRowModelStore();
+ const big = Array.from({ length: 5000 }, (_, i) => i);
+ await store.getState().init(big);
+
+ // root array (expanded) + first PAGE_SIZE children + one load-more row.
+ expect(store.getState().totalVisible).toBe(1 + PAGE_SIZE + 1);
+ const rows = visibleRows(store);
+ expect(rows[rows.length - 1]?.isLoadMore).toBe(true);
+ });
+
+ it("expand/collapse changes the visible count and bumps the revision", async () => {
+ const store = createRowModelStore();
+ await store.getState().init({ a: 1, b: [10, 20, 30] });
+ const revBefore = store.getState().revision;
+
+ const b = findRow(store, "b")!;
+ await store.getState().toggle(b.nodeId, false); // expand
+ expect(store.getState().totalVisible).toBe(6); // + 3 array elements
+ expect(store.getState().revision).toBeGreaterThan(revBefore);
+ // the three elements are now visible
+ expect(visibleRows(store).filter((r) => r.type === "number")).toHaveLength(
+ 4, // a:1 plus 10,20,30
+ );
+
+ await store.getState().toggle(b.nodeId, true); // collapse
+ expect(store.getState().totalVisible).toBe(3);
+ });
+
+ it("load-more reveals the next page and drops the load-more row when drained", async () => {
+ const store = createRowModelStore();
+ await store.getState().init(Array.from({ length: 150 }, (_, i) => i));
+
+ // one page + load-more
+ expect(store.getState().totalVisible).toBe(1 + PAGE_SIZE + 1);
+ const loadMore = visibleRows(store).find((r) => r.isLoadMore)!;
+ expect(loadMore).toBeDefined();
+
+ await store.getState().loadMore(loadMore.nodeId);
+ // all 150 now loaded, no more load-more row: root + 150.
+ expect(store.getState().totalVisible).toBe(1 + 150);
+ expect(visibleRows(store).some((r) => r.isLoadMore)).toBe(false);
+ });
+
+ it("materializes a leaf value on demand into the values cache", async () => {
+ const store = createRowModelStore();
+ await store.getState().init({ greeting: "hello world" });
+
+ const leaf = findRow(store, "greeting")!;
+ expect(store.getState().values.has(leaf.nodeId)).toBe(false);
+
+ await store.getState().materialize(leaf.nodeId);
+ const result = store.getState().values.get(leaf.nodeId);
+ expect(result?.ok).toBe(true);
+ if (result?.ok) expect(result.value.value).toBe("hello world");
+ });
+
+ it("abandons in-flight work after dispose (no state churn)", async () => {
+ const store = createRowModelStore();
+ await store.getState().init({ a: 1 });
+ const revBefore = store.getState().revision;
+
+ store.getState().dispose();
+ // A toggle after dispose must no-op (model released, generation bumped).
+ const a = { nodeId: 0, expanded: false } as JsonRow;
+ await store.getState().toggle(a.nodeId, false);
+ expect(store.getState().revision).toBe(revBefore);
+ });
+});
+
+// The in-process source resolves in one microtask, so it can't express the
+// async races the store must survive under a real Worker source. These use a
+// controllable model injected via `buildModel` to force out-of-order responses
+// and overlapping mutations.
+function makeRow(index: number): JsonRow {
+ return {
+ nodeId: index,
+ depth: 1,
+ keyOrIndex: index,
+ type: "number",
+ preview: `row-${index}`,
+ truncatedPreview: false,
+ expandable: false,
+ expanded: false,
+ };
+}
+
+function makeControllableModel(total: number) {
+ let revision = 0;
+ let gated = false;
+ const gatedCalls: Array<{ start: number; resolve: () => void }> = [];
+ let expandActive = 0;
+ let maxExpandConcurrency = 0;
+
+ const model: RowModel = {
+ getRevision: () => revision,
+ getTotalVisible: () => total,
+ getRows: (start, count) => {
+ const rows: JsonRow[] = [];
+ const n = Math.max(0, Math.min(count, total - start));
+ for (let k = 0; k < n; k++) rows.push(makeRow(start + k));
+ const win: RowWindow = { revision, rows };
+ if (!gated) return Promise.resolve(win);
+ return new Promise<RowWindow>((resolve) => {
+ gatedCalls.push({ start, resolve: () => resolve(win) });
+ });
+ },
+ expand: async () => {
+ expandActive += 1;
+ maxExpandConcurrency = Math.max(maxExpandConcurrency, expandActive);
+ await Promise.resolve();
+ revision += 1;
+ expandActive -= 1;
+ },
+ collapse: async () => {
+ revision += 1;
+ },
+ loadMore: async () => {
+ revision += 1;
+ },
+ getValue: async (nodeId) => ({
+ ok: true as const,
+ value: {
+ nodeId,
+ type: "number" as const,
+ value: nodeId,
+ lossyNumber: false,
+ truncated: false,
+ byteLength: 1,
+ },
+ }),
+ };
+
+ return {
+ model,
+ gate: () => {
+ gated = true;
+ },
+ resolveGated: (start: number) => {
+ const i = gatedCalls.findIndex((c) => c.start === start);
+ if (i >= 0) gatedCalls.splice(i, 1)[0]!.resolve();
+ },
+ getMaxExpandConcurrency: () => maxExpandConcurrency,
+ };
+}
+
+describe("rowModelStore async correctness", () => {
+ it("merges an out-of-order window at its OWN offset, not the latest requested", async () => {
+ const fake = makeControllableModel(10_000);
+ const store = createRowModelStore({ buildModel: async () => fake.model });
+ await store.getState().init(null); // prefetches [0,200) while ungated
+
+ fake.gate();
+ // Two overlapping requests for uncached ranges; the second moves the shared
+ // lastStart. Resolve the FIRST after the second was issued.
+ const pA = store.getState().ensureRange(300, 100);
+ const pB = store.getState().ensureRange(5000, 100);
+ fake.resolveGated(300);
+ fake.resolveGated(5000);
+ await Promise.all([pA, pB]);
+
+ expect(store.getState().rows.get(300)?.nodeId).toBe(300);
+ expect(store.getState().rows.get(5000)?.nodeId).toBe(5000);
+ // The 300-window must NOT have landed at index 5000.
+ expect(store.getState().rows.get(5000)?.nodeId).not.toBe(300);
+ });
+
+ it("serializes concurrent structural mutations (no double-page)", async () => {
+ const fake = makeControllableModel(10);
+ const store = createRowModelStore({ buildModel: async () => fake.model });
+ await store.getState().init(null);
+
+ // Fire two expands without awaiting the first β€” unserialized, both would be
+ // active at once (the reentrancy that double-pages children).
+ const t1 = store.getState().toggle(0, false);
+ const t2 = store.getState().toggle(1, false);
+ await Promise.all([t1, t2]);
+
+ expect(fake.getMaxExpandConcurrency()).toBe(1);
+ });
+
+ it("abandons a queued mutation across a document swap (stale nodeId not applied)", async () => {
+ // nodeIds restart per engine, so a mutation queued against document A must
+ // NOT run against document B after a swap β€” it would toggle an unrelated
+ // node. The generation is captured at ENQUEUE time to catch this.
+ const leaf = (over: Partial<RowModel>): RowModel => ({
+ getRevision: () => 0,
+ getTotalVisible: () => 2,
+ getRows: async () => ({ revision: 0, rows: [makeRow(0)] }),
+ expand: async () => {},
+ collapse: async () => {},
+ loadMore: async () => {},
+ getValue: async () => ({
+ ok: true as const,
+ value: {
+ nodeId: 0,
+ type: "number" as const,
+ value: 0,
+ lossyNumber: false,
+ truncated: false,
+ byteLength: 1,
+ },
+ }),
+ ...over,
+ });
+
+ let releaseM1!: () => void;
+ const bExpand = vi.fn(async () => {});
+ let call = 0;
+ const store = createRowModelStore({
+ buildModel: async () =>
+ call++ === 0
+ ? leaf({ expand: () => new Promise<void>((r) => (releaseM1 = r)) })
+ : leaf({ expand: bExpand }),
+ });
+ await store.getState().init(null); // document A
+
+ const m1 = store.getState().toggle(1, false); // holds the serialize queue
+ // Let m1 actually start (call A.expand and suspend) BEFORE the swap β€”
+ // otherwise init's synchronous gen bump would abandon m1 before it runs.
+ await new Promise((r) => setTimeout(r, 0));
+ const stale = store.getState().toggle(9, false); // queued behind m1, doc A
+ await store.getState().init(null); // swap to document B (gen bumped)
+ releaseM1(); // m1 resolves β†’ the queued stale mutation runs
+ await Promise.all([m1, stale]);
+
+ // The stale toggle targeted doc A's node 9; it must be abandoned, never
+ // applied to document B's engine.
+ expect(bExpand).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.ts
new file mode 100644
index 0000000000..b2333caa77
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.ts
@@ -0,0 +1,282 @@
+/**
+ * rowModelStore β€” the per-mount state owner for the lazy JSON renderer
+ * (LFE-11080).
+ *
+ * The renderer talks to a JSON document only through the async `RowModel` seam
+ * (revision-stamped windows, expand/collapse/load-more, on-demand value). That
+ * model is a mutable, imperative, genuinely-async system (a Worker tomorrow),
+ * so per the frontend-large-feature architecture it is owned OUTSIDE React by a
+ * view-scoped vanilla Zustand store:
+ *
+ * - The store creates and disposes the model (its lifecycle boundary).
+ * - All async work (build, expand, page, materialize) lives in store actions β€”
+ * plain async functions, never component effects.
+ * - Row views subscribe to narrow slices; the virtualizer only positions shells
+ * and reports the visible range back into `ensureRange`.
+ *
+ * Correctness under a REAL async source (the whole point) rests on three things:
+ * - each `ensureRange` merges at ITS OWN offset (captured locally), so a slow
+ * window resolving after a later one can't land at the wrong indices;
+ * - the seam's revision stamp drops a window resolved against a since-mutated
+ * model, and within one revision a visible row is immutable;
+ * - structural mutations (expand/collapse/load-more) are SERIALIZED, because the
+ * model's tree mutation is not reentrant β€” two concurrent expands would
+ * otherwise page in the same children twice.
+ */
+
+import { createStore, type StoreApi } from "zustand/vanilla";
+import { TreeRowModel } from "../treeRowModel";
+import { sourceFromValue } from "../asyncJsonSource";
+import type { JsonRow, RowModel, ValueResult } from "../rowModel";
+
+/** Rows fetched for the first paint before the virtualizer reports a range. */
+export const INITIAL_ROW_COUNT = 200;
+
+export type LoadStatus = "loading" | "ready" | "error";
+
+export interface RowModelState {
+ status: LoadStatus;
+ error: string | null;
+ /** Mirrors the model's revision; a bump re-renders the list and its rows. */
+ revision: number;
+ /** Currently-visible row count β€” the virtualizer's item count. */
+ totalVisible: number;
+ /** visible-index β†’ row, for the CURRENT revision (cleared on any mutation). */
+ rows: Map<number, JsonRow>;
+ /** nodeId β†’ materialized value (lazily populated by `materialize`). */
+ values: Map<number, ValueResult>;
+ /** nodeIds (or load-more ids) with an in-flight structural mutation. */
+ pending: Set<number>;
+
+ /** Build the model over an in-memory value and prefetch the first window. */
+ init: (value: unknown) => Promise<void>;
+ /** Ensure rows for `[start, start+count)` are cached (called on scroll). */
+ ensureRange: (start: number, count: number) => Promise<void>;
+ /** Expand or collapse a container, then refresh the visible window. */
+ toggle: (nodeId: number, currentlyExpanded: boolean) => Promise<void>;
+ /** Reveal the next page of a wide container (given its load-more row id). */
+ loadMore: (loadMoreId: number) => Promise<void>;
+ /** Materialize one node's full value on demand (result stored in `values`).
+ * `maxBytes` overrides the engine's default cap (e.g. copy needs the whole
+ * value, not the preview-sized default). */
+ materialize: (nodeId: number, maxBytes?: number) => Promise<void>;
+ /** Mark the store torn down so in-flight async work no-ops on resolve. */
+ dispose: () => void;
+}
+
+export type RowModelStore = StoreApi<RowModelState>;
+
+export interface RowModelStoreOptions {
+ /**
+ * How to build the model for a value. Defaults to the in-memory path
+ * (stringify β†’ byte engine β†’ TreeRowModel). The Worker-backed model for the
+ * streamed ~1 GB path will be injected here β€” the store and renderer do not
+ * change. Also the seam tests use to drive genuinely-async / out-of-order
+ * responses the in-process source cannot express.
+ */
+ buildModel?: (value: unknown) => Promise<RowModel>;
+}
+
+export function createRowModelStore(
+ options: RowModelStoreOptions = {},
+): RowModelStore {
+ const buildModel =
+ options.buildModel ??
+ ((value: unknown) => TreeRowModel.create(sourceFromValue(value)));
+ // Non-reactive internals live in the factory closure, not in store state:
+ // they must not trigger renders and must survive across actions.
+ let model: RowModel | null = null;
+ let lastStart = 0;
+ let lastCount = INITIAL_ROW_COUNT;
+ // Generation token. `init` (a fresh document) and `dispose` (unmount) both
+ // bump it; every async continuation checks it stayed current, so work from a
+ // previous document or from before teardown is abandoned on resolve. Unlike a
+ // permanent "disposed" flag, this lets the SAME store be re-`init`ed when the
+ // controller's value prop changes.
+ let gen = 0;
+ // Serializes structural mutations β€” see the class comment on reentrancy.
+ let mutationChain: Promise<void> = Promise.resolve();
+
+ return createStore<RowModelState>((set, get) => {
+ const setPending = (id: number, on: boolean) => {
+ const pending = new Set(get().pending);
+ if (on) pending.add(id);
+ else pending.delete(id);
+ set({ pending });
+ };
+
+ /** Run a structural mutation after any in-flight one completes. */
+ const serialize = (fn: () => Promise<void>): Promise<void> => {
+ const next = mutationChain.then(fn, fn);
+ // Keep the chain alive regardless of individual failures.
+ mutationChain = next.then(
+ () => undefined,
+ () => undefined,
+ );
+ return next;
+ };
+
+ /**
+ * After a structural mutation, re-read the model's cheap sync facts and
+ * drop the now-stale row cache, then re-fetch the last visible window so
+ * the list repaints against the new revision.
+ */
+ const refreshAfterMutation = async () => {
+ if (!model) return;
+ set({
+ revision: model.getRevision(),
+ totalVisible: model.getTotalVisible(),
+ rows: new Map(),
+ });
+ await get().ensureRange(lastStart, lastCount);
+ };
+
+ return {
+ status: "loading",
+ error: null,
+ revision: 0,
+ totalVisible: 0,
+ rows: new Map(),
+ values: new Map(),
+ pending: new Set(),
+
+ init: async (value) => {
+ const myGen = ++gen;
+ model = null;
+ set({
+ status: "loading",
+ error: null,
+ rows: new Map(),
+ values: new Map(),
+ pending: new Set(),
+ });
+ try {
+ const built = await buildModel(value);
+ if (gen !== myGen) return;
+ model = built;
+ // Publish the model's facts, but stay in "loading" until the first
+ // window is fetched, so the gate never drops the spinner onto empty
+ // shells under real (worker) latency.
+ set({
+ revision: built.getRevision(),
+ totalVisible: built.getTotalVisible(),
+ });
+ await get().ensureRange(0, INITIAL_ROW_COUNT);
+ if (gen !== myGen) return;
+ set({ status: "ready" });
+ } catch (e) {
+ if (gen !== myGen) return;
+ set({
+ status: "error",
+ error: e instanceof Error ? e.message : String(e),
+ });
+ }
+ },
+
+ ensureRange: async (start, count) => {
+ if (!model) return;
+ const myGen = gen;
+ // Capture THIS request's window locally. `lastStart`/`lastCount` are
+ // shared closure state (used to refetch after a mutation), and a
+ // concurrent ensureRange moves them β€” so the merge after the await must
+ // key off the offset this call actually fetched, never the shared one.
+ const s = Math.max(0, start);
+ const c = Math.max(0, count);
+ lastStart = s;
+ lastCount = c;
+ const end = s + c;
+
+ // Skip if every requested index is already cached at this revision.
+ const current = get().rows;
+ let hasGap = false;
+ for (let i = s; i < end; i++) {
+ if (!current.has(i)) {
+ hasGap = true;
+ break;
+ }
+ }
+ if (!hasGap) return;
+
+ const window = await model.getRows(s, c);
+ if (gen !== myGen) return;
+ // Drop a window whose revision no longer matches what we render. Within
+ // a revision a row is immutable, so an out-of-order same-revision window
+ // is safe to merge at its own offset below.
+ // NOTE: this drops a window from a NEWER revision too. That's correct
+ // for the current model (revision only advances via our own mutations,
+ // which refetch). A future self-advancing source (streaming append)
+ // would need to notify the store so it resyncs forward instead of
+ // dropping β€” a seam concern, out of scope here.
+ if (window.revision !== get().revision) return;
+
+ // Merge only missing indices: preserving existing objects keeps scroll
+ // re-fetches from re-rendering unchanged rows. Only allocate a new Map
+ // if something was added.
+ const existing = get().rows;
+ let nextRows: Map<number, JsonRow> | null = null;
+ window.rows.forEach((row, k) => {
+ const index = s + k;
+ if (!existing.has(index)) {
+ if (!nextRows) nextRows = new Map(existing);
+ nextRows.set(index, row);
+ }
+ });
+ if (nextRows) set({ rows: nextRows });
+ },
+
+ toggle: (nodeId, currentlyExpanded) => {
+ // Capture the generation NOW, at enqueue time β€” not inside the queued
+ // callback. nodeIds restart per engine, so if the document is swapped
+ // (init bumps gen, new model) while this mutation waits in the serialize
+ // queue, applying the stale nodeId to the new model would toggle an
+ // unrelated node. Abandon it instead.
+ const callGen = gen;
+ return serialize(async () => {
+ if (!model || gen !== callGen) return;
+ setPending(nodeId, true);
+ try {
+ if (currentlyExpanded) {
+ await model.collapse(nodeId);
+ } else {
+ await model.expand(nodeId);
+ }
+ if (gen !== callGen) return;
+ await refreshAfterMutation();
+ } finally {
+ if (gen === callGen) setPending(nodeId, false);
+ }
+ });
+ },
+
+ loadMore: (loadMoreId) => {
+ const callGen = gen;
+ return serialize(async () => {
+ if (!model || gen !== callGen) return;
+ setPending(loadMoreId, true);
+ try {
+ await model.loadMore(loadMoreId);
+ if (gen !== callGen) return;
+ await refreshAfterMutation();
+ } finally {
+ if (gen === callGen) setPending(loadMoreId, false);
+ }
+ });
+ },
+
+ materialize: async (nodeId, maxBytes) => {
+ if (!model) return;
+ const myGen = gen;
+ const result = await model.getValue(nodeId, maxBytes);
+ if (gen !== myGen) return;
+ const next = new Map(get().values);
+ next.set(nodeId, result);
+ set({ values: next });
+ },
+
+ dispose: () => {
+ gen++;
+ model = null;
+ },
+ };
+ });
+}
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/rowModel.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/rowModel.ts
new file mode 100644
index 0000000000..6d67b4a0ec
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/rowModel.ts
@@ -0,0 +1,93 @@
+/**
+ * RowModel β€” the renderer-facing seam for the lazy JSON viewer (LFE-11080).
+ *
+ * The virtualized viewer talks to a JSON document ONLY through this async
+ * contract: revision, total-visible count, a window of rows, expand/collapse,
+ * page-in a wide container, and materialize one value. It never sees the
+ * underlying bytes/tree β€” so the SAME renderer runs over the byte-indexer whether
+ * that engine lives on the main thread (in-memory payloads, fed as bytes) or in
+ * a Worker (the ~1 GB path). There is ONE tree/flatten implementation
+ * (`TreeRowModel`) over one child source (`AsyncJsonSource`).
+ *
+ * Hardening the review (LFE-11079 Fable pass) demanded before a renderer is
+ * built against this seam:
+ * - **revision**: every structural mutation bumps a counter, and `getRows`
+ * stamps its result, so a renderer can discard a row window that resolved
+ * against a since-mutated model (worker responses race expand/collapse).
+ * - **error envelope**: `getValue` returns a Result, never throws (malformed
+ * slices / unknown ids must not crash the UI).
+ * - **truncation passthrough**: a value capped by the engine's byte budget is
+ * reported as such, so the UI can offer "download full" instead of lying.
+ */
+
+import type { JsonNodeType, GetValueResult } from "./byteJsonIndex";
+
+export type { JsonNodeType };
+
+/**
+ * One visible line. Carries only a BOUNDED preview of its value β€” never the
+ * full value. The full value is fetched on demand via `getValue`.
+ */
+export interface JsonRow {
+ /** Stable id (engine nodeId β‰₯ 0; synthetic load-more rows use negative ids). */
+ nodeId: number;
+ depth: number;
+ /** Key in the parent: object property, array index, or null for the root. */
+ keyOrIndex: string | number | null;
+ type: JsonNodeType;
+ /** Immediate child count for containers (undefined for primitives/unknown). */
+ childCount?: number;
+ /** Bounded, display-ready preview of the value (from the engine). */
+ preview: string;
+ /** Whether the preview was cut short of the full value. */
+ truncatedPreview: boolean;
+ expandable: boolean;
+ expanded: boolean;
+ /** Synthetic "reveal next page" row for a paginated wide container. */
+ isLoadMore?: boolean;
+}
+
+/** A window of visible rows, stamped with the revision it was computed at. */
+export interface RowWindow {
+ revision: number;
+ rows: JsonRow[];
+}
+
+/** Result of materializing a value: never throws β€” errors are data. */
+export type ValueResult =
+ | { ok: true; value: GetValueResult }
+ | { ok: false; error: string };
+
+/**
+ * Async, source-agnostic model of the currently-visible rows of a JSON document.
+ * Cost stays proportional to what is expanded/visible, never to total size.
+ */
+export interface RowModel {
+ /** Monotonic counter; bumped on every structural mutation (expand/collapse/
+ * load-more). Compare against `RowWindow.revision` to detect stale reads. */
+ getRevision(): number;
+
+ /** Number of currently-visible rows (the virtualizer's row count). Cheap. */
+ getTotalVisible(): number;
+
+ /** The visible rows in `[start, start+count)`, stamped with the revision. */
+ getRows(start: number, count: number): Promise<RowWindow>;
+
+ /** Expand a container (materializes only its first page of children). */
+ expand(nodeId: number): Promise<void>;
+
+ /** Collapse a container (drops its visible descendants). */
+ collapse(nodeId: number): Promise<void>;
+
+ /** Reveal the next page of a paginated wide container, given the container's
+ * nodeId or its load-more row id. */
+ loadMore(nodeId: number): Promise<void>;
+
+ /**
+ * Materialize a single node's full value on demand (never throws).
+ * `maxBytes` caps how much of an oversized leaf is decoded (the engine's own
+ * default otherwise); a caller that needs the whole value (e.g. copy) passes
+ * a larger cap. The result still reports `truncated` if it hits the cap.
+ */
+ getValue(nodeId: number, maxBytes?: number): Promise<ValueResult>;
+}
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/treeRowModel.clienttest.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/treeRowModel.clienttest.ts
new file mode 100644
index 0000000000..cc3e7b500e
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/treeRowModel.clienttest.ts
@@ -0,0 +1,180 @@
+/**
+ * TreeRowModel is the single flatten/expand/paginate implementation, driven here
+ * over the real byte engine via `sourceFromValue` (stringify β†’ UTF-8 β†’ engine).
+ * It must keep cost proportional to what is expanded/visible, page wide
+ * containers, carry bounded previews, materialize values on demand, stamp reads
+ * with a revision, and never throw from getValue (LFE-11080, Fable-hardened).
+ */
+import { describe, it, expect } from "vitest";
+import { TreeRowModel, PAGE_SIZE } from "./treeRowModel";
+import { sourceFromValue } from "./asyncJsonSource";
+
+const model = (value: unknown) => TreeRowModel.create(sourceFromValue(value));
+const allRows = async (m: TreeRowModel) =>
+ (await m.getRows(0, m.getTotalVisible())).rows;
+const keys = (rows: { keyOrIndex: string | number | null }[]) =>
+ rows.map((r) => r.keyOrIndex);
+
+describe("TreeRowModel over the byte engine", () => {
+ it("expands only the root level; deeper containers stay collapsed", async () => {
+ const m = await model({ a: 1, b: { deep: { deeper: 1 } }, c: [1, 2] });
+ const rows = await allRows(m);
+ expect(keys(rows)).toEqual([null, "a", "b", "c"]);
+ expect(rows.find((r) => r.keyOrIndex === "b")).toMatchObject({
+ expandable: true,
+ expanded: false,
+ });
+ expect(rows.some((r) => r.keyOrIndex === "deep")).toBe(false);
+ });
+
+ it("expand materializes only that container's immediate children", async () => {
+ const m = await model({ b: { deep: { deeper: 1 } } });
+ const bId = (await allRows(m)).find((r) => r.keyOrIndex === "b")!.nodeId;
+ await m.expand(bId);
+ const rows = await allRows(m);
+ expect(rows.some((r) => r.keyOrIndex === "deep")).toBe(true);
+ expect(rows.some((r) => r.keyOrIndex === "deeper")).toBe(false);
+ });
+
+ it("collapse drops descendants; re-expand restores them (state preserved)", async () => {
+ const m = await model({ b: { deep: { x: 1 } } });
+ const bId = (await allRows(m)).find((r) => r.keyOrIndex === "b")!.nodeId;
+ await m.expand(bId);
+ const deepId = (await allRows(m)).find(
+ (r) => r.keyOrIndex === "deep",
+ )!.nodeId;
+ await m.expand(deepId); // expand two levels
+ expect((await allRows(m)).some((r) => r.keyOrIndex === "x")).toBe(true);
+
+ await m.collapse(bId);
+ expect(keys(await allRows(m))).toEqual([null, "b"]);
+
+ await m.expand(bId); // re-expand: deep AND its expanded child x return
+ const rows = await allRows(m);
+ expect(rows.some((r) => r.keyOrIndex === "deep")).toBe(true);
+ expect(rows.some((r) => r.keyOrIndex === "x")).toBe(true);
+ });
+
+ it("does NOT scan a huge collapsed container", async () => {
+ const huge = {
+ messages: Array.from({ length: 100_000 }, () => ({ role: "user" })),
+ };
+ const m = await model(huge);
+ expect(m.getTotalVisible()).toBe(2); // root + collapsed "messages"
+ });
+
+ it("paginates a wide container: first page + load-more, then the rest", async () => {
+ const wide = {
+ items: Array.from({ length: PAGE_SIZE + 50 }, (_, i) => i),
+ };
+ const m = await model(wide);
+ const itemsId = (await allRows(m)).find(
+ (r) => r.keyOrIndex === "items",
+ )!.nodeId;
+
+ await m.expand(itemsId);
+ let rows = await allRows(m);
+ expect(rows.filter((r) => typeof r.keyOrIndex === "number")).toHaveLength(
+ PAGE_SIZE,
+ );
+ const loadMore = rows.find((r) => r.isLoadMore)!;
+ expect(loadMore).toBeDefined();
+
+ await m.loadMore(loadMore.nodeId);
+ rows = await allRows(m);
+ expect(rows.filter((r) => typeof r.keyOrIndex === "number")).toHaveLength(
+ PAGE_SIZE + 50,
+ );
+ expect(rows.some((r) => r.isLoadMore)).toBe(false);
+ });
+
+ it("carries a bounded preview for a huge string; full value on demand", async () => {
+ const m = await model({ blob: "A".repeat(5_000_000) });
+ const blobRow = (await allRows(m)).find((r) => r.keyOrIndex === "blob")!;
+ expect(blobRow.truncatedPreview).toBe(true);
+ expect(blobRow.preview.length).toBeLessThanOrEqual(220); // bounded, not 5MB
+ const res = await m.getValue(blobRow.nodeId);
+ expect(res.ok).toBe(true);
+ if (res.ok) expect((res.value.value as string).length).toBe(5_000_000);
+ });
+
+ it("round-trips multibyte UTF-8 through the byte path", async () => {
+ const m = await model({ text: "πŸ˜€ CJK ζ–‡ε­— cafΓ©" });
+ const textRow = (await allRows(m)).find((r) => r.keyOrIndex === "text")!;
+ const res = await m.getValue(textRow.nodeId);
+ expect(res.ok).toBe(true);
+ if (res.ok) expect(res.value.value).toBe("πŸ˜€ CJK ζ–‡ε­— cafΓ©");
+ });
+
+ it("bumps revision on structural change and stamps row windows", async () => {
+ const m = await model({ a: { b: 1 } });
+ const before = m.getRevision();
+ const aId = (await m.getRows(0, m.getTotalVisible())).rows.find(
+ (r) => r.keyOrIndex === "a",
+ )!.nodeId;
+ await m.expand(aId);
+ expect(m.getRevision()).toBeGreaterThan(before);
+ const window = await m.getRows(0, m.getTotalVisible());
+ expect(window.revision).toBe(m.getRevision());
+ });
+
+ it("getValue never throws β€” returns an error envelope for bad ids", async () => {
+ const m = await model({ a: 1 });
+ expect(await m.getValue(-1)).toMatchObject({ ok: false }); // load-more id
+ expect(await m.getValue(999999)).toMatchObject({ ok: false }); // unknown id
+ });
+
+ it("refreshes a container's descriptor after scan (summary preview + count survives collapse)", async () => {
+ const m = await model({ obj: { a: 1, b: 2, c: 3 }, empty: {} });
+
+ // Symptom 1: an expanded container's OWN row shows a structural summary, not
+ // the stale pre-scan raw-JSON preview duplicating the child rows below it.
+ const objId = (await allRows(m)).find(
+ (r) => r.keyOrIndex === "obj",
+ )!.nodeId;
+ await m.expand(objId);
+ const objRow = (await allRows(m)).find((r) => r.keyOrIndex === "obj")!;
+ expect(objRow.preview).not.toContain('"a"'); // not the raw {"a":1,...}
+ expect(objRow.childCount).toBe(3);
+
+ // Symptom 2: an EMPTY container keeps its 0 count after expand→collapse.
+ // loadedCount stays 0 for an empty container, so the earlier
+ // `loadedCount > 0` fallback dropped the badge; the refreshed descriptor
+ // (childCount === 0) fixes it.
+ const emptyId = (await allRows(m)).find(
+ (r) => r.keyOrIndex === "empty",
+ )!.nodeId;
+ await m.expand(emptyId);
+ await m.collapse(emptyId);
+ const emptyRow = (await allRows(m)).find((r) => r.keyOrIndex === "empty")!;
+ expect(emptyRow.childCount).toBe(0);
+ });
+
+ it("re-expanding an empty container scans it only once", async () => {
+ // An empty {}/[] never pushes into childIds, so `childIds.length === 0`
+ // could not tell "never scanned" from "scanned and empty" β€” every re-expand
+ // would re-issue childrenPage. Harmless in-process (cached), but a wasted
+ // round-trip once the Worker source lands, so an explicit `scanned` flag
+ // guards the rescan. Count childrenPage calls per node to prove it.
+ const source = sourceFromValue({ empty: {} });
+ const scans = new Map<number, number>();
+ const origChildrenPage = source.childrenPage.bind(source);
+ source.childrenPage = (nodeId, offset, limit) => {
+ scans.set(nodeId, (scans.get(nodeId) ?? 0) + 1);
+ return origChildrenPage(nodeId, offset, limit);
+ };
+
+ const m = await TreeRowModel.create(source);
+ const emptyId = (await allRows(m)).find(
+ (r) => r.keyOrIndex === "empty",
+ )!.nodeId;
+
+ await m.expand(emptyId); // first scan
+ await m.collapse(emptyId);
+ await m.expand(emptyId); // must reuse the known-empty result, not rescan
+ await m.collapse(emptyId);
+ await m.expand(emptyId);
+
+ expect(scans.get(emptyId)).toBe(1);
+ });
+});
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/treeRowModel.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/treeRowModel.ts
new file mode 100644
index 0000000000..66fa466a02
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/treeRowModel.ts
@@ -0,0 +1,264 @@
+/**
+ * TreeRowModel β€” the ONE flatten/expand/paginate implementation (LFE-11080).
+ *
+ * Source-agnostic: it drives any `AsyncJsonSource` (the byte engine on the main
+ * thread today, a Worker tomorrow), so the virtualized renderer is built exactly
+ * once against this. Cost stays proportional to what is expanded/visible:
+ * - a container's children are fetched (paged) only when it is expanded;
+ * - a wide container reveals a first page plus a synthetic "load more" row;
+ * - the flattened visible list is rebuilt iteratively (deep-tree safe) only on
+ * structural change, and every change bumps `revision` so a renderer can drop
+ * a row window that resolved against a stale model.
+ */
+
+import type { NodeDescriptor } from "./byteJsonIndex";
+import type { AsyncJsonSource } from "./asyncJsonSource";
+import type { JsonRow, RowModel, RowWindow, ValueResult } from "./rowModel";
+
+/** Children fetched per expand / load-more. */
+export const PAGE_SIZE = 100;
+
+interface NodeState {
+ descriptor: NodeDescriptor;
+ depth: number;
+ keyOrIndex: string | number | null;
+ expandable: boolean;
+ expanded: boolean;
+ /**
+ * True once this container has been scanned at least once (its first page
+ * fetched). Distinguishes "never scanned" from "scanned and empty" β€” an empty
+ * `{}`/`[]` never pushes into `childIds`, so `childIds.length` cannot tell
+ * them apart, which would re-scan an empty container on every re-expand.
+ */
+ scanned: boolean;
+ /** Materialized child nodeIds, in order (grows as pages load). */
+ childIds: number[];
+ loadedCount: number;
+ total: number;
+ hasMore: boolean;
+ /** Synthetic negative id of this container's load-more row, when more remain. */
+ loadMoreId: number | null;
+}
+
+type VisibleEntry =
+ | { kind: "node"; nodeId: number }
+ | { kind: "loadMore"; ownerId: number; id: number };
+
+function keyOrIndexOf(d: NodeDescriptor): string | number | null {
+ if (d.key !== undefined) return d.key;
+ if (d.index !== undefined) return d.index;
+ return null;
+}
+
+export class TreeRowModel implements RowModel {
+ private readonly source: AsyncJsonSource;
+ private readonly states = new Map<number, NodeState>();
+ private readonly loadMoreOwner = new Map<number, number>();
+ private readonly rootId: number;
+ private revision = 0;
+ private nextLoadMoreId = -1; // synthetic load-more rows use negative ids
+ private visible: VisibleEntry[] = [];
+
+ private constructor(source: AsyncJsonSource) {
+ this.source = source;
+ const root = source.root;
+ this.rootId = root.nodeId;
+ this.states.set(root.nodeId, this.newState(root, 0, keyOrIndexOf(root)));
+ this.rebuildVisible();
+ }
+
+ /** Construct and expand the root one level (so the viewer isn't empty). */
+ static async create(source: AsyncJsonSource): Promise<TreeRowModel> {
+ const model = new TreeRowModel(source);
+ if (model.states.get(model.rootId)!.expandable) {
+ await model.expand(model.rootId);
+ }
+ return model;
+ }
+
+ private newState(
+ descriptor: NodeDescriptor,
+ depth: number,
+ keyOrIndex: string | number | null,
+ ): NodeState {
+ return {
+ descriptor,
+ depth,
+ keyOrIndex,
+ expandable: descriptor.expandable,
+ expanded: false,
+ scanned: false,
+ childIds: [],
+ loadedCount: 0,
+ total: descriptor.childCount ?? 0,
+ hasMore: false,
+ loadMoreId: null,
+ };
+ }
+
+ /** Fetch and register the next page of `state`'s children. */
+ private async loadPage(state: NodeState): Promise<void> {
+ const page = await this.source.childrenPage(
+ state.descriptor.nodeId,
+ state.loadedCount,
+ PAGE_SIZE,
+ );
+ for (const childDesc of page.children) {
+ if (!this.states.has(childDesc.nodeId)) {
+ this.states.set(
+ childDesc.nodeId,
+ this.newState(childDesc, state.depth + 1, keyOrIndexOf(childDesc)),
+ );
+ }
+ state.childIds.push(childDesc.nodeId);
+ }
+ state.loadedCount += page.children.length;
+ state.total = page.total;
+ state.hasMore = page.hasMore;
+ state.scanned = true;
+ // The container has now been scanned (childrenPage built its child table),
+ // so re-describe it. The descriptor captured pre-scan (from the parent's
+ // page) carries the raw-JSON preview and an unknown childCount; the
+ // refreshed one carries the Object(N)/Array(N) summary and the exact count
+ // (including 0 for an empty container) β€” so the row's preview isn't a stale
+ // duplicate of its own children, and the count badge survives a collapse.
+ state.descriptor = this.source.describe(state.descriptor.nodeId);
+ if (state.hasMore && state.loadMoreId === null) {
+ state.loadMoreId = this.nextLoadMoreId--;
+ this.loadMoreOwner.set(state.loadMoreId, state.descriptor.nodeId);
+ } else if (!state.hasMore && state.loadMoreId !== null) {
+ this.loadMoreOwner.delete(state.loadMoreId);
+ state.loadMoreId = null;
+ }
+ }
+
+ /** Rebuild the flattened visible list β€” iterative pre-order (deep-tree safe). */
+ private rebuildVisible(): void {
+ const out: VisibleEntry[] = [];
+ type Frame =
+ | { kind: "node"; nodeId: number }
+ | { kind: "loadMore"; ownerId: number };
+ const stack: Frame[] = [{ kind: "node", nodeId: this.rootId }];
+ while (stack.length > 0) {
+ const frame = stack.pop()!;
+ if (frame.kind === "loadMore") {
+ const owner = this.states.get(frame.ownerId)!;
+ out.push({
+ kind: "loadMore",
+ ownerId: frame.ownerId,
+ id: owner.loadMoreId!,
+ });
+ continue;
+ }
+ const state = this.states.get(frame.nodeId);
+ if (!state) continue;
+ out.push({ kind: "node", nodeId: frame.nodeId });
+ if (state.expandable && state.expanded) {
+ // Push in reverse so children pop in order, with the load-more marker
+ // (pushed first β†’ popped last) landing after all children.
+ if (state.loadMoreId !== null) {
+ stack.push({ kind: "loadMore", ownerId: frame.nodeId });
+ }
+ for (let i = state.childIds.length - 1; i >= 0; i--) {
+ stack.push({ kind: "node", nodeId: state.childIds[i]! });
+ }
+ }
+ }
+ this.visible = out;
+ }
+
+ private toRow(entry: VisibleEntry): JsonRow {
+ if (entry.kind === "loadMore") {
+ const owner = this.states.get(entry.ownerId)!;
+ const remaining = Math.max(0, owner.total - owner.loadedCount);
+ return {
+ nodeId: entry.id,
+ depth: owner.depth + 1,
+ keyOrIndex: null,
+ type: "null",
+ preview: `Show ${remaining} more…`,
+ truncatedPreview: false,
+ expandable: false,
+ expanded: false,
+ isLoadMore: true,
+ };
+ }
+ const state = this.states.get(entry.nodeId)!;
+ const d = state.descriptor;
+ return {
+ nodeId: entry.nodeId,
+ depth: state.depth,
+ keyOrIndex: state.keyOrIndex,
+ type: d.type,
+ // `d` is refreshed post-scan (see loadPage), so `d.childCount` is the
+ // exact count after a container has been expanded β€” including 0 for an
+ // empty one β€” and the badge survives a collapse. Before any scan it's the
+ // parent-provided count (or undefined).
+ childCount: state.expandable
+ ? state.expanded
+ ? state.total
+ : d.childCount
+ : undefined,
+ preview: d.preview,
+ truncatedPreview: d.truncatedPreview,
+ expandable: state.expandable,
+ expanded: state.expanded,
+ };
+ }
+
+ getRevision(): number {
+ return this.revision;
+ }
+
+ getTotalVisible(): number {
+ return this.visible.length;
+ }
+
+ async getRows(start: number, count: number): Promise<RowWindow> {
+ const s = Math.max(0, start);
+ const rows = this.visible
+ .slice(s, s + Math.max(0, count))
+ .map((e) => this.toRow(e));
+ return { revision: this.revision, rows };
+ }
+
+ async expand(nodeId: number): Promise<void> {
+ const state = this.states.get(nodeId);
+ if (!state || !state.expandable || state.expanded) return;
+ if (!state.scanned) await this.loadPage(state);
+ state.expanded = true;
+ this.revision++;
+ this.rebuildVisible();
+ }
+
+ async collapse(nodeId: number): Promise<void> {
+ const state = this.states.get(nodeId);
+ if (!state || !state.expanded) return;
+ // Keep childIds/loadedCount so re-expand restores sub-expansion + progress.
+ state.expanded = false;
+ this.revision++;
+ this.rebuildVisible();
+ }
+
+ async loadMore(loadMoreOrNodeId: number): Promise<void> {
+ const ownerId =
+ this.loadMoreOwner.get(loadMoreOrNodeId) ?? loadMoreOrNodeId;
+ const state = this.states.get(ownerId);
+ if (!state || !state.expandable || !state.hasMore) return;
+ await this.loadPage(state);
+ this.revision++;
+ this.rebuildVisible();
+ }
+
+ async getValue(nodeId: number, maxBytes?: number): Promise<ValueResult> {
+ if (nodeId < 0) {
+ return { ok: false, error: "load-more row has no value" };
+ }
+ try {
+ const value = await this.source.getValue(nodeId, maxBytes);
+ return { ok: true, value };
+ } catch (e) {
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
+ }
+ }
+}