The Open Standard for Generative UI
Register createLibrary() with Devtools and mute preview streams (#1004)
AB79449561a48b
diff --git a/packages/react-lang/package.json b/packages/react-lang/package.jsonindex b60ef3c44..1687f4115 100644--- a/packages/react-lang/package.json+++ b/packages/react-lang/package.json@@ -1,6 +1,6 @@{"name": "@openuidev/react-lang",- "version": "0.2.11",+ "version": "0.2.12","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",diff --git a/packages/react-lang/src/Renderer.tsx b/packages/react-lang/src/Renderer.tsxindex 6b113a424..669ddb5b5 100644--- a/packages/react-lang/src/Renderer.tsx+++ b/packages/react-lang/src/Renderer.tsx@@ -50,6 +50,7 @@ export interface RendererProps {* Called with [] when all errors are resolved.*/onError?: (errors: OpenUIError[]) => void;+ publishObservability?: boolean;}// ─── Error boundary ───@@ -207,6 +208,7 @@ export function Renderer({toolProvider,queryLoader,onError,+ publishObservability,}: RendererProps) {useInsertionEffect(() => {ensureLoadingStyle();@@ -253,6 +255,7 @@ export function Renderer({initialState,toolProvider: resolvedToolProvider,onError,+ publishObservability,},renderDeep,);diff --git a/packages/react-lang/src/devtoolsBootstrap.ts b/packages/react-lang/src/devtoolsBootstrap.tsindex 3b732ed44..4654e036c 100644--- a/packages/react-lang/src/devtoolsBootstrap.ts+++ b/packages/react-lang/src/devtoolsBootstrap.ts@@ -1,5 +1,5 @@/**- * Auto-mounts the OpenUI devtools widget in development.+ * Auto-mounts the OpenUI Inspect 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 bydiff --git a/packages/react-lang/src/hooks/useOpenUIState.ts b/packages/react-lang/src/hooks/useOpenUIState.tsindex 899e38826..9628c65c7 100644--- a/packages/react-lang/src/hooks/useOpenUIState.ts+++ b/packages/react-lang/src/hooks/useOpenUIState.ts@@ -48,6 +48,7 @@ export interface UseOpenUIStateOptions {toolProvider?: ToolProvider | null;/** Callback for structured, LLM-friendly errors. See OpenUIError type. */onError?: (errors: OpenUIError[]) => void;+ publishObservability?: boolean;}export interface OpenUIState {@@ -77,6 +78,7 @@ export function useOpenUIState(initialState,toolProvider,onError,+ publishObservability,}: UseOpenUIStateOptions,renderDeep: (value: unknown) => React.ReactNode,): OpenUIState {@@ -452,7 +454,14 @@ export function useOpenUIState(onError,});- useStreamingObservability({ response, isStreaming, result, errorsRef, errorRevision });+ useStreamingObservability({+ response,+ isStreaming,+ result,+ errorsRef,+ errorRevision,+ publish: publishObservability,+ });return { result: evaluatedResult, parseResult: result, contextValue, isQueryLoading };}diff --git a/packages/react-lang/src/hooks/useStreamingObservability.integration.test.ts b/packages/react-lang/src/hooks/useStreamingObservability.integration.test.tsindex 7a772424e..34fb897d9 100644--- a/packages/react-lang/src/hooks/useStreamingObservability.integration.test.ts+++ b/packages/react-lang/src/hooks/useStreamingObservability.integration.test.ts@@ -39,10 +39,12 @@ function Harness({isStreaming,queryErrors,currentResponse = response,+ publish,}: {isStreaming: boolean;queryErrors: OpenUIError[];currentResponse?: string;+ publish?: boolean;}) {const parseExceptionRef = useRef<OpenUIError | null>(null);const runtimeErrorsRef = useRef<OpenUIError[]>([]);@@ -71,6 +73,7 @@ function Harness({result,errorsRef,errorRevision,+ publish,});return null;}@@ -146,6 +149,23 @@ describe("streaming observability integration", () => {expect(streamIds[2]).not.toBe(streamIds[0]);});+ it("stays off the bus when publishing is disabled", () => {+ const events: ObservabilityEvent[] = [];+ const removeListener = observability.listenAll((event) => {+ if (event.detail.kind === "react-lang:stream") events.push(event);+ });++ act(() =>+ root.render(createElement(Harness, { isStreaming: true, queryErrors: [], publish: false })),+ );+ act(() =>+ root.render(createElement(Harness, { isStreaming: false, queryErrors: [], publish: false })),+ );+ removeListener();++ expect(events).toEqual([]);+ });+it("republishes settled with the same id when a query error arrives later", () => {const events: ObservabilityEvent[] = [];const removeListener = observability.listenAll((event) => {diff --git a/packages/react-lang/src/hooks/useStreamingObservability.ts b/packages/react-lang/src/hooks/useStreamingObservability.tsindex 5509631b9..8eab5313b 100644--- a/packages/react-lang/src/hooks/useStreamingObservability.ts+++ b/packages/react-lang/src/hooks/useStreamingObservability.ts@@ -17,6 +17,7 @@ export interface UseStreamingObservabilityOptions {result: ParseResult | null;errorsRef: CurrentRef<OpenUIError[]>;errorRevision: number;+ publish?: boolean;}export interface StreamingObservabilityState {@@ -26,6 +27,10 @@ export interface StreamingObservabilityState {hasPublishedStreamingSnapshot: boolean;settled: boolean;lastSettledErrorKey: string | null;+ /** Epoch ms when this stream first published. Frozen across later snapshots. */+ startedAt: number | null;+ /** Frozen once the stream first settles, so later error republishes don't grow it. */+ durationMs: number | null;}export interface StreamingObservabilityUpdate {@@ -52,6 +57,21 @@ export function createStreamingObservabilityState(): StreamingObservabilityStatehasPublishedStreamingSnapshot: false,settled: false,lastSettledErrorKey: null,+ startedAt: null,+ durationMs: null,+ };+}++function captureStreamTiming(state: StreamingObservabilityState, now = Date.now()) {+ state.startedAt ??= now;+ if (state.settled) {+ state.durationMs ??= Math.max(0, now - state.startedAt);+ }+ const elapsedMs = state.durationMs ?? Math.max(0, now - state.startedAt);+ return {+ startedAt: state.startedAt,+ elapsedMs,+ ...(state.durationMs != null ? { durationMs: state.durationMs } : {}),};}@@ -112,10 +132,12 @@ export function useStreamingObservability({result,errorsRef,errorRevision,+ publish = true,}: UseStreamingObservabilityOptions): void {const streamRef = useRef<StreamingObservabilityState>(createStreamingObservabilityState());useEffect(() => {+ if (!publish) return;const errors = errorsRef.current;const settledErrorKey = isStreaming ? null : JSON.stringify(errors);const update = advanceStreamingObservability(@@ -135,6 +157,7 @@ export function useStreamingObservability({response,responseLength: response?.length ?? 0,parser: parserMetadata(result),+ ...captureStreamTiming(streamRef.current),message: "OpenUI Lang is streaming",});}@@ -152,11 +175,12 @@ export function useStreamingObservability({parser: parserMetadata(result),errors,errorCount: errors.length,+ ...captureStreamTiming(streamRef.current),message:errors.length > 0? `OpenUI Lang settled with ${errors.length} error${errors.length === 1 ? "" : "s"}`: "OpenUI Lang settled",} satisfies SettledStreamEventDetail);}- }, [isStreaming, response, result, errorsRef, errorRevision]);+ }, [publish, isStreaming, response, result, errorsRef, errorRevision]);}diff --git a/packages/react-lang/src/index.ts b/packages/react-lang/src/index.tsindex 0a56ff8f8..d34526f1f 100644--- a/packages/react-lang/src/index.ts+++ b/packages/react-lang/src/index.ts@@ -1,4 +1,4 @@-// Web entry ("." default export). Auto-mounts the OpenUI devtools widget in+// Web entry ("." default export). Auto-mounts the OpenUI Inspect 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).diff --git a/packages/react-lang/src/library.test.ts b/packages/react-lang/src/library.test.tsnew file mode 100644index 000000000..24f348c44--- /dev/null+++ b/packages/react-lang/src/library.test.ts@@ -0,0 +1,85 @@+import { observability } from "@openuidev/observability";+import { afterEach, describe, expect, it, vi } from "vitest";+import { z } from "zod/v4";+import { createLibrary, defineComponent } from "./library";+import { DEVTOOLS_LIBRARIES_KEY, LIBRARY_EVENT_KIND, type LibraryRegistry } from "./publishLibrary";++const Dummy = (() => null) as any;++function makeComponent(name: string) {+ return defineComponent({+ name,+ props: z.object({ label: z.string() }),+ description: `${name} component`,+ component: Dummy,+ });+}++function registry(): LibraryRegistry {+ return (+ (globalThis as { [DEVTOOLS_LIBRARIES_KEY]?: LibraryRegistry })[DEVTOOLS_LIBRARIES_KEY] ?? {}+ );+}++function clearRegistry(): void {+ delete (globalThis as { [DEVTOOLS_LIBRARIES_KEY]?: LibraryRegistry })[DEVTOOLS_LIBRARIES_KEY];+}++afterEach(() => {+ clearRegistry();+ vi.unstubAllEnvs();+});++describe("createLibrary publish", () => {+ it("stashes the live library and emits a serializable ping", () => {+ const events: unknown[] = [];+ const remove = observability.listenAll((event) => events.push(event));++ const Card = makeComponent("Card");+ const library = createLibrary({ root: "Card", id: "demo", components: [Card] });++ expect(registry()).toEqual({ demo: library });+ expect(events).toHaveLength(1);+ const event = events[0] as {+ detail: Record<string, unknown>;+ };+ expect(event.detail["kind"]).toBe(LIBRARY_EVENT_KIND);+ expect(event.detail["id"]).toBe("demo");+ expect(event.detail["root"]).toBe("Card");+ expect(event.detail["components"]).toEqual(["Card"]);+ expect(event.detail["library"]).toBeUndefined();+ expect(() => JSON.stringify(event.detail)).not.toThrow();++ remove();+ });++ it("replaces a library with the same key on re-create (HMR)", () => {+ const Card = makeComponent("Card");+ createLibrary({ root: "Card", id: "demo", components: [Card] });+ const second = createLibrary({ root: "Card", id: "demo", components: [Card] });++ expect(Object.keys(registry())).toEqual(["demo"]);+ expect(registry()["demo"]).toBe(second);+ });++ it("keeps distinct libraries side by side", () => {+ const Card = makeComponent("Card");+ const Stack = makeComponent("Stack");+ createLibrary({ root: "Card", components: [Card] });+ createLibrary({ root: "Stack", components: [Stack] });++ expect(Object.keys(registry())).toEqual(["Card", "Stack"]);+ });++ it("does not publish in production", () => {+ vi.stubEnv("NODE_ENV", "production");+ const events: unknown[] = [];+ const remove = observability.listenAll((event) => events.push(event));++ createLibrary({ root: "Card", components: [makeComponent("Card")] });++ expect(registry()).toEqual({});+ expect(events).toEqual([]);+ remove();+ });+});diff --git a/packages/react-lang/src/library.ts b/packages/react-lang/src/library.tsindex a98d4faea..e34d41a56 100644--- a/packages/react-lang/src/library.ts+++ b/packages/react-lang/src/library.ts@@ -9,6 +9,7 @@ import {import type { ReactNode } from "react";import type { z } from "zod/v4";import type { $ZodObject } from "zod/v4/core";+import { publishLibrary } from "./publishLibrary";// Re-export framework-agnostic types unchangedexport type {@@ -51,5 +52,9 @@ export function defineComponent<T extends $ZodObject>(config: {// ─── createLibrary (React) ──────────────────────────────────────────────────export function createLibrary(input: LibraryDefinition): Library {- return coreCreateLibrary<ComponentRenderer<any>>(input) as Library;+ const library = coreCreateLibrary<ComponentRenderer<any>>(input) as Library;+ if (process.env["NODE_ENV"] !== "production") {+ publishLibrary(library);+ }+ return library;}diff --git a/packages/react-lang/src/publishLibrary.ts b/packages/react-lang/src/publishLibrary.tsnew file mode 100644index 000000000..193246e36--- /dev/null+++ b/packages/react-lang/src/publishLibrary.ts@@ -0,0 +1,48 @@+import { observability } from "@openuidev/observability";+import type { Library } from "./library";++/**+ * Shared with `@openuidev/devtools` via `Symbol.for`. Not a public API —+ * the live library object stays off the observability bus (serializable ping+ * only). Keep the string in sync with `packages/devtools/src/libraryRegistry.ts`.+ */+export const DEVTOOLS_LIBRARIES_KEY = Symbol.for("openui.devtools.libraries");++export const LIBRARY_EVENT_KIND = "react-lang:library";++export type LibraryRegistry = Record<string, Library>;++interface RegistryStore {+ [DEVTOOLS_LIBRARIES_KEY]?: LibraryRegistry;+}++export function libraryKey(library: {+ id?: string;+ root?: string;+ components: Record<string, unknown>;+}): string {+ return library.id ?? library.root ?? Object.keys(library.components).sort().join(",");+}++function getRegistry(): LibraryRegistry {+ const store = globalThis as RegistryStore;+ return (store[DEVTOOLS_LIBRARIES_KEY] ??= {});+}++function upsertRegistry(library: Library): void {+ getRegistry()[libraryKey(library)] = library;+}++/** Dev-only: stash the live library and emit a serializable registration ping. */+export function publishLibrary(library: Library): void {+ upsertRegistry(library);+ observability.info({+ kind: LIBRARY_EVENT_KIND,+ ...(library.id !== undefined ? { id: library.id } : {}),+ ...(library.root !== undefined ? { root: library.root } : {}),+ components: Object.keys(library.components),+ message: library.id+ ? `Library "${library.id}" registered`+ : `Library registered (root: ${library.root ?? "none"})`,+ });+}