The Open Standard for Generative UI
Embed Debug in the drawer and restyle Devtools (#1006)
AB99ee893407e9
diff --git a/packages/devtools/README.md b/packages/devtools/README.mdindex dfdb8aec7..517938bd3 100644--- a/packages/devtools/README.md+++ b/packages/devtools/README.md@@ -1,6 +1,6 @@# @openuidev/devtools-Development-only UI widget for OpenUI apps. Renders a floating button that opens a left side drawer listing the events captured by [`@openuidev/observability`](../observability) — level, a one-line summary, and a drill-in stack trace per entry.+Development-only UI widget for OpenUI apps. Renders a floating button that opens **OpenUI Inspect**, listing the events captured by [`@openuidev/observability`](../observability).## Usage@@ -21,6 +21,10 @@ The widget renders nothing in production builds (`NODE_ENV === "production"`) un`@openuidev/react-lang` ships with this package and auto-mounts the widget in development — no manual `<OpenUIDevtools />` needed. Mounting it manually still works (e.g. to customize props): only one instance ever renders, and a manually mounted instance takes precedence over the auto-mounted one.+In development, `createLibrary()` registers the live library with the widget. A stream event's **Debug** button opens **OpenUI Debug** in its own tray — an editor against that library (host CSS included), with Render / Validation / Tree / JSON / Stream panels and simulated stream playback.++Debug renders through the host's own `Renderer`. Its previews stay off the event bus so a Stream replay does not append cards to Inspect.+## Props| Prop | Default | Description |@@ -29,5 +33,6 @@ The widget renders nothing in production builds (`NODE_ENV === "production"`) un| `position` | `"bottom-right"` | Corner for the toggle button: `top-left`/`top-right`/`bottom-*`. || `maxEvents` | `50` | How many events to keep; oldest are dropped first. || `errorsOnly` | `true` | Capture only error/warning events, or all. |-| `autoOpenOnError` | `true` | Initial state of the drawer's "auto-open on error" checkbox. |+| `autoOpenOnError` | `true` | Initial state of the "auto-open on error" setting. |+| `theme` | `"light"` | Initial widget chrome theme: `"light"` or `"dark"` (Settings overrides). || `bus` | shared singleton | An `Observability` instance to listen to. |diff --git a/packages/devtools/src/OpenUIDevtools.test.ts b/packages/devtools/src/OpenUIDevtools.test.tsindex c2122af1c..f2492ec26 100644--- a/packages/devtools/src/OpenUIDevtools.test.ts+++ b/packages/devtools/src/OpenUIDevtools.test.ts@@ -2,17 +2,73 @@import { observability, toErrorInfo } from "@openuidev/observability";import { act, createElement } from "react";import { createRoot, type Root } from "react-dom/client";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { OpenUIDevtools, type OpenUIDevtoolsProps } from "./index";-// React's act() requires this flag to flush effects/state synchronously in tests.-(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+vi.mock("@openuidev/react-lang", async () => {+ const { createElement: el } = await import("react");+ const parse = (src: string) => ({+ root: /\broot\s*=/.test(src)+ ? { type: "element" as const, typeName: "Card", props: {}, partial: false }+ : null,+ meta: {+ incomplete: false,+ unresolved: [] as string[],+ orphaned: [] as string[],+ statementCount: src.trim() ? 1 : 0,+ errors: [] as unknown[],+ },+ });+ return {+ Renderer: (props: { response: string | null }) =>+ el("div", { "data-testid": "openui-renderer" }, props.response ?? ""),+ createParser: () => ({ parse }),+ createStreamingParser: () => {+ let buf = "";+ return {+ push: (chunk: string) => {+ buf += chunk;+ return parse(buf);+ },+ getResult: () => parse(buf),+ };+ },+ };+});++const LIBRARIES_KEY = Symbol.for("openui.devtools.libraries");++function seedLibrary(): void {+ (+ globalThis as {+ [LIBRARIES_KEY]?: Record<+ string,+ {+ root: string;+ components: Record<string, unknown>;+ toJSONSchema: () => unknown;+ }+ >;+ }+ )[LIBRARIES_KEY] = {+ Card: {+ root: "Card",+ components: { Card: {} },+ toJSONSchema: () => ({ $defs: { Card: { type: "object", properties: {} } } }),+ },+ };+}++function clearLibraries(): void {+ delete (globalThis as { [LIBRARIES_KEY]?: unknown })[LIBRARIES_KEY];+}let container: HTMLDivElement;let root: Root;beforeEach(() => {window.localStorage.clear();+ clearLibraries();container = document.createElement("div");document.body.appendChild(container);root = createRoot(container);@@ -45,6 +101,41 @@ function buttonByText(text: string): HTMLButtonElement | undefined {HTMLButtonElement | undefined;}+/** Emits a settled stream event and expands its row, exposing the Debug button. */+function seedStream(response: string): void {+ act(() =>+ observability.info({+ kind: "react-lang:stream",+ id: "stream-debug-entry",+ phase: "settled",+ response,+ parser: { statementCount: response.trim() ? 1 : 0, orphaned: [] },+ errors: [],+ }),+ );+ const row = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Toggle OpenUI Lang stream details"]',+ );+ if (!row) throw new Error("stream row not found");+ click(row);+}++function streamDebugButton(): HTMLButtonElement | undefined {+ return container.querySelector<HTMLButtonElement>('button[aria-label="Debug"]') ?? undefined;+}++/**+ * Debug has no banner of its own — a stream event's Debug button is the way in.+ * The default response is blank so the editor opens effectively empty (the+ * button is disabled on a truly empty response).+ */+function openDebugTray(response = " "): void {+ seedStream(response);+ const debug = streamDebugButton();+ if (!debug) throw new Error("stream Debug button not found");+ click(debug);+}+/*** The stream row's overview stats, each read back as "2 statements" — the count* lives in its own badge, so textContent alone would say "2statements".@@ -59,6 +150,15 @@ function overviewStats(): string[] {});}+/**+ * Both trays stay mounted so they can transition; a retracted one carries+ * `inert`. "Showing" therefore means present and not inert.+ */+function trayShown(label: "OpenUI Inspect" | "OpenUI Debug"): boolean {+ const tray = container.querySelector<HTMLElement>(`aside[aria-label="${label}"]`);+ return !!tray && !tray.hasAttribute("inert");+}+/** The display filters live behind the header settings button. */function openSettings(): void {const button = container.querySelector<HTMLButtonElement>(@@ -300,6 +400,34 @@ describe("OpenUIDevtools", () => {expect(toggle().textContent).toContain("1");});+ it("debugs a stream response in OpenUI Debug", () => {+ seedLibrary();+ render({ enabled: true, errorsOnly: false });+ act(() =>+ observability.info({+ kind: "react-lang:stream",+ id: "stream-1",+ phase: "settled",+ response: 'root = Card("from stream")',+ parser: { statementCount: 1, orphaned: [] },+ errors: [],+ }),+ );++ click(+ container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Toggle OpenUI Lang stream details"]',+ )!,+ );+ click(container.querySelector('button[aria-label="Debug"]')!);++ const editor = container.querySelector<HTMLTextAreaElement>(+ 'textarea[aria-label="OpenUI Lang"]',+ );+ expect(trayShown("OpenUI Debug")).toBe(true);+ expect(editor?.value).toBe('root = Card("from stream")');+ });+it("hides provisional errors while the stream is still running", () => {render({ enabled: true, errorsOnly: false });@@ -418,4 +546,187 @@ describe("OpenUIDevtools", () => {expect(container.textContent).not.toContain("OpenUI Lang stream");expect(container.textContent).toContain("No events captured yet.");});++ it("disables OpenUI Debug until a library is registered", () => {+ render({ enabled: true });+ seedStream('root = Card("x")');+ expect(streamDebugButton()?.disabled).toBe(true);+ });++ it("opens OpenUI Debug from a late-mounted registry entry", () => {+ seedLibrary();+ render({ enabled: true });+ seedStream('root = Card("x")');+ const debug = streamDebugButton();+ expect(debug?.disabled).toBe(false);+ click(debug!);+ expect(trayShown("OpenUI Debug")).toBe(true);+ expect(container.querySelector('textarea[aria-label="OpenUI Lang"]')).not.toBeNull();+ });++ it("shows Debug panels and stream controls", () => {+ seedLibrary();+ render({ enabled: true });+ openDebugTray();+ expect(container.querySelector('[aria-label="Playback controls"]')).not.toBeNull();+ expect(container.querySelector('button[aria-label="Stream"]')).not.toBeNull();+ const tabs = container.querySelector('[role="tablist"]')?.textContent ?? "";+ expect(tabs).toContain("Render");+ expect(tabs).toContain("Validation");+ expect(tabs).toContain("Tree");+ expect(tabs).toContain("JSON");+ expect(tabs).toContain("Stream");+ });++ it("switches to the validation panel", async () => {+ seedLibrary();+ render({ enabled: true });+ openDebugTray();+ await act(async () => {+ await Promise.resolve();+ });+ const validation = [...container.querySelectorAll('[role="tab"]')].find((tab) =>+ tab.textContent?.startsWith("Validation"),+ );+ click(validation!);+ expect(container.textContent).toContain("Add some OpenUI Lang to validate it.");+ });++ it("does not list library registration pings as events", () => {+ render({ enabled: true, errorsOnly: false });+ act(() =>+ observability.info({+ kind: "react-lang:library",+ root: "Card",+ components: ["Card"],+ message: "Library registered (root: Card)",+ }),+ );+ click(toggle());+ expect(container.textContent).not.toContain("Library registered");+ expect(container.textContent).toContain("No events captured yet.");+ });++ it("opens OpenUI Debug on its own tray beside Inspect", () => {+ seedLibrary();+ render({ enabled: true });+ click(toggle());+ openDebugTray();++ expect(trayShown("OpenUI Inspect")).toBe(true);+ expect(trayShown("OpenUI Debug")).toBe(true);+ });++ it("closes only the Debug tray, leaving Inspect open", () => {+ seedLibrary();+ render({ enabled: true });+ click(toggle());+ openDebugTray();++ click(container.querySelector('button[aria-label="Close OpenUI Debug"]')!);++ expect(trayShown("OpenUI Debug")).toBe(false);+ expect(trayShown("OpenUI Inspect")).toBe(true);+ expect(toggle().getAttribute("aria-expanded")).toBe("true");+ });++ it("closes only the Inspect tray, leaving Debug open", () => {+ seedLibrary();+ render({ enabled: true });+ click(toggle());+ openDebugTray();++ click(container.querySelector('button[aria-label="Close OpenUI Inspect"]')!);++ expect(trayShown("OpenUI Inspect")).toBe(false);+ expect(trayShown("OpenUI Debug")).toBe(true);+ });++ it("ejects OpenUI Debug into a separate window", () => {+ seedLibrary();+ const popupDoc = document.implementation.createHTMLDocument("debug");+ const popup = {+ document: popupDoc,+ focus: vi.fn(),+ close: vi.fn(),+ closed: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ };+ const open = vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window);++ render({ enabled: true });+ openDebugTray();+ click(container.querySelector('button[aria-label="Open OpenUI Debug in a new window"]')!);++ expect(open).toHaveBeenCalled();+ expect(trayShown("OpenUI Debug")).toBe(false);+ expect(popupDoc.getElementById("openui-debug-root")).not.toBeNull();+ expect(popupDoc.body.textContent).toContain("OpenUI Debug");+ open.mockRestore();+ });++ it("focuses the ejected window when OpenUI Debug is clicked again", () => {+ seedLibrary();+ const popupDoc = document.implementation.createHTMLDocument("debug");+ const popup = {+ document: popupDoc,+ focus: vi.fn(),+ close: vi.fn(),+ closed: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ };+ const open = vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window);++ render({ enabled: true });+ openDebugTray();+ click(container.querySelector('button[aria-label="Open OpenUI Debug in a new window"]')!);+ popup.focus.mockClear();++ // Same entry point again, with the row still expanded from the first open.+ click(streamDebugButton()!);++ expect(popup.focus).toHaveBeenCalled();+ expect(trayShown("OpenUI Debug")).toBe(false);+ open.mockRestore();+ });++ it("returns an ejected window to the tray", () => {+ seedLibrary();+ const popupDoc = document.implementation.createHTMLDocument("debug");+ const popup = {+ document: popupDoc,+ focus: vi.fn(),+ close: vi.fn(),+ closed: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ };+ const open = vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window);++ render({ enabled: true });+ openDebugTray();+ click(container.querySelector('button[aria-label="Open OpenUI Debug in a new window"]')!);+ expect(trayShown("OpenUI Debug")).toBe(false);++ click(popupDoc.querySelector('button[aria-label="Return OpenUI Debug to the tray"]')!);++ expect(popup.close).toHaveBeenCalled();+ expect(trayShown("OpenUI Debug")).toBe(true);+ open.mockRestore();+ });++ it("stays in the drawer when the popup is blocked", () => {+ seedLibrary();+ const open = vi.spyOn(window, "open").mockReturnValue(null);++ render({ enabled: true });+ openDebugTray();+ click(container.querySelector('button[aria-label="Open OpenUI Debug in a new window"]')!);++ expect(trayShown("OpenUI Debug")).toBe(true);+ expect(container.textContent).toContain("Allow popups for this origin");+ open.mockRestore();+ });});diff --git a/packages/devtools/src/OpenUIDevtools.tsx b/packages/devtools/src/OpenUIDevtools.tsxindex ed370d3ff..6f7e490e0 100644--- a/packages/devtools/src/OpenUIDevtools.tsx+++ b/packages/devtools/src/OpenUIDevtools.tsx@@ -3,6 +3,7 @@import { observability, type ObservabilityEvent } from "@openuidev/observability";import { Inbox, RotateCcw, Settings, X } from "lucide-react";import { useEffect, useRef, useState, type CSSProperties } from "react";+import { DEFAULT_EDITOR_PCT, useDebug } from "./debug";import {EventRow,getQuotaError,@@ -12,6 +13,7 @@ import {} from "./inspect";import {addOrReplaceEvent,+ isLibraryEvent,useDevtoolsConfig,useDevtoolsSingleton,type DevtoolsConfig,@@ -26,19 +28,22 @@ import {type ColorMode,type ThemeTokens,} from "./theme";-import { IconButton, ShiroLogo, ThemeSegmented } from "./ui";--const RELIABILITY_DOCS_URL = "https://www.openui.com/docs/openui-lang/reliability";+import { ErrorBoundary, IconButton, ShiroLogo, ThemeSegmented } from "./ui";/** Uniform row height for the settings menu, set by its tallest control. */const MENU_ROW_HEIGHT = 28;/**- * Inspect tray geometry. Anchored to the bottom right — 85% of the viewport- * tall, 480px wide, capped so it stops growing on very large displays.+ * Tray geometry. The two trays together fill a block anchored to the bottom+ * right — 85% of the viewport, capped so it stops growing on very large+ * displays. Inspect keeps a fixed width and Debug takes whatever is left,+ * overlapping Inspect rather than collapsing once it hits its floor.*/const TRAY_EDGE = 12;+const TRAY_GAP = 12;const INSPECT_WIDTH = 480;+const DEBUG_MIN_WIDTH = 360;+const BLOCK_W = `min(85vw, 3456px)`;const BLOCK_H = `min(85vh, 2234px)`;export type DevtoolsPosition = "top-left" | "top-right" | "bottom-left" | "bottom-right";@@ -72,8 +77,11 @@ export interface OpenUIDevtoolsProps {* dev-only widget that surfaces events captured by `@openuidev/observability` —* a Shiro-logo button (which turns red with the error count) that opens a side* drawer listing every captured event. Errors expand in place to show the- * stack trace. Display filters and the theme live in the header settings menu.- * Renders nothing in production unless `enabled` is set explicitly.+ * stack trace. OpenUI Inspect and OpenUI Debug are independent tools on+ * independent trays: a stream's Debug button opens Debug beside Inspect, and+ * either closes without disturbing the other. Display filters and the theme+ * live in the header settings menu. Renders nothing in production unless+ * `enabled` is set explicitly.*/export function OpenUIDevtools({enabled,@@ -92,44 +100,57 @@ export function OpenUIDevtools({const [events, setEvents] = useState<ObservabilityEvent[]>([]);const [open, setOpen] = useState(false);const [toggleHovered, setToggleHovered] = useState(false);- const [bannerHovered, setBannerHovered] = useState(false);const { config, setConfig, configRef } = useDevtoolsConfig({autoOpen: autoOpenOnError,onlyErrors: errorsOnly,theme: DEFAULT_COLOR_MODE,+ helpSeen: false,+ editorPct: DEFAULT_EDITOR_PCT,},{ theme: themeProp },);const { onlyErrors, theme: mode } = config;+ const debug = useDebug({+ theme: mode,+ helpSeen: config.helpSeen,+ editorPct: config.editorPct,+ setConfig,+ });const styles = uiStyles(theme(mode));// Read configRef inside the (stable) subscription without re-subscribing.useEffect(() => {if (!isEnabled) return;return observability.listenAll((event) => {+ if (isLibraryEvent(event)) return;setEvents((prev) => addOrReplaceEvent(prev, event, maxEvents));if (event.level === "error" && configRef.current.autoOpen) setOpen(true);});}, [isEnabled, maxEvents, configRef]);- // Escape closes Inspect. The settings menu handles its own Escape first- // (capture phase), so it never falls through to here.+ // Escape dismisses the top tray first: Debug → Inspect → closed. The+ // settings menu handles its own Escape first (capture phase), so it never+ // falls through to here.useEffect(() => {- if (!open) return;+ if (!open && !debug.trayOpen) return;const onKeyDown = (event: KeyboardEvent) => {if (event.key !== "Escape") return;- setOpen(false);+ if (debug.trayOpen) debug.retract();+ else setOpen(false);};document.addEventListener("keydown", onKeyDown);return () => document.removeEventListener("keydown", onKeyDown);- }, [open]);+ }, [open, debug.trayOpen, debug.retract]);if (!isEnabled || !isSingleton) return null;const errorCount = events.filter((event) => event.level === "error").length;const visibleEvents = onlyErrors ? events.filter((event) => event.level !== "info") : events;+ // Inspect is pinned to the right edge; Debug fills the rest of the block and+ // slides over to reclaim Inspect's slot whenever Inspect is out.+ const inspectSlot = open ? INSPECT_WIDTH + TRAY_GAP : 0;const inspectTray: CSSProperties = {right: TRAY_EDGE,bottom: TRAY_EDGE,@@ -137,6 +158,19 @@ export function OpenUIDevtools({width: `min(${INSPECT_WIDTH}px, calc(100vw - ${TRAY_EDGE * 2}px))`,transform: open ? "translateX(0)" : `translateX(calc(100% + ${TRAY_EDGE}px))`,};+ // Debug is a workspace rather than a peek at the app behind it: it fills+ // everything Inspect leaves (left/right edges rather than a width, so the+ // inset matches top and bottom) and cuts straight in instead of sliding.+ // Overrides the shared UI, so it is spread last.+ const debugTray: CSSProperties = {+ right: TRAY_EDGE + inspectSlot,+ bottom: TRAY_EDGE,+ height: BLOCK_H,+ width: `max(${DEBUG_MIN_WIDTH}px, calc(${BLOCK_W} - ${inspectSlot}px))`,+ transform: "none",+ transition: "none",+ visibility: debug.trayOpen ? "visible" : "hidden",+ };return (<DevtoolsModeProvider mode={mode}>@@ -165,71 +199,38 @@ export function OpenUIDevtools({</div>{/* Kept mounted so open/close can transition; hidden + inert when closed. */}- <div+ <asidestyle={{- ...styles.backdrop,+ ...styles.drawer,...rootStyle(mode),- ...(open ? styles.backdropOpen : null),+ ...inspectTray,+ ...(open ? styles.drawerOpen : null),}}- onClick={() => setOpen(false)}+ role="dialog"+ aria-modal={false}+ aria-label="OpenUI Inspect"+ inert={!open}>- <aside- style={{- ...styles.drawer,- ...inspectTray,- ...(open ? styles.drawerOpen : null),- }}- role="dialog"- aria-modal="true"- aria-label="OpenUI Inspect"- inert={!open}- onClick={(event) => event.stopPropagation()}- >- <div style={styles.header}>- <div style={styles.headerLeft}>- <span style={styles.title}>OpenUI Inspect</span>- </div>- <div style={styles.headerActions}>- <IconButton- onClick={() => setEvents([])}- aria-label="Reset events"- title="Reset events"- >- <RotateCcw size={14} />- </IconButton>- <SettingsMenu config={config} onChange={setConfig} />- <IconButton onClick={() => setOpen(false)} aria-label="Close OpenUI Inspect">- <X size={15} />- </IconButton>- </div>+ <div style={styles.header}>+ <div style={styles.headerLeft}>+ <span style={styles.title}>OpenUI Inspect</span></div>-- <div style={styles.bannerGroup}>- <span style={styles.bannerFade} aria-hidden />- <a- style={styles.docsBanner}- href={RELIABILITY_DOCS_URL}- target="_blank"- rel="noreferrer"- title="Learn how to track and fix errors in production"- onMouseEnter={() => setBannerHovered(true)}- onMouseLeave={() => setBannerHovered(false)}+ <div style={styles.headerActions}>+ <IconButton+ onClick={() => setEvents([])}+ aria-label="Reset events"+ title="Reset events">- <span style={styles.docsBannerText}>- <span style={styles.docsBannerTitle}>- Want to track and fix errors in production?- </span>- </span>- <span- style={{- ...styles.docsBannerAction,- ...(bannerHovered ? styles.docsBannerActionHover : null),- }}- >- Learn more- </span>- </a>+ <RotateCcw size={14} />+ </IconButton>+ <SettingsMenu config={config} onChange={setConfig} />+ <IconButton onClick={() => setOpen(false)} aria-label="Close OpenUI Inspect">+ <X size={15} />+ </IconButton></div>+ </div>++ <ErrorBoundary title="Inspect ran into a problem"><div style={styles.list}>{visibleEvents.length === 0 ? (<div style={styles.empty}>@@ -248,15 +249,39 @@ export function OpenUIDevtools({if (quotaError) return <QuotaErrorRow key={key} info={quotaError} />;const stream = getReactLangStreamDetail(event);if (stream) {- return <ReactLangStreamEventRow key={key} event={event} stream={stream} />;+ return (+ <ReactLangStreamEventRow+ key={key}+ event={event}+ stream={stream}+ canOpenInDebug={debug.canOpen}+ onOpenInDebug={debug.openWith}+ />+ );}return <EventRow key={key} event={event} />;}))}</div>- <span style={styles.trayFade} aria-hidden />- </aside>- </div>+ </ErrorBoundary>+ <span style={styles.trayFade} aria-hidden />+ </aside>++ <aside+ style={{+ ...styles.drawer,+ ...rootStyle(mode),+ ...(debug.trayOpen ? styles.drawerOpen : null),+ ...debugTray,+ }}+ role="dialog"+ aria-modal={false}+ aria-label="OpenUI Debug"+ inert={!debug.trayOpen}+ >+ <div style={styles.debugHost}>{debug.view}</div>+ </aside>+ {debug.portal}</DevtoolsModeProvider>);}@@ -295,7 +320,7 @@ function SettingSwitch({/*** Header dropdown for the display filters and the widget theme, so the list is* all list. Escape is handled in the capture phase so closing the menu doesn't- * also close the drawer.+ * also step the drawer back.*/function SettingsMenu({config,@@ -421,25 +446,13 @@ function uiStyles(t: ThemeTokens) {fontWeight: 700,lineHeight: 1,},- backdrop: {- position: "fixed",- inset: 0,- background: t.overlay,- // Max 32-bit signed int — the open drawer sits above everything, including the toggle.- zIndex: 2147483647,- opacity: 0,- visibility: "hidden",- pointerEvents: "none",- transition: "opacity 200ms ease, visibility 0s linear 200ms",- },- backdropOpen: {- opacity: 1,- visibility: "visible",- pointerEvents: "auto",- transition: "opacity 200ms ease, visibility 0s",- },+ // Geometry (right/width/transform) is per-tray and set inline; this is the+ // shared UI. Each tray hides itself when closed so the other can stay open+ // without a retracted tray remaining focusable.drawer: {position: "fixed",+ // Max 32-bit signed int — sit above any app UI, including the toggle.+ zIndex: 2147483647,boxSizing: "border-box",display: "flex",flexDirection: "column",@@ -453,12 +466,18 @@ function uiStyles(t: ThemeTokens) {fontFamily: FONT,fontSize: 13,visibility: "hidden",- transition: "transform 220ms cubic-bezier(0.32, 0.72, 0, 1), visibility 0s linear 220ms",+ transition:+ "transform 220ms cubic-bezier(0.32, 0.72, 0, 1), right 260ms cubic-bezier(0.32, 0.72, 0, 1), width 260ms cubic-bezier(0.32, 0.72, 0, 1), visibility 0s linear 220ms",overflow: "hidden",},drawerOpen: {visibility: "visible",- transition: "transform 220ms cubic-bezier(0.32, 0.72, 0, 1), visibility 0s",+ transition:+ "transform 220ms cubic-bezier(0.32, 0.72, 0, 1), right 260ms cubic-bezier(0.32, 0.72, 0, 1), width 260ms cubic-bezier(0.32, 0.72, 0, 1), visibility 0s",+ },+ debugHost: {+ flex: 1,+ minHeight: 0,},header: {display: "flex",@@ -573,16 +592,9 @@ function uiStyles(t: ThemeTokens) {fontWeight: 500,color: t.fg,},- bannerGroup: {- position: "relative",- zIndex: 1,- display: "flex",- flexDirection: "column",- gap: 8,- flexShrink: 0,- background: t.bg,- padding: "12px 12px 18px",- },+ // Mirrors bannerFade at the tray's bottom edge, so rows dissolve into the+ // drawer instead of meeting the border mid-row. Pinned to the tray rather+ // than the list, so it covers the stack-trace view too.trayFade: {position: "absolute",left: 0,@@ -592,57 +604,6 @@ function uiStyles(t: ThemeTokens) {background: `linear-gradient(to top, ${t.bg}, transparent)`,pointerEvents: "none",},- bannerFade: {- position: "absolute",- left: 0,- right: 0,- top: "100%",- height: 12,- background: `linear-gradient(to bottom, ${t.bg}, transparent)`,- pointerEvents: "none",- },- docsBanner: {- display: "flex",- alignItems: "center",- justifyContent: "space-between",- gap: 12,- flexShrink: 0,- textDecoration: "none",- borderRadius: 12,- background: t.promoBg,- color: t.fg,- cursor: "pointer",- fontFamily: FONT,- textAlign: "left",- padding: "12px 14px",- },- docsBannerText: {- display: "flex",- flexDirection: "column",- gap: 2,- minWidth: 0,- },- docsBannerTitle: {- fontSize: 12,- fontWeight: 500,- },- docsBannerAction: {- display: "inline-flex",- alignItems: "center",- justifyContent: "center",- flexShrink: 0,- border: `1px solid ${t.controlBorder}`,- borderRadius: 8,- background: t.controlBg,- color: t.fg,- boxShadow: t.shadowSubtle,- fontSize: 11,- padding: "5px 12px",- transition: "transform 150ms ease",- },- docsBannerActionHover: {- transform: "scale(0.96)",- },list: {flex: 1,minHeight: 0,@@ -652,6 +613,8 @@ function uiStyles(t: ThemeTokens) {flexDirection: "column",gap: 10,},+ // Fills the list so the message sits in the middle of the tray, not pinned+ // under the header.empty: {flex: 1,minHeight: 0,diff --git a/packages/devtools/src/debug/DebugUI.tsx b/packages/devtools/src/debug/DebugUI.tsxindex 6c1d73459..8e93e5413 100644--- a/packages/devtools/src/debug/DebugUI.tsx+++ b/packages/devtools/src/debug/DebugUI.tsx@@ -1,5 +1,5 @@import { Maximize2, Minimize2, X } from "lucide-react";-import { Component, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";+import { useMemo, useRef, useState, type CSSProperties } from "react";import { type RegisteredLibrary } from "../lib";import {FONT,@@ -9,7 +9,7 @@ import {type ColorMode,type ThemeTokens,} from "../theme";-import { IconButton, ThemeToggle } from "../ui";+import { ErrorBoundary, IconButton, ThemeToggle } from "../ui";import { librarySchema, useReactLang, useStream, useValidation } from "./lib";import { JsonPanel, RenderPanel, StreamTimeline, TreePanel, ValidationPanel } from "./panels";import { debugStyles } from "./styles";@@ -31,30 +31,6 @@ const TABS: { id: Tab; label: string }[] = [{ 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;@@ -189,115 +165,117 @@ export function DebugUI({</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>+ <ErrorBoundary title="Debug ran into a problem">+ {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- 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));+ ref={bodyRef}+ style={{+ ...styles.body,+ gridTemplateColumns: `${editorPct}% ${SPLITTER}px minmax(0, 1fr)`,}}- 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),+ <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));}}- aria-hidden+ 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.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>- );- })}+ <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.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 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" }}>+ <ErrorBoundary title="This preview crashed" resetKey={stream.renderedCode}>+ <RenderPanel+ Renderer={lang.Renderer}+ library={selected.library}+ code={stream.renderedCode}+ isStreaming={stream.isStreaming}+ />+ </ErrorBoundary>+ </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>+ </ErrorBoundary></div>);}diff --git a/packages/devtools/src/debug/index.ts b/packages/devtools/src/debug/index.tsindex 2a9bda496..4a6cd2872 100644--- a/packages/devtools/src/debug/index.ts+++ b/packages/devtools/src/debug/index.ts@@ -6,3 +6,4 @@ export {type DebugUIProps,} from "./DebugUI";export { debugMountNode, openDebugWindow } from "./eject";+export { useDebug } from "./useDebug";diff --git a/packages/devtools/src/debug/styles.ts b/packages/devtools/src/debug/styles.tsindex 0327d5888..ef422b517 100644--- a/packages/devtools/src/debug/styles.ts+++ b/packages/devtools/src/debug/styles.ts@@ -10,6 +10,7 @@ export function debugStyles(t: ThemeTokens) {alignItems: "center",gap: 10,flexWrap: "wrap",+ flexShrink: 0,padding: "8px 16px",borderBottom: `1px solid ${t.borderSubtle}`,background: t.bg,diff --git a/packages/devtools/src/debug/useDebug.tsx b/packages/devtools/src/debug/useDebug.tsxnew file mode 100644index 000000000..2fd32da7a--- /dev/null+++ b/packages/devtools/src/debug/useDebug.tsx@@ -0,0 +1,128 @@+import { useCallback, useEffect, useState, type ReactNode } from "react";+import { createPortal } from "react-dom";+import { useRegisteredLibraries, type DevtoolsConfig } from "../lib";+import type { ColorMode } from "../theme";+import { DebugUI } from "./DebugUI";+import { debugMountNode, openDebugWindow } from "./eject";++/**+ * Session for OpenUI Debug: editor contents, registered libraries, tray vs+ * ejected window. Inspect stays independent — this hook never opens or closes+ * that tray. Escape should call `retract` (tray only); Debug's own close+ * button calls `close` (tray and popup).+ */+export function useDebug({+ theme,+ helpSeen,+ editorPct,+ setConfig,+}: {+ theme: ColorMode;+ helpSeen: boolean;+ editorPct: number;+ setConfig: (patch: Partial<DevtoolsConfig>) => void;+}): {+ trayOpen: boolean;+ canOpen: boolean;+ openWith: (response: string, libraryId?: string) => void;+ close: () => void;+ retract: () => void;+ view: ReactNode;+ portal: ReactNode;+} {+ const libraries = useRegisteredLibraries();+ const [trayOpen, setTrayOpen] = useState(false);+ const [popup, setPopup] = useState<Window | null>(null);+ const [popupBlocked, setPopupBlocked] = useState(false);+ const [code, setCode] = useState("");+ const [libraryId, setLibraryId] = useState<string | undefined>();+ const markHelpSeen = useCallback(() => setConfig({ helpSeen: true }), [setConfig]);++ useEffect(() => {+ if (!popup) return;+ const onGone = () => setPopup(null);+ popup.addEventListener("pagehide", onGone);+ return () => popup.removeEventListener("pagehide", onGone);+ }, [popup]);++ const close = useCallback(() => {+ if (popup) {+ popup.close();+ setPopup(null);+ }+ setTrayOpen(false);+ setPopupBlocked(false);+ }, [popup]);++ const retract = useCallback(() => setTrayOpen(false), []);++ const eject = useCallback(() => {+ const next = openDebugWindow();+ if (!next) {+ setPopupBlocked(true);+ return;+ }+ setPopupBlocked(false);+ setPopup(next);+ setTrayOpen(false);+ }, []);++ const minimize = useCallback(() => {+ if (popup) {+ popup.close();+ setPopup(null);+ }+ setPopupBlocked(false);+ setTrayOpen(true);+ }, [popup]);++ const open = useCallback(() => {+ setPopupBlocked(false);+ if (popup && !popup.closed) {+ popup.focus();+ return;+ }+ if (popup) setPopup(null);+ setTrayOpen(true);+ }, [popup]);++ const openWith = useCallback(+ (response: string, nextLibraryId?: string) => {+ setCode(response);+ setLibraryId(nextLibraryId);+ open();+ },+ [open],+ );++ const view = (+ <DebugUI+ libraries={libraries}+ code={code}+ onCodeChange={setCode}+ libraryId={libraryId}+ editorPct={editorPct}+ onEditorPctChange={(pct) => setConfig({ editorPct: pct })}+ ejected={Boolean(popup)}+ onEject={eject}+ onMinimize={minimize}+ onClose={close}+ theme={theme}+ onThemeChange={(next) => setConfig({ theme: next })}+ helpSeen={helpSeen}+ onHelpSeen={markHelpSeen}+ popupBlocked={popupBlocked}+ />+ );+ const popupRoot = popup ? debugMountNode(popup) : null;++ return {+ trayOpen,+ canOpen: libraries.length > 0,+ openWith,+ close,+ retract,+ view,+ portal: popupRoot ? createPortal(view, popupRoot) : null,+ };+}diff --git a/packages/devtools/src/index.ts b/packages/devtools/src/index.tsindex aec6480b8..e935246f0 100644--- a/packages/devtools/src/index.ts+++ b/packages/devtools/src/index.ts@@ -1,3 +1,4 @@"use client";export { OpenUIDevtools, type OpenUIDevtoolsProps } from "./OpenUIDevtools";+export type { ColorMode } from "./theme";diff --git a/packages/devtools/src/lib/useDevtoolsConfig.ts b/packages/devtools/src/lib/useDevtoolsConfig.tsindex 058745d4c..ad57ec705 100644--- a/packages/devtools/src/lib/useDevtoolsConfig.ts+++ b/packages/devtools/src/lib/useDevtoolsConfig.ts@@ -1,4 +1,5 @@import { useCallback, useEffect, useRef, useState } from "react";+import { MAX_EDITOR_PCT, MIN_EDITOR_PCT } from "../debug/DebugUI";import type { ColorMode } from "../theme";const STORAGE_KEY = "openui.devtools.config";@@ -7,6 +8,10 @@ export type DevtoolsConfig = {autoOpen: boolean;onlyErrors: boolean;theme: ColorMode;+ /** Set once the Debug help dialog has been dismissed, so it only greets once. */+ helpSeen: boolean;+ /** Editor column width in OpenUI Debug, as a percentage of the split. */+ editorPct: number;};function isColorMode(value: unknown): value is ColorMode {@@ -18,6 +23,10 @@ function sanitize(patch: Partial<DevtoolsConfig>): Partial<DevtoolsConfig> {if (typeof patch.autoOpen === "boolean") next.autoOpen = patch.autoOpen;if (typeof patch.onlyErrors === "boolean") next.onlyErrors = patch.onlyErrors;if (isColorMode(patch.theme)) next.theme = patch.theme;+ if (typeof patch.helpSeen === "boolean") next.helpSeen = patch.helpSeen;+ if (typeof patch.editorPct === "number" && Number.isFinite(patch.editorPct)) {+ next.editorPct = Math.min(MAX_EDITOR_PCT, Math.max(MIN_EDITOR_PCT, patch.editorPct));+ }return next;}diff --git a/packages/devtools/src/ui/ErrorBoundary.tsx b/packages/devtools/src/ui/ErrorBoundary.tsxnew file mode 100644index 000000000..c37d7e61a--- /dev/null+++ b/packages/devtools/src/ui/ErrorBoundary.tsx@@ -0,0 +1,164 @@+import { CircleAlert } from "lucide-react";+import { Component, type CSSProperties, type ReactNode } from "react";+import { FONT, useStyles, type ThemeTokens } from "../theme";++/** GitHub Issues for the OpenUI repo — the report destination from a crashed tray. */+export const ISSUES_URL = "https://github.com/thesysdev/openui/issues/new?template=bug_report.md";++const FILL: CSSProperties = {+ flex: 1,+ minHeight: 0,+ display: "flex",+ flexDirection: "column",+ overflow: "hidden",+};++/**+ * Catches render crashes in Inspect and Debug so the tray stays up and the+ * host app is not taken down with it. The fallback points at OpenUI's Issues+ * page; Try again remounts the children.+ */+export class ErrorBoundary extends Component<+ { children: ReactNode; title: string; resetKey?: string },+ { error: Error | null; lastResetKey: string | undefined }+> {+ constructor(props: { children: ReactNode; title: string; resetKey?: string }) {+ super(props);+ this.state = { error: null, lastResetKey: props.resetKey };+ }++ static getDerivedStateFromError(error: Error) {+ return { error };+ }++ static getDerivedStateFromProps(+ props: { resetKey?: string },+ state: { error: Error | null; lastResetKey: string | undefined },+ ) {+ if (props.resetKey !== state.lastResetKey) {+ return { error: null, lastResetKey: props.resetKey };+ }+ return null;+ }++ override componentDidCatch(error: Error) {+ console.error("[OpenUI Devtools]", error);+ }++ override render() {+ if (this.state.error) {+ return (+ <div style={FILL} role="alert">+ <ErrorFallback+ title={this.props.title}+ error={this.state.error}+ onRetry={() => this.setState({ error: null })}+ />+ </div>+ );+ }+ return <div style={FILL}>{this.props.children}</div>;+ }+}++function ErrorFallback({+ title,+ error,+ onRetry,+}: {+ title: string;+ error: Error;+ onRetry: () => void;+}) {+ const styles = useStyles(fallbackStyles);+ return (+ <div style={styles.wrap}>+ <span style={styles.icon} aria-hidden>+ <CircleAlert size={20} />+ </span>+ <p style={styles.title}>{title}</p>+ {error.message ? <pre style={styles.message}>{error.message}</pre> : null}+ <p style={styles.hint}>Help us improve OpenUI by reporting it on GitHub.</p>+ <div style={styles.actions}>+ <button type="button" style={styles.action} onClick={onRetry}>+ Try again+ </button>+ <a style={styles.action} href={ISSUES_URL} target="_blank" rel="noreferrer">+ Report an issue+ </a>+ </div>+ </div>+ );+}++function fallbackStyles(t: ThemeTokens) {+ const action: CSSProperties = {+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ boxSizing: "border-box",+ border: `1px solid ${t.controlBorder}`,+ borderRadius: 8,+ background: t.controlBg,+ color: t.fg,+ boxShadow: t.shadowSubtle,+ cursor: "pointer",+ fontFamily: FONT,+ fontSize: 12,+ fontWeight: 500,+ textDecoration: "none",+ padding: "6px 12px",+ };+ return {+ wrap: {+ flex: 1,+ minHeight: 0,+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ gap: 10,+ padding: 24,+ color: t.fg,+ textAlign: "center",+ },+ icon: {+ display: "inline-flex",+ color: t.danger,+ },+ title: {+ margin: 0,+ fontSize: 13,+ fontWeight: 600,+ },+ message: {+ margin: 0,+ maxWidth: "100%",+ maxHeight: 96,+ overflow: "auto",+ borderRadius: 8,+ color: t.fgSecondary,+ fontFamily: FONT,+ fontSize: 12,+ lineHeight: 1.45,+ textAlign: "left",+ whiteSpace: "pre-wrap",+ wordBreak: "break-word",+ },+ hint: {+ margin: 0,+ color: t.fgMuted,+ fontSize: 12,+ lineHeight: 1.45,+ },+ actions: {+ display: "flex",+ flexWrap: "wrap",+ alignItems: "center",+ justifyContent: "center",+ gap: 8,+ marginTop: 4,+ },+ action,+ } satisfies Record<string, CSSProperties>;+}diff --git a/packages/devtools/src/ui/index.ts b/packages/devtools/src/ui/index.tsindex 896118b8e..baa351da0 100644--- a/packages/devtools/src/ui/index.ts+++ b/packages/devtools/src/ui/index.ts@@ -1,3 +1,4 @@+export { ErrorBoundary, ISSUES_URL } from "./ErrorBoundary";export { IconButton } from "./IconButton";export { ShiroLogo } from "./ShiroLogo";export { ThemeSegmented, ThemeToggle } from "./ThemeToggle";