The Open Standard for Generative UI
Add a JS token map for Devtools theming. (#1013)
ABaba19bd1d16d
diff --git a/packages/devtools/src/OpenUIDevtools.test.ts b/packages/devtools/src/OpenUIDevtools.test.tsindex 0f4a4bf61..c2122af1c 100644--- a/packages/devtools/src/OpenUIDevtools.test.ts+++ b/packages/devtools/src/OpenUIDevtools.test.ts@@ -30,7 +30,7 @@ function render(props: OpenUIDevtoolsProps): void {/** The floating toggle button. */function toggle(): HTMLButtonElement {const button = container.querySelector<HTMLButtonElement>(- 'button[aria-label="Open OpenUI devtools"]',+ 'button[aria-label="Open OpenUI Inspect"]',);if (!button) throw new Error("toggle button not found");return button;@@ -45,6 +45,29 @@ function buttonByText(text: string): HTMLButtonElement | undefined {HTMLButtonElement | undefined;}+/**+ * 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".+ */+function overviewStats(): string[] {+ const row = container.querySelector<HTMLElement>(+ 'button[aria-label="Toggle OpenUI Lang stream details"] > div:last-child',+ );+ return [...(row?.children ?? [])].map((stat) => {+ const count = stat.firstElementChild?.textContent ?? "";+ return `${count} ${(stat.textContent ?? "").slice(count.length)}`;+ });+}++/** The display filters live behind the header settings button. */+function openSettings(): void {+ const button = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Devtools settings"]',+ );+ if (!button) throw new Error("settings button not found");+ click(button);+}+function checkboxLabeled(text: string): HTMLInputElement {const label = [...container.querySelectorAll("label")].find((el) =>el.textContent?.includes(text),@@ -99,12 +122,14 @@ describe("OpenUIDevtools", () => {it("restores auto-open on error from a previous session", () => {render({ enabled: true, autoOpenOnError: true });+ openSettings();expect(checkboxLabeled("Auto-open on error").checked).toBe(true);act(() => checkboxLabeled("Auto-open on error").click());expect(checkboxLabeled("Auto-open on error").checked).toBe(false);remount({ enabled: true, autoOpenOnError: true });+ openSettings();expect(checkboxLabeled("Auto-open on error").checked).toBe(false);act(() => observability.error({ kind: "boom" }));@@ -113,11 +138,13 @@ describe("OpenUIDevtools", () => {it("restores the errors-only filter from a previous session", () => {render({ enabled: true, errorsOnly: false });- act(() => checkboxLabeled("Errors only").click());- expect(checkboxLabeled("Errors only").checked).toBe(true);+ openSettings();+ act(() => checkboxLabeled("Show errors only").click());+ expect(checkboxLabeled("Show errors only").checked).toBe(true);remount({ enabled: true, errorsOnly: false });- expect(checkboxLabeled("Errors only").checked).toBe(true);+ openSettings();+ expect(checkboxLabeled("Show errors only").checked).toBe(true);act(() => observability.info({ kind: "just-info" }));act(() => observability.error({ kind: "real-error" }));@@ -159,15 +186,23 @@ describe("OpenUIDevtools", () => {expect(container.textContent).toContain("Needs attention");});- it("drills into the stack trace when a row's Stack Trace is clicked", () => {+ it("expands the stack trace on the error card", () => {render({ enabled: true, errorsOnly: false });- act(() => observability.error({ kind: "boom", error: toErrorInfo(new Error("kaboom")) }));+ const err = new Error("kaboom");+ err.stack = "Error: kaboom\n at boom (app.ts:1:1)";+ act(() => observability.error({ kind: "boom", error: toErrorInfo(err) }));- const stackButton = buttonByText("Stack Trace");- expect(stackButton).toBeDefined();- click(stackButton!);+ expect(container.textContent).toContain("kaboom");+ expect(container.textContent).not.toContain("at boom (app.ts:1:1)");++ const expand = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Toggle stack trace"]',+ );+ expect(expand).not.toBeNull();+ click(expand!);- expect(container.textContent).toContain("stack trace");+ expect(container.textContent).toContain("at boom (app.ts:1:1)");+ expect(buttonByText("Copy")).toBeDefined();});it("coalesces react-lang stream updates by their stable event id", () => {@@ -195,10 +230,10 @@ describe("OpenUIDevtools", () => {);expect(container.textContent?.match(/OpenUI Lang stream/g)).toHaveLength(1);- expect(container.textContent).toContain("info");+ expect(container.querySelector('[aria-label="info"]')).not.toBeNull();expect(container.textContent).toContain("Streaming");- expect(container.textContent).toContain("2 statements");- expect(container.textContent).toContain("1 orphaned statement");+ expect(overviewStats()).toContain("2 statements");+ expect(overviewStats()).toContain("1 orphaned statement");expect(container.textContent).not.toContain("stream-1");expect(container.textContent).not.toContain('root = Card("done")');@@ -248,8 +283,8 @@ describe("OpenUIDevtools", () => {expect(container.textContent?.match(/OpenUI Lang stream/g)).toHaveLength(1);expect(container.textContent).not.toContain("settled");expect(container.textContent).not.toContain("Streaming");- expect(container.textContent).toContain("1 statement");- expect(container.textContent).toContain("1 error");+ expect(overviewStats()).toContain("1 statement");+ expect(overviewStats()).toContain("1 error");expect(container.textContent).not.toContain("Unknown component Ghost");const expand = container.querySelector<HTMLButtonElement>(@@ -332,7 +367,7 @@ describe("OpenUIDevtools", () => {render({ enabled: true });act(() => secondRoot.render(createElement(OpenUIDevtools, { enabled: true })));- expect(document.querySelectorAll('button[aria-label="Open OpenUI devtools"]')).toHaveLength(1);+ expect(document.querySelectorAll('button[aria-label="Open OpenUI Inspect"]')).toHaveLength(1);act(() => secondRoot.unmount());second.remove();@@ -341,7 +376,7 @@ describe("OpenUIDevtools", () => {it("lets a manual instance win over an auto-mounted one", () => {// Auto-mounted instance first (as react-lang's bootstrap would do) …render({ enabled: true, __autoMounted: true });- expect(container.querySelector('button[aria-label="Open OpenUI devtools"]')).not.toBeNull();+ expect(container.querySelector('button[aria-label="Open OpenUI Inspect"]')).not.toBeNull();// … then a manual instance mounts and takes over.const manual = document.createElement("div");@@ -349,13 +384,13 @@ describe("OpenUIDevtools", () => {const manualRoot = createRoot(manual);act(() => manualRoot.render(createElement(OpenUIDevtools, { enabled: true })));- expect(container.querySelector('button[aria-label="Open OpenUI devtools"]')).toBeNull();- expect(manual.querySelector('button[aria-label="Open OpenUI devtools"]')).not.toBeNull();+ expect(container.querySelector('button[aria-label="Open OpenUI Inspect"]')).toBeNull();+ expect(manual.querySelector('button[aria-label="Open OpenUI Inspect"]')).not.toBeNull();// When the manual instance unmounts, the auto instance takes back over.act(() => manualRoot.unmount());manual.remove();- expect(container.querySelector('button[aria-label="Open OpenUI devtools"]')).not.toBeNull();+ expect(container.querySelector('button[aria-label="Open OpenUI Inspect"]')).not.toBeNull();});it("removes a resolved stream from the errors-only view", () => {diff --git a/packages/devtools/src/OpenUIDevtools.tsx b/packages/devtools/src/OpenUIDevtools.tsxindex 1b673d92e..ed370d3ff 100644--- a/packages/devtools/src/OpenUIDevtools.tsx+++ b/packages/devtools/src/OpenUIDevtools.tsx@@ -1,18 +1,45 @@"use client";+import { observability, type ObservabilityEvent } from "@openuidev/observability";+import { Inbox, RotateCcw, Settings, X } from "lucide-react";+import { useEffect, useRef, useState, type CSSProperties } from "react";import {- observability,- type ObservabilityErrorInfo,- type ObservabilityEvent,-} from "@openuidev/observability";-import { ArrowLeft, Check, Copy, WrapText, X } from "lucide-react";-import { useEffect, useState, type CSSProperties } from "react";-import { getQuotaError, QuotaErrorRow } from "./QuotaErrorRow";-import { getReactLangStreamDetail, ReactLangStreamEventRow } from "./ReactLangStreamEventRow";-import { ShiroLogo } from "./ShiroLogo";-import { addOrReplaceEvent } from "./eventBuffer";-import { useDevtoolsSingleton } from "./singleton";-import { useDevtoolsConfig } from "./useDevtoolsConfig";+ EventRow,+ getQuotaError,+ getReactLangStreamDetail,+ QuotaErrorRow,+ ReactLangStreamEventRow,+} from "./inspect";+import {+ addOrReplaceEvent,+ useDevtoolsConfig,+ useDevtoolsSingleton,+ type DevtoolsConfig,+} from "./lib";+import {+ DEFAULT_COLOR_MODE,+ DevtoolsModeProvider,+ FONT,+ rootStyle,+ theme,+ useStyles,+ type ColorMode,+ type ThemeTokens,+} from "./theme";+import { IconButton, ShiroLogo, ThemeSegmented } from "./ui";++const RELIABILITY_DOCS_URL = "https://www.openui.com/docs/openui-lang/reliability";++/** 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.+ */+const TRAY_EDGE = 12;+const INSPECT_WIDTH = 480;+const BLOCK_H = `min(85vh, 2234px)`;export type DevtoolsPosition = "top-left" | "top-right" | "bottom-left" | "bottom-right";@@ -28,6 +55,12 @@ export interface OpenUIDevtoolsProps {errorsOnly?: boolean;/** Initial state of the drawer's "auto-open on error" checkbox. Defaults to true. */autoOpenOnError?: boolean;+ /**+ * Widget UI theme. If passed, it wins over the stored Settings choice+ * and is written to config. Otherwise the stored theme is used, then light.+ * Never auto-detected from the host page or the OS.+ */+ theme?: ColorMode;/*** @internal Set by react-lang's auto-mount. Auto-mounted instances yield to* any manually rendered <OpenUIDevtools /> so host-provided props win.@@ -37,10 +70,10 @@ export interface OpenUIDevtoolsProps {/*** dev-only widget that surfaces events captured by `@openuidev/observability` —- * a Shiro-logo button (with an error-count badge) that opens a left side drawer- * listing every captured event; selecting one drills into its stack trace. A- * checkbox in the drawer controls whether it auto-opens on error. Renders- * nothing in production unless `enabled` is set explicitly.+ * 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.*/export function OpenUIDevtools({enabled,@@ -48,6 +81,7 @@ export function OpenUIDevtools({maxEvents = 50,errorsOnly = false,autoOpenOnError = true,+ theme: themeProp,__autoMounted = false,}: OpenUIDevtoolsProps) {const isEnabled =@@ -57,14 +91,18 @@ export function OpenUIDevtools({const isSingleton = useDevtoolsSingleton(__autoMounted);const [events, setEvents] = useState<ObservabilityEvent[]>([]);const [open, setOpen] = useState(false);- const [selected, setSelected] = useState<ObservabilityEvent | null>(null);- const [wrapStack, setWrapStack] = useState(false);- const [copied, setCopied] = useState(false);- const { config, setConfig, configRef } = useDevtoolsConfig({- autoOpen: autoOpenOnError,- onlyErrors: errorsOnly,- });- const { autoOpen, onlyErrors } = config;+ const [toggleHovered, setToggleHovered] = useState(false);+ const [bannerHovered, setBannerHovered] = useState(false);+ const { config, setConfig, configRef } = useDevtoolsConfig(+ {+ autoOpen: autoOpenOnError,+ onlyErrors: errorsOnly,+ theme: DEFAULT_COLOR_MODE,+ },+ { theme: themeProp },+ );+ const { onlyErrors, theme: mode } = config;+ const styles = uiStyles(theme(mode));// Read configRef inside the (stable) subscription without re-subscribing.useEffect(() => {@@ -75,267 +113,256 @@ export function OpenUIDevtools({});}, [isEnabled, maxEvents, configRef]);- // Escape steps back: stack view → list, list → closed.+ // Escape closes Inspect. The settings menu handles its own Escape first+ // (capture phase), so it never falls through to here.useEffect(() => {if (!open) return;const onKeyDown = (event: KeyboardEvent) => {if (event.key !== "Escape") return;- if (selected) setSelected(null);- else setOpen(false);+ setOpen(false);};document.addEventListener("keydown", onKeyDown);return () => document.removeEventListener("keydown", onKeyDown);- }, [open, selected]);+ }, [open]);if (!isEnabled || !isSingleton) return null;const errorCount = events.filter((event) => event.level === "error").length;const visibleEvents = onlyErrors ? events.filter((event) => event.level !== "info") : events;- const openDrawer = () => {- setSelected(null);- setOpen(true);- };-- const showStack = (event: ObservabilityEvent) => {- setSelected(event);- setCopied(false);- };-- const copyStack = () => {- if (!selected || typeof navigator === "undefined" || !navigator.clipboard) return;- navigator.clipboard- .writeText(getErrorInfo(selected)?.stack ?? "")- .then(() => {- setCopied(true);- setTimeout(() => setCopied(false), 1500);- })- .catch(() => {});+ const inspectTray: CSSProperties = {+ right: TRAY_EDGE,+ bottom: TRAY_EDGE,+ height: BLOCK_H,+ width: `min(${INSPECT_WIDTH}px, calc(100vw - ${TRAY_EDGE * 2}px))`,+ transform: open ? "translateX(0)" : `translateX(calc(100% + ${TRAY_EDGE}px))`,};- const selectedStack = selected ? (getErrorInfo(selected)?.stack ?? "") : "";-return (- <>- <div style={{ ...styles.toggleWrap, ...positionStyles[position] }}>+ <DevtoolsModeProvider mode={mode}>+ <div style={{ ...styles.toggleWrap, ...rootStyle(mode), ...positionStyles[position] }}><button- style={{ ...styles.toggle, ...(errorCount > 0 ? styles.toggleError : null) }}- onClick={openDrawer}- aria-label="Open OpenUI devtools"+ style={{+ ...styles.toggle,+ ...(errorCount > 0 ? styles.toggleError : null),+ ...(toggleHovered ? styles.toggleHover : null),+ }}+ onClick={() => setOpen(true)}+ onMouseEnter={() => setToggleHovered(true)}+ onMouseLeave={() => setToggleHovered(false)}+ aria-label="Open OpenUI Inspect"aria-expanded={open}+ title={+ errorCount > 0 ? `${errorCount} error${errorCount === 1 ? "" : "s"}` : "OpenUI Inspect"+ }>- <ShiroLogo size={22} />- {errorCount > 0 ? <span style={styles.toggleCount}>{errorCount}</span> : null}+ {errorCount > 0 ? (+ <span style={styles.toggleCount}>{errorCount > 99 ? "99+" : errorCount}</span>+ ) : (+ <ShiroLogo size={22} />+ )}</button></div>{/* Kept mounted so open/close can transition; hidden + inert when closed. */}<div- style={{ ...styles.backdrop, ...(open ? styles.backdropOpen : null) }}+ style={{+ ...styles.backdrop,+ ...rootStyle(mode),+ ...(open ? styles.backdropOpen : null),+ }}onClick={() => setOpen(false)}><aside- style={{ ...styles.drawer, ...(open ? styles.drawerOpen : null) }}+ style={{+ ...styles.drawer,+ ...inspectTray,+ ...(open ? styles.drawerOpen : null),+ }}role="dialog"aria-modal="true"- aria-label="OpenUI devtools"+ aria-label="OpenUI Inspect"+ inert={!open}onClick={(event) => event.stopPropagation()}><div style={styles.header}><div style={styles.headerLeft}>- {selected ? (- <button- style={styles.iconButton}- onClick={() => setSelected(null)}- aria-label="Back to event list"- >- <ArrowLeft size={14} />- </button>- ) : null}- <span style={styles.title}>- {selected ? `${selected.level} — stack trace` : "OpenUI Devtools"}- </span>+ <span style={styles.title}>OpenUI Inspect</span></div><div style={styles.headerActions}>- {selected ? (- <>- <button- style={{- ...styles.textButton,- ...(wrapStack ? styles.textButtonActive : null),- }}- onClick={() => setWrapStack((prev) => !prev)}- aria-pressed={wrapStack}- >- <WrapText size={12} />- Wrap- </button>- <button style={styles.textButton} onClick={copyStack}>- {copied ? <Check size={12} /> : <Copy size={12} />}- {copied ? "Copied" : "Copy"}- </button>- </>- ) : (- <button style={styles.textButton} onClick={() => setEvents([])}>- Clear- </button>- )}- <button- style={styles.iconButton}- onClick={() => setOpen(false)}- aria-label="Close OpenUI devtools"+ <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} />- </button>+ </IconButton></div></div>- {selected ? (- <div style={styles.stackBody}>- {selectedStack.split("\n").map((line, index) => (- <div key={index} style={styles.stackLine}>- <span style={styles.lineNumber}>{index + 1}</span>- <span style={{ ...styles.lineText, ...(wrapStack ? styles.lineTextWrap : null) }}>- {line || " "}- </span>- </div>- ))}- </div>- ) : (- <>- <div style={styles.controlsRow}>- <label style={styles.checkboxLabel}>- <input- type="checkbox"- checked={autoOpen}- onChange={(event) => setConfig({ autoOpen: event.target.checked })}- />- Auto-open on error- </label>- <label style={styles.checkboxLabel}>- <input- type="checkbox"- checked={onlyErrors}- onChange={(event) => setConfig({ onlyErrors: event.target.checked })}- />- Errors only- </label>- </div>- <div style={styles.list}>- {visibleEvents.length === 0 ? (- <div style={styles.empty}>No events captured yet.</div>- ) : (- visibleEvents.map((event, index) => {- const key =- typeof event.detail["id"] === "string"- ? event.detail["id"]- : `${event.timestamp}-${index}`;- const quotaError = getQuotaError(event);- if (quotaError) return <QuotaErrorRow key={key} info={quotaError} />;- const stream = getReactLangStreamDetail(event);- if (stream) {- return <ReactLangStreamEventRow key={key} event={event} stream={stream} />;- }-- const error = getErrorInfo(event);- const detail = asRecord(event.detail);- const kind = asString(detail["kind"]);- const status =- typeof detail["status"] === "number" ? String(detail["status"]) : undefined;- const message = error?.message ?? asString(detail["message"]);- return (- <div key={key} style={styles.row}>- <div style={styles.rowHeader}>- <div style={styles.badgeGroup}>- <span style={{ ...styles.badge, ...badgeByLevel[event.level] }}>- {event.level}- </span>- {kind ? (- <span style={{ ...styles.badge, ...styles.badgeNeutral }}>- {kind}- </span>- ) : null}- {status ? (- <span style={{ ...styles.badge, ...styles.badgeNeutral }}>- {status}- </span>- ) : null}- </div>- <span style={styles.time}>- {new Date(event.timestamp).toLocaleTimeString()}- </span>- </div>- {message ? (- <div style={styles.summary}>{message}</div>- ) : kind ? null : (- <div style={styles.summary}>{summarize(event)}</div>- )}- {error?.stack ? (- <button style={styles.stackButton} onClick={() => showStack(event)}>- Stack Trace- </button>- ) : null}- </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)}+ >+ <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>+ </div>+ <div style={styles.list}>+ {visibleEvents.length === 0 ? (+ <div style={styles.empty}>+ <span style={styles.emptyIcon}>+ <Inbox size={20} />+ </span>+ No events captured yet.</div>- </>- )}+ ) : (+ visibleEvents.map((event, index) => {+ const key =+ typeof event.detail["id"] === "string"+ ? event.detail["id"]+ : `${event.timestamp}-${index}`;+ const quotaError = getQuotaError(event);+ if (quotaError) return <QuotaErrorRow key={key} info={quotaError} />;+ const stream = getReactLangStreamDetail(event);+ if (stream) {+ return <ReactLangStreamEventRow key={key} event={event} stream={stream} />;+ }+ return <EventRow key={key} event={event} />;+ })+ )}+ </div>+ <span style={styles.trayFade} aria-hidden /></aside></div>- </>+ </DevtoolsModeProvider>);}-function asRecord(detail: unknown): Record<string, unknown> {- return typeof detail === "object" && detail !== null ? (detail as Record<string, unknown>) : {};-}--function asString(value: unknown): string | undefined {- return typeof value === "string" ? value : undefined;-}--function getErrorInfo(event: ObservabilityEvent): ObservabilityErrorInfo | undefined {- const error = asRecord(event.detail)["error"];- if (typeof error === "object" && error !== null && "message" in error) {- return error as ObservabilityErrorInfo;- }- return undefined;+/**+ * A real checkbox painted as a switch — the input stays in the tree (hidden but+ * clickable and focusable) so keyboard, form semantics, and screen readers get+ * the native control rather than a div pretending to be one.+ */+function SettingSwitch({+ label,+ checked,+ onChange,+}: {+ label: string;+ checked: boolean;+ onChange: (checked: boolean) => void;+}) {+ const styles = useStyles(uiStyles);+ return (+ <label style={styles.menuCheckbox}>+ <span style={styles.menuLabel}>{label}</span>+ <span style={{ ...styles.switchTrack, ...(checked ? styles.switchTrackOn : null) }}>+ <input+ type="checkbox"+ checked={checked}+ onChange={(event) => onChange(event.target.checked)}+ style={styles.switchInput}+ />+ <span style={{ ...styles.switchKnob, ...(checked ? styles.switchKnobOn : null) }} />+ </span>+ </label>+ );}/**- * Best-effort one-line summary from conventional detail fields- * (kind/component/toolName/target/method+url/status/message/error.message).- * Falls back to JSON for unconventional payloads.+ * 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.*/-function summarize(event: ObservabilityEvent): string {- const detail = asRecord(event.detail);- const error = getErrorInfo(event);- const method = asString(detail["method"]);- const url = asString(detail["url"]);- const subject =- asString(detail["kind"]) ??- asString(detail["component"]) ??- asString(detail["toolName"]) ??- asString(detail["target"]) ??- (url ? [method, url].filter(Boolean).join(" ") : undefined);- const status = typeof detail["status"] === "number" ? `→ ${detail["status"]}` : undefined;- const message = error ? `— ${error.message}` : asString(detail["message"]);+function SettingsMenu({+ config,+ onChange,+}: {+ config: DevtoolsConfig;+ onChange: (patch: Partial<DevtoolsConfig>) => void;+}) {+ const [open, setOpen] = useState(false);+ const styles = useStyles(uiStyles);+ const wrap = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (!open) return;+ const onPointerDown = (event: MouseEvent) => {+ if (!wrap.current?.contains(event.target as Node)) setOpen(false);+ };+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ event.stopPropagation();+ setOpen(false);+ };+ document.addEventListener("mousedown", onPointerDown);+ document.addEventListener("keydown", onKeyDown, true);+ return () => {+ document.removeEventListener("mousedown", onPointerDown);+ document.removeEventListener("keydown", onKeyDown, true);+ };+ }, [open]);- const parts = [subject, status, message].filter(Boolean);- if (parts.length > 0) return parts.join(" ");- try {- return JSON.stringify(event.detail) ?? "(no detail)";- } catch {- return "(no detail)";- }+ return (+ <div ref={wrap} style={styles.menuWrap}>+ <IconButton+ active={open}+ onClick={() => setOpen((current) => !current)}+ aria-label="Devtools settings"+ aria-haspopup="true"+ aria-expanded={open}+ title="Settings"+ >+ <Settings size={14} />+ </IconButton>+ {open ? (+ <div style={styles.menu} role="group" aria-label="Devtools settings">+ {/* Every row reads the same way: name on the left, control on the+ right, hairline between. */}+ <SettingSwitch+ label="Auto-open on error"+ checked={config.autoOpen}+ onChange={(autoOpen) => onChange({ autoOpen })}+ />+ <div style={styles.menuDivider} />+ <SettingSwitch+ label="Show errors only"+ checked={config.onlyErrors}+ onChange={(onlyErrors) => onChange({ onlyErrors })}+ />+ <div style={styles.menuDivider} />+ <div style={styles.menuRow}>+ <span style={styles.menuLabel}>Theme</span>+ <ThemeSegmented value={config.theme} onChange={(theme) => onChange({ theme })} />+ </div>+ </div>+ ) : null}+ </div>+ );}-const badgeByLevel: Record<ObservabilityEvent["level"], CSSProperties> = {- error: { background: "#fef2f2", color: "#b91c1c", borderColor: "#fecaca" },- warning: { background: "#fffbeb", color: "#b45309", borderColor: "#fde68a" },- info: { background: "#eff6ff", color: "#1d4ed8", borderColor: "#bfdbfe" },-};const positionStyles: Record<DevtoolsPosition, CSSProperties> = {"top-left": { top: 16, left: 16 },@@ -344,280 +371,302 @@ const positionStyles: Record<DevtoolsPosition, CSSProperties> = {"bottom-right": { bottom: 16, right: 16 },};-// Mirrors react-ui's look (Inter, hairline borders, soft shadows) without-// depending on it — values, not tokens.-const FONT = '"Inter", system-ui, sans-serif';-const MONO = "ui-monospace, SFMono-Regular, Menlo, monospace";--const styles = {- toggleWrap: {- position: "fixed",- // Max 32-bit signed int — sit above any app chrome.- zIndex: 2147483647,- },- toggle: {- position: "relative",- width: 40,- height: 40,- display: "flex",- alignItems: "center",- justifyContent: "center",- borderRadius: "50%",- borderWidth: 1,- borderStyle: "solid",- borderColor: "rgba(0, 0, 0, 0.08)",- background: "#18181b",- color: "#fff",- cursor: "pointer",- boxShadow: "0 2px 8px rgba(0, 0, 0, 0.16)",- transition: "transform 150ms ease, box-shadow 150ms ease",- },- toggleError: {- background: "#b91c1c",- borderColor: "#fecaca",- },- toggleCount: {- position: "absolute",- top: -6,- right: -6,- boxSizing: "border-box",- minWidth: 16,- height: 16,- display: "flex",- alignItems: "center",- justifyContent: "center",- borderRadius: 999,- background: "#dc2626",- border: "2px solid #fff",- color: "#fff",- fontSize: 9,- fontWeight: 700,- padding: "0 3px",- },- backdrop: {- position: "fixed",- inset: 0,- background: "rgba(24, 24, 27, 0.4)",- // 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",- },- drawer: {- position: "fixed",- top: 12,- right: 12,- bottom: 12,- boxSizing: "border-box",- width: "min(420px, calc(100vw - 24px))",- display: "flex",- flexDirection: "column",- border: "1px solid #e4e4e7",- borderRadius: 16,- background: "#ffffff",- color: "#18181b",- fontFamily: FONT,- fontSize: 13,- boxShadow: "0 16px 48px rgba(24, 24, 27, 0.18)",- transform: "translateX(calc(100% + 12px))",- transition: "transform 220ms cubic-bezier(0.32, 0.72, 0, 1)",- overflow: "hidden",- },- drawerOpen: {- transform: "translateX(0)",- },- header: {- display: "flex",- justifyContent: "space-between",- alignItems: "center",- gap: 8,- padding: "12px 16px",- borderBottom: "1px solid #f4f4f5",- fontWeight: 600,- fontSize: 14,- },- headerLeft: {- display: "flex",- alignItems: "center",- gap: 6,- minWidth: 0,- },- title: {- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- },- headerActions: {- display: "flex",- alignItems: "center",- gap: 6,- flexShrink: 0,- },- textButton: {- display: "inline-flex",- alignItems: "center",- gap: 4,- border: "1px solid #e4e4e7",- borderRadius: 8,- background: "#ffffff",- color: "#3f3f46",- cursor: "pointer",- fontFamily: FONT,- fontSize: 12,- fontWeight: 500,- padding: "4px 10px",- },- textButtonActive: {- background: "#18181b",- borderColor: "#18181b",- color: "#ffffff",- },- iconButton: {- display: "inline-flex",- alignItems: "center",- justifyContent: "center",- width: 26,- height: 26,- border: "none",- borderRadius: 8,- background: "transparent",- color: "#71717a",- cursor: "pointer",- padding: 0,- },- controlsRow: {- display: "flex",- alignItems: "center",- gap: 16,- padding: "10px 16px",- borderBottom: "1px solid #f4f4f5",- },- checkboxLabel: {- display: "flex",- alignItems: "center",- gap: 6,- color: "#52525b",- fontSize: 12,- cursor: "pointer",- accentColor: "#18181b",- },- list: {- overflowY: "auto",- padding: 12,- display: "flex",- flexDirection: "column",- gap: 10,- },- empty: {- color: "#a1a1aa",- padding: "32px 0",- textAlign: "center",- },- row: {- border: "1px solid #e4e4e7",- borderRadius: 12,- padding: 12,- display: "flex",- flexDirection: "column",- gap: 6,- background: "#ffffff",- boxShadow: "0 1px 2px rgba(24, 24, 27, 0.04)",- },- badgeCredits: {- background: "#fef3c7",- color: "#92400e",- borderColor: "#fde68a",- },- rowHeader: {- display: "flex",- justifyContent: "space-between",- alignItems: "center",- gap: 8,- },- badgeGroup: {- display: "flex",- alignItems: "center",- flexWrap: "wrap",- gap: 6,- minWidth: 0,- },- badgeNeutral: {- background: "#f4f4f5",- color: "#52525b",- borderColor: "#e4e4e7",- fontFamily: MONO,- },- badge: {- display: "inline-flex",- alignItems: "center",- borderRadius: 999,- borderWidth: 1,- borderStyle: "solid",- borderColor: "transparent",- padding: "1px 8px",- fontSize: 11,- fontWeight: 500,- fontFamily: FONT,- },- time: {- color: "#a1a1aa",- fontSize: 11,- },- summary: {- wordBreak: "break-word",- color: "#3f3f46",- fontSize: 12,- lineHeight: 1.5,- },- stackButton: {- alignSelf: "flex-start",- border: "none",- background: "transparent",- color: "#52525b",- cursor: "pointer",- fontFamily: FONT,- fontSize: 12,- fontWeight: 500,- padding: 0,- textDecoration: "underline",- textUnderlineOffset: 2,- },- stackBody: {- flex: 1,- overflow: "auto",- padding: "8px 0",- background: "#fafafa",- fontFamily: MONO,- fontSize: 11,- color: "#3f3f46",- },- stackLine: {- display: "flex",- gap: 8,- paddingRight: 12,- },- lineNumber: {- flexShrink: 0,- width: 32,- textAlign: "right",- color: "#a1a1aa",- userSelect: "none",- padding: "0 4px",- borderRight: "1px solid #e4e4e7",- },- lineText: {- whiteSpace: "pre",- },- lineTextWrap: {- whiteSpace: "pre-wrap",- wordBreak: "break-all",- },-} satisfies Record<string, CSSProperties>;+function uiStyles(t: ThemeTokens) {+ return {+ toggleWrap: {+ position: "fixed",+ // Max 32-bit signed int — sit above any app UI.+ zIndex: 2147483647,+ },+ toggle: {+ boxSizing: "border-box",+ width: 40,+ height: 40,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ borderRadius: "50%",+ borderWidth: 1,+ borderStyle: "solid",+ borderColor: t.toggleBorder,+ background: t.toggleBg,+ color: t.toggleFg,+ cursor: "pointer",+ boxShadow: t.toggleShadow,+ fontFamily: FONT,+ padding: 0,+ transition: "background 150ms ease, box-shadow 150ms ease, transform 150ms ease",+ },+ toggleHover: {+ transform: "scale(1.08)",+ },+ // Errors swap the mark for a count on a red disc, held inside a light puck so+ // the number reads as a badge rather than flooding the whole button red.+ toggleError: {+ background: t.toggleErrorSurface,+ borderColor: t.toggleErrorRing,+ },+ toggleCount: {+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ boxSizing: "border-box",+ minWidth: 24,+ height: 24,+ padding: "0 6px",+ borderRadius: 999,+ background: t.toggleError,+ color: "#fff",+ fontSize: 13,+ 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",+ },+ drawer: {+ position: "fixed",+ boxSizing: "border-box",+ display: "flex",+ flexDirection: "column",+ borderWidth: 1,+ borderStyle: "solid",+ borderColor: t.trayRing,+ borderRadius: 16,+ background: t.bg,+ boxShadow: t.trayShadow,+ color: t.fg,+ fontFamily: FONT,+ fontSize: 13,+ visibility: "hidden",+ transition: "transform 220ms 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",+ },+ header: {+ display: "flex",+ justifyContent: "space-between",+ alignItems: "center",+ gap: 8,+ padding: "12px 16px",+ fontWeight: 600,+ fontSize: 14,+ },+ headerLeft: {+ display: "flex",+ alignItems: "center",+ gap: 6,+ minWidth: 0,+ },+ title: {+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ },+ headerActions: {+ display: "flex",+ alignItems: "center",+ gap: 6,+ flexShrink: 0,+ },+ menuWrap: {+ position: "relative",+ display: "inline-flex",+ },+ menu: {+ position: "absolute",+ top: "calc(100% + 6px)",+ right: 0,+ // Above the banner group, which lifts itself over the list for its fade.+ zIndex: 2,+ boxSizing: "border-box",+ width: 236,+ display: "flex",+ flexDirection: "column",+ gap: 10,+ border: `1px solid ${t.border}`,+ borderRadius: 12,+ background: t.bg,+ boxShadow: t.shadow,+ padding: 12,+ fontWeight: 400,+ },+ // Every row is the height of the tallest control (the theme toggle), so the+ // dividers land on an even rhythm no matter what each row holds.+ menuCheckbox: {+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ gap: 12,+ minHeight: MENU_ROW_HEIGHT,+ cursor: "pointer",+ },+ switchTrack: {+ position: "relative",+ boxSizing: "border-box",+ flexShrink: 0,+ width: 30,+ height: 18,+ borderRadius: 999,+ background: t.border,+ transition: "background 150ms ease",+ },+ switchTrackOn: {+ background: t.inverted,+ },+ // Covers the whole track so the hit area and focus ring stay on the input.+ switchInput: {+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ margin: 0,+ borderRadius: 999,+ opacity: 0,+ cursor: "pointer",+ },+ switchKnob: {+ position: "absolute",+ top: 2,+ left: 2,+ width: 14,+ height: 14,+ borderRadius: "50%",+ background: t.bg,+ boxShadow: t.shadowSubtle,+ transition: "transform 150ms ease",+ pointerEvents: "none",+ },+ switchKnobOn: {+ transform: "translateX(12px)",+ },+ menuDivider: {+ height: 1,+ background: t.borderSubtle,+ },+ menuRow: {+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ gap: 12,+ minHeight: MENU_ROW_HEIGHT,+ },+ menuLabel: {+ fontSize: 12,+ 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",+ },+ trayFade: {+ position: "absolute",+ left: 0,+ right: 0,+ bottom: 0,+ height: 28,+ 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,+ overflowY: "auto",+ padding: 12,+ display: "flex",+ flexDirection: "column",+ gap: 10,+ },+ empty: {+ flex: 1,+ minHeight: 0,+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ gap: 12,+ color: t.fgFaint,+ textAlign: "center",+ },+ emptyIcon: {+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ },+ } satisfies Record<string, CSSProperties>;+}diff --git a/packages/devtools/src/QuotaErrorRow.tsx b/packages/devtools/src/QuotaErrorRow.tsxdeleted file mode 100644index 149429be0..000000000--- a/packages/devtools/src/QuotaErrorRow.tsx+++ /dev/null@@ -1,141 +0,0 @@-import { type ObservabilityEvent } from "@openuidev/observability";-import { CreditCard, KeyRound } from "lucide-react";-import type { CSSProperties } from "react";--export interface QuotaErrorInfo {- title: string;- message: string;- showPurchaseCta: boolean;- showByokCta: boolean;-}--const QUOTA_ERROR_MESSAGES: Record<string, QuotaErrorInfo> = {- ERR_BILLING_THRESHOLD_EXCEEDED: {- title: "Add credits to keep going",- message:- "Looks like this workspace is out of OpenUI Cloud credits. Purchase credits, or bring your own OpenAI, Anthropic, or Google key (BYOK) at no extra cost, then try your request again. This notice is only shown in development.",- showPurchaseCta: true,- showByokCta: true,- },- ERR_QUOTA_EXCEEDED: {- title: "Rate limit reached",- message:- "This workspace has hit a rate limit, usually from sending requests too quickly, or exceeding the per-model token/request limit for the current plan. Wait a moment and try again. This notice is only shown in development.",- showPurchaseCta: false,- showByokCta: false,- },-};--export function getQuotaError(event: ObservabilityEvent): QuotaErrorInfo | undefined {- if (event.level !== "error") return undefined;- const error = asRecord(event.detail)["error"];- const type = asString(asRecord(error)["type"]);- return type ? QUOTA_ERROR_MESSAGES[type] : undefined;-}--/** Billing/rate-limit list entry — the highlighted card a known 429 code renders as. */-export function QuotaErrorRow({ info }: { info: QuotaErrorInfo }) {- return (- <div style={{ ...styles.row, ...styles.rowCredits }}>- <div style={styles.creditsNote}>- <div style={styles.creditsTitle}>{info.title}</div>- <p style={styles.creditsMessage}>{info.message}</p>- {info.showPurchaseCta || info.showByokCta ? (- <div style={styles.actions}>- {info.showPurchaseCta ? (- <button- type="button"- style={styles.action}- onClick={() =>- window.open("https://console.thesys.dev/billing", "_blank", "noopener,noreferrer")- }- >- <CreditCard size={13} />- Purchase Credits- </button>- ) : null}- {info.showByokCta ? (- <button- type="button"- style={{ ...styles.action, ...styles.actionSecondary }}- onClick={() =>- window.open("https://console.thesys.dev/byok", "_blank", "noopener,noreferrer")- }- >- <KeyRound size={13} />- Add your own key- </button>- ) : null}- </div>- ) : null}- </div>- </div>- );-}--function asRecord(detail: unknown): Record<string, unknown> {- return typeof detail === "object" && detail !== null ? (detail as Record<string, unknown>) : {};-}--function asString(value: unknown): string | undefined {- return typeof value === "string" ? value : undefined;-}--const FONT = '"Inter", system-ui, sans-serif';--const styles = {- row: {- border: "1px solid #e4e4e7",- borderRadius: 12,- padding: 12,- display: "flex",- flexDirection: "column",- gap: 6,- background: "#ffffff",- boxShadow: "0 1px 2px rgba(24, 24, 27, 0.04)",- },- rowCredits: {- border: "1px solid #fde68a",- background: "linear-gradient(135deg, #fffbeb 0%, #fff7ed 100%)",- },- creditsNote: {- display: "flex",- flexDirection: "column",- gap: 6,- },- creditsTitle: {- fontSize: 13,- fontWeight: 600,- color: "#18181b",- },- creditsMessage: {- margin: 0,- fontSize: 12,- lineHeight: 1.55,- color: "#52525b",- },- actions: {- display: "flex",- gap: 8,- marginTop: 2,- },- action: {- display: "inline-flex",- alignItems: "center",- gap: 6,- border: "none",- borderRadius: 8,- background: "#18181b",- color: "#ffffff",- padding: "6px 12px",- fontFamily: FONT,- fontSize: 12,- fontWeight: 500,- cursor: "pointer",- },- actionSecondary: {- background: "#ffffff",- color: "#18181b",- border: "1px solid #e4e4e7",- },-} satisfies Record<string, CSSProperties>;diff --git a/packages/devtools/src/ReactLangStreamEventRow.tsx b/packages/devtools/src/ReactLangStreamEventRow.tsxdeleted file mode 100644index 50f234b05..000000000--- a/packages/devtools/src/ReactLangStreamEventRow.tsx+++ /dev/null@@ -1,365 +0,0 @@-import { type ObservabilityEvent } from "@openuidev/observability";-import { Check, ChevronDown, ChevronRight, Copy } from "lucide-react";-import { useState, type CSSProperties } from "react";--export interface ReactLangStreamDetail {- phase: "streaming" | "settled";- response?: string;- errors: Record<string, unknown>[];- parser?: {- incomplete?: boolean;- unresolved?: string[];- orphaned?: string[];- statementCount?: number;- };-}--export function getReactLangStreamDetail(event: ObservabilityEvent): ReactLangStreamDetail | null {- const detail = asRecord(event.detail);- if (- detail["kind"] !== "react-lang:stream" ||- (detail["phase"] !== "streaming" && detail["phase"] !== "settled")- ) {- return null;- }-- const parser = asRecord(detail["parser"]);- return {- phase: detail["phase"],- response: asString(detail["response"]),- errors: Array.isArray(detail["errors"]) ? detail["errors"].map((error) => asRecord(error)) : [],- parser:- Object.keys(parser).length > 0- ? {- incomplete:- typeof parser["incomplete"] === "boolean" ? parser["incomplete"] : undefined,- unresolved: Array.isArray(parser["unresolved"])- ? parser["unresolved"].filter((value): value is string => typeof value === "string")- : undefined,- orphaned: Array.isArray(parser["orphaned"])- ? parser["orphaned"].filter((value): value is string => typeof value === "string")- : undefined,- statementCount:- typeof parser["statementCount"] === "number" ? parser["statementCount"] : undefined,- }- : undefined,- };-}--export function ReactLangStreamEventRow({- event,- stream,-}: {- event: ObservabilityEvent;- stream: ReactLangStreamDetail;-}) {- const [expanded, setExpanded] = useState(false);- const [responseCopied, setResponseCopied] = useState(false);- const isStreaming = stream.phase === "streaming";- const visibleErrors = isStreaming ? [] : stream.errors;- const statementCount = stream.parser?.statementCount;- const orphaned = stream.parser?.orphaned ?? [];- const parserIssues = [- !isStreaming && stream.parser?.incomplete ? "Incomplete input" : null,- !isStreaming && stream.parser?.unresolved?.length- ? `Unresolved: ${stream.parser.unresolved.join(", ")}`- : null,- orphaned.length > 0 ? `Orphaned: ${orphaned.join(", ")}` : null,- ].filter((issue): issue is string => Boolean(issue));-- const copyResponse = () => {- if (typeof navigator === "undefined" || !navigator.clipboard || !stream.response) return;- navigator.clipboard- .writeText(stream.response)- .then(() => {- setResponseCopied(true);- setTimeout(() => setResponseCopied(false), 1500);- })- .catch(() => {});- };-- return (- <div style={styles.row}>- <button- type="button"- style={styles.streamToggle}- onClick={() => setExpanded((current) => !current)}- aria-expanded={expanded}- aria-label="Toggle OpenUI Lang stream details"- >- <div style={styles.rowHeader}>- <div style={styles.badgeGroup}>- {expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}- <span style={{ ...styles.badge, ...badgeByLevel[event.level] }}>{event.level}</span>- <span style={{ ...styles.badge, ...styles.badgeNeutral }}>OpenUI Lang stream</span>- {isStreaming ? (- <span style={{ ...styles.badge, ...styles.badgeStreaming }}>Streaming</span>- ) : null}- </div>- <span style={styles.time}>{new Date(event.timestamp).toLocaleTimeString()}</span>- </div>- <div style={styles.streamOverview}>- {statementCount !== undefined ? (- <span>- {statementCount} statement{statementCount === 1 ? "" : "s"}- </span>- ) : null}- {orphaned.length > 0 ? (- <span>- {orphaned.length} orphaned statement{orphaned.length === 1 ? "" : "s"}- </span>- ) : null}- {visibleErrors.length > 0 ? (- <span style={styles.errorSummary}>- {visibleErrors.length} error{visibleErrors.length === 1 ? "" : "s"}- </span>- ) : null}- </div>- </button>-- {expanded ? (- <div style={styles.streamExpanded}>- {visibleErrors.length > 0 ? (- <section style={styles.streamSection}>- <div style={styles.streamSectionTitle}>Errors ({visibleErrors.length})</div>- <div style={styles.diagnosticList}>- {visibleErrors.map((error, index) => (- <Diagnostic- key={`${asString(error["source"]) ?? "error"}-${asString(error["code"]) ?? "unknown"}-${index}`}- error={error}- />- ))}- </div>- </section>- ) : null}-- {parserIssues.length > 0 ? (- <section style={styles.streamSection}>- <div style={styles.streamSectionTitle}>Parser details</div>- <div style={styles.parserIssues}>{parserIssues.join(" · ")}</div>- </section>- ) : null}-- <section style={styles.streamSection}>- <div style={styles.responseHeader}>- <div style={styles.streamSectionTitle}>Response</div>- <button type="button" style={styles.copyResponseButton} onClick={copyResponse}>- {responseCopied ? <Check size={12} /> : <Copy size={12} />}- {responseCopied ? "Copied" : "Copy"}- </button>- </div>- <pre style={styles.responseCode}>{stream.response || "(empty response)"}</pre>- </section>- </div>- ) : null}- </div>- );-}--function Diagnostic({ error }: { error: Record<string, unknown> }) {- const source = asString(error["source"]);- const code = asString(error["code"]);- const message = asString(error["message"]) ?? "Unknown OpenUI Lang error";- const location = [- asString(error["component"]),- asString(error["statementId"]),- asString(error["path"]),- ].filter(Boolean);- const hint = asString(error["hint"]);-- return (- <div style={styles.diagnostic}>- <div style={styles.diagnosticHeader}>- {[source, code].filter(Boolean).join(" / ") || "error"}- </div>- <div>{message}</div>- {location.length > 0 ? (- <div style={styles.diagnosticLocation}>{location.join(" · ")}</div>- ) : null}- {hint ? <div style={styles.diagnosticHint}>{hint}</div> : null}- </div>- );-}--function asRecord(detail: unknown): Record<string, unknown> {- return typeof detail === "object" && detail !== null ? (detail as Record<string, unknown>) : {};-}--function asString(value: unknown): string | undefined {- return typeof value === "string" ? value : undefined;-}--const FONT = '"Inter", system-ui, sans-serif';-const MONO = "ui-monospace, SFMono-Regular, Menlo, monospace";--const badgeByLevel: Record<ObservabilityEvent["level"], CSSProperties> = {- error: { background: "#fef2f2", color: "#b91c1c", borderColor: "#fecaca" },- warning: { background: "#fffbeb", color: "#b45309", borderColor: "#fde68a" },- info: { background: "#eff6ff", color: "#1d4ed8", borderColor: "#bfdbfe" },-};--const styles = {- row: {- border: "1px solid #e4e4e7",- borderRadius: 12,- padding: 12,- display: "flex",- flexDirection: "column",- gap: 6,- background: "#ffffff",- boxShadow: "0 1px 2px rgba(24, 24, 27, 0.04)",- },- rowHeader: {- display: "flex",- justifyContent: "space-between",- alignItems: "center",- gap: 8,- },- badgeGroup: {- display: "flex",- alignItems: "center",- flexWrap: "wrap",- gap: 6,- minWidth: 0,- },- badge: {- display: "inline-flex",- alignItems: "center",- borderRadius: 999,- borderWidth: 1,- borderStyle: "solid",- borderColor: "transparent",- padding: "1px 8px",- fontSize: 11,- fontWeight: 500,- fontFamily: FONT,- },- badgeNeutral: {- background: "#f4f4f5",- color: "#52525b",- borderColor: "#e4e4e7",- fontFamily: MONO,- },- badgeStreaming: {- background: "#ecfdf5",- color: "#047857",- borderColor: "#a7f3d0",- },- time: {- color: "#a1a1aa",- fontSize: 11,- },- streamToggle: {- width: "100%",- border: "none",- background: "transparent",- color: "inherit",- cursor: "pointer",- fontFamily: FONT,- padding: 0,- textAlign: "left",- },- streamOverview: {- display: "flex",- flexWrap: "wrap",- gap: "4px 10px",- color: "#71717a",- fontSize: 11,- marginTop: 7,- paddingLeft: 20,- },- errorSummary: {- color: "#b91c1c",- fontWeight: 600,- },- streamExpanded: {- display: "flex",- flexDirection: "column",- gap: 14,- borderTop: "1px solid #f4f4f5",- marginTop: 4,- paddingTop: 12,- },- streamSection: {- display: "flex",- flexDirection: "column",- gap: 6,- },- streamSectionTitle: {- color: "#52525b",- fontSize: 11,- fontWeight: 600,- textTransform: "uppercase",- letterSpacing: "0.04em",- },- responseHeader: {- display: "flex",- alignItems: "center",- justifyContent: "space-between",- gap: 8,- },- copyResponseButton: {- display: "inline-flex",- alignItems: "center",- gap: 4,- border: "none",- background: "transparent",- color: "#52525b",- cursor: "pointer",- fontFamily: FONT,- fontSize: 11,- padding: 0,- },- responseCode: {- maxHeight: 260,- overflow: "auto",- margin: 0,- border: "1px solid #e4e4e7",- borderRadius: 8,- background: "#fafafa",- color: "#27272a",- fontFamily: MONO,- fontSize: 11,- lineHeight: 1.5,- padding: 10,- whiteSpace: "pre-wrap",- wordBreak: "break-word",- },- parserIssues: {- borderRadius: 8,- background: "#fffbeb",- color: "#92400e",- fontSize: 11,- lineHeight: 1.45,- padding: "6px 8px",- },- diagnosticList: {- display: "flex",- flexDirection: "column",- gap: 6,- },- diagnostic: {- borderLeft: "2px solid #fca5a5",- background: "#fef2f2",- color: "#3f3f46",- fontSize: 11,- lineHeight: 1.45,- padding: "7px 8px",- },- diagnosticHeader: {- color: "#991b1b",- fontFamily: MONO,- fontWeight: 600,- marginBottom: 3,- },- diagnosticLocation: {- color: "#71717a",- fontFamily: MONO,- marginTop: 3,- },- diagnosticHint: {- color: "#52525b",- fontStyle: "italic",- marginTop: 4,- },-} satisfies Record<string, CSSProperties>;diff --git a/packages/devtools/src/inspect/EventRow.tsx b/packages/devtools/src/inspect/EventRow.tsxnew file mode 100644index 000000000..731f56eaf--- /dev/null+++ b/packages/devtools/src/inspect/EventRow.tsx@@ -0,0 +1,259 @@+import { type ObservabilityErrorInfo, type ObservabilityEvent } from "@openuidev/observability";+import { Check, ChevronDown, ChevronRight, Copy } from "lucide-react";+import { useState, type CSSProperties } from "react";+import { FONT, MONO, useStyles, type ThemeTokens } from "../theme";+import { LevelIcon } from "./LevelIcon";++export function EventRow({ event }: { event: ObservabilityEvent }) {+ const styles = useStyles(eventRowStyles);+ const [expanded, setExpanded] = useState(false);+ const [copied, setCopied] = useState(false);+ const [hovered, setHovered] = useState(false);+ const error = getErrorInfo(event);+ const detail = asRecord(event.detail);+ const kind = asString(detail["kind"]);+ const status = typeof detail["status"] === "number" ? String(detail["status"]) : undefined;+ const message = error?.message ?? asString(detail["message"]);+ const summary = message ? null : kind ? null : summarize(event);+ const stack = error?.stack;+ const expandable = Boolean(stack);++ const copyStack = () => {+ if (!stack || typeof navigator === "undefined" || !navigator.clipboard) return;+ navigator.clipboard+ .writeText(stack)+ .then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ })+ .catch(() => {});+ };++ const header = (+ <>+ <div style={styles.rowHeader}>+ <div style={styles.badgeGroup}>+ <LevelIcon level={event.level} />+ {kind ? <span style={styles.kind}>{kind}</span> : null}+ {status ? (+ <span style={{ ...styles.badge, ...styles.badgeNeutral }}>{status}</span>+ ) : null}+ </div>+ <div style={styles.rowHeaderRight}>+ <span style={styles.time}>{new Date(event.timestamp).toLocaleTimeString()}</span>+ <span style={styles.chevron} aria-hidden>+ {expandable ? expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} /> : null}+ </span>+ </div>+ </div>+ {message ? <div style={styles.summary}>{message}</div> : null}+ {summary ? <div style={styles.summary}>{summary}</div> : null}+ </>+ );++ return (+ <div+ style={{ ...styles.row, ...(expandable && hovered ? styles.rowHover : null) }}+ onMouseEnter={() => setHovered(true)}+ onMouseLeave={() => setHovered(false)}+ >+ {expandable ? (+ <button+ type="button"+ style={styles.toggle}+ onClick={() => setExpanded((current) => !current)}+ aria-expanded={expanded}+ aria-label="Toggle stack trace"+ >+ {header}+ </button>+ ) : (+ header+ )}++ {expanded && stack ? (+ <div style={styles.expanded}>+ <pre style={styles.stack}>{stack}</pre>+ <div style={styles.actions}>+ <button type="button" style={styles.action} onClick={copyStack}>+ {copied ? <Check size={12} /> : <Copy size={12} />}+ {copied ? "Copied" : "Copy"}+ </button>+ </div>+ </div>+ ) : null}+ </div>+ );+}++function asRecord(detail: unknown): Record<string, unknown> {+ return typeof detail === "object" && detail !== null ? (detail as Record<string, unknown>) : {};+}++function asString(value: unknown): string | undefined {+ return typeof value === "string" ? value : undefined;+}++function getErrorInfo(event: ObservabilityEvent): ObservabilityErrorInfo | undefined {+ const error = asRecord(event.detail)["error"];+ if (typeof error === "object" && error !== null && "message" in error) {+ return error as ObservabilityErrorInfo;+ }+ return undefined;+}++function summarize(event: ObservabilityEvent): string {+ const detail = asRecord(event.detail);+ const error = getErrorInfo(event);+ const method = asString(detail["method"]);+ const url = asString(detail["url"]);+ const subject =+ asString(detail["kind"]) ??+ asString(detail["component"]) ??+ asString(detail["toolName"]) ??+ asString(detail["target"]) ??+ (url ? [method, url].filter(Boolean).join(" ") : undefined);+ const status = typeof detail["status"] === "number" ? `→ ${detail["status"]}` : undefined;+ const message = error ? `— ${error.message}` : asString(detail["message"]);++ const parts = [subject, status, message].filter(Boolean);+ if (parts.length > 0) return parts.join(" ");+ try {+ return JSON.stringify(event.detail) ?? "(no detail)";+ } catch {+ return "(no detail)";+ }+}++function eventRowStyles(t: ThemeTokens) {+ return {+ row: {+ borderWidth: 1,+ borderStyle: "solid",+ borderColor: t.border,+ borderRadius: 12,+ padding: 12,+ display: "flex",+ flexDirection: "column",+ gap: 6,+ background: t.card,+ transition: "border-color 150ms ease, box-shadow 150ms ease",+ },+ rowHover: {+ borderColor: t.borderStrong,+ boxShadow: t.shadowSubtle,+ },+ toggle: {+ width: "100%",+ border: "none",+ background: "transparent",+ color: "inherit",+ cursor: "pointer",+ fontFamily: FONT,+ padding: 0,+ textAlign: "left",+ },+ rowHeader: {+ display: "flex",+ justifyContent: "space-between",+ alignItems: "center",+ gap: 8,+ },+ rowHeaderRight: {+ display: "flex",+ alignItems: "center",+ gap: 6,+ flexShrink: 0,+ },+ chevron: {+ display: "inline-flex",+ width: 14,+ flexShrink: 0,+ color: t.fgMuted,+ },+ badgeGroup: {+ display: "flex",+ alignItems: "center",+ flexWrap: "wrap",+ gap: 6,+ minWidth: 0,+ },+ kind: {+ color: t.fg,+ fontSize: 12,+ fontWeight: 600,+ wordBreak: "break-word",+ },+ badge: {+ display: "inline-flex",+ alignItems: "center",+ borderRadius: 999,+ borderWidth: 1,+ borderStyle: "solid",+ borderColor: "transparent",+ padding: "1px 8px",+ fontSize: 11,+ fontWeight: 500,+ fontFamily: FONT,+ },+ badgeNeutral: {+ background: t.bgSubtle,+ color: t.fgSecondary,+ borderColor: t.border,+ fontFamily: MONO,+ },+ time: {+ color: t.fgFaint,+ fontSize: 11,+ },+ summary: {+ wordBreak: "break-word",+ color: t.fgTertiary,+ fontSize: 12,+ lineHeight: 1.5,+ marginTop: 7,+ paddingLeft: 24,+ },+ expanded: {+ display: "flex",+ flexDirection: "column",+ gap: 6,+ marginTop: 4,+ },+ stack: {+ maxHeight: 260,+ overflow: "auto",+ margin: 0,+ border: `1px solid ${t.border}`,+ borderRadius: 8,+ background: t.bgMuted,+ color: t.fgTertiary,+ fontFamily: MONO,+ fontSize: 11,+ lineHeight: 1.5,+ padding: 10,+ whiteSpace: "pre-wrap",+ wordBreak: "break-word",+ },+ actions: {+ display: "flex",+ alignItems: "center",+ gap: 6,+ marginTop: 2,+ },+ action: {+ display: "inline-flex",+ alignItems: "center",+ gap: 4,+ border: `1px solid ${t.border}`,+ borderRadius: 8,+ background: t.bg,+ color: t.fgSecondary,+ cursor: "pointer",+ fontFamily: FONT,+ fontSize: 11,+ fontWeight: 500,+ padding: "4px 9px",+ },+ } satisfies Record<string, CSSProperties>;+}diff --git a/packages/devtools/src/inspect/LevelIcon.tsx b/packages/devtools/src/inspect/LevelIcon.tsxnew file mode 100644index 000000000..3c950688b--- /dev/null+++ b/packages/devtools/src/inspect/LevelIcon.tsx@@ -0,0 +1,56 @@+import { type ObservabilityEvent } from "@openuidev/observability";+import { X } from "lucide-react";+import type { CSSProperties, ReactNode } from "react";+import { useStyles, type ThemeTokens } from "../theme";++const GLYPH: Record<ObservabilityEvent["level"], ReactNode> = {+ info: "i",+ warning: <X size={11} strokeWidth={2.75} />,+ error: <X size={11} strokeWidth={2.75} />,+};++/**+ * Severity as a colored glyph instead of a word, so the row header has room for+ * the fields that actually differ between events. The level stays the accessible+ * name, which is also what tests and screen readers read.+ */+export function LevelIcon({ level }: { level: ObservabilityEvent["level"] }) {+ const styles = useStyles(levelIconStyles);+ return (+ <span style={{ ...styles.chip, ...styles[level] }} role="img" aria-label={level} title={level}>+ {GLYPH[level]}+ </span>+ );+}++function levelIconStyles(t: ThemeTokens) {+ return {+ chip: {+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ flexShrink: 0,+ boxSizing: "border-box",+ width: 18,+ height: 18,+ borderRadius: 6,+ fontSize: 11,+ fontWeight: 700,+ lineHeight: 1,+ },+ // The chip is already the container, so info is a bare letter rather than an+ // icon that draws its own circle around one.+ info: {+ background: t.levelNeutral,+ color: t.fgMuted,+ },+ warning: {+ background: t.levelWarning,+ color: t.warning,+ },+ error: {+ background: t.levelDanger,+ color: t.danger,+ },+ } satisfies Record<string, CSSProperties>;+}diff --git a/packages/devtools/src/inspect/QuotaErrorRow.tsx b/packages/devtools/src/inspect/QuotaErrorRow.tsxnew file mode 100644index 000000000..15735119f--- /dev/null+++ b/packages/devtools/src/inspect/QuotaErrorRow.tsx@@ -0,0 +1,170 @@+import { type ObservabilityEvent } from "@openuidev/observability";+import { CreditCard, KeyRound } from "lucide-react";+import { useState, type CSSProperties } from "react";+import { FONT, useStyles, type ThemeTokens } from "../theme";+import { LevelIcon } from "./LevelIcon";++export interface QuotaErrorInfo {+ title: string;+ message: string;+ showPurchaseCta: boolean;+ showByokCta: boolean;+}++const QUOTA_ERROR_MESSAGES: Record<string, QuotaErrorInfo> = {+ ERR_BILLING_THRESHOLD_EXCEEDED: {+ title: "Add credits to keep going",+ message:+ "Looks like this workspace is out of OpenUI Cloud credits. Purchase credits, or bring your own OpenAI, Anthropic, or Google key (BYOK) at no extra cost, then try your request again. This notice is only shown in development.",+ showPurchaseCta: true,+ showByokCta: true,+ },+ ERR_QUOTA_EXCEEDED: {+ title: "Rate limit reached",+ message:+ "This workspace has hit a rate limit, usually from sending requests too quickly, or exceeding the per-model token/request limit for the current plan. Wait a moment and try again. This notice is only shown in development.",+ showPurchaseCta: false,+ showByokCta: false,+ },+};++export function getQuotaError(event: ObservabilityEvent): QuotaErrorInfo | undefined {+ if (event.level !== "error") return undefined;+ const error = asRecord(event.detail)["error"];+ const type = asString(asRecord(error)["type"]);+ return type ? QUOTA_ERROR_MESSAGES[type] : undefined;+}++/** Billing/rate-limit list entry — the highlighted card a known 429 code renders as. */+export function QuotaErrorRow({ info }: { info: QuotaErrorInfo }) {+ const styles = useStyles(quotaRowStyles);+ const [hoveredCta, setHoveredCta] = useState<string | null>(null);++ return (+ <div style={styles.row}>+ <div style={styles.creditsNote}>+ <div style={styles.creditsHeader}>+ <LevelIcon level="warning" />+ <div style={styles.creditsTitle}>{info.title}</div>+ </div>+ <p style={styles.creditsMessage}>{info.message}</p>+ </div>+ {info.showPurchaseCta || info.showByokCta ? (+ <div style={styles.actions}>+ {info.showPurchaseCta ? (+ <button+ type="button"+ style={{+ ...styles.action,+ ...(hoveredCta === "purchase" ? styles.actionHover : null),+ }}+ onMouseEnter={() => setHoveredCta("purchase")}+ onMouseLeave={() => setHoveredCta(null)}+ onClick={() =>+ window.open("https://console.thesys.dev/billing", "_blank", "noopener,noreferrer")+ }+ >+ <CreditCard size={13} />+ Purchase Credits+ </button>+ ) : null}+ {info.showByokCta ? (+ <button+ type="button"+ style={{+ ...styles.action,+ ...styles.actionSecondary,+ ...(hoveredCta === "byok" ? styles.actionHover : null),+ }}+ onMouseEnter={() => setHoveredCta("byok")}+ onMouseLeave={() => setHoveredCta(null)}+ onClick={() =>+ window.open("https://console.thesys.dev/byok", "_blank", "noopener,noreferrer")+ }+ >+ <KeyRound size={13} />+ Add your own key+ </button>+ ) : null}+ </div>+ ) : null}+ </div>+ );+}++function asRecord(detail: unknown): Record<string, unknown> {+ return typeof detail === "object" && detail !== null ? (detail as Record<string, unknown>) : {};+}++function asString(value: unknown): string | undefined {+ return typeof value === "string" ? value : undefined;+}++function quotaRowStyles(t: ThemeTokens) {+ return {+ row: {+ border: `1px solid ${t.border}`,+ borderRadius: 12,+ padding: 12,+ display: "flex",+ flexDirection: "column",+ gap: 6,+ background: t.card,+ },+ // The card matches every other row; the chip and title colour carry the+ // billing/rate-limit signal.+ creditsNote: {+ display: "flex",+ flexDirection: "column",+ gap: 12,+ },+ creditsHeader: {+ display: "flex",+ alignItems: "center",+ gap: 6,+ minWidth: 0,+ },+ // Identical to the `kind` title on every other row; the chip alone carries+ // the billing/rate-limit signal.+ creditsTitle: {+ fontSize: 12,+ fontWeight: 600,+ color: t.fg,+ },+ creditsMessage: {+ margin: 0,+ fontSize: 12,+ lineHeight: 1.55,+ color: t.fgSecondary,+ },+ actions: {+ display: "flex",+ gap: 8,+ marginTop: 10,+ },+ action: {+ display: "inline-flex",+ alignItems: "center",+ gap: 6,+ border: "none",+ borderRadius: 8,+ background: t.inverted,+ color: t.invertedFg,+ padding: "6px 12px",+ fontFamily: FONT,+ fontSize: 12,+ fontWeight: 500,+ cursor: "pointer",+ transition: "transform 150ms ease",+ },+ actionHover: {+ transform: "scale(0.96)",+ },+ actionSecondary: {+ background: t.controlBg,+ color: t.fg,+ border: `1px solid ${t.controlBorder}`,+ boxShadow: t.shadowSubtle,+ },+ } satisfies Record<string, CSSProperties>;+}diff --git a/packages/devtools/src/inspect/ReactLangStreamEventRow.tsx b/packages/devtools/src/inspect/ReactLangStreamEventRow.tsxnew file mode 100644index 000000000..daa76fa4c--- /dev/null+++ b/packages/devtools/src/inspect/ReactLangStreamEventRow.tsx@@ -0,0 +1,592 @@+import { type ObservabilityEvent } from "@openuidev/observability";+import { Bug, Check, ChevronDown, ChevronRight, Copy } from "lucide-react";+import { useEffect, useMemo, useState, type CSSProperties, type ReactNode } from "react";+import { tokenColor, tokenizeLang } from "../lib";+import { FONT, MONO, useStyles, type ThemeTokens } from "../theme";+import { LevelIcon } from "./LevelIcon";++export interface ReactLangStreamDetail {+ phase: "streaming" | "settled";+ response?: string;+ errors: Record<string, unknown>[];+ parser?: {+ incomplete?: boolean;+ unresolved?: string[];+ orphaned?: string[];+ statementCount?: number;+ };+ startedAt?: number;+ elapsedMs?: number;+ durationMs?: number;+}++export function getReactLangStreamDetail(event: ObservabilityEvent): ReactLangStreamDetail | null {+ const detail = asRecord(event.detail);+ if (+ detail["kind"] !== "react-lang:stream" ||+ (detail["phase"] !== "streaming" && detail["phase"] !== "settled")+ ) {+ return null;+ }++ const parser = asRecord(detail["parser"]);+ return {+ phase: detail["phase"],+ response: asString(detail["response"]),+ errors: Array.isArray(detail["errors"]) ? detail["errors"].map((error) => asRecord(error)) : [],+ parser:+ Object.keys(parser).length > 0+ ? {+ incomplete:+ typeof parser["incomplete"] === "boolean" ? parser["incomplete"] : undefined,+ unresolved: Array.isArray(parser["unresolved"])+ ? parser["unresolved"].filter((value): value is string => typeof value === "string")+ : undefined,+ orphaned: Array.isArray(parser["orphaned"])+ ? parser["orphaned"].filter((value): value is string => typeof value === "string")+ : undefined,+ statementCount:+ typeof parser["statementCount"] === "number" ? parser["statementCount"] : undefined,+ }+ : undefined,+ startedAt: asNumber(detail["startedAt"]),+ elapsedMs: asNumber(detail["elapsedMs"]),+ durationMs: asNumber(detail["durationMs"]),+ };+}++export function ReactLangStreamEventRow({+ event,+ stream,+ onOpenInDebug,+ canOpenInDebug = false,+}: {+ event: ObservabilityEvent;+ stream: ReactLangStreamDetail;+ onOpenInDebug?: (response: string) => void;+ canOpenInDebug?: boolean;+}) {+ const [expanded, setExpanded] = useState(false);+ const [hovered, setHovered] = useState(false);+ const [hoveredAction, setHoveredAction] = useState<string | null>(null);+ const [responseCopied, setResponseCopied] = useState(false);+ const styles = useStyles(streamRowStyles);+ const colors = useStyles(tokenColor);+ // Collapsed rows skip tokenizing: a live stream re-renders this on every chunk.+ const responseTokens = useMemo(+ () => (expanded && stream.response ? tokenizeLang(stream.response) : []),+ [expanded, stream.response],+ );+ const isStreaming = stream.phase === "streaming";+ const elapsedMs = useStreamElapsedMs(stream, isStreaming);+ const visibleErrors = isStreaming ? [] : stream.errors;+ const statementCount = stream.parser?.statementCount;+ const orphaned = stream.parser?.orphaned ?? [];+ const parserIssues = [+ !isStreaming && stream.parser?.incomplete ? "Incomplete input" : null,+ !isStreaming && stream.parser?.unresolved?.length+ ? `Unresolved: ${stream.parser.unresolved.join(", ")}`+ : null,+ orphaned.length > 0 ? `Orphaned: ${orphaned.join(", ")}` : null,+ ].filter((issue): issue is string => Boolean(issue));++ const copyResponse = () => {+ if (typeof navigator === "undefined" || !navigator.clipboard || !stream.response) return;+ navigator.clipboard+ .writeText(stream.response)+ .then(() => {+ setResponseCopied(true);+ setTimeout(() => setResponseCopied(false), 1500);+ })+ .catch(() => {});+ };++ const openInDebugDisabled = isStreaming || !stream.response || !canOpenInDebug;++ return (+ <div+ style={{ ...styles.row, ...(hovered ? styles.rowHover : null) }}+ onMouseEnter={() => setHovered(true)}+ onMouseLeave={() => setHovered(false)}+ >+ <button+ type="button"+ style={styles.streamToggle}+ onClick={() => setExpanded((current) => !current)}+ aria-expanded={expanded}+ aria-label="Toggle OpenUI Lang stream details"+ >+ <div style={styles.rowHeader}>+ <div style={styles.badgeGroup}>+ <LevelIcon level={event.level} />+ <span style={styles.kind}>OpenUI Lang stream</span>+ {isStreaming ? (+ <span style={{ ...styles.badge, ...styles.badgeStreaming }}>Streaming</span>+ ) : null}+ </div>+ <div style={styles.rowHeaderRight}>+ <span style={styles.time}>+ {elapsedMs != null ? (+ <>+ <span title="Stream duration">{formatElapsed(elapsedMs)}</span>+ {" • "}+ </>+ ) : null}+ {new Date(event.timestamp).toLocaleTimeString()}+ </span>+ <span style={{ ...styles.chevron, ...(hovered ? styles.chevronHover : null) }}>+ {expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}+ </span>+ </div>+ </div>+ <div style={styles.streamOverview}>+ {visibleErrors.length > 0 ? (+ <Tally count={visibleErrors.length} danger>+ error{visibleErrors.length === 1 ? "" : "s"}+ </Tally>+ ) : null}+ {statementCount !== undefined ? (+ <Tally count={statementCount}>statement{statementCount === 1 ? "" : "s"}</Tally>+ ) : null}+ {orphaned.length > 0 ? (+ <Tally count={orphaned.length}>+ orphaned statement{orphaned.length === 1 ? "" : "s"}+ </Tally>+ ) : null}+ </div>+ </button>++ {expanded ? (+ <div style={styles.streamExpanded}>+ <section style={styles.responseActions}>+ <span style={styles.responseActionsLabel}>Actions</span>+ <div style={styles.responseActionsButtons}>+ {onOpenInDebug ? (+ <button+ type="button"+ style={{+ ...styles.responseButton,+ ...(openInDebugDisabled ? styles.responseButtonDisabled : null),+ ...(hoveredAction === "debug" ? styles.responseButtonHover : null),+ }}+ onMouseEnter={() => setHoveredAction("debug")}+ onMouseLeave={() => setHoveredAction(null)}+ onClick={() => {+ if (isStreaming || !stream.response) return;+ onOpenInDebug(stream.response);+ }}+ disabled={openInDebugDisabled}+ title={+ isStreaming+ ? "Wait until the stream finishes"+ : !stream.response+ ? "Empty response"+ : !canOpenInDebug+ ? "No createLibrary() call detected"+ : "Open this response in OpenUI Debug"+ }+ aria-label="Debug"+ >+ <Bug size={12} />+ Debug+ </button>+ ) : null}+ <button+ type="button"+ style={{+ ...styles.responseButton,+ ...(hoveredAction === "copy" ? styles.responseButtonHover : null),+ }}+ onMouseEnter={() => setHoveredAction("copy")}+ onMouseLeave={() => setHoveredAction(null)}+ onClick={copyResponse}+ >+ {responseCopied ? <Check size={12} /> : <Copy size={12} />}+ {responseCopied ? "Copied" : "Copy"}+ </button>+ </div>+ </section>++ {visibleErrors.length > 0 ? (+ <section style={styles.streamSection}>+ <div style={styles.streamSectionTitle}>+ Errors <span style={styles.streamSectionCount}>{visibleErrors.length}</span>+ </div>+ <div style={styles.diagnosticList}>+ {visibleErrors.map((error, index) => (+ <Diagnostic+ key={`${asString(error["source"]) ?? "error"}-${asString(error["code"]) ?? "unknown"}-${index}`}+ error={error}+ />+ ))}+ </div>+ </section>+ ) : null}++ {parserIssues.length > 0 ? (+ <section style={styles.streamSection}>+ <div style={styles.streamSectionTitle}>Parser details</div>+ <div style={styles.parserIssues}>{parserIssues.join(" · ")}</div>+ </section>+ ) : null}++ <section style={styles.streamSection}>+ <pre style={styles.responseCode}>+ {stream.response+ ? responseTokens.map((token, index) => (+ <span key={index} style={{ color: colors[token.kind] }}>+ {token.value}+ </span>+ ))+ : "(empty response)"}+ </pre>+ </section>+ </div>+ ) : null}+ </div>+ );+}++/**+ * One overview stat: the number in a circle, then what it counts. Errors get+ * the danger tint so severity still reads at a glance.+ */+function Tally({+ count,+ danger = false,+ children,+}: {+ count: number;+ danger?: boolean;+ children: ReactNode;+}) {+ const styles = useStyles(streamRowStyles);+ return (+ <span style={styles.tally}>+ <span style={{ ...styles.tallyCount, ...(danger ? styles.tallyCountDanger : null) }}>+ {count}+ </span>+ {children}+ </span>+ );+}++function Diagnostic({ error }: { error: Record<string, unknown> }) {+ const source = asString(error["source"]);+ const code = asString(error["code"]);+ const message = asString(error["message"]) ?? "Unknown OpenUI Lang error";+ const location = [+ asString(error["component"]),+ asString(error["statementId"]),+ asString(error["path"]),+ ].filter(Boolean);+ const hint = asString(error["hint"]);+ const styles = useStyles(streamRowStyles);++ return (+ <div style={styles.diagnostic}>+ <div style={styles.diagnosticHeader}>+ {[source, code].filter(Boolean).join(" / ") || "error"}+ </div>+ <div>{message}</div>+ {location.length > 0 ? (+ <div style={styles.diagnosticLocation}>{location.join(" · ")}</div>+ ) : null}+ {hint ? <div style={styles.diagnosticHint}>{hint}</div> : null}+ </div>+ );+}++function asRecord(detail: unknown): Record<string, unknown> {+ return typeof detail === "object" && detail !== null ? (detail as Record<string, unknown>) : {};+}++function asString(value: unknown): string | undefined {+ return typeof value === "string" ? value : undefined;+}++function asNumber(value: unknown): number | undefined {+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;+}++function formatElapsed(ms: number): string {+ if (ms < 1000) return `${Math.round(ms)}ms`;+ if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`;+ if (ms < 60_000) return `${Math.round(ms / 1000)}s`;+ const minutes = Math.floor(ms / 60_000);+ const seconds = Math.round((ms % 60_000) / 1000);+ return `${minutes}m ${String(seconds).padStart(2, "0")}s`;+}++function useStreamElapsedMs(+ stream: ReactLangStreamDetail,+ isStreaming: boolean,+): number | undefined {+ const frozen = stream.durationMs ?? (isStreaming ? undefined : stream.elapsedMs);+ const [now, setNow] = useState(() => Date.now());++ useEffect(() => {+ if (!isStreaming || stream.startedAt == null) return;+ const id = window.setInterval(() => setNow(Date.now()), 200);+ return () => window.clearInterval(id);+ }, [isStreaming, stream.startedAt]);++ if (frozen != null) return frozen;+ if (stream.startedAt == null) return stream.elapsedMs;+ return Math.max(0, now - stream.startedAt);+}++function streamRowStyles(t: ThemeTokens) {+ return {+ // Longhands, not the `border` shorthand: rowHover overrides borderColor, and+ // React blanks a shorthand's longhands when a later style touches one of them.+ row: {+ borderWidth: 1,+ borderStyle: "solid",+ borderColor: t.border,+ borderRadius: 12,+ padding: 12,+ display: "flex",+ flexDirection: "column",+ gap: 6,+ background: t.card,+ transition: "border-color 150ms ease, box-shadow 150ms ease",+ },+ // Only this row expands, so hover is the affordance that says so.+ rowHover: {+ borderColor: t.borderStrong,+ boxShadow: t.shadowSubtle,+ },+ rowHeader: {+ display: "flex",+ justifyContent: "space-between",+ alignItems: "center",+ gap: 8,+ },+ rowHeaderRight: {+ display: "flex",+ alignItems: "center",+ gap: 6,+ flexShrink: 0,+ },+ // Width is fixed to match the empty slot plain rows reserve, so timestamps align.+ // Sized like an icon button so it can take the same fill; the card's own+ // hover drives it, since the whole card is the toggle.+ chevron: {+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ boxSizing: "border-box",+ width: 22,+ height: 22,+ flexShrink: 0,+ borderRadius: 6,+ color: t.fgMuted,+ transition: "background 150ms ease, color 150ms ease",+ },+ chevronHover: {+ background: t.bgSubtle,+ color: t.fg,+ },+ badgeGroup: {+ display: "flex",+ alignItems: "center",+ flexWrap: "wrap",+ gap: 6,+ minWidth: 0,+ },+ badge: {+ display: "inline-flex",+ alignItems: "center",+ borderRadius: 999,+ borderWidth: 1,+ borderStyle: "solid",+ borderColor: "transparent",+ padding: "1px 8px",+ fontSize: 11,+ fontWeight: 500,+ fontFamily: FONT,+ },+ kind: {+ color: t.fg,+ fontSize: 12,+ fontWeight: 600,+ },+ badgeStreaming: {+ background: t.successBg,+ color: t.success,+ borderColor: t.successBorder,+ },+ time: {+ color: t.fgFaint,+ fontSize: 11,+ },+ streamToggle: {+ width: "100%",+ border: "none",+ background: "transparent",+ color: "inherit",+ cursor: "pointer",+ fontFamily: FONT,+ padding: 0,+ textAlign: "left",+ },+ streamOverview: {+ display: "flex",+ flexWrap: "wrap",+ gap: "4px 10px",+ color: t.fgMuted,+ fontSize: 11,+ marginTop: 7,+ paddingLeft: 24,+ },+ tally: {+ display: "inline-flex",+ alignItems: "center",+ gap: 4,+ },+ tallyCount: {+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ boxSizing: "border-box",+ minWidth: 14,+ height: 14,+ padding: "0 3px",+ borderRadius: 999,+ background: t.bgSubtle,+ color: t.fgSecondary,+ fontSize: 10,+ lineHeight: 1,+ },+ tallyCountDanger: {+ background: t.dangerBg,+ color: t.danger,+ },+ streamExpanded: {+ display: "flex",+ flexDirection: "column",+ gap: 14,+ marginTop: 4,+ paddingTop: 12,+ },+ streamSection: {+ display: "flex",+ flexDirection: "column",+ gap: 6,+ },+ streamSectionTitle: {+ display: "flex",+ alignItems: "center",+ gap: 6,+ color: t.fgSecondary,+ fontSize: 11,+ },+ streamSectionCount: {+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ minWidth: 16,+ height: 16,+ borderRadius: 999,+ padding: "0 5px",+ boxSizing: "border-box",+ background: t.bgSubtle,+ color: t.fgMuted,+ fontSize: 10,+ lineHeight: 1,+ },+ // Label and buttons share one unstroked panel: label left, buttons right.+ responseActions: {+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ gap: 10,+ borderRadius: 8,+ background: t.bgMuted,+ padding: "8px 8px 8px 14px",+ },+ responseActionsLabel: {+ color: t.fgSecondary,+ fontSize: 11,+ },+ responseActionsButtons: {+ display: "flex",+ alignItems: "center",+ gap: 6,+ },+ responseButton: {+ display: "inline-flex",+ alignItems: "center",+ gap: 4,+ border: `1px solid ${t.controlBorder}`,+ borderRadius: 8,+ background: t.controlBg,+ color: t.fg,+ cursor: "pointer",+ fontFamily: FONT,+ fontSize: 11,+ padding: "4px 9px",+ boxShadow: t.shadowSubtle,+ transition: "transform 150ms ease",+ },+ responseButtonHover: {+ transform: "scale(0.96)",+ },+ responseButtonDisabled: {+ opacity: 0.45,+ cursor: "not-allowed",+ },+ responseCode: {+ maxHeight: 260,+ overflow: "auto",+ margin: 0,+ borderRadius: 8,+ background: t.bgMuted,+ color: t.fgTertiary,+ fontFamily: MONO,+ fontSize: 11,+ lineHeight: 1.5,+ padding: 10,+ whiteSpace: "pre-wrap",+ wordBreak: "break-word",+ },+ parserIssues: {+ borderRadius: 8,+ background: t.warningBg,+ color: t.warningStrong,+ fontSize: 11,+ lineHeight: 1.45,+ padding: "6px 8px",+ },+ diagnosticList: {+ display: "flex",+ flexDirection: "column",+ gap: 6,+ },+ diagnostic: {+ borderLeft: `2px solid ${t.dangerBorder}`,+ background: t.dangerBg,+ color: t.fgTertiary,+ fontSize: 11,+ lineHeight: 1.45,+ padding: "7px 8px",+ },+ diagnosticHeader: {+ color: t.dangerStrong,+ fontFamily: MONO,+ fontWeight: 600,+ marginBottom: 3,+ },+ diagnosticLocation: {+ color: t.fgMuted,+ fontFamily: MONO,+ marginTop: 3,+ },+ diagnosticHint: {+ color: t.fgSecondary,+ fontStyle: "italic",+ marginTop: 4,+ },+ } satisfies Record<string, CSSProperties>;+}diff --git a/packages/devtools/src/inspect/index.ts b/packages/devtools/src/inspect/index.tsnew file mode 100644index 000000000..970c1b2ae--- /dev/null+++ b/packages/devtools/src/inspect/index.ts@@ -0,0 +1,8 @@+export { EventRow } from "./EventRow";+export { LevelIcon } from "./LevelIcon";+export { QuotaErrorRow, getQuotaError, type QuotaErrorInfo } from "./QuotaErrorRow";+export {+ ReactLangStreamEventRow,+ getReactLangStreamDetail,+ type ReactLangStreamDetail,+} from "./ReactLangStreamEventRow";diff --git a/packages/devtools/src/eventBuffer.ts b/packages/devtools/src/lib/eventBuffer.tssimilarity index 100%rename from packages/devtools/src/eventBuffer.tsrename to packages/devtools/src/lib/eventBuffer.tsdiff --git a/packages/devtools/src/lib/highlight.ts b/packages/devtools/src/lib/highlight.tsnew file mode 100644index 000000000..1e6219a7c--- /dev/null+++ b/packages/devtools/src/lib/highlight.ts@@ -0,0 +1,96 @@+import type { ThemeTokens } from "../theme";++export type TokenKind =+ | "string"+ | "state"+ | "number"+ | "atom"+ | "type"+ | "ident"+ | "keyword"+ | "operator"+ | "punct"+ | "text";++export interface Token {+ kind: TokenKind;+ value: string;+}++/** Shared by the Debug editor and the Inspect stream log. */+export function tokenColor(t: ThemeTokens): Record<TokenKind, string> {+ return {+ string: t.syntaxString,+ state: t.syntaxState,+ number: t.syntaxNumber,+ atom: t.syntaxAtom,+ type: t.syntaxType,+ ident: t.syntaxIdent,+ keyword: t.syntaxKeyword,+ operator: t.syntaxOperator,+ punct: t.syntaxPunct,+ text: t.syntaxText,+ };+}++const RULES: { kind: Exclude<TokenKind, "text">; re: RegExp }[] = [+ { kind: "string", re: /^"(?:[^"\\]|\\.)*"?/ },+ { kind: "state", re: /^\$[A-Za-z_][\w]*/ },+ { kind: "number", re: /^-?\d+(?:\.\d+)?/ },+ { kind: "atom", re: /^(?:true|false|null)\b/ },+ { kind: "type", re: /^[A-Z][\w]*/ },+ { kind: "ident", re: /^[a-z_][\w]*/ },+ { kind: "keyword", re: /^@[A-Za-z_][\w]*/ },+ { kind: "operator", re: /^=/ },+ { kind: "punct", re: /^[[\]{}(),:]/ },+];++/**+ * Regroup tokens into one array per source line, dropping the newlines.+ * The editor renders a row per line so the gutter number stays with its line+ * even when the line soft-wraps. Always returns at least one (empty) line.+ */+export function toTokenLines(tokens: Token[]): Token[][] {+ const lines: Token[][] = [[]];+ for (const token of tokens) {+ const parts = token.value.split("\n");+ for (const [index, part] of parts.entries()) {+ if (index > 0) lines.push([]);+ if (part) lines[lines.length - 1]!.push({ kind: token.kind, value: part });+ }+ }+ return lines;+}++/** Same token rules as the docs highlighter, without CodeMirror. */+export function tokenizeLang(source: string): Token[] {+ const tokens: Token[] = [];+ // Runs of one kind collapse into a single token — the fallback below matches a+ // character at a time, so whitespace would otherwise dominate the output.+ const push = (kind: TokenKind, value: string) => {+ const last = tokens[tokens.length - 1];+ if (last?.kind === kind) last.value += value;+ else tokens.push({ kind, value });+ };++ let i = 0;+ while (i < source.length) {+ const slice = source.slice(i);+ let matched = false;+ for (const rule of RULES) {+ const match = rule.re.exec(slice);+ if (!match) continue;+ const value = match[0];+ const kind: TokenKind = rule.kind === "ident" && value === "root" ? "keyword" : rule.kind;+ push(kind, value);+ i += value.length;+ matched = true;+ break;+ }+ if (!matched) {+ push("text", source[i]!);+ i += 1;+ }+ }+ return tokens;+}diff --git a/packages/devtools/src/lib/index.ts b/packages/devtools/src/lib/index.tsnew file mode 100644index 000000000..09d4a4f3d--- /dev/null+++ b/packages/devtools/src/lib/index.ts@@ -0,0 +1,5 @@+export { addOrReplaceEvent } from "./eventBuffer";+export { toTokenLines, tokenColor, tokenizeLang } from "./highlight";+export type { Token, TokenKind } from "./highlight";+export { useDevtoolsSingleton } from "./singleton";+export { useDevtoolsConfig, type DevtoolsConfig } from "./useDevtoolsConfig";diff --git a/packages/devtools/src/singleton.ts b/packages/devtools/src/lib/singleton.tssimilarity index 100%rename from packages/devtools/src/singleton.tsrename to packages/devtools/src/lib/singleton.tsdiff --git a/packages/devtools/src/lib/useDevtoolsConfig.ts b/packages/devtools/src/lib/useDevtoolsConfig.tsnew file mode 100644index 000000000..058745d4c--- /dev/null+++ b/packages/devtools/src/lib/useDevtoolsConfig.ts@@ -0,0 +1,95 @@+import { useCallback, useEffect, useRef, useState } from "react";+import type { ColorMode } from "../theme";++const STORAGE_KEY = "openui.devtools.config";++export type DevtoolsConfig = {+ autoOpen: boolean;+ onlyErrors: boolean;+ theme: ColorMode;+};++function isColorMode(value: unknown): value is ColorMode {+ return value === "light" || value === "dark";+}++function sanitize(patch: Partial<DevtoolsConfig>): Partial<DevtoolsConfig> {+ const next: 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;+ return next;+}++function readStored(): Partial<DevtoolsConfig> {+ if (typeof window === "undefined") return {};+ try {+ const raw = window.localStorage.getItem(STORAGE_KEY);+ if (!raw) return {};+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed !== "object" || parsed === null) return {};+ return sanitize(parsed as Partial<DevtoolsConfig>);+ } catch {+ return {};+ }+}++function writeStored(patch: Partial<DevtoolsConfig>): void {+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(+ STORAGE_KEY,+ JSON.stringify({ ...readStored(), ...sanitize(patch) }),+ );+ } catch {+ // private mode / quota / disabled storage+ }+}++function merge(base: DevtoolsConfig, patch: Partial<DevtoolsConfig>): DevtoolsConfig {+ return { ...base, ...sanitize(patch) };+}++/**+ * Drawer settings as one object, restored from localStorage.+ * `setConfig({ autoOpen: false })` patches and persists.+ *+ * Theme is arg-first: a passed `theme` wins over storage and is written+ * back so Settings stays in sync. With no arg, the stored theme is used.+ */+export function useDevtoolsConfig(defaults: DevtoolsConfig, provided: { theme?: ColorMode } = {}) {+ const resolveTheme = (stored: Partial<DevtoolsConfig>, fallback: ColorMode): ColorMode =>+ provided.theme ?? stored.theme ?? fallback;++ const [config, setConfigState] = useState(() => {+ const stored = readStored();+ const next = { ...merge(defaults, stored), theme: resolveTheme(stored, defaults.theme) };+ if (provided.theme) writeStored({ theme: provided.theme });+ return next;+ });+ const configRef = useRef(config);+ configRef.current = config;++ // After SSR hydration the lazy initializer reused the server snapshot+ // (prop defaults). Re-read storage so a previous session's checkboxes win.+ // Theme still prefers a provided arg over that stored value.+ useEffect(() => {+ const stored = readStored();+ setConfigState((prev) => {+ const next = { ...merge(prev, stored), theme: resolveTheme(stored, prev.theme) };+ configRef.current = next;+ return next;+ });+ }, []);++ const setConfig = useCallback((patch: Partial<DevtoolsConfig>) => {+ setConfigState((prev) => {+ const next = merge(prev, patch);+ configRef.current = next;+ writeStored(patch);+ return next;+ });+ }, []);++ return { config, setConfig, configRef };+}diff --git a/packages/devtools/src/theme.ts b/packages/devtools/src/theme.tsnew file mode 100644index 000000000..a3b3b72a7--- /dev/null+++ b/packages/devtools/src/theme.ts@@ -0,0 +1,196 @@+import { createContext, createElement, useContext, type ReactNode } from "react";++/**+ * The widget's own theme. Chosen explicitly in Settings (persisted) — the+ * widget never sniffs the host page or the OS, so it looks the same in+ * every app until you change it.+ */+export type ColorMode = "light" | "dark";++export const DEFAULT_COLOR_MODE: ColorMode = "light";++/**+ * Zinc-based UI for the injected widget. Independent of the host design+ * system so the same drawer works in any app.+ */+const LIGHT = {+ bg: "#ffffff",+ // Event cards. Level with the tray in light; lifted off it in dark, where a+ // border alone is too faint to separate them.+ card: "#ffffff",+ // Small outlined controls. They sit on recessed panels, so in dark they need+ // to be lighter than the tray to read as raised.+ controlBg: "#ffffff",+ controlBorder: "#e4e4e7",+ // Inset fills are alpha, not fixed hex, so they read the same shade deeper+ // wherever they land — on the tray, on a card, or inside another panel.+ promoBg: "rgba(24, 24, 27, 0.035)",+ bgMuted: "rgba(24, 24, 27, 0.035)",+ bgSubtle: "#f4f4f5",+ fg: "#18181b",+ fgMuted: "#71717a",+ fgFaint: "#8a8a94",+ fgSecondary: "#52525b",+ fgTertiary: "#3f3f46",+ border: "#e4e4e7",+ borderStrong: "#cfcfd4",+ // LevelIcon chip fills: a step tinted past the surface, softer than the+ // matching -border tokens they sit next to.+ levelNeutral: "#ececee",+ levelWarning: "#ffedd5",+ levelDanger: "#fee2e2",+ borderSubtle: "#f4f4f5",+ overlay: "rgba(24, 24, 27, 0.4)",+ shadow: "0 16px 48px rgba(24, 24, 27, 0.18)",+ shadowSubtle: "0 1px 2px rgba(24, 24, 27, 0.07)",+ trayShadow: "rgba(99, 99, 99, 0.2) 0px 2px 8px 0px",+ toggleBg: "#18181b",+ toggleFg: "#ffffff",+ // Rim on the trays: a hairline of the opposite tone, so the panel edge+ // reads without the weight of a solid border.+ trayRing: "rgba(24, 24, 27, 0.10)",+ toggleBorder: "rgba(0, 0, 0, 0.08)",+ toggleShadow: "0 1px 4px rgba(0, 0, 0, 0.10)",+ toggleError: "#e05252",+ // The error toggle is a light puck in both themes, so the red count disc+ // inside it keeps the same contrast wherever the widget is mounted.+ toggleErrorSurface: "#ffffff",+ toggleErrorRing: "rgba(0, 0, 0, 0.14)",+ inverted: "#18181b",+ invertedFg: "#ffffff",+ danger: "#b91c1c",+ dangerBg: "#fef2f2",+ dangerBorder: "#fecaca",+ dangerStrong: "#991b1b",+ warning: "#c2410c",+ warningBg: "#fff7ed",+ warningBorder: "#fed7aa",+ warningStrong: "#9a3412",+ info: "#1d4ed8",+ infoBg: "#eff6ff",+ infoBorder: "#bfdbfe",+ success: "#047857",+ successBg: "#ecfdf5",+ successBorder: "#a7f3d0",+ creditsBg: "#fef3c7",+ creditsFg: "#92400e",+ creditsBorder: "#fde68a",+ creditsGradient: "linear-gradient(135deg, #fffbeb 0%, #fff7ed 100%)",+ selection: "#bfdbfe",+ syntaxString: "#15803d",+ syntaxState: "#a21caf",+ syntaxNumber: "#c2410c",+ syntaxAtom: "#7c3aed",+ syntaxType: "#1d4ed8",+ syntaxIdent: "#3f3f46",+ syntaxKeyword: "#0f766e",+ syntaxOperator: "#71717a",+ syntaxPunct: "#a1a1aa",+ syntaxText: "#18181b",+} as const;++const DARK = {+ // Lightness is the depth cue: raised surfaces step up from the tray, inset+ // ones step down. One neutral hue throughout, so nothing reads muddy.+ // inset (alpha) < tray #17171a < card #1f1f23 < chips #2e2e34+ bg: "#17171a",+ card: "#1f1f23",+ // Fill sits just above the card; the stroke a step above the fill, so the+ // control catches light on its edge the way a raised surface does.+ controlBg: "#26262b",+ controlBorder: "#33333a",+ bgMuted: "rgba(0, 0, 0, 0.20)",+ promoBg: "rgba(0, 0, 0, 0.20)",+ bgSubtle: "#2e2e34",+ // Five distinct steps. `fg` stops short of pure white to avoid halation.+ fg: "#ededf0",+ fgTertiary: "#d0d0d6",+ fgSecondary: "#b0b0b8",+ fgMuted: "#9494a0",+ fgFaint: "#74747f",+ border: "#262629",+ borderStrong: "#3f3f47",+ borderSubtle: "#26262b",+ levelNeutral: "#2e2e34",+ levelWarning: "#3b2a13",+ levelDanger: "#3b1f23",+ overlay: "rgba(0, 0, 0, 0.6)",+ shadow: "0 16px 48px rgba(0, 0, 0, 0.5)",+ shadowSubtle: "0 1px 2px rgba(0, 0, 0, 0.4)",+ trayShadow: "rgba(0, 0, 0, 0.16) 0px 10px 36px 0px, rgba(0, 0, 0, 0.06) 0px 0px 0px 1px",+ toggleBg: "#17171a",+ toggleFg: "#ffffff",+ trayRing: "rgba(255, 255, 255, 0.09)",+ toggleBorder: "rgba(255, 255, 255, 0.18)",+ toggleShadow: "0 1px 4px rgba(0, 0, 0, 0.28)",+ toggleError: "#e05252",+ toggleErrorSurface: "#ffffff",+ toggleErrorRing: "rgba(0, 0, 0, 0.14)",+ inverted: "#ededf0",+ invertedFg: "#17171a",+ // Accent surfaces are the base neutral nudged toward the hue (~10% sat), not+ // the hue itself darkened — that reads as a solid block on a dark tray.+ danger: "#f78b8b",+ dangerBg: "#331a1e",+ dangerBorder: "#5c2a31",+ dangerStrong: "#fcbcbc",+ warning: "#f5a04a",+ warningBg: "#332110",+ warningBorder: "#5c3d1e",+ warningStrong: "#f9c893",+ info: "#86b3fa",+ infoBg: "#17253d",+ infoBorder: "#2b4778",+ success: "#5fd6a4",+ successBg: "#122e23",+ successBorder: "#1f5240",+ creditsBg: "#332110",+ creditsFg: "#f9c893",+ creditsBorder: "#5c3d1e",+ creditsGradient: "linear-gradient(135deg, #332110 0%, #331a18 100%)",+ selection: "#2b4778",+ syntaxString: "#5fd97f",+ syntaxState: "#dd8bf0",+ syntaxNumber: "#f5a04a",+ syntaxAtom: "#b9a6fb",+ syntaxType: "#86b3fa",+ syntaxIdent: "#d0d0d6",+ syntaxKeyword: "#4dd3c0",+ syntaxOperator: "#9494a0",+ syntaxPunct: "#74747f",+ syntaxText: "#ededf0",+} as const;++export type ThemeTokens = { [K in keyof typeof LIGHT]: string };++export const FONT = '"Inter", system-ui, sans-serif';+export const MONO = "ui-monospace, SFMono-Regular, Menlo, monospace";++/** Palette for the chosen mode. Native `colorScheme` still goes on the root. */+export function theme(mode: ColorMode): ThemeTokens {+ return mode === "dark" ? DARK : LIGHT;+}++export function rootStyle(mode: ColorMode): { colorScheme: ColorMode } {+ return { colorScheme: mode };+}++const ModeContext = createContext<ColorMode>(DEFAULT_COLOR_MODE);++export function DevtoolsModeProvider({ mode, children }: { mode: ColorMode; children: ReactNode }) {+ return createElement(ModeContext.Provider, { value: mode }, children);+}++/** The mode chosen in Settings, shared with the Debug tray and popup. */+export function useDevtoolsMode(): ColorMode {+ return useContext(ModeContext);+}++/** Tokens for the mode in context. */+export function useTheme(): ThemeTokens {+ return theme(useDevtoolsMode());+}++export function useStyles<T>(factory: (tokens: ThemeTokens) => T): T {+ return factory(useTheme());+}diff --git a/packages/devtools/src/ui/IconButton.tsx b/packages/devtools/src/ui/IconButton.tsxnew file mode 100644index 000000000..24a8d564b--- /dev/null+++ b/packages/devtools/src/ui/IconButton.tsx@@ -0,0 +1,67 @@+import { useState, type ButtonHTMLAttributes, type CSSProperties } from "react";+import { useStyles, type ThemeTokens } from "../theme";++/**+ * The widget's square icon buttons — header actions, close crosses, the+ * settings trigger. They sit on their tray unfilled until pointed at,+ * then take a fill; keeping that in one component means every one of them+ * behaves the same without threading hover state through each call site.+ */+export function IconButton({+ active = false,+ outlined = false,+ style,+ ...props+}: ButtonHTMLAttributes<HTMLButtonElement> & {+ /** Held open, e.g. the settings trigger while its menu shows. */+ active?: boolean;+ /** Carries its own border, for buttons that sit on a busy surface. */+ outlined?: boolean;+}) {+ const [hovered, setHovered] = useState(false);+ const styles = useStyles(buttonStyles);+ return (+ <button+ {...props}+ style={{+ ...styles.button,+ ...(outlined ? styles.outlined : null),+ ...(hovered || active ? styles.filled : null),+ ...style,+ }}+ onMouseEnter={() => setHovered(true)}+ onMouseLeave={() => setHovered(false)}+ />+ );+}++function buttonStyles(t: ThemeTokens) {+ return {+ button: {+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ boxSizing: "border-box",+ width: 26,+ height: 26,+ borderWidth: 1,+ borderStyle: "solid",+ borderColor: "transparent",+ borderRadius: 8,+ background: "transparent",+ color: t.fgMuted,+ cursor: "pointer",+ padding: 0,+ transition: "background 150ms ease, color 150ms ease",+ },+ outlined: {+ borderColor: t.controlBorder,+ background: t.controlBg,+ color: t.fg,+ },+ filled: {+ background: t.bgSubtle,+ color: t.fg,+ },+ } satisfies Record<string, CSSProperties>;+}diff --git a/packages/devtools/src/ShiroLogo.tsx b/packages/devtools/src/ui/ShiroLogo.tsxsimilarity index 100%rename from packages/devtools/src/ShiroLogo.tsxrename to packages/devtools/src/ui/ShiroLogo.tsxdiff --git a/packages/devtools/src/ui/ThemeToggle.tsx b/packages/devtools/src/ui/ThemeToggle.tsxnew file mode 100644index 000000000..050ab80ae--- /dev/null+++ b/packages/devtools/src/ui/ThemeToggle.tsx@@ -0,0 +1,85 @@+import { Moon, Sun } from "lucide-react";+import type { CSSProperties } from "react";+import { useStyles, type ColorMode, type ThemeTokens } from "../theme";+import { IconButton } from "./IconButton";++const OPTIONS: { id: ColorMode; label: string; icon: typeof Sun }[] = [+ { id: "light", label: "Light", icon: Sun },+ { id: "dark", label: "Dark", icon: Moon },+];++/**+ * Two icon buttons for the Inspect settings menu, where the row has a label+ * and room to show both choices. The selected one is filled; the other is+ * unfilled until pointed at.+ */+export function ThemeSegmented({+ value,+ onChange,+}: {+ value: ColorMode;+ onChange: (value: ColorMode) => void;+}) {+ const styles = useStyles(segmentedStyles);+ return (+ <div style={styles.segmented} role="radiogroup" aria-label="Theme">+ {OPTIONS.map((option) => {+ const active = value === option.id;+ const Icon = option.icon;+ return (+ <IconButton+ key={option.id}+ type="button"+ role="radio"+ aria-checked={active}+ style={active ? styles.selected : undefined}+ onClick={() => onChange(option.id)}+ aria-label={option.label}+ title={option.label}+ >+ <Icon size={14} />+ </IconButton>+ );+ })}+ </div>+ );+}++/**+ * Single-button flip for the Debug header, which is a row of icon buttons with+ * no room for a labelled pair. It shows the theme you would get, not the one+ * you are in — the icon is the outcome of pressing it.+ */+export function ThemeToggle({+ value,+ onChange,+}: {+ value: ColorMode;+ onChange: (value: ColorMode) => void;+}) {+ const next: ColorMode = value === "dark" ? "light" : "dark";+ const label = next === "dark" ? "Switch to dark theme" : "Switch to light theme";+ const Icon = next === "dark" ? Moon : Sun;++ return (+ <IconButton onClick={() => onChange(next)} aria-label={label} title={label}>+ <Icon size={14} />+ </IconButton>+ );+}++function segmentedStyles(t: ThemeTokens) {+ return {+ segmented: {+ display: "inline-flex",+ alignItems: "center",+ gap: 2,+ flexShrink: 0,+ },+ selected: {+ background: t.inverted,+ color: t.invertedFg,+ borderColor: t.inverted,+ },+ } satisfies Record<string, CSSProperties>;+}diff --git a/packages/devtools/src/ui/index.ts b/packages/devtools/src/ui/index.tsnew file mode 100644index 000000000..896118b8e--- /dev/null+++ b/packages/devtools/src/ui/index.ts@@ -0,0 +1,3 @@+export { IconButton } from "./IconButton";+export { ShiroLogo } from "./ShiroLogo";+export { ThemeSegmented, ThemeToggle } from "./ThemeToggle";diff --git a/packages/devtools/src/useDevtoolsConfig.ts b/packages/devtools/src/useDevtoolsConfig.tsdeleted file mode 100644index 7c9dfa0d2..000000000--- a/packages/devtools/src/useDevtoolsConfig.ts+++ /dev/null@@ -1,77 +0,0 @@-import { useCallback, useEffect, useRef, useState } from "react";--const STORAGE_KEY = "openui.devtools.config";--/** Add a boolean here when a new drawer setting should persist. */-const BOOLEAN_KEYS = ["autoOpen", "onlyErrors"] as const;--export type DevtoolsConfig = { [K in (typeof BOOLEAN_KEYS)[number]]: boolean };--function readStored(): Partial<DevtoolsConfig> {- if (typeof window === "undefined") return {};- try {- const raw = window.localStorage.getItem(STORAGE_KEY);- if (!raw) return {};- const parsed: unknown = JSON.parse(raw);- if (typeof parsed !== "object" || parsed === null) return {};- const record = parsed as Record<string, unknown>;- const config: Partial<DevtoolsConfig> = {};- for (const key of BOOLEAN_KEYS) {- if (typeof record[key] === "boolean") config[key] = record[key];- }- return config;- } catch {- return {};- }-}--function writeStored(patch: Partial<DevtoolsConfig>): void {- if (typeof window === "undefined") return;- try {- window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ ...readStored(), ...patch }));- } catch {- // private mode / quota / disabled storage- }-}--function merge(base: DevtoolsConfig, patch: Partial<DevtoolsConfig>): DevtoolsConfig {- const next = { ...base };- for (const key of BOOLEAN_KEYS) {- const value = patch[key];- if (typeof value === "boolean") next[key] = value;- }- return next;-}--/**- * Drawer checkbox state as one object, restored from localStorage.- * `setConfig({ autoOpen: false })` patches and persists; add keys to- * `BOOLEAN_KEYS` when a new setting should survive refresh.- */-export function useDevtoolsConfig(defaults: DevtoolsConfig) {- const [config, setConfigState] = useState(() => merge(defaults, readStored()));- const configRef = useRef(config);- configRef.current = config;-- // After SSR hydration the lazy initializer reused the server snapshot- // (prop defaults). Re-read storage so a previous session's checkboxes win.- useEffect(() => {- const stored = readStored();- setConfigState((prev) => {- const next = merge(prev, stored);- configRef.current = next;- return next;- });- }, []);-- const setConfig = useCallback((patch: Partial<DevtoolsConfig>) => {- setConfigState((prev) => {- const next = merge(prev, patch);- configRef.current = next;- writeStored(patch);- return next;- });- }, []);-- return { config, setConfig, configRef };-}