Skip to content

The Open Standard for Generative UI

Automount devtools in react-lang (#934)

abhithesys9c17d16027ef
diff --git a/packages/devtools/README.md b/packages/devtools/README.md
index b6472ea42..dfdb8aec7 100644
--- a/packages/devtools/README.md
+++ b/packages/devtools/README.md
@@ -19,6 +19,8 @@ function App() {
The widget renders nothing in production builds (`NODE_ENV === "production"`) unless `enabled` is passed explicitly.
+`@openuidev/react-lang` ships with this package and auto-mounts the widget in development — no manual `<OpenUIDevtools />` needed. Mounting it manually still works (e.g. to customize props): only one instance ever renders, and a manually mounted instance takes precedence over the auto-mounted one.
+
## Props
| Prop | Default | Description |
diff --git a/packages/devtools/src/OpenUIDevtools.test.ts b/packages/devtools/src/OpenUIDevtools.test.ts
index 9c12fd36c..e4ad3758a 100644
--- a/packages/devtools/src/OpenUIDevtools.test.ts
+++ b/packages/devtools/src/OpenUIDevtools.test.ts
@@ -280,6 +280,40 @@ describe("OpenUIDevtools", () => {
expect(container.textContent).toContain("root = Second()");
});
+ it("renders only one widget when multiple instances are mounted", () => {
+ const second = document.createElement("div");
+ document.body.appendChild(second);
+ const secondRoot = createRoot(second);
+
+ render({ enabled: true });
+ act(() => secondRoot.render(createElement(OpenUIDevtools, { enabled: true })));
+
+ expect(document.querySelectorAll('button[aria-label="Open OpenUI devtools"]')).toHaveLength(1);
+
+ act(() => secondRoot.unmount());
+ second.remove();
+ });
+
+ 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();
+
+ // … then a manual instance mounts and takes over.
+ const manual = document.createElement("div");
+ document.body.appendChild(manual);
+ 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();
+
+ // 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();
+ });
+
it("removes a resolved stream from the errors-only view", () => {
render({ enabled: true, errorsOnly: true, autoOpenOnError: false });
diff --git a/packages/devtools/src/OpenUIDevtools.tsx b/packages/devtools/src/OpenUIDevtools.tsx
index 8b3310061..53b0e8cff 100644
--- a/packages/devtools/src/OpenUIDevtools.tsx
+++ b/packages/devtools/src/OpenUIDevtools.tsx
@@ -11,6 +11,7 @@ import { getQuotaError, QuotaErrorRow } from "./QuotaErrorRow";
import { getReactLangStreamDetail, ReactLangStreamEventRow } from "./ReactLangStreamEventRow";
import { ShiroLogo } from "./ShiroLogo";
import { addOrReplaceEvent } from "./eventBuffer";
+import { useDevtoolsSingleton } from "./singleton";
export type DevtoolsPosition = "top-left" | "top-right" | "bottom-left" | "bottom-right";
@@ -26,6 +27,11 @@ export interface OpenUIDevtoolsProps {
errorsOnly?: boolean;
/** Initial state of the drawer's "auto-open on error" checkbox. Defaults to true. */
autoOpenOnError?: boolean;
+ /**
+ * @internal Set by react-lang's auto-mount. Auto-mounted instances yield to
+ * any manually rendered <OpenUIDevtools /> so host-provided props win.
+ */
+ __autoMounted?: boolean;
}
/**
@@ -41,9 +47,13 @@ export function OpenUIDevtools({
maxEvents = 50,
errorsOnly = false,
autoOpenOnError = true,
+ __autoMounted = false,
}: OpenUIDevtoolsProps) {
const isEnabled =
enabled ?? (typeof process === "undefined" || process.env["NODE_ENV"] !== "production");
+ // Only one instance renders even when several are mounted (e.g. react-lang's
+ // auto-mount plus a manual <OpenUIDevtools /> in the host's layout).
+ const isSingleton = useDevtoolsSingleton(__autoMounted);
const [events, setEvents] = useState<ObservabilityEvent[]>([]);
const [open, setOpen] = useState(false);
const [selected, setSelected] = useState<ObservabilityEvent | null>(null);
@@ -76,7 +86,7 @@ export function OpenUIDevtools({
return () => document.removeEventListener("keydown", onKeyDown);
}, [open, selected]);
- if (!isEnabled) return null;
+ if (!isEnabled || !isSingleton) return null;
const errorCount = events.filter((event) => event.level === "error").length;
const visibleEvents = onlyErrors ? events.filter((event) => event.level !== "info") : events;
diff --git a/packages/devtools/src/singleton.ts b/packages/devtools/src/singleton.ts
new file mode 100644
index 000000000..11988e1d6
--- /dev/null
+++ b/packages/devtools/src/singleton.ts
@@ -0,0 +1,57 @@
+import { useEffect, useState } from "react";
+
+/**
+ * Cross-instance (and cross-bundle-copy) registry that elects a single
+ * OpenUIDevtools instance to actually render. Keyed on globalThis via
+ * Symbol.for so duplicate copies of this module (ESM/CJS dual builds,
+ * multiple package versions) still share one registry.
+ *
+ * Election rule: manually mounted instances outrank auto-mounted ones
+ * (react-lang's Renderer auto-mounts a widget; a host that renders
+ * <OpenUIDevtools /> itself — possibly with custom props — should win).
+ * Ties break by mount order. When the owner unmounts, the next candidate
+ * takes over.
+ */
+
+interface Claimant {
+ auto: boolean;
+ notify: (isOwner: boolean) => void;
+}
+
+interface Registry {
+ claimants: Claimant[];
+}
+
+const REGISTRY_KEY = Symbol.for("openui.devtools.singleton");
+
+function getRegistry(): Registry {
+ const store = globalThis as { [REGISTRY_KEY]?: Registry };
+ return (store[REGISTRY_KEY] ??= { claimants: [] });
+}
+
+function electOwner(registry: Registry): void {
+ const winner = registry.claimants.find((c) => !c.auto) ?? registry.claimants[0];
+ for (const claimant of registry.claimants) claimant.notify(claimant === winner);
+}
+
+/**
+ * Returns true only for the elected OpenUIDevtools instance; all others
+ * should render nothing.
+ */
+export function useDevtoolsSingleton(auto: boolean): boolean {
+ const [isOwner, setIsOwner] = useState(false);
+
+ useEffect(() => {
+ const registry = getRegistry();
+ const claimant: Claimant = { auto, notify: setIsOwner };
+ registry.claimants.push(claimant);
+ electOwner(registry);
+ return () => {
+ const index = registry.claimants.indexOf(claimant);
+ if (index !== -1) registry.claimants.splice(index, 1);
+ electOwner(registry);
+ };
+ }, [auto]);
+
+ return isOwner;
+}
diff --git a/packages/react-lang/package.json b/packages/react-lang/package.json
index 5ba24c84a..b60ef3c44 100644
--- a/packages/react-lang/package.json
+++ b/packages/react-lang/package.json
@@ -1,19 +1,34 @@
{
"name": "@openuidev/react-lang",
- "version": "0.2.10",
+ "version": "0.2.11",
"description": "Define component libraries, generate LLM system prompts, and render streaming OpenUI Lang output in React — the core runtime for OpenUI generative UI",
"license": "MIT",
"type": "module",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"types": "dist/index.d.cts",
- "sideEffects": false,
+ "sideEffects": [
+ "./dist/index.mjs",
+ "./dist/index.cjs",
+ "./src/index.ts",
+ "./src/devtoolsBootstrap.ts"
+ ],
"files": [
"dist",
"README.md"
],
"exports": {
".": {
+ "react-native": {
+ "import": {
+ "types": "./dist/index.native.d.mts",
+ "default": "./dist/index.native.mjs"
+ },
+ "require": {
+ "types": "./dist/index.native.d.cts",
+ "default": "./dist/index.native.cjs"
+ }
+ },
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
@@ -24,6 +39,7 @@
}
}
},
+ "react-native": "./dist/index.native.cjs",
"scripts": {
"test": "vitest run --passWithNoTests",
"build": "tsdown",
@@ -66,21 +82,27 @@
},
"author": "[email protected]",
"dependencies": {
+ "@openuidev/devtools": "workspace:^",
"@openuidev/lang-core": "workspace:^",
"@openuidev/observability": "workspace:^"
},
"peerDependencies": {
"@modelcontextprotocol/sdk": ">=1.0.0",
- "react": "catalog:",
+ "react": "*",
+ "react-dom": "*",
"zod": "catalog:"
},
"peerDependenciesMeta": {
"@modelcontextprotocol/sdk": {
"optional": true
+ },
+ "react-dom": {
+ "optional": true
}
},
"devDependencies": {
"@modelcontextprotocol/sdk": "^1.27.1",
+ "@types/node": "catalog:",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"jsdom": "catalog:",
diff --git a/packages/react-lang/src/devtoolsBootstrap.ts b/packages/react-lang/src/devtoolsBootstrap.ts
new file mode 100644
index 000000000..3b732ed44
--- /dev/null
+++ b/packages/react-lang/src/devtoolsBootstrap.ts
@@ -0,0 +1,44 @@
+/**
+ * Auto-mounts the OpenUI devtools widget in development.
+ *
+ * This module runs as a top-level side effect when the web entry is loaded in
+ * a browser. In production builds the whole block is dead-code-eliminated by
+ * the consumer's bundler (the NODE_ENV condition folds to false), so neither
+ * `@openuidev/devtools` nor `react-dom/client` enters the production graph.
+ * The React Native entry (index.native.ts) never imports this module.
+ *
+ * This module is inlined into the web entry (dist/index.*), which is listed
+ * in package.json's `sideEffects` so bundlers preserve the side effect while
+ * the rest of the package stays tree-shakeable.
+ */
+
+// Strict equality with "development" (rather than !== "production") keeps the
+// widget out of test runners like Jest with jsdom, where NODE_ENV is "test".
+if (process.env.NODE_ENV === "development" && typeof document !== "undefined") {
+ const AUTO_MOUNT_FLAG = Symbol.for("openui.devtools.autoMount");
+ const flags = globalThis as { [key: symbol]: boolean | undefined };
+ // Once per document, even if multiple copies of this module load
+ // (ESM/CJS dual build, multiple package versions).
+ if (!flags[AUTO_MOUNT_FLAG]) {
+ flags[AUTO_MOUNT_FLAG] = true;
+ Promise.all([import("@openuidev/devtools"), import("react"), import("react-dom/client")])
+ .then(([devtools, react, reactDomClient]) => {
+ const mount = () => {
+ const host = document.createElement("div");
+ host.setAttribute("data-openui-devtools-root", "");
+ document.body.appendChild(host);
+ reactDomClient
+ .createRoot(host)
+ .render(react.createElement(devtools.OpenUIDevtools, { __autoMounted: true }));
+ };
+ // Module evaluation can happen before <body> exists (script in <head>).
+ if (document.body) mount();
+ else document.addEventListener("DOMContentLoaded", mount, { once: true });
+ })
+ .catch(() => {
+ // Never let a devtools loading failure break the host app.
+ });
+ }
+}
+
+export {};
diff --git a/packages/react-lang/src/exports.ts b/packages/react-lang/src/exports.ts
new file mode 100644
index 000000000..586c5ef99
--- /dev/null
+++ b/packages/react-lang/src/exports.ts
@@ -0,0 +1,88 @@
+// define library
+export { tagSchemaId } from "@openuidev/lang-core";
+export { createLibrary, defineComponent } from "./library";
+export type {
+ ComponentGroup,
+ ComponentRenderProps,
+ ComponentRenderer,
+ DefinedComponent,
+ Library,
+ LibraryDefinition,
+ PromptOptions,
+ SubComponentOf,
+ ToolDescriptor,
+} from "./library";
+
+// openui-lang renderer
+export { Renderer } from "./Renderer";
+export type { RendererProps } from "./Renderer";
+
+// openui-lang action types
+export { ACTION_STEPS, BuiltinActionType } from "@openuidev/lang-core";
+export type {
+ ActionEvent,
+ ActionPlan,
+ ActionStep,
+ ElementNode,
+ OpenUIError,
+ ParseResult,
+} from "@openuidev/lang-core";
+
+// openui-lang parser (server-side use)
+export { createParser, createStreamingParser } from "@openuidev/lang-core";
+
+// Standalone prompt generation (no Zod deps — usable on backend)
+export { generatePrompt, generateSystemPrompt } from "@openuidev/lang-core";
+export type {
+ ComponentPromptSpec,
+ PromptSpec,
+ SystemPromptOptions,
+ SystemPromptSpec,
+ ToolSpec,
+} from "@openuidev/lang-core";
+
+// openui-lang edit/merge
+export { mergeStatements } from "@openuidev/lang-core";
+
+// openui-lang context hooks (for use inside component renderers)
+export {
+ FormNameContext,
+ useFormName,
+ useGetFieldValue,
+ useIsQueryLoading,
+ useIsStreaming,
+ useRenderNode,
+ useSetDefaultValue,
+ useSetFieldValue,
+ useTriggerAction,
+} from "./context";
+
+// Runtime — reactive bindings, store, evaluator, query manager, field binding
+export { ToolNotFoundError, extractToolResult, isReactiveAssign } from "@openuidev/lang-core";
+export type {
+ EvaluationContext,
+ McpClientLike,
+ ReactiveAssign,
+ StateField,
+ ToolProvider,
+} from "@openuidev/lang-core";
+export { reactive } from "./runtime";
+
+// Unified field state hook — component authors use this
+export { useStateField } from "./hooks/useStateField";
+
+// openui-lang form validation
+export {
+ FormValidationContext,
+ useCreateFormValidation,
+ useFormValidation,
+} from "./hooks/useFormValidation";
+export type { FormValidationContextValue } from "./hooks/useFormValidation";
+
+export {
+ builtInValidators,
+ parseRules,
+ parseStructuredRules,
+ validate,
+} from "@openuidev/lang-core";
+export type { ParsedRule, ValidatorFn } from "@openuidev/lang-core";
diff --git a/packages/react-lang/src/index.native.ts b/packages/react-lang/src/index.native.ts
new file mode 100644
index 000000000..e7a2e2d1d
--- /dev/null
+++ b/packages/react-lang/src/index.native.ts
@@ -0,0 +1,4 @@
+// React Native entry — identical to the web entry minus the devtools
+// bootstrap: Metro resolves all import specifiers statically (including
+// dynamic import()), and react-dom does not exist on native platforms.
+export * from "./exports";
diff --git a/packages/react-lang/src/index.ts b/packages/react-lang/src/index.ts
index 586c5ef99..0a56ff8f8 100644
--- a/packages/react-lang/src/index.ts
+++ b/packages/react-lang/src/index.ts
@@ -1,88 +1,7 @@
-// define library
-export { tagSchemaId } from "@openuidev/lang-core";
-export { createLibrary, defineComponent } from "./library";
-export type {
- ComponentGroup,
- ComponentRenderProps,
- ComponentRenderer,
- DefinedComponent,
- Library,
- LibraryDefinition,
- PromptOptions,
- SubComponentOf,
- ToolDescriptor,
-} from "./library";
+// Web entry ("." default export). Auto-mounts the OpenUI devtools widget in
+// development via the side-effect import below. React Native resolves the
+// "react-native" condition / legacy root field to index.native.ts instead,
+// which omits the bootstrap (react-dom is not resolvable under Metro).
+import "./devtoolsBootstrap";
-// openui-lang renderer
-export { Renderer } from "./Renderer";
-export type { RendererProps } from "./Renderer";
-
-// openui-lang action types
-export { ACTION_STEPS, BuiltinActionType } from "@openuidev/lang-core";
-export type {
- ActionEvent,
- ActionPlan,
- ActionStep,
- ElementNode,
- OpenUIError,
- ParseResult,
-} from "@openuidev/lang-core";
-
-// openui-lang parser (server-side use)
-export { createParser, createStreamingParser } from "@openuidev/lang-core";
-
-// Standalone prompt generation (no Zod deps — usable on backend)
-export { generatePrompt, generateSystemPrompt } from "@openuidev/lang-core";
-export type {
- ComponentPromptSpec,
- PromptSpec,
- SystemPromptOptions,
- SystemPromptSpec,
- ToolSpec,
-} from "@openuidev/lang-core";
-
-// openui-lang edit/merge
-export { mergeStatements } from "@openuidev/lang-core";
-
-// openui-lang context hooks (for use inside component renderers)
-export {
- FormNameContext,
- useFormName,
- useGetFieldValue,
- useIsQueryLoading,
- useIsStreaming,
- useRenderNode,
- useSetDefaultValue,
- useSetFieldValue,
- useTriggerAction,
-} from "./context";
-
-// Runtime — reactive bindings, store, evaluator, query manager, field binding
-export { ToolNotFoundError, extractToolResult, isReactiveAssign } from "@openuidev/lang-core";
-export type {
- EvaluationContext,
- McpClientLike,
- ReactiveAssign,
- StateField,
- ToolProvider,
-} from "@openuidev/lang-core";
-export { reactive } from "./runtime";
-
-// Unified field state hook — component authors use this
-export { useStateField } from "./hooks/useStateField";
-
-// openui-lang form validation
-export {
- FormValidationContext,
- useCreateFormValidation,
- useFormValidation,
-} from "./hooks/useFormValidation";
-export type { FormValidationContextValue } from "./hooks/useFormValidation";
-
-export {
- builtInValidators,
- parseRules,
- parseStructuredRules,
- validate,
-} from "@openuidev/lang-core";
-export type { ParsedRule, ValidatorFn } from "@openuidev/lang-core";
+export * from "./exports";
diff --git a/packages/react-lang/tsdown.config.ts b/packages/react-lang/tsdown.config.ts
index bd5f1a3e1..e2715120b 100644
--- a/packages/react-lang/tsdown.config.ts
+++ b/packages/react-lang/tsdown.config.ts
@@ -1,7 +1,7 @@
import { defineConfig } from "tsdown";
export default defineConfig({
- entry: ["src/index.ts"],
+ entry: ["src/index.ts", "src/index.native.ts"],
format: ["esm", "cjs"],
dts: true,
sourcemap: true,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d9024066d..39f4d0a37 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1778,7 +1778,7 @@ importers:
version: 20.19.43
vitest:
specifier: ^4.0.18
packages/langchain:
dependencies:
@@ -1900,6 +1900,9 @@ importers:
packages/react-lang:
dependencies:
+ '@openuidev/devtools':
+ specifier: workspace:^
+ version: link:../devtools
'@openuidev/lang-core':
specifier: workspace:^
version: link:../lang-core
@@ -1907,7 +1910,7 @@ importers:
specifier: workspace:^
version: link:../observability
react:
- specifier: 'catalog:'
+ specifier: '*'
version: 19.2.4
zod:
specifier: 'catalog:'
@@ -1916,6 +1919,9 @@ importers:
'@modelcontextprotocol/sdk':
specifier: ^1.27.1
version: 1.30.0(@cfworker/[email protected])([email protected])
+ '@types/node':
+ specifier: 'catalog:'
+ version: 22.20.1
'@types/react':
specifier: 'catalog:'
version: 19.2.17
@@ -1930,7 +1936,7 @@ importers:
version: 19.2.4([email protected])
vitest:
specifier: ^4.0.18
packages/react-ui:
dependencies:
@@ -19555,8 +19561,8 @@ snapshots:
dependencies:
- '@babel/parser': 8.0.0-rc.3
- '@babel/types': 8.0.0-rc.3
+ '@babel/parser': 8.0.4
+ '@babel/types': 8.0.4
'@jridgewell/gen-mapping': 0.3.13
'@jridgewell/trace-mapping': 0.3.31
'@types/jsesc': 2.5.1
@@ -19699,7 +19705,7 @@ snapshots:
dependencies:
- '@babel/types': 8.0.0-rc.3
+ '@babel/types': 8.0.4
dependencies: