Skip to content

The Open Standard for Generative UI

Add the OpenUI Debug (#1005)

AB8e5b3e193ee1
diff --git a/packages/devtools/package.json b/packages/devtools/package.json
index 468753a1b..19903e42b 100644
--- a/packages/devtools/package.json
+++ b/packages/devtools/package.json
@@ -1,6 +1,6 @@
{
"name": "@openuidev/devtools",
- "version": "0.0.6",
+ "version": "0.0.7",
"description": "Development-only UI widget for OpenUI apps: surfaces errors captured by @openuidev/observability",
"license": "MIT",
"type": "module",
@@ -41,9 +41,15 @@
},
"peerDependencies": {
"@openuidev/observability": "workspace:^",
+ "@openuidev/react-lang": "workspace:^",
"react": "catalog:",
"react-dom": "catalog:"
},
+ "peerDependenciesMeta": {
+ "@openuidev/react-lang": {
+ "optional": true
+ }
+ },
"keywords": [
"openui",
"devtools",
@@ -64,6 +70,7 @@
"author": "[email protected]",
"devDependencies": {
"@openuidev/observability": "workspace:^",
+ "@openuidev/react-lang": "workspace:^",
"@types/node": "catalog:",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
diff --git a/packages/devtools/src/debug/DebugUI.tsx b/packages/devtools/src/debug/DebugUI.tsx
new file mode 100644
index 000000000..6c1d73459
--- /dev/null
+++ b/packages/devtools/src/debug/DebugUI.tsx
@@ -0,0 +1,441 @@
+import { Maximize2, Minimize2, X } from "lucide-react";
+import { Component, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
+import { type RegisteredLibrary } from "../lib";
+import {
+ FONT,
+ rootStyle,
+ useDevtoolsMode,
+ useTheme,
+ type ColorMode,
+ type ThemeTokens,
+} from "../theme";
+import { IconButton, ThemeToggle } from "../ui";
+import { librarySchema, useReactLang, useStream, useValidation } from "./lib";
+import { JsonPanel, RenderPanel, StreamTimeline, TreePanel, ValidationPanel } from "./panels";
+import { debugStyles } from "./styles";
+import { HelpDialog, LangEditor, StreamToolbar } from "./ui";
+
+/** Editor's share of the split, as a percentage. The panels get the rest. */
+export const DEFAULT_EDITOR_PCT = 25;
+export const MIN_EDITOR_PCT = 12;
+export const MAX_EDITOR_PCT = 75;
+const SPLITTER = 14;
+
+type Tab = "render" | "validation" | "tree" | "json" | "stream";
+
+const TABS: { id: Tab; label: string }[] = [
+ { id: "render", label: "Render" },
+ { id: "validation", label: "Validation" },
+ { id: "tree", label: "Tree" },
+ { id: "json", label: "JSON" },
+ { id: "stream", label: "Stream" },
+];
+
+class DebugErrorBoundary extends Component<{ children: ReactNode }, { error: Error | null }> {
+ constructor(props: { children: ReactNode }) {
+ super(props);
+ this.state = { error: null };
+ }
+
+ static getDerivedStateFromError(error: Error) {
+ return { error };
+ }
+
+ override componentDidUpdate(prevProps: { children: ReactNode }) {
+ if (this.state.error && prevProps.children !== this.props.children) {
+ this.setState({ error: null });
+ }
+ }
+
+ override render() {
+ if (this.state.error) {
+ return <div style={{ padding: 16, fontSize: 12 }}>{this.state.error.message}</div>;
+ }
+ return this.props.children;
+ }
+}
+
+export interface DebugUIProps {
+ libraries: RegisteredLibrary[];
+ code: string;
+ onCodeChange: (code: string) => void;
+ ejected?: boolean;
+ onEject?: () => void;
+ /** Returns an ejected window to the tray. */
+ onMinimize?: () => void;
+ /** Dismisses the whole widget (or the ejected window). */
+ onClose: () => void;
+ theme: ColorMode;
+ onThemeChange: (theme: ColorMode) => void;
+ /** False on the first ever visit, which opens the help guide unprompted. */
+ helpSeen?: boolean;
+ onHelpSeen?: () => void;
+ popupBlocked?: boolean;
+ /** Editor column width. Lifted so ejecting to a window keeps the same split. */
+ editorPct?: number;
+ onEditorPctChange?: (pct: number) => void;
+ /** `createLibrary()` instance id from the stream that opened Debug. */
+ libraryId?: string;
+}
+
+function pickLibrary(
+ libraries: RegisteredLibrary[],
+ libraryId?: string,
+): RegisteredLibrary | undefined {
+ if (libraryId) {
+ const byId = libraries.find((entry) => entry.library.__libraryId === libraryId);
+ if (byId) return byId;
+ }
+ return libraries[0];
+}
+
+export function DebugUI({
+ libraries,
+ code,
+ onCodeChange,
+ ejected = false,
+ onEject,
+ onMinimize,
+ onClose,
+ theme,
+ onThemeChange,
+ helpSeen = true,
+ onHelpSeen,
+ popupBlocked = false,
+ editorPct: editorPctProp,
+ onEditorPctChange,
+ libraryId,
+}: DebugUIProps) {
+ const selected = pickLibrary(libraries, libraryId);
+ const lang = useReactLang();
+ const schema = useMemo(() => librarySchema(selected?.library), [selected]);
+ const rootName = selected?.library.root;
+ const outcome = useValidation(code, lang, schema, rootName);
+ const stream = useStream({ code, lang, schema, rootName, outcome });
+ const [tab, setTab] = useState<Tab>("render");
+ const [editorPctState, setEditorPctState] = useState(editorPctProp ?? DEFAULT_EDITOR_PCT);
+ const editorPct = editorPctProp ?? editorPctState;
+ const setEditorPct = (pct: number) => {
+ setEditorPctState(pct);
+ onEditorPctChange?.(pct);
+ };
+ const [resizing, setResizing] = useState(false);
+ const [splitHover, setSplitHover] = useState(false);
+ const bodyRef = useRef<HTMLDivElement>(null);
+ const mode = useDevtoolsMode();
+ const t = useTheme();
+ const debug = debugStyles(t);
+ const styles = shellStyles(t);
+
+ const clampPct = (pct: number) => Math.min(MAX_EDITOR_PCT, Math.max(MIN_EDITOR_PCT, pct));
+
+ // Listeners go on the captured handle, not on `window` — when Debug is
+ // ejected the tray is portaled into the popup's document, and the
+ // module-scope window never sees those pointer events. Pointer capture also
+ // keeps the drag alive once the cursor leaves the handle.
+ const startResize = (event: React.PointerEvent<HTMLDivElement>) => {
+ const body = bodyRef.current;
+ if (!body) return;
+ const handle = event.currentTarget;
+ handle.setPointerCapture(event.pointerId);
+ setResizing(true);
+
+ const onMove = (move: PointerEvent) => {
+ const bounds = body.getBoundingClientRect();
+ if (bounds.width === 0) return;
+ setEditorPct(clampPct(((move.clientX - bounds.left) / bounds.width) * 100));
+ };
+ const onEnd = () => {
+ setResizing(false);
+ handle.removeEventListener("pointermove", onMove);
+ handle.removeEventListener("pointerup", onEnd);
+ handle.removeEventListener("pointercancel", onEnd);
+ };
+
+ handle.addEventListener("pointermove", onMove);
+ handle.addEventListener("pointerup", onEnd);
+ handle.addEventListener("pointercancel", onEnd);
+ };
+
+ const changeCode = (next: string) => {
+ stream.prepareEdit();
+ onCodeChange(next);
+ };
+
+ return (
+ <div style={{ ...styles.shell, ...rootStyle(mode) }}>
+ <div style={styles.header}>
+ <div style={styles.headerLeft}>
+ <span style={styles.title}>OpenUI Debug</span>
+ </div>
+ <div style={styles.headerActions}>
+ <HelpDialog defaultOpen={!helpSeen} onSeen={onHelpSeen} />
+ <ThemeToggle value={theme} onChange={onThemeChange} />
+ {!ejected && onEject ? (
+ <IconButton onClick={onEject} aria-label="Open OpenUI Debug in a new window">
+ <Maximize2 size={14} />
+ </IconButton>
+ ) : null}
+ {ejected && onMinimize ? (
+ <IconButton onClick={onMinimize} aria-label="Return OpenUI Debug to the tray">
+ <Minimize2 size={14} />
+ </IconButton>
+ ) : null}
+ <IconButton
+ onClick={onClose}
+ aria-label={ejected ? "Close OpenUI Debug window" : "Close OpenUI Debug"}
+ >
+ <X size={15} />
+ </IconButton>
+ </div>
+ </div>
+ {popupBlocked ? (
+ <div style={styles.banner}>Allow popups for this origin to eject OpenUI Debug.</div>
+ ) : null}
+ <StreamToolbar
+ playback={stream.playback}
+ settings={stream.settings}
+ bigInput={stream.bigInput}
+ disabled={stream.disabled}
+ />
+ <div
+ ref={bodyRef}
+ style={{
+ ...styles.body,
+ gridTemplateColumns: `${editorPct}% ${SPLITTER}px minmax(0, 1fr)`,
+ }}
+ >
+ <div style={styles.editorWrap}>
+ <LangEditor value={code} onChange={changeCode} readOnly={stream.active} />
+ {stream.active ? <span style={debug.editorLock}>Streaming…</span> : null}
+ </div>
+ <div
+ style={styles.splitter}
+ onPointerDown={startResize}
+ onMouseEnter={() => setSplitHover(true)}
+ onMouseLeave={() => setSplitHover(false)}
+ onKeyDown={(event) => {
+ if (event.key === "ArrowLeft") setEditorPct(clampPct(editorPct - 2));
+ if (event.key === "ArrowRight") setEditorPct(clampPct(editorPct + 2));
+ }}
+ role="separator"
+ aria-orientation="vertical"
+ aria-label="Resize editor"
+ aria-valuenow={Math.round(editorPct)}
+ aria-valuemin={MIN_EDITOR_PCT}
+ aria-valuemax={MAX_EDITOR_PCT}
+ tabIndex={0}
+ >
+ <span
+ style={{
+ ...styles.splitterLine,
+ ...(splitHover || resizing ? styles.splitterLineOn : null),
+ }}
+ aria-hidden
+ />
+ <span
+ style={{
+ ...styles.splitterGrip,
+ ...(splitHover || resizing ? styles.splitterGripOn : null),
+ }}
+ aria-hidden
+ >
+ <span style={styles.splitterDot} />
+ <span style={styles.splitterDot} />
+ <span style={styles.splitterDot} />
+ </span>
+ </div>
+ <div style={styles.output}>
+ <div style={debug.tabStrip} role="tablist" aria-label="Debug panels">
+ {TABS.map((item) => {
+ const label =
+ item.id === "validation" && stream.displayed.result
+ ? `${item.label} (${stream.displayed.result.meta.errors.length})`
+ : item.label;
+ const active = tab === item.id;
+ return (
+ <button
+ key={item.id}
+ role="tab"
+ aria-selected={active}
+ style={{ ...debug.tab, ...(active ? debug.tabActive : null) }}
+ onClick={() => setTab(item.id)}
+ >
+ {label}
+ </button>
+ );
+ })}
+ </div>
+ <div style={styles.tabBody}>
+ {lang === undefined ? (
+ <div style={styles.missing}>Loading renderer…</div>
+ ) : lang === null ? (
+ <div style={styles.missing}>
+ Install <code>@openuidev/react-lang</code> to use OpenUI Debug.
+ </div>
+ ) : selected ? (
+ <>
+ {tab === "render" ? (
+ <div style={{ ...styles.tabPanel, display: "flex" }}>
+ <DebugErrorBoundary>
+ <RenderPanel
+ Renderer={lang.Renderer}
+ library={selected.library}
+ code={stream.renderedCode}
+ isStreaming={stream.isStreaming}
+ />
+ </DebugErrorBoundary>
+ </div>
+ ) : null}
+ {tab === "validation" ? <ValidationPanel outcome={stream.displayed} /> : null}
+ {tab === "tree" ? <TreePanel result={stream.displayed.result} /> : null}
+ {tab === "json" ? <JsonPanel result={stream.displayed.result} /> : null}
+ {tab === "stream" ? <StreamTimeline state={stream.state} /> : null}
+ </>
+ ) : (
+ <div style={styles.missing}>No library registered.</div>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function shellStyles(t: ThemeTokens) {
+ return {
+ shell: {
+ display: "flex",
+ flexDirection: "column",
+ height: "100%",
+ minHeight: 0,
+ background: t.bg,
+ color: t.fg,
+ fontFamily: FONT,
+ fontSize: 13,
+ position: "relative",
+ },
+ header: {
+ display: "flex",
+ justifyContent: "space-between",
+ alignItems: "center",
+ gap: 8,
+ padding: "12px 16px",
+ fontWeight: 600,
+ fontSize: 14,
+ },
+ headerLeft: {
+ display: "flex",
+ alignItems: "center",
+ gap: 10,
+ minWidth: 0,
+ },
+ title: {
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ },
+ headerActions: {
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ flexShrink: 0,
+ },
+ banner: {
+ padding: "8px 16px",
+ background: t.warningBg,
+ color: t.warningStrong,
+ fontSize: 12,
+ borderBottom: `1px solid ${t.warningBorder}`,
+ },
+ // Columns are set inline so the drag can move them.
+ body: {
+ flex: 1,
+ minHeight: 0,
+ display: "grid",
+ },
+ // A hairline that reads as a divider, inside a wider transparent strip so
+ // it is still easy to grab. The handle only shows once you are on it.
+ splitter: {
+ position: "relative",
+ cursor: "col-resize",
+ background: "transparent",
+ touchAction: "none",
+ },
+ splitterLine: {
+ position: "absolute",
+ top: 0,
+ bottom: 0,
+ left: 0,
+ width: 1,
+ background: t.borderSubtle,
+ transition: "width 150ms ease, background 150ms ease",
+ pointerEvents: "none",
+ },
+ splitterLineOn: {
+ width: 3,
+ background: t.borderStrong,
+ },
+ // Thin rounded chip with three stacked dots, centred on the divider.
+ splitterGrip: {
+ position: "absolute",
+ top: "50%",
+ left: 0,
+ transform: "translate(-50%, -50%)",
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ justifyContent: "center",
+ gap: 3,
+ boxSizing: "border-box",
+ width: 11,
+ height: 30,
+ borderRadius: 999,
+ border: `1px solid ${t.controlBorder}`,
+ background: t.controlBg,
+ opacity: 0,
+ transition: "opacity 150ms ease",
+ pointerEvents: "none",
+ },
+ splitterGripOn: {
+ opacity: 1,
+ },
+ splitterDot: {
+ width: 2,
+ height: 2,
+ borderRadius: "50%",
+ background: t.fg,
+ },
+ editorWrap: {
+ position: "relative",
+ minWidth: 0,
+ minHeight: 0,
+ overflow: "hidden",
+ },
+ output: {
+ display: "flex",
+ flexDirection: "column",
+ minWidth: 0,
+ minHeight: 0,
+ background: t.bg,
+ },
+ tabBody: {
+ flex: 1,
+ minHeight: 0,
+ display: "flex",
+ flexDirection: "column",
+ overflow: "hidden",
+ },
+ tabPanel: {
+ flex: 1,
+ minHeight: 0,
+ overflow: "hidden",
+ flexDirection: "column",
+ },
+ missing: {
+ color: t.fgFaint,
+ padding: 16,
+ fontSize: 12,
+ },
+ } satisfies Record<string, CSSProperties>;
+}
diff --git a/packages/devtools/src/debug/eject.ts b/packages/devtools/src/debug/eject.ts
new file mode 100644
index 000000000..0ec064cbd
--- /dev/null
+++ b/packages/devtools/src/debug/eject.ts
@@ -0,0 +1,65 @@
+const WINDOW_NAME = "openui-debug";
+const ROOT_ID = "openui-debug-root";
+
+export function debugMountNode(popup: Window): HTMLElement | null {
+ return popup.document.getElementById(ROOT_ID);
+}
+
+/**
+ * Open (or focus) a named same-origin window and copy host styles into it.
+ * Must run inside a click handler. Do not pass `noopener` — we need the Window.
+ */
+export function openDebugWindow(): Window | null {
+ if (typeof window === "undefined") return null;
+ const width = Math.max(640, Math.min(window.screen?.availWidth ?? 1280, 1600));
+ const height = Math.max(480, Math.min(window.screen?.availHeight ?? 800, 1000));
+ const popup = window.open("", WINDOW_NAME, `popup=yes,width=${width},height=${height}`);
+ if (!popup) return null;
+ prepareDebugDocument(document, popup.document);
+ popup.focus();
+ return popup;
+}
+
+function prepareDebugDocument(from: Document, to: Document): void {
+ if (to.documentElement.dataset["openuiDebug"] === "true") return;
+ to.documentElement.dataset["openuiDebug"] = "true";
+ to.title = "OpenUI Debug";
+ // Mirror the host's root classes/attrs/color-scheme so the rendered preview
+ // resolves the same CSS it would in the app. Devtools UI is unaffected —
+ // it uses the mode chosen in Settings.
+ to.documentElement.className = from.documentElement.className;
+ to.body.className = from.body.className;
+ copyAttributes(from.documentElement, to.documentElement);
+ copyAttributes(from.body, to.body);
+ const colorScheme = getComputedStyle(from.documentElement).colorScheme;
+ if (colorScheme) to.documentElement.style.colorScheme = colorScheme;
+
+ for (const node of from.head.querySelectorAll("link[rel='stylesheet'], style")) {
+ to.head.appendChild(node.cloneNode(true));
+ }
+
+ const fromSheets = from.adoptedStyleSheets;
+ if (fromSheets && fromSheets.length > 0) {
+ try {
+ to.adoptedStyleSheets = [...fromSheets];
+ } catch {
+ // Some browsers reject cross-document adoptedStyleSheets.
+ }
+ }
+
+ to.documentElement.style.height = "100%";
+ to.body.style.margin = "0";
+ to.body.style.height = "100%";
+
+ const root = to.createElement("div");
+ root.id = ROOT_ID;
+ root.style.height = "100%";
+ to.body.appendChild(root);
+}
+
+function copyAttributes(from: Element, to: Element): void {
+ for (const attr of from.attributes) {
+ if (attr.name === "class") continue;
+ to.setAttribute(attr.name, attr.value);
+ }
+}
diff --git a/packages/devtools/src/debug/index.ts b/packages/devtools/src/debug/index.ts
new file mode 100644
index 000000000..2a9bda496
--- /dev/null
+++ b/packages/devtools/src/debug/index.ts
@@ -0,0 +1,8 @@
+export {
+ DEFAULT_EDITOR_PCT,
+ DebugUI,
+ MAX_EDITOR_PCT,
+ MIN_EDITOR_PCT,
+ type DebugUIProps,
+} from "./DebugUI";
+export { debugMountNode, openDebugWindow } from "./eject";
diff --git a/packages/devtools/src/debug/lib/chunker.ts b/packages/devtools/src/debug/lib/chunker.ts
new file mode 100644
index 000000000..cc26cfacd
--- /dev/null
+++ b/packages/devtools/src/debug/lib/chunker.ts
@@ -0,0 +1,52 @@
+export interface StreamChunk {
+ text: string;
+ delayMs: number;
+}
+
+export type ChunkStrategy = "24" | "line" | "char" | "llm";
+
+export const CHUNK_STRATEGIES: { id: ChunkStrategy; label: string }[] = [
+ { id: "llm", label: "LLM-like" },
+ { id: "24", label: "24 chars" },
+ { id: "line", label: "Per line" },
+ { id: "char", label: "Per char" },
+];
+
+export function mulberry32(seed: number): () => number {
+ let a = seed >>> 0;
+ return () => {
+ a |= 0;
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+export function splitChunks(source: string, spec: ChunkStrategy, rng: () => number): StreamChunk[] {
+ if (spec === "llm") {
+ const chunks: StreamChunk[] = [];
+ let i = 0;
+ while (i < source.length) {
+ const len = rng() < 0.8 ? 1 + Math.floor(rng() * 12) : 13 + Math.floor(rng() * 48);
+ const text = source.slice(i, i + len);
+ i += text.length;
+ const r = rng();
+ const delayMs =
+ r < 0.15 ? 0 : r < 0.9 ? 5 + Math.floor(rng() * 75) : 200 + Math.floor(rng() * 400);
+ chunks.push({ text, delayMs });
+ }
+ return chunks;
+ }
+ if (spec === "line") {
+ return source
+ .split(/(?<=\n)/)
+ .filter((s) => s.length > 0)
+ .map((text) => ({ text, delayMs: 0 }));
+ }
+ const n = spec === "char" ? 1 : Math.max(1, parseInt(spec, 10) || 24);
+ const chunks: StreamChunk[] = [];
+ for (let i = 0; i < source.length; i += n)
+ chunks.push({ text: source.slice(i, i + n), delayMs: 0 });
+ return chunks;
+}
diff --git a/packages/devtools/src/debug/lib/index.ts b/packages/devtools/src/debug/lib/index.ts
new file mode 100644
index 000000000..3ebebd5b6
--- /dev/null
+++ b/packages/devtools/src/debug/lib/index.ts
@@ -0,0 +1,27 @@
+export { CHUNK_STRATEGIES, mulberry32, splitChunks } from "./chunker";
+export type { ChunkStrategy, StreamChunk } from "./chunker";
+export { createMockToolProvider } from "./mockTools";
+export type { MockToolCall } from "./mockTools";
+export {
+ EMPTY_OUTCOME,
+ KNOWN_ERROR_CODES,
+ groupByCode,
+ librarySchema,
+ runValidation,
+} from "./parse";
+export type {
+ ElementNode,
+ LangModule,
+ LibrarySchema,
+ OpenUIError,
+ ParseResult,
+ StreamParser,
+ ValidationError,
+ ValidationOutcome,
+} from "./types";
+export { usePlayback } from "./usePlayback";
+export type { PlaybackControls, PlaybackState, PlaybackStatus, TraceRow } from "./usePlayback";
+export { loadReactLang, useReactLang } from "./useReactLang";
+export { useStream } from "./useStream";
+export type { StreamSettings } from "./useStream";
+export { useValidation } from "./useValidation";
diff --git a/packages/devtools/src/debug/lib/mockTools.ts b/packages/devtools/src/debug/lib/mockTools.ts
new file mode 100644
index 000000000..b7f5cb879
--- /dev/null
+++ b/packages/devtools/src/debug/lib/mockTools.ts
@@ -0,0 +1,31 @@
+const CANNED_RESULT = {
+ status: "ok",
+ note: "Mock response from OpenUI Debug — tools are not connected.",
+ items: [
+ { id: 1, label: "Alpha", value: 42 },
+ { id: 2, label: "Beta", value: 17 },
+ { id: 3, label: "Gamma", value: 8 },
+ ],
+};
+
+export interface MockToolCall {
+ tool: string;
+ args: Record<string, unknown>;
+ at: number;
+}
+
+const RESERVED = new Set(["callTool", "then", "toJSON", "constructor"]);
+
+export function createMockToolProvider(onCall?: (call: MockToolCall) => void) {
+ return new Proxy({} as Record<string, (args: Record<string, unknown>) => Promise<unknown>>, {
+ get: (_target, prop) => {
+ if (typeof prop !== "string" || RESERVED.has(prop)) return undefined;
+ return async (args: Record<string, unknown>) => {
+ onCall?.({ tool: prop, args, at: Date.now() });
+ await new Promise((r) => setTimeout(r, 400));
+ return { ...CANNED_RESULT, tool: prop, receivedArgs: args };
+ };
+ },
+ has: (_target, prop) => typeof prop === "string" && !RESERVED.has(prop),
+ });
+}
diff --git a/packages/devtools/src/debug/lib/parse.ts b/packages/devtools/src/debug/lib/parse.ts
new file mode 100644
index 000000000..08354ba65
--- /dev/null
+++ b/packages/devtools/src/debug/lib/parse.ts
@@ -0,0 +1,59 @@
+import {
+ EMPTY_OUTCOME,
+ type LangModule,
+ type LibrarySchema,
+ type ValidationError,
+ type ValidationOutcome,
+} from "./types";
+
+export { EMPTY_OUTCOME, type ValidationOutcome } from "./types";
+
+export function runValidation(
+ code: string,
+ lang: LangModule,
+ schema: LibrarySchema | null,
+ rootName: string | undefined,
+): ValidationOutcome {
+ if (!code.trim() || !schema) return EMPTY_OUTCOME;
+ try {
+ return { result: lang.createParser(schema, rootName).parse(code), fatal: null };
+ } catch (err) {
+ return {
+ result: null,
+ fatal: err instanceof Error ? err.message : String(err),
+ };
+ }
+}
+
+export const KNOWN_ERROR_CODES = [
+ "type-mismatch",
+ "missing-required",
+ "null-required",
+ "excess-args",
+ "unknown-component",
+ "inline-reserved",
+] as const satisfies readonly ValidationError["code"][];
+
+export function groupByCode<T extends { code: string }>(errors: T[]): Map<string, T[]> {
+ const map = new Map<string, T[]>();
+ for (const code of KNOWN_ERROR_CODES) map.set(code, []);
+ for (const e of errors) {
+ const list = map.get(e.code) ?? [];
+ list.push(e);
+ map.set(e.code, list);
+ }
+ for (const [code, list] of map) if (list.length === 0) map.delete(code);
+ return map;
+}
+
+export function librarySchema(
+ library: { toJSONSchema?: () => unknown } | undefined,
+): LibrarySchema | null {
+ try {
+ const schema = library?.toJSONSchema?.();
+ if (!schema || typeof schema !== "object") return null;
+ return schema as LibrarySchema;
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/devtools/src/debug/lib/types.ts b/packages/devtools/src/debug/lib/types.ts
new file mode 100644
index 000000000..b4c525b7d
--- /dev/null
+++ b/packages/devtools/src/debug/lib/types.ts
@@ -0,0 +1,31 @@
+import type {
+ ParseResult,
+ Renderer,
+ createParser,
+ createStreamingParser,
+} from "@openuidev/react-lang";
+
+export type { ElementNode, OpenUIError, ParseResult } from "@openuidev/react-lang";
+
+/** JSON Schema document `createParser` expects — `library.toJSONSchema()`. */
+export type LibrarySchema = Parameters<typeof createParser>[0];
+export type StreamParser = ReturnType<typeof createStreamingParser>;
+export type ValidationError = ParseResult["meta"]["errors"][number];
+
+/**
+ * The `@openuidev/react-lang` surface Debug actually calls. Loaded dynamically
+ * so the package can stay an optional peer; this type is the compile-time
+ * contract for that namespace.
+ */
+export type LangModule = {
+ Renderer: typeof Renderer;
+ createParser: typeof createParser;
+ createStreamingParser?: typeof createStreamingParser;
+};
+
+export interface ValidationOutcome {
+ result: ParseResult | null;
+ fatal: string | null;
+}
+
+export const EMPTY_OUTCOME: ValidationOutcome = { result: null, fatal: null };
diff --git a/packages/devtools/src/debug/lib/usePlayback.ts b/packages/devtools/src/debug/lib/usePlayback.ts
new file mode 100644
index 000000000..bfe34fd6e
--- /dev/null
+++ b/packages/devtools/src/debug/lib/usePlayback.ts
@@ -0,0 +1,311 @@
+import { useCallback, useRef, useState } from "react";
+import { type ChunkStrategy, type StreamChunk, mulberry32, splitChunks } from "./chunker";
+import type { LangModule, LibrarySchema, ParseResult } from "./types";
+
+export interface TraceRow {
+ i: number;
+ chunkPreview: string;
+ delayMs: number;
+ rootPresent: boolean;
+ rootAppeared: boolean;
+ rootDropped: boolean;
+ statementCount: number;
+ incomplete: boolean;
+ unresolvedCount: number;
+ errorCount: number;
+}
+
+export type PlaybackStatus = "idle" | "playing" | "paused" | "done";
+
+export interface PlaybackState {
+ status: PlaybackStatus;
+ prefix: string;
+ chunkIndex: number;
+ totalChunks: number;
+ trace: TraceRow[];
+ traceTruncated: boolean;
+ result: ParseResult | null;
+ convergence: "converged" | "diverged" | null;
+ emulated: boolean;
+ fatal: string | null;
+}
+
+const IDLE: PlaybackState = {
+ status: "idle",
+ prefix: "",
+ chunkIndex: 0,
+ totalChunks: 0,
+ trace: [],
+ traceTruncated: false,
+ result: null,
+ convergence: null,
+ emulated: false,
+ fatal: null,
+};
+
+const TRACE_CAP = 5000;
+const BASE_INTERVAL_MS = 40;
+
+interface Session {
+ source: string;
+ chunks: StreamChunk[];
+ strategy: ChunkStrategy;
+ emulated: boolean;
+ push: (chunk: string, prefix: string) => ParseResult | null;
+ getFinal: () => ParseResult | null;
+ prefix: string;
+ index: number;
+ lastRootPresent: boolean;
+ rows: TraceRow[];
+ truncated: boolean;
+}
+
+export interface PlaybackControls {
+ state: PlaybackState;
+ start: (opts: { strategy: ChunkStrategy; seed: number }) => void;
+ pause: () => void;
+ resume: () => void;
+ step: () => void;
+ reset: () => void;
+ setSpeed: (speed: number) => void;
+ speed: number;
+}
+
+export function usePlayback(
+ code: string,
+ lang: LangModule | null | undefined,
+ schema: LibrarySchema | null,
+ rootName: string | undefined,
+): PlaybackControls {
+ const [state, setState] = useState<PlaybackState>(IDLE);
+ const [speed, setSpeedState] = useState(1);
+ const speedRef = useRef(1);
+ const generation = useRef(0);
+ const session = useRef<Session | null>(null);
+
+ const setSpeed = useCallback((s: number) => {
+ speedRef.current = s;
+ setSpeedState(s);
+ }, []);
+
+ const finish = useCallback(
+ (s: Session, module: LangModule) => {
+ let convergence: PlaybackState["convergence"] = null;
+ let fatal: string | null = null;
+ let result: ParseResult | null = null;
+ try {
+ result = s.getFinal();
+ if (!schema) throw new Error("No library schema");
+ const oneShot = module.createParser(schema, rootName).parse(s.source);
+ convergence =
+ JSON.stringify(result?.root) === JSON.stringify(oneShot?.root) ? "converged" : "diverged";
+ } catch (err) {
+ fatal = err instanceof Error ? err.message : String(err);
+ }
+ setState((prev) => ({
+ ...prev,
+ status: "done",
+ result: result ?? prev.result,
+ convergence,
+ fatal,
+ }));
+ },
+ [schema, rootName],
+ );
+
+ const applyChunk = useCallback(
+ (s: Session): { result: ParseResult | null; fatal: string | null } => {
+ const chunk = s.chunks[s.index];
+ if (!chunk) return { result: null, fatal: null };
+ s.prefix += chunk.text;
+ let result: ParseResult | null = null;
+ let fatal: string | null = null;
+ try {
+ result = s.push(chunk.text, s.prefix);
+ } catch (err) {
+ fatal = err instanceof Error ? err.message : String(err);
+ }
+ const rootPresent = !!result?.root;
+ if (result) {
+ if (s.rows.length >= TRACE_CAP) {
+ s.truncated = true;
+ } else {
+ s.rows.push({
+ i: s.index,
+ chunkPreview: chunk.text.length > 40 ? `${chunk.text.slice(0, 40)}…` : chunk.text,
+ delayMs: chunk.delayMs,
+ rootPresent,
+ rootAppeared: rootPresent && !s.lastRootPresent,
+ rootDropped: !rootPresent && s.lastRootPresent,
+ statementCount: result.meta.statementCount,
+ incomplete: result.meta.incomplete,
+ unresolvedCount: result.meta.unresolved.length,
+ errorCount: result.meta.errors.length,
+ });
+ }
+ }
+ s.lastRootPresent = rootPresent;
+ s.index += 1;
+ return { result, fatal };
+ },
+ [],
+ );
+
+ const snapshot = useCallback(
+ (s: Session, status: PlaybackStatus, result: ParseResult | null, fatal: string | null) => {
+ setState({
+ status: fatal ? "done" : status,
+ prefix: s.prefix,
+ chunkIndex: s.index,
+ totalChunks: s.chunks.length,
+ trace: [...s.rows],
+ traceTruncated: s.truncated,
+ result,
+ convergence: null,
+ emulated: s.emulated,
+ fatal,
+ });
+ },
+ [],
+ );
+
+ const advance = useCallback(
+ (s: Session, status: PlaybackStatus): boolean => {
+ const { result, fatal } = applyChunk(s);
+ snapshot(s, status, result, fatal);
+ return !fatal;
+ },
+ [applyChunk, snapshot],
+ );
+
+ const chunkDelay = useCallback((s: Session, chunk: StreamChunk | undefined) => {
+ if (!chunk) return 0;
+ const base = s.strategy === "llm" ? chunk.delayMs : BASE_INTERVAL_MS;
+ return Math.max(0, base / speedRef.current);
+ }, []);
+
+ const play = useCallback(
+ (s: Session, module: LangModule) => {
+ const gen = generation.current;
+ // Wait *before* each chunk. Cap catch-up so a slow first paint cannot
+ // mark the whole stream overdue and flush it in one frame.
+ const MAX_PLAYBACK_MS_PER_TICK = 50;
+ let nextAt = performance.now() + chunkDelay(s, s.chunks[s.index]);
+
+ const tick = () => {
+ if (generation.current !== gen || session.current !== s) return;
+ if (s.index >= s.chunks.length) {
+ finish(s, module);
+ return;
+ }
+
+ const now = performance.now();
+ if (nextAt > now) {
+ setTimeout(tick, nextAt - now);
+ return;
+ }
+
+ let last: { result: ParseResult | null; fatal: string | null } | null = null;
+ let played = 0;
+
+ while (s.index < s.chunks.length && nextAt <= now && played < MAX_PLAYBACK_MS_PER_TICK) {
+ const appliedDelay = chunkDelay(s, s.chunks[s.index]);
+ last = applyChunk(s);
+ if (last.fatal) {
+ snapshot(s, "done", last.result, last.fatal);
+ return;
+ }
+ nextAt += chunkDelay(s, s.chunks[s.index]);
+ played += appliedDelay > 0 ? appliedDelay : 4;
+ }
+
+ if (last) snapshot(s, "playing", last.result, last.fatal);
+ if (s.index >= s.chunks.length) {
+ finish(s, module);
+ return;
+ }
+
+ const wait = nextAt - performance.now();
+ if (wait <= 0) requestAnimationFrame(tick);
+ else setTimeout(tick, wait);
+ };
+
+ const wait = nextAt - performance.now();
+ if (wait <= 0) requestAnimationFrame(tick);
+ else setTimeout(tick, wait);
+ },
+ [applyChunk, chunkDelay, finish, snapshot],
+ );
+
+ const start = useCallback(
+ ({ strategy, seed }: { strategy: ChunkStrategy; seed: number }) => {
+ if (!lang || !code.trim() || schema == null) return;
+ generation.current += 1;
+
+ const emulated = typeof lang.createStreamingParser !== "function";
+ let push: Session["push"];
+ let getFinal: Session["getFinal"];
+ if (emulated) {
+ let last: ParseResult | null = null;
+ push = (_chunk, prefix) => {
+ last = lang.createParser(schema, rootName).parse(prefix);
+ return last;
+ };
+ getFinal = () => last ?? lang.createParser(schema, rootName).parse(code);
+ } else {
+ const sp = lang.createStreamingParser!(schema, rootName);
+ push = (chunk) => sp.push(chunk);
+ getFinal = () => sp.getResult();
+ }
+
+ const s: Session = {
+ source: code,
+ chunks: splitChunks(code, strategy, mulberry32(seed)),
+ strategy,
+ emulated,
+ push,
+ getFinal,
+ prefix: "",
+ index: 0,
+ lastRootPresent: false,
+ rows: [],
+ truncated: false,
+ };
+ session.current = s;
+ setState({ ...IDLE, status: "playing", totalChunks: s.chunks.length, emulated });
+ play(s, lang);
+ },
+ [code, lang, schema, rootName, play],
+ );
+
+ const pause = useCallback(() => {
+ generation.current += 1;
+ setState((prev) => (prev.status === "playing" ? { ...prev, status: "paused" } : prev));
+ }, []);
+
+ const resume = useCallback(() => {
+ const s = session.current;
+ if (!s || !lang) return;
+ generation.current += 1;
+ setState((prev) => (prev.status === "paused" ? { ...prev, status: "playing" } : prev));
+ play(s, lang);
+ }, [lang, play]);
+
+ const step = useCallback(() => {
+ const s = session.current;
+ if (!s || !lang) return;
+ if (s.index >= s.chunks.length) {
+ finish(s, lang);
+ return;
+ }
+ if (advance(s, "paused") && s.index >= s.chunks.length) finish(s, lang);
+ }, [advance, finish, lang]);
+
+ const reset = useCallback(() => {
+ generation.current += 1;
+ session.current = null;
+ setState(IDLE);
+ }, []);
+
+ return { state, start, pause, resume, step, reset, setSpeed, speed };
+}
diff --git a/packages/devtools/src/debug/lib/useReactLang.ts b/packages/devtools/src/debug/lib/useReactLang.ts
new file mode 100644
index 000000000..fa33fbe4d
--- /dev/null
+++ b/packages/devtools/src/debug/lib/useReactLang.ts
@@ -0,0 +1,48 @@
+import { useEffect, useState } from "react";
+import type { LangModule } from "./types";
+
+let pending: Promise<LangModule | null> | null = null;
+
+/**
+ * Reads an export that older react-lang builds may not have. Some module
+ * namespaces (test mocks, exotic bundlers) throw on a missing export instead of
+ * answering undefined, and a throw here would look like react-lang is missing.
+ */
+function optionalExport<T>(read: () => T | undefined): T | undefined {
+ try {
+ return read();
+ } catch {
+ return undefined;
+ }
+}
+
+export function loadReactLang(): Promise<LangModule | null> {
+ pending ??= import("@openuidev/react-lang")
+ .then((mod) => {
+ const loaded = mod as unknown as Partial<LangModule>;
+ if (typeof loaded.createParser !== "function" || !loaded.Renderer) return null;
+ return {
+ Renderer: loaded.Renderer,
+ createParser: loaded.createParser,
+ createStreamingParser: optionalExport(() => loaded.createStreamingParser),
+ };
+ })
+ .catch(() => null);
+ return pending;
+}
+
+export function useReactLang(): LangModule | null | undefined {
+ const [mod, setMod] = useState<LangModule | null | undefined>(undefined);
+
+ useEffect(() => {
+ let cancelled = false;
+ loadReactLang().then((next) => {
+ if (!cancelled) setMod(next);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ return mod;
+}
diff --git a/packages/devtools/src/debug/lib/useStream.ts b/packages/devtools/src/debug/lib/useStream.ts
new file mode 100644
index 000000000..aab73cf04
--- /dev/null
+++ b/packages/devtools/src/debug/lib/useStream.ts
@@ -0,0 +1,73 @@
+import { useCallback, useState } from "react";
+import type { ChunkStrategy } from "./chunker";
+import type { LangModule, LibrarySchema, ValidationOutcome } from "./types";
+import { usePlayback, type PlaybackControls, type PlaybackState } from "./usePlayback";
+
+const CHAR_STRATEGY_LIMIT = 50 * 1024;
+
+export interface StreamSettings {
+ strategy: ChunkStrategy;
+ onStrategyChange: (s: ChunkStrategy) => void;
+ seed: number;
+ onSeedChange: (n: number) => void;
+}
+
+/**
+ * Streaming controls for Debug: chunk strategy, seed, and the playback engine.
+ * DebugUI keeps validation and layout; this hook is the Stream toolbar + the
+ * prefix that panels show while a replay is running.
+ */
+export function useStream({
+ code,
+ lang,
+ schema,
+ rootName,
+ outcome,
+}: {
+ code: string;
+ lang: LangModule | null | undefined;
+ schema: LibrarySchema | null;
+ rootName: string | undefined;
+ outcome: ValidationOutcome;
+}): {
+ playback: PlaybackControls;
+ settings: StreamSettings;
+ state: PlaybackState;
+ active: boolean;
+ isStreaming: boolean;
+ disabled: boolean;
+ displayed: ValidationOutcome;
+ renderedCode: string;
+ bigInput: boolean;
+ prepareEdit: () => void;
+} {
+ const playback = usePlayback(code, lang, schema, rootName);
+ const [strategy, setStrategy] = useState<ChunkStrategy>("llm");
+ const [seed, setSeed] = useState(42);
+ const { state, reset } = playback;
+ const active = state.status === "playing" || state.status === "paused";
+ const displayed =
+ active || state.status === "done" ? { result: state.result, fatal: state.fatal } : outcome;
+
+ const prepareEdit = useCallback(() => {
+ if (state.status !== "idle") reset();
+ }, [reset, state.status]);
+
+ return {
+ playback,
+ settings: {
+ strategy,
+ onStrategyChange: setStrategy,
+ seed,
+ onSeedChange: setSeed,
+ },
+ state,
+ active,
+ isStreaming: state.status === "playing",
+ disabled: !lang || !code.trim() || schema == null,
+ displayed,
+ renderedCode: active ? state.prefix : code,
+ bigInput: code.length > CHAR_STRATEGY_LIMIT,
+ prepareEdit,
+ };
+}
diff --git a/packages/devtools/src/debug/lib/useValidation.ts b/packages/devtools/src/debug/lib/useValidation.ts
new file mode 100644
index 000000000..2df149631
--- /dev/null
+++ b/packages/devtools/src/debug/lib/useValidation.ts
@@ -0,0 +1,27 @@
+import { useEffect, useMemo, useState } from "react";
+import { EMPTY_OUTCOME, runValidation, type ValidationOutcome } from "./parse";
+import type { LangModule, LibrarySchema } from "./types";
+
+const DEBOUNCE_MS = 150;
+
+function useDebounced<T>(value: T, ms: number): T {
+ const [debounced, setDebounced] = useState(value);
+ useEffect(() => {
+ const timer = setTimeout(() => setDebounced(value), ms);
+ return () => clearTimeout(timer);
+ }, [value, ms]);
+ return debounced;
+}
+
+export function useValidation(
+ code: string,
+ lang: LangModule | null | undefined,
+ schema: LibrarySchema | null,
+ rootName: string | undefined,
+): ValidationOutcome {
+ const debouncedCode = useDebounced(code, DEBOUNCE_MS);
+ return useMemo(() => {
+ if (!lang) return EMPTY_OUTCOME;
+ return runValidation(debouncedCode, lang, schema, rootName);
+ }, [debouncedCode, lang, schema, rootName]);
+}
diff --git a/packages/devtools/src/debug/panels/JsonPanel.tsx b/packages/devtools/src/debug/panels/JsonPanel.tsx
new file mode 100644
index 000000000..584df5af8
--- /dev/null
+++ b/packages/devtools/src/debug/panels/JsonPanel.tsx
@@ -0,0 +1,42 @@
+import { useMemo, useState } from "react";
+import type { ParseResult } from "../lib";
+import { useDebugStyles } from "../styles";
+
+const COLLAPSE_BYTES = 200 * 1024;
+
+export function JsonPanel({ result }: { result: ParseResult | null }) {
+ const s = useDebugStyles();
+ const [forceExpand, setForceExpand] = useState(false);
+ const json = useMemo(() => {
+ if (!result) return null;
+ try {
+ return JSON.stringify(
+ result,
+ (_key, value) =>
+ typeof value === "function" ? `[function]` : value === undefined ? null : value,
+ 2,
+ );
+ } catch (err) {
+ return `/* could not stringify: ${err instanceof Error ? err.message : String(err)} */`;
+ }
+ }, [result]);
+
+ if (!json) return <div style={s.panelEmpty}>No parse result yet.</div>;
+ if (json.length > COLLAPSE_BYTES && !forceExpand) {
+ return (
+ <div style={s.panelScroll}>
+ <p>
+ Result is {(json.length / 1024).toFixed(0)} KB.{" "}
+ <button type="button" onClick={() => setForceExpand(true)}>
+ Expand anyway
+ </button>
+ </p>
+ </div>
+ );
+ }
+ return (
+ <div style={s.panelScroll}>
+ <pre style={s.treeJson}>{json}</pre>
+ </div>
+ );
+}
diff --git a/packages/devtools/src/debug/panels/RenderPanel.tsx b/packages/devtools/src/debug/panels/RenderPanel.tsx
new file mode 100644
index 000000000..0c7e04975
--- /dev/null
+++ b/packages/devtools/src/debug/panels/RenderPanel.tsx
@@ -0,0 +1,142 @@
+import type { Library } from "@openuidev/react-lang";
+import { FlaskConical } from "lucide-react";
+import { useMemo, useState } from "react";
+import type { LibraryLike } from "../../lib";
+import {
+ createMockToolProvider,
+ type LangModule,
+ type MockToolCall,
+ type OpenUIError,
+} from "../lib";
+import { useDebugStyles } from "../styles";
+
+const TOOL_CALL_LOG_CAP = 20;
+
+function safeDescribe(event: unknown): string {
+ try {
+ return JSON.stringify(event);
+ } catch {
+ return String(event);
+ }
+}
+
+function isOpenUIError(error: unknown): error is OpenUIError {
+ return !!error && typeof error === "object";
+}
+
+function ErrorRow({ error }: { error: unknown }) {
+ const s = useDebugStyles();
+ if (isOpenUIError(error) && (error.message || error.code)) {
+ return (
+ <li style={s.errorRow}>
+ <div style={s.errHead}>
+ {error.code ? <code style={s.errComponent}>{error.code}</code> : null}
+ {error.component ? <code style={s.errPath}>{error.component}</code> : null}
+ {error.path ? <code style={s.errPath}>{error.path}</code> : null}
+ {error.statementId ? <span style={s.tag}>{error.statementId}</span> : null}
+ </div>
+ {error.message ? <p style={s.errMessage}>{error.message}</p> : null}
+ {error.hint ? <p style={s.errHint}>{error.hint}</p> : null}
+ </li>
+ );
+ }
+ return <li style={s.errorRow}>{safeDescribe(error)}</li>;
+}
+
+export function RenderPanel({
+ Renderer,
+ library,
+ code,
+ isStreaming,
+}: {
+ Renderer: LangModule["Renderer"];
+ library: LibraryLike;
+ code: string;
+ isStreaming: boolean;
+}) {
+ const s = useDebugStyles();
+ const [runtimeErrors, setRuntimeErrors] = useState<OpenUIError[]>([]);
+ const [formState, setFormState] = useState<Record<string, unknown>>({});
+ const [actionLog, setActionLog] = useState<string[]>([]);
+ const [toolCalls, setToolCalls] = useState<MockToolCall[]>([]);
+ const [lastCode, setLastCode] = useState(code);
+ if (code !== lastCode && !isStreaming) {
+ setLastCode(code);
+ setToolCalls([]);
+ setActionLog([]);
+ }
+
+ const toolProvider = useMemo(
+ () =>
+ createMockToolProvider((call) =>
+ setToolCalls((log) => [...log.slice(-(TOOL_CALL_LOG_CAP - 1)), call]),
+ ),
+ [],
+ );
+
+ const usesTools = /\b(Query|Mutation)\s*\(/.test(code);
+ // Whitespace-only input has nothing to render. Handing it to the Renderer anyway
+ // reports a "parse-failed" error that then sticks around, since an empty editor
+ // never produces another report to replace it. runValidation() guards the same way.
+ const source = code.trim() ? code : null;
+
+ return (
+ <div style={s.renderPanel}>
+ {usesTools ? (
+ <p style={s.mockNote}>
+ <FlaskConical size={13} aria-hidden />
+ <span>
+ <code>Query()</code> and <code>Mutation()</code> run against a mock tool provider. Calls
+ are logged below the canvas.
+ </span>
+ </p>
+ ) : null}
+ <div style={s.renderCanvas}>
+ <Renderer
+ response={source}
+ library={library as Library}
+ isStreaming={isStreaming}
+ publishObservability={false}
+ toolProvider={toolProvider}
+ onError={setRuntimeErrors}
+ onStateUpdate={setFormState}
+ onAction={(event) => setActionLog((log) => [...log.slice(-19), safeDescribe(event)])}
+ />
+ </div>
+ {toolCalls.length > 0 ? (
+ <details style={s.renderDetails} open>
+ <summary>Mock tool calls ({toolCalls.length})</summary>
+ <ul style={s.errorList}>
+ {toolCalls.map((call, index) => (
+ <li key={`${call.at}-${index}`} style={s.errorRow}>
+ <code>{call.tool}</code>({safeDescribe(call.args)}) → sample data
+ </li>
+ ))}
+ </ul>
+ </details>
+ ) : null}
+ {source && runtimeErrors.length > 0 ? (
+ <details style={s.renderDetails} open>
+ <summary>Runtime errors ({runtimeErrors.length})</summary>
+ <ul style={s.errorList}>
+ {runtimeErrors.map((error, index) => (
+ <ErrorRow key={index} error={error} />
+ ))}
+ </ul>
+ </details>
+ ) : null}
+ {actionLog.length > 0 ? (
+ <details style={s.renderDetails}>
+ <summary>Actions ({actionLog.length})</summary>
+ <pre style={s.treeJson}>{actionLog.join("\n")}</pre>
+ </details>
+ ) : null}
+ {Object.keys(formState).length > 0 ? (
+ <details style={s.renderDetails}>
+ <summary>Form state</summary>
+ <pre style={s.treeJson}>{JSON.stringify(formState, null, 2)}</pre>
+ </details>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/devtools/src/debug/panels/StreamTimeline.tsx b/packages/devtools/src/debug/panels/StreamTimeline.tsx
new file mode 100644
index 000000000..6ed537374
--- /dev/null
+++ b/packages/devtools/src/debug/panels/StreamTimeline.tsx
@@ -0,0 +1,94 @@
+import { CheckCircle2, Circle, CircleDot, CircleMinus, CirclePlus, XCircle } from "lucide-react";
+import type { PlaybackState } from "../lib";
+import { useDebugStyles } from "../styles";
+
+export function StreamTimeline({ state }: { state: PlaybackState }) {
+ const s = useDebugStyles();
+ if (state.status === "idle") {
+ return (
+ <div style={s.panelEmpty}>
+ Press <strong>Stream</strong> to replay the current code as simulated LLM output and watch
+ the parser converge chunk by chunk.
+ </div>
+ );
+ }
+ return (
+ <div style={s.panelScroll}>
+ {state.convergence ? (
+ <div
+ style={{
+ ...s.convergence,
+ ...(state.convergence === "converged" ? s.convergenceOk : s.convergenceBad),
+ }}
+ >
+ {state.convergence === "converged" ? (
+ <>
+ <CheckCircle2 size={15} /> Streaming result converged with one-shot parse
+ </>
+ ) : (
+ <>
+ <XCircle size={15} /> Diverged from one-shot parse
+ </>
+ )}
+ </div>
+ ) : null}
+ {state.fatal ? (
+ <div style={s.fatalCard}>
+ <strong>Streaming parse threw</strong>
+ <pre style={s.fatalPre}>{state.fatal}</pre>
+ </div>
+ ) : null}
+ {state.traceTruncated ? (
+ <p style={{ color: s.label.color, fontSize: 12 }}>
+ Trace capped at 5,000 rows — remaining chunks not logged.
+ </p>
+ ) : null}
+ <table style={s.traceTable}>
+ <thead>
+ <tr>
+ {["#", "chunk", "delay", "root", "stmts", "state", "unres", "errs"].map((heading) => (
+ <th key={heading} style={s.traceTh}>
+ {heading}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {state.trace.map((row) => (
+ <tr
+ key={row.i}
+ style={row.rootAppeared ? s.rowAppeared : row.rootDropped ? s.rowDropped : undefined}
+ >
+ <td style={s.traceTd}>{row.i}</td>
+ <td style={s.traceTd}>{visualize(row.chunkPreview)}</td>
+ <td style={s.traceTd}>{row.delayMs}ms</td>
+ <td style={{ ...s.traceTd, ...s.rootCell }}>
+ {row.rootAppeared ? (
+ <>
+ <CirclePlus size={12} /> appeared
+ </>
+ ) : row.rootDropped ? (
+ <>
+ <CircleMinus size={12} /> dropped
+ </>
+ ) : row.rootPresent ? (
+ <CircleDot size={12} />
+ ) : (
+ <Circle size={12} />
+ )}
+ </td>
+ <td style={s.traceTd}>{row.statementCount}</td>
+ <td style={s.traceTd}>{row.incomplete ? "incomplete" : "complete"}</td>
+ <td style={s.traceTd}>{row.unresolvedCount}</td>
+ <td style={s.traceTd}>{row.errorCount}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
+
+function visualize(text: string): string {
+ return text.replace(/\n/g, "⏎").replace(/\t/g, "⇥");
+}
diff --git a/packages/devtools/src/debug/panels/TreePanel.tsx b/packages/devtools/src/debug/panels/TreePanel.tsx
new file mode 100644
index 000000000..069236244
--- /dev/null
+++ b/packages/devtools/src/debug/panels/TreePanel.tsx
@@ -0,0 +1,116 @@
+import { ChevronDown, ChevronRight } from "lucide-react";
+import { useState } from "react";
+import type { ElementNode, ParseResult } from "../lib";
+import { useDebugStyles } from "../styles";
+
+function isElementNode(value: unknown): value is ElementNode {
+ return !!value && typeof value === "object" && (value as { type?: unknown }).type === "element";
+}
+
+function isExprLike(value: unknown): boolean {
+ if (!value || typeof value !== "object") return false;
+ const type = (value as { type?: unknown }).type;
+ return typeof type === "string" && type !== "element";
+}
+
+function safeStringify(value: unknown): string {
+ try {
+ const text = JSON.stringify(value);
+ return text && text.length > 120 ? `${text.slice(0, 120)}…` : (text ?? String(value));
+ } catch {
+ return String(value);
+ }
+}
+
+function PropValue({ value }: { value: unknown }) {
+ const s = useDebugStyles();
+ if (isElementNode(value)) return <NodeView node={value} />;
+ if (Array.isArray(value)) {
+ if (value.some((item) => isElementNode(item))) {
+ return (
+ <div style={{ minWidth: 0 }}>
+ {value.map((item, index) => (
+ <PropValue key={index} value={item} />
+ ))}
+ </div>
+ );
+ }
+ return <code style={s.treeScalar}>{safeStringify(value)}</code>;
+ }
+ if (isExprLike(value)) {
+ return <code style={s.treeExpr}>⟨{(value as { type: string }).type}⟩</code>;
+ }
+ return <code style={s.treeScalar}>{safeStringify(value)}</code>;
+}
+
+function NodeView({ node }: { node: ElementNode }) {
+ const [open, setOpen] = useState(true);
+ const s = useDebugStyles();
+ const entries = Object.entries(node.props ?? {});
+ return (
+ <div style={{ minWidth: 0 }}>
+ <button style={s.treeHeader} onClick={() => setOpen((value) => !value)}>
+ {open ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
+ <span style={s.treeType}>{node.typeName}</span>
+ {node.statementId ? <span style={s.tag}>{node.statementId}</span> : null}
+ {node.partial ? <span style={{ ...s.tag, ...s.tagWarning }}>partial</span> : null}
+ </button>
+ {open && entries.length > 0 ? (
+ <dl style={s.treeProps}>
+ {entries.map(([key, value]) => (
+ <div key={key} style={s.treeProp}>
+ <dt style={s.treeDt}>{key}</dt>
+ <dd style={s.treeDd}>
+ <PropValue value={value} />
+ </dd>
+ </div>
+ ))}
+ </dl>
+ ) : null}
+ </div>
+ );
+}
+
+export function TreePanel({ result }: { result: ParseResult | null }) {
+ const s = useDebugStyles();
+ if (!result) return <div style={s.panelEmpty}>No parse result yet.</div>;
+ const state = result.stateDeclarations ?? {};
+ const queries = result.queryStatements ?? [];
+ const mutations = result.mutationStatements ?? [];
+ return (
+ <div style={s.panelScroll}>
+ {result.root ? (
+ <NodeView node={result.root} />
+ ) : (
+ <div style={s.panelEmpty}>root is null — nothing would render for this input.</div>
+ )}
+ {Object.keys(state).length > 0 ? (
+ <section style={s.treeExtra}>
+ <h3 style={s.treeExtraTitle}>State declarations</h3>
+ <dl style={s.treeProps}>
+ {Object.entries(state).map(([key, value]) => (
+ <div key={key} style={s.treeProp}>
+ <dt style={s.treeDt}>${key.replace(/^\$/, "")}</dt>
+ <dd style={s.treeDd}>
+ <code style={s.treeScalar}>{safeStringify(value)}</code>
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </section>
+ ) : null}
+ {queries.length > 0 ? (
+ <section style={s.treeExtra}>
+ <h3 style={s.treeExtraTitle}>Queries ({queries.length})</h3>
+ <pre style={s.treeJson}>{safeStringify(queries)}</pre>
+ </section>
+ ) : null}
+ {mutations.length > 0 ? (
+ <section style={s.treeExtra}>
+ <h3 style={s.treeExtraTitle}>Mutations ({mutations.length})</h3>
+ <pre style={s.treeJson}>{safeStringify(mutations)}</pre>
+ </section>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/devtools/src/debug/panels/ValidationPanel.tsx b/packages/devtools/src/debug/panels/ValidationPanel.tsx
new file mode 100644
index 000000000..9cabb9c65
--- /dev/null
+++ b/packages/devtools/src/debug/panels/ValidationPanel.tsx
@@ -0,0 +1,75 @@
+import { CheckCircle2 } from "lucide-react";
+import { groupByCode, type ValidationOutcome } from "../lib";
+import { useDebugStyles } from "../styles";
+
+export function ValidationPanel({ outcome }: { outcome: ValidationOutcome }) {
+ const s = useDebugStyles();
+ const { result, fatal } = outcome;
+
+ if (fatal) {
+ return (
+ <div style={s.panelScroll}>
+ <div style={s.fatalCard}>
+ <strong>Parser threw</strong>
+ <pre style={s.fatalPre}>{fatal}</pre>
+ </div>
+ </div>
+ );
+ }
+ if (!result) {
+ return <div style={s.panelEmpty}>Add some OpenUI Lang to validate it.</div>;
+ }
+
+ const { meta } = result;
+ const groups = groupByCode(meta.errors);
+
+ return (
+ <div style={s.panelScroll}>
+ <div style={s.metaStrip}>
+ <span style={s.tag}>Statements: {meta.statementCount}</span>
+ <span style={{ ...s.tag, ...(meta.incomplete ? s.tagWarning : s.tagSuccess) }}>
+ {meta.incomplete ? "Incomplete" : "Complete"}
+ </span>
+ <span style={{ ...s.tag, ...(result.root ? s.tagSuccess : s.tagWarning) }}>
+ Root: {result.root ? result.root.typeName : "none"}
+ </span>
+ {meta.unresolved.map((item) => (
+ <span key={item} style={{ ...s.tag, ...s.tagWarning }}>
+ unresolved: {item}
+ </span>
+ ))}
+ {meta.orphaned.map((item) => (
+ <span key={item} style={s.tag}>
+ orphaned: {item}
+ </span>
+ ))}
+ </div>
+
+ {meta.errors.length === 0 ? (
+ <div style={s.allClear}>
+ <CheckCircle2 size={16} /> No validation errors
+ </div>
+ ) : (
+ [...groups.entries()].map(([code, errors]) => (
+ <section key={code} style={s.errorGroup}>
+ <h3 style={s.errorGroupTitle}>
+ <code>{code}</code> <span style={s.count}>({errors.length})</span>
+ </h3>
+ <ul style={s.errorList}>
+ {errors.map((error, index) => (
+ <li key={`${error.path}-${index}`} style={s.errorRow}>
+ <div style={s.errHead}>
+ <code style={s.errComponent}>{error.component}</code>
+ <code style={s.errPath}>{error.path}</code>
+ {error.statementId ? <span style={s.tag}>{error.statementId}</span> : null}
+ </div>
+ <p style={s.errMessage}>{error.message}</p>
+ </li>
+ ))}
+ </ul>
+ </section>
+ ))
+ )}
+ </div>
+ );
+}
diff --git a/packages/devtools/src/debug/panels/index.ts b/packages/devtools/src/debug/panels/index.ts
new file mode 100644
index 000000000..133c426fd
--- /dev/null
+++ b/packages/devtools/src/debug/panels/index.ts
@@ -0,0 +1,5 @@
+export { JsonPanel } from "./JsonPanel";
+export { RenderPanel } from "./RenderPanel";
+export { StreamTimeline } from "./StreamTimeline";
+export { TreePanel } from "./TreePanel";
+export { ValidationPanel } from "./ValidationPanel";
diff --git a/packages/devtools/src/debug/styles.ts b/packages/devtools/src/debug/styles.ts
new file mode 100644
index 000000000..0327d5888
--- /dev/null
+++ b/packages/devtools/src/debug/styles.ts
@@ -0,0 +1,417 @@
+import type { CSSProperties } from "react";
+import { FONT, MONO, useTheme, type ThemeTokens } from "../theme";
+
+export { FONT, MONO };
+
+export function debugStyles(t: ThemeTokens) {
+ return {
+ toolbar: {
+ display: "flex",
+ alignItems: "center",
+ gap: 10,
+ flexWrap: "wrap",
+ padding: "8px 16px",
+ borderBottom: `1px solid ${t.borderSubtle}`,
+ background: t.bg,
+ },
+ field: {
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ },
+ label: {
+ color: t.fgMuted,
+ fontSize: 11,
+ fontWeight: 500,
+ },
+ select: {
+ border: `1px solid ${t.controlBorder}`,
+ borderRadius: 8,
+ background: t.controlBg,
+ color: t.fg,
+ fontFamily: FONT,
+ fontSize: 12,
+ // The native chevron sits flush against the label otherwise, so the inline
+ // end gets its own gutter; the start is padded to balance it.
+ padding: "4px 24px 4px 12px",
+ },
+ seedInput: {
+ width: 64,
+ border: `1px solid ${t.controlBorder}`,
+ borderRadius: 8,
+ background: t.controlBg,
+ color: t.fg,
+ fontFamily: FONT,
+ fontSize: 12,
+ padding: "4px 8px",
+ },
+ btnGroup: {
+ display: "inline-flex",
+ alignItems: "stretch",
+ },
+ groupButton: {
+ display: "inline-flex",
+ alignItems: "center",
+ justifyContent: "center",
+ width: 28,
+ height: 26,
+ border: `1px solid ${t.controlBorder}`,
+ background: t.controlBg,
+ color: t.fgTertiary,
+ cursor: "pointer",
+ padding: 0,
+ },
+ groupButtonDisabled: {
+ opacity: 0.45,
+ cursor: "not-allowed",
+ },
+ progress: {
+ color: t.fgMuted,
+ fontSize: 11,
+ fontFamily: MONO,
+ },
+ tabStrip: {
+ display: "flex",
+ gap: 2,
+ padding: "6px 12px",
+ borderBottom: `1px solid ${t.borderSubtle}`,
+ flexShrink: 0,
+ },
+ tab: {
+ border: "none",
+ background: "transparent",
+ color: t.fgMuted,
+ fontFamily: FONT,
+ fontSize: 12,
+ fontWeight: 500,
+ padding: "6px 8px",
+ borderRadius: 8,
+ cursor: "pointer",
+ },
+ tabActive: {
+ color: t.fg,
+ background: t.bgSubtle,
+ },
+ panelScroll: {
+ overflow: "auto",
+ padding: 16,
+ flex: 1,
+ minHeight: 0,
+ },
+ panelEmpty: {
+ padding: 32,
+ color: t.fgFaint,
+ textAlign: "center",
+ fontSize: 12,
+ },
+ metaStrip: {
+ display: "flex",
+ gap: 6,
+ flexWrap: "wrap",
+ marginBottom: 16,
+ },
+ tag: {
+ display: "inline-flex",
+ alignItems: "center",
+ borderRadius: 999,
+ padding: "2px 8px",
+ fontSize: 11,
+ fontWeight: 500,
+ background: t.bgSubtle,
+ color: t.fgTertiary,
+ },
+ tagSuccess: {
+ background: t.successBg,
+ color: t.success,
+ },
+ tagWarning: {
+ background: t.warningBg,
+ color: t.warning,
+ },
+ allClear: {
+ color: t.success,
+ fontWeight: 500,
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ fontSize: 13,
+ },
+ errorGroup: {
+ marginBottom: 20,
+ },
+ errorGroupTitle: {
+ fontSize: 13,
+ margin: "0 0 8px",
+ fontWeight: 600,
+ },
+ count: {
+ color: t.fgFaint,
+ fontWeight: 400,
+ },
+ errorList: {
+ listStyle: "none",
+ margin: 0,
+ padding: 0,
+ },
+ errorRow: {
+ padding: 8,
+ border: `1px solid ${t.border}`,
+ borderRadius: 6,
+ marginBottom: 8,
+ minWidth: 0,
+ overflowWrap: "anywhere",
+ wordBreak: "break-word",
+ whiteSpace: "pre-wrap",
+ },
+ errHead: {
+ display: "flex",
+ alignItems: "center",
+ flexWrap: "wrap",
+ gap: 8,
+ minWidth: 0,
+ },
+ errComponent: {
+ fontWeight: 600,
+ fontFamily: MONO,
+ fontSize: 12,
+ overflowWrap: "anywhere",
+ },
+ errPath: {
+ color: t.fgMuted,
+ fontFamily: MONO,
+ fontSize: 12,
+ overflowWrap: "anywhere",
+ },
+ errMessage: {
+ margin: "4px 0 0",
+ fontSize: 12,
+ overflowWrap: "anywhere",
+ wordBreak: "break-word",
+ whiteSpace: "pre-wrap",
+ },
+ errHint: {
+ margin: "4px 0 0",
+ fontSize: 12,
+ color: t.info,
+ overflowWrap: "anywhere",
+ wordBreak: "break-word",
+ whiteSpace: "pre-wrap",
+ },
+ fatalCard: {
+ border: `1px solid ${t.dangerBorder}`,
+ borderRadius: 8,
+ padding: 16,
+ color: t.danger,
+ fontSize: 12,
+ },
+ fatalPre: {
+ margin: "8px 0 0",
+ fontFamily: MONO,
+ whiteSpace: "pre-wrap",
+ },
+ renderPanel: {
+ display: "flex",
+ flexDirection: "column",
+ flex: 1,
+ minHeight: 0,
+ overflow: "auto",
+ },
+ mockNote: {
+ display: "flex",
+ alignItems: "flex-start",
+ gap: 6,
+ padding: "8px 16px",
+ color: t.info,
+ background: t.infoBg,
+ fontSize: 12,
+ },
+ renderCanvas: {
+ padding: 16,
+ flex: 1,
+ },
+ renderDetails: {
+ borderTop: `1px solid ${t.borderSubtle}`,
+ padding: "8px 16px",
+ fontSize: 12,
+ color: t.fgSecondary,
+ minWidth: 0,
+ overflowWrap: "anywhere",
+ },
+ treeHeader: {
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 6,
+ border: "none",
+ background: "none",
+ cursor: "pointer",
+ color: "inherit",
+ font: "inherit",
+ padding: "2px 0",
+ },
+ treeType: {
+ fontFamily: MONO,
+ fontWeight: 600,
+ fontSize: 12,
+ },
+ treeProps: {
+ margin: "0 0 0 24px",
+ borderLeft: `1px solid ${t.border}`,
+ paddingLeft: 10,
+ minWidth: 0,
+ },
+ treeProp: {
+ display: "flex",
+ flexWrap: "wrap",
+ gap: "2px 10px",
+ alignItems: "baseline",
+ padding: "1px 0",
+ minWidth: 0,
+ },
+ treeDt: {
+ color: t.fgMuted,
+ fontFamily: MONO,
+ fontSize: 11,
+ flex: "0 0 auto",
+ margin: 0,
+ },
+ treeDd: {
+ margin: 0,
+ minWidth: 0,
+ // Own row once the remaining slot is too narrow for a readable value.
+ flex: "1 1 12em",
+ },
+ treeScalar: {
+ display: "block",
+ maxWidth: "100%",
+ minWidth: 0,
+ fontFamily: MONO,
+ fontSize: 11,
+ overflowWrap: "anywhere",
+ wordBreak: "break-word",
+ whiteSpace: "pre-wrap",
+ },
+ treeExpr: {
+ fontFamily: MONO,
+ fontSize: 11,
+ color: t.info,
+ },
+ treeExtra: {
+ marginTop: 24,
+ },
+ treeExtraTitle: {
+ fontSize: 13,
+ margin: "0 0 8px",
+ },
+ treeJson: {
+ fontFamily: MONO,
+ fontSize: 11,
+ whiteSpace: "pre-wrap",
+ wordBreak: "break-word",
+ margin: 0,
+ },
+ convergence: {
+ padding: "8px 12px",
+ borderRadius: 6,
+ marginBottom: 16,
+ fontWeight: 600,
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ fontSize: 12,
+ },
+ convergenceOk: {
+ background: t.successBg,
+ color: t.success,
+ },
+ convergenceBad: {
+ background: t.dangerBg,
+ color: t.danger,
+ },
+ traceTable: {
+ width: "100%",
+ borderCollapse: "collapse",
+ fontSize: 11,
+ tableLayout: "fixed",
+ },
+ traceTh: {
+ textAlign: "left",
+ color: t.fgMuted,
+ fontWeight: 500,
+ padding: "2px 8px",
+ borderBottom: `1px solid ${t.borderSubtle}`,
+ },
+ traceTd: {
+ padding: "2px 8px",
+ borderBottom: `1px solid ${t.borderSubtle}`,
+ fontFamily: MONO,
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ },
+ rowAppeared: {
+ background: t.successBg,
+ },
+ rowDropped: {
+ background: t.dangerBg,
+ },
+ rootCell: {
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ },
+ helpOverlay: {
+ position: "absolute",
+ inset: 0,
+ background: t.overlay,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ zIndex: 5,
+ padding: 24,
+ },
+ helpDialog: {
+ background: t.bg,
+ border: `1px solid ${t.border}`,
+ borderRadius: 12,
+ boxShadow: t.shadow,
+ maxWidth: 440,
+ width: "100%",
+ maxHeight: "80%",
+ display: "flex",
+ flexDirection: "column",
+ overflow: "hidden",
+ },
+ // Same treatment as the Inspect tray header, with the dialog's wider gutter.
+ helpHeader: {
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ gap: 8,
+ padding: "14px 20px 0",
+ fontWeight: 600,
+ fontSize: 14,
+ },
+ helpBody: {
+ padding: "20px 20px 24px",
+ overflowY: "auto",
+ fontSize: 13,
+ lineHeight: 1.55,
+ fontWeight: 400,
+ color: t.fgTertiary,
+ },
+ editorLock: {
+ position: "absolute",
+ bottom: 10,
+ right: 10,
+ background: t.bgSubtle,
+ border: `1px solid ${t.border}`,
+ borderRadius: 999,
+ padding: "2px 10px",
+ fontSize: 10,
+ color: t.fgMuted,
+ },
+ } satisfies Record<string, CSSProperties>;
+}
+
+export function useDebugStyles() {
+ return debugStyles(useTheme());
+}
diff --git a/packages/devtools/src/debug/ui/HelpDialog.tsx b/packages/devtools/src/debug/ui/HelpDialog.tsx
new file mode 100644
index 000000000..bed00ac1a
--- /dev/null
+++ b/packages/devtools/src/debug/ui/HelpDialog.tsx
@@ -0,0 +1,207 @@
+import { X } from "lucide-react";
+import { useEffect, useState, type CSSProperties } from "react";
+import { useStyles, type ThemeTokens } from "../../theme";
+import { IconButton } from "../../ui";
+import { useDebugStyles } from "../styles";
+
+const SUMMARY =
+ "OpenUI Debug is a scratchpad for OpenUI Lang: drop in a model response and see how it parses, validates, and renders against this app's own components.";
+
+const STEPS: { title: string; text: string }[] = [
+ {
+ title: "Load OpenUI Lang",
+ text: "Drop in a model response, or write Lang by hand, in the editor on the left.",
+ },
+ {
+ title: "Watch it render",
+ text: "Render uses the host app's real createLibrary() components and CSS. Query() and Mutation() resolve with mocked data.",
+ },
+ {
+ title: "Read the diagnostics",
+ text: "Validation groups parse errors by code and lists unresolved refs; Tree and JSON show the parsed result.",
+ },
+ {
+ title: "Replay it as a stream",
+ text: "Stream re-emits the editor chunk by chunk with LLM-like jitter. Pause, step, or fix the Seed to reproduce a run.",
+ },
+];
+
+export function HelpDialog({
+ defaultOpen = false,
+ onSeen,
+}: {
+ /** First run opens this unprompted; dismissing it marks the guide as seen. */
+ defaultOpen?: boolean;
+ onSeen?: () => void;
+}) {
+ const [open, setOpen] = useState(defaultOpen);
+ const s = useDebugStyles();
+ const styles = useStyles(helpStyles);
+
+ const close = () => {
+ setOpen(false);
+ onSeen?.();
+ };
+
+ // Captured so Escape closes the help first, without also stepping the drawer back.
+ useEffect(() => {
+ if (!open) return;
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ event.stopPropagation();
+ event.preventDefault();
+ setOpen(false);
+ onSeen?.();
+ };
+ document.addEventListener("keydown", onKey, true);
+ return () => document.removeEventListener("keydown", onKey, true);
+ }, [open, onSeen]);
+
+ return (
+ <>
+ <button
+ style={styles.trigger}
+ onClick={() => setOpen(true)}
+ aria-haspopup="dialog"
+ aria-label="How to use OpenUI Debug"
+ >
+ Help
+ </button>
+ {open ? (
+ <div style={s.helpOverlay} onClick={close} role="presentation">
+ <div
+ style={s.helpDialog}
+ role="dialog"
+ aria-modal="true"
+ aria-label="How to use OpenUI Debug"
+ onClick={(event) => event.stopPropagation()}
+ >
+ <div style={s.helpHeader}>
+ <span>How to use OpenUI Debug</span>
+ <IconButton onClick={close} aria-label="Close help">
+ <X size={15} />
+ </IconButton>
+ </div>
+ <div style={s.helpBody}>
+ <p style={styles.summary}>{SUMMARY}</p>
+ <ol style={styles.steps}>
+ {STEPS.map((step, index) => (
+ <li key={step.title} style={styles.step}>
+ <span style={styles.badge} aria-hidden>
+ {index + 1}
+ </span>
+ <div style={styles.stepBody}>
+ <div style={styles.stepTitle}>{step.title}</div>
+ <p style={styles.stepText}>{step.text}</p>
+ </div>
+ </li>
+ ))}
+ </ol>
+ </div>
+ <div style={styles.footer}>
+ <button style={styles.dismiss} onClick={close}>
+ Close
+ </button>
+ </div>
+ </div>
+ </div>
+ ) : null}
+ </>
+ );
+}
+
+const BADGE = 18;
+
+function helpStyles(t: ThemeTokens) {
+ return {
+ // Matches the Inspect header's text buttons (Wrap / Copy).
+ trigger: {
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 4,
+ border: `1px solid ${t.controlBorder}`,
+ borderRadius: 8,
+ background: t.controlBg,
+ color: t.fg,
+ cursor: "pointer",
+ fontFamily: "inherit",
+ fontSize: 12,
+ fontWeight: 500,
+ padding: "4px 10px",
+ },
+ // What the tool is, before the how.
+ summary: {
+ margin: "0 0 16px",
+ maxWidth: "62ch",
+ fontSize: 12,
+ fontWeight: 400,
+ lineHeight: 1.55,
+ color: t.fgSecondary,
+ },
+ steps: {
+ listStyle: "none",
+ display: "flex",
+ flexDirection: "column",
+ gap: 20,
+ margin: 0,
+ padding: 0,
+ },
+ step: {
+ display: "flex",
+ alignItems: "flex-start",
+ gap: 10,
+ },
+ // Same chip proportions as LevelIcon, so the dialog matches the event rows.
+ badge: {
+ display: "inline-flex",
+ alignItems: "center",
+ justifyContent: "center",
+ flexShrink: 0,
+ boxSizing: "border-box",
+ width: BADGE,
+ height: BADGE,
+ borderRadius: 6,
+ background: t.bgSubtle,
+ color: t.fgSecondary,
+ fontSize: 11,
+ fontWeight: 500,
+ lineHeight: 1,
+ },
+ stepBody: {
+ minWidth: 0,
+ },
+ // Medium title over regular body.
+ stepTitle: {
+ color: t.fg,
+ fontSize: 12,
+ fontWeight: 500,
+ },
+ stepText: {
+ margin: "3px 0 0",
+ maxWidth: "52ch",
+ fontSize: 12,
+ fontWeight: 400,
+ lineHeight: 1.55,
+ color: t.fgMuted,
+ },
+ // Second way out, for anyone who reads to the end rather than reaching for
+ // the cross.
+ footer: {
+ display: "flex",
+ justifyContent: "flex-end",
+ padding: "0 20px 16px",
+ },
+ dismiss: {
+ border: `1px solid ${t.border}`,
+ borderRadius: 8,
+ background: t.bg,
+ color: t.fgSecondary,
+ boxShadow: t.shadowSubtle,
+ cursor: "pointer",
+ fontFamily: "inherit",
+ fontSize: 12,
+ fontWeight: 500,
+ padding: "6px 14px",
+ },
+ } satisfies Record<string, CSSProperties>;
+}
diff --git a/packages/devtools/src/debug/ui/LangEditor.tsx b/packages/devtools/src/debug/ui/LangEditor.tsx
new file mode 100644
index 000000000..a3cf37d02
--- /dev/null
+++ b/packages/devtools/src/debug/ui/LangEditor.tsx
@@ -0,0 +1,158 @@
+import { useMemo, useRef, type CSSProperties, type UIEvent } from "react";
+import { tokenColor, tokenizeLang, toTokenLines } from "../../lib";
+import { MONO, useTheme, type ThemeTokens } from "../../theme";
+
+// One line on purpose: the empty editor renders it as a single numbered row.
+const PLACEHOLDER = 'root = TextContent("Hello")';
+
+function selectionCss(t: ThemeTokens) {
+ return `
+.openui-debug-lang-editor textarea::selection {
+ background: ${t.selection};
+ color: transparent;
+}
+.openui-debug-lang-editor textarea::-moz-selection {
+ background: ${t.selection};
+ color: transparent;
+}
+.openui-debug-lang-editor pre {
+ scrollbar-width: none;
+}
+.openui-debug-lang-editor pre::-webkit-scrollbar {
+ display: none;
+}
+`;
+}
+
+const PAD = 16;
+const NUMBER_WIDTH = 36;
+const NUMBER_GAP = 10;
+
+// Both layers must share one text column, or the highlight drifts from the caret.
+const shared: CSSProperties = {
+ boxSizing: "border-box",
+ width: "100%",
+ height: "100%",
+ paddingTop: PAD,
+ paddingRight: PAD,
+ paddingBottom: PAD,
+ paddingLeft: PAD + NUMBER_WIDTH + NUMBER_GAP,
+ margin: 0,
+ border: "none",
+ fontFamily: MONO,
+ fontSize: 12,
+ lineHeight: 1.5,
+ tabSize: 2,
+ whiteSpace: "pre-wrap",
+ overflowWrap: "anywhere",
+ wordBreak: "normal",
+};
+
+export function LangEditor({
+ value,
+ onChange,
+ readOnly = false,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+ readOnly?: boolean;
+}) {
+ const t = useTheme();
+ const colors = tokenColor(t);
+ const styles = editorStyles(t);
+ const highlightRef = useRef<HTMLPreElement>(null);
+ const lines = useMemo(() => toTokenLines(tokenizeLang(value)), [value]);
+
+ const syncScroll = (event: UIEvent<HTMLTextAreaElement>) => {
+ const highlight = highlightRef.current;
+ if (!highlight) return;
+ highlight.scrollTop = event.currentTarget.scrollTop;
+ highlight.scrollLeft = event.currentTarget.scrollLeft;
+ };
+
+ return (
+ <div className="openui-debug-lang-editor" style={styles.wrap}>
+ <style>{selectionCss(t)}</style>
+ <pre ref={highlightRef} style={styles.highlight} aria-hidden>
+ {value ? (
+ lines.map((line, index) => (
+ <div key={index} style={styles.line}>
+ <span style={styles.lineNumber}>{index + 1}</span>
+ {line.length === 0
+ ? // Keeps a blank line one row tall.
+ "\u200b"
+ : line.map((token, tokenIndex) => (
+ <span key={tokenIndex} style={{ color: colors[token.kind] }}>
+ {token.value}
+ </span>
+ ))}
+ </div>
+ ))
+ ) : (
+ <div style={styles.line}>
+ <span style={styles.lineNumber}>1</span>
+ <span style={{ color: t.fgFaint }}>{PLACEHOLDER}</span>
+ </div>
+ )}
+ </pre>
+ <textarea
+ style={styles.textarea}
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ onScroll={syncScroll}
+ spellCheck={false}
+ readOnly={readOnly}
+ aria-label="OpenUI Lang"
+ />
+ </div>
+ );
+}
+
+function editorStyles(t: ThemeTokens) {
+ return {
+ wrap: {
+ position: "relative",
+ minWidth: 0,
+ minHeight: 0,
+ height: "100%",
+ background: t.bgMuted,
+ },
+ highlight: {
+ ...shared,
+ position: "absolute",
+ inset: 0,
+ overflow: "auto",
+ pointerEvents: "none",
+ color: t.fg,
+ background: "transparent",
+ },
+ line: {
+ position: "relative",
+ },
+ lineNumber: {
+ position: "absolute",
+ // The gutter lives in the text column's left padding.
+ left: -(NUMBER_WIDTH + NUMBER_GAP),
+ top: 0,
+ bottom: 0,
+ boxSizing: "border-box",
+ width: NUMBER_WIDTH,
+ paddingRight: NUMBER_GAP,
+ borderRight: `1px solid ${t.border}`,
+ color: t.fgFaint,
+ textAlign: "right",
+ whiteSpace: "pre",
+ },
+ textarea: {
+ ...shared,
+ position: "absolute",
+ inset: 0,
+ resize: "none",
+ color: "transparent",
+ caretColor: t.fg,
+ background: "transparent",
+ outline: "none",
+ overflow: "auto",
+ },
+ } satisfies Record<string, CSSProperties>;
+}
diff --git a/packages/devtools/src/debug/ui/StreamToolbar.tsx b/packages/devtools/src/debug/ui/StreamToolbar.tsx
new file mode 100644
index 000000000..d550d8723
--- /dev/null
+++ b/packages/devtools/src/debug/ui/StreamToolbar.tsx
@@ -0,0 +1,159 @@
+import { Pause, Play, RotateCcw, StepForward } from "lucide-react";
+import type { CSSProperties } from "react";
+import {
+ CHUNK_STRATEGIES,
+ type ChunkStrategy,
+ type PlaybackControls,
+ type StreamSettings,
+} from "../lib";
+import { useDebugStyles } from "../styles";
+
+const SPEEDS = ["0.25", "0.5", "1", "2", "4", "8"];
+// Every control in the toolbar draws its icon at one size and one stroke.
+const ICON = { size: 14 };
+
+function groupStyle(
+ s: ReturnType<typeof useDebugStyles>,
+ disabled: boolean,
+ first: boolean,
+ last: boolean,
+): CSSProperties {
+ return {
+ ...s.groupButton,
+ ...(disabled ? s.groupButtonDisabled : null),
+ borderTopLeftRadius: first ? 8 : 0,
+ borderBottomLeftRadius: first ? 8 : 0,
+ borderTopRightRadius: last ? 8 : 0,
+ borderBottomRightRadius: last ? 8 : 0,
+ marginLeft: first ? 0 : -1,
+ };
+}
+
+export function StreamToolbar({
+ playback,
+ settings,
+ bigInput,
+ disabled,
+}: {
+ playback: PlaybackControls;
+ settings: StreamSettings;
+ bigInput: boolean;
+ disabled?: boolean;
+}) {
+ const { state, start, pause, resume, step, reset, setSpeed, speed } = playback;
+ const playbackActive = state.status === "playing" || state.status === "paused";
+ const settingsLocked = disabled || playbackActive;
+ const { strategy, onStrategyChange, seed, onSeedChange } = settings;
+ const s = useDebugStyles();
+
+ return (
+ <div style={s.toolbar}>
+ <div style={s.btnGroup} role="group" aria-label="Playback controls">
+ {state.status === "playing" ? (
+ <button
+ style={groupStyle(s, !!disabled, true, false)}
+ onClick={pause}
+ disabled={disabled}
+ aria-label="Pause"
+ title="Pause"
+ >
+ <Pause {...ICON} />
+ </button>
+ ) : state.status === "paused" ? (
+ <button
+ style={groupStyle(s, !!disabled, true, false)}
+ onClick={resume}
+ disabled={disabled}
+ aria-label="Resume"
+ title="Resume"
+ >
+ <Play {...ICON} />
+ </button>
+ ) : (
+ <button
+ style={groupStyle(s, !!disabled, true, false)}
+ onClick={() => start({ strategy, seed })}
+ disabled={disabled}
+ aria-label="Stream"
+ title="Stream (replay as simulated LLM output)"
+ >
+ <Play {...ICON} />
+ </button>
+ )}
+ <button
+ style={groupStyle(s, !!disabled || state.status !== "paused", false, false)}
+ onClick={step}
+ disabled={disabled || state.status !== "paused"}
+ aria-label="Step one chunk"
+ title="Step one chunk"
+ >
+ <StepForward {...ICON} />
+ </button>
+ {/* Stays live even with an empty editor: otherwise clearing the input during
+ a run leaves the panels showing a playback nothing can clear. */}
+ <button
+ style={groupStyle(s, state.status === "idle", false, true)}
+ onClick={reset}
+ disabled={state.status === "idle"}
+ aria-label="Reset playback"
+ title="Reset playback"
+ >
+ <RotateCcw {...ICON} />
+ </button>
+ </div>
+ {state.totalChunks > 0 ? (
+ <span style={s.progress}>
+ {state.chunkIndex}/{state.totalChunks}
+ {state.emulated ? " · emulated" : ""}
+ </span>
+ ) : null}
+
+ <div style={s.field}>
+ <span style={s.label}>Chunks</span>
+ <select
+ style={s.select}
+ value={strategy}
+ onChange={(event) => onStrategyChange(event.target.value as ChunkStrategy)}
+ disabled={settingsLocked}
+ aria-label="Chunk strategy"
+ >
+ {CHUNK_STRATEGIES.map((item) => (
+ <option key={item.id} value={item.id} disabled={item.id === "char" && bigInput}>
+ {item.label}
+ {item.id === "char" && bigInput ? " (input too large)" : ""}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <div style={s.field}>
+ <span style={s.label}>Speed</span>
+ <select
+ style={s.select}
+ value={String(speed)}
+ onChange={(event) => setSpeed(Number(event.target.value))}
+ disabled={disabled}
+ aria-label="Playback speed"
+ >
+ {SPEEDS.map((item) => (
+ <option key={item} value={item}>
+ {item}×
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <div style={s.field}>
+ <span style={s.label}>Seed</span>
+ <input
+ style={s.seedInput}
+ type="number"
+ value={seed}
+ onChange={(event) => onSeedChange(Number(event.target.value) || 0)}
+ disabled={settingsLocked || strategy !== "llm"}
+ aria-label="Chunk seed"
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/devtools/src/debug/ui/index.ts b/packages/devtools/src/debug/ui/index.ts
new file mode 100644
index 000000000..595397413
--- /dev/null
+++ b/packages/devtools/src/debug/ui/index.ts
@@ -0,0 +1,3 @@
+export { HelpDialog } from "./HelpDialog";
+export { LangEditor } from "./LangEditor";
+export { StreamToolbar } from "./StreamToolbar";
diff --git a/packages/devtools/src/inspect/ReactLangStreamEventRow.tsx b/packages/devtools/src/inspect/ReactLangStreamEventRow.tsx
index daa76fa4c..34294f176 100644
--- a/packages/devtools/src/inspect/ReactLangStreamEventRow.tsx
+++ b/packages/devtools/src/inspect/ReactLangStreamEventRow.tsx
@@ -18,6 +18,7 @@ export interface ReactLangStreamDetail {
startedAt?: number;
elapsedMs?: number;
durationMs?: number;
+ __libraryId?: string;
}
export function getReactLangStreamDetail(event: ObservabilityEvent): ReactLangStreamDetail | null {
@@ -52,6 +53,7 @@ export function getReactLangStreamDetail(event: ObservabilityEvent): ReactLangSt
startedAt: asNumber(detail["startedAt"]),
elapsedMs: asNumber(detail["elapsedMs"]),
durationMs: asNumber(detail["durationMs"]),
+ __libraryId: asString(detail["__libraryId"]),
};
}
@@ -63,7 +65,7 @@ export function ReactLangStreamEventRow({
}: {
event: ObservabilityEvent;
stream: ReactLangStreamDetail;
- onOpenInDebug?: (response: string) => void;
+ onOpenInDebug?: (response: string, libraryId?: string) => void;
canOpenInDebug?: boolean;
}) {
const [expanded, setExpanded] = useState(false);
@@ -173,7 +175,7 @@ export function ReactLangStreamEventRow({
onMouseLeave={() => setHoveredAction(null)}
onClick={() => {
if (isStreaming || !stream.response) return;
- onOpenInDebug(stream.response);
+ onOpenInDebug(stream.response, stream.__libraryId);
}}
disabled={openInDebugDisabled}
title={
diff --git a/packages/devtools/src/lib/index.ts b/packages/devtools/src/lib/index.ts
index 09d4a4f3d..c2b86a207 100644
--- a/packages/devtools/src/lib/index.ts
+++ b/packages/devtools/src/lib/index.ts
@@ -1,5 +1,12 @@
export { addOrReplaceEvent } from "./eventBuffer";
export { toTokenLines, tokenColor, tokenizeLang } from "./highlight";
export type { Token, TokenKind } from "./highlight";
+export {
+ LIBRARY_EVENT_KIND,
+ isLibraryEvent,
+ useRegisteredLibraries,
+ type LibraryLike,
+ type RegisteredLibrary,
+} from "./libraryRegistry";
export { useDevtoolsSingleton } from "./singleton";
export { useDevtoolsConfig, type DevtoolsConfig } from "./useDevtoolsConfig";
diff --git a/packages/devtools/src/lib/libraryRegistry.ts b/packages/devtools/src/lib/libraryRegistry.ts
new file mode 100644
index 000000000..1e2afee41
--- /dev/null
+++ b/packages/devtools/src/lib/libraryRegistry.ts
@@ -0,0 +1,52 @@
+import { observability, type ObservabilityEvent } from "@openuidev/observability";
+import { useEffect, useState } from "react";
+
+/**
+ * Shared with `@openuidev/react-lang` via `Symbol.for`. Not a public API.
+ * Keep the string in sync with `packages/react-lang/src/publishLibrary.ts`.
+ */
+const DEVTOOLS_LIBRARIES_KEY = Symbol.for("openui.devtools.libraries");
+
+export const LIBRARY_EVENT_KIND = "react-lang:library";
+
+/** Structural slice of a `createLibrary()` result — enough to label, parse, and render. */
+export interface LibraryLike {
+ id?: string;
+ root?: string;
+ /** Instance id minted by `createLibrary()`. */
+ __libraryId?: string;
+ components: Record<string, unknown>;
+ toJSONSchema?: () => unknown;
+}
+
+export interface RegisteredLibrary {
+ key: string;
+ library: LibraryLike;
+}
+
+interface RegistryStore {
+ [DEVTOOLS_LIBRARIES_KEY]?: Record<string, LibraryLike>;
+}
+
+export function isLibraryEvent(event: ObservabilityEvent): boolean {
+ return event.detail.kind === LIBRARY_EVENT_KIND;
+}
+
+export function readRegisteredLibraries(): RegisteredLibrary[] {
+ const byKey = (globalThis as RegistryStore)[DEVTOOLS_LIBRARIES_KEY] ?? {};
+ return Object.entries(byKey).map(([key, library]) => ({ key, library }));
+}
+
+/** Live `createLibrary()` results, seeded from the stash and refreshed on ping. */
+export function useRegisteredLibraries(): RegisteredLibrary[] {
+ const [libraries, setLibraries] = useState(readRegisteredLibraries);
+
+ useEffect(() => {
+ setLibraries(readRegisteredLibraries());
+ return observability.listenAll((event) => {
+ if (isLibraryEvent(event)) setLibraries(readRegisteredLibraries());
+ });
+ }, []);
+
+ return libraries;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 47949c0c5..19bf98fb4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1749,6 +1749,9 @@ importers:
'@openuidev/observability':
specifier: workspace:^
version: link:../observability
+ '@openuidev/react-lang':
+ specifier: workspace:^
+ version: link:../react-lang
'@types/node':
specifier: 'catalog:'
version: 22.20.1