The Open Standard for Generative UI
Open ended Generative UI example (#823)
Rabi Shanker Guhafc2c4a435565
diff --git a/docs/content/blog/state-of-generative-ui-report.mdx b/docs/content/blog/state-of-generative-ui-report.mdxindex 06500c99c..5af947a6a 100644--- a/docs/content/blog/state-of-generative-ui-report.mdx+++ b/docs/content/blog/state-of-generative-ui-report.mdx@@ -163,6 +163,8 @@ The result is that the spectrum becomes per-component rather than per-applicatioThis also keeps the governance story simple. The security review localizes to one component instead of the entire output surface, prompt guidance can steer the model toward catalog primitives first, and deployments that don't want arbitrary generation can omit the component from the catalog entirely; the same mechanism that enables the escape hatch is the mechanism that disables it.+OpenUI ships a working implementation of this pattern: [`examples/html-artifact`](https://github.com/thesysdev/openui/tree/main/examples/html-artifact), documented in the [Open-ended HTML guide](/docs/agent/guides/open-ended-html).+## Token efficiency benchmarks: format choice is a latency and cost choicediff --git a/docs/content/docs/agent/core-concepts/generative-ui.mdx b/docs/content/docs/agent/core-concepts/generative-ui.mdxindex e3bb03293..b97bc2abe 100644--- a/docs/content/docs/agent/core-concepts/generative-ui.mdx+++ b/docs/content/docs/agent/core-concepts/generative-ui.mdx@@ -46,3 +46,10 @@ Form state is tracked automatically and saved with the thread, so a half-filled## GenUI vs artifactsUse GenUI when the UI is the reply: a form to fill, a table to scan. Use [artifacts](/docs/agent/core-concepts/artifacts) when the output is a durable thing the user returns to on its own surface. An agent can do both in one thread.+++## Open-ended HTML++OpenUI can also let the model generate a complete HTML/CSS/JavaScript experience instead of composing predefined components. The same response stream can show the incoming source, then render the completed document in a sandboxed iframe inside the detailed-view panel.++See [Open-ended HTML](/docs/agent/guides/open-ended-html) for the minimal pattern.diff --git a/docs/content/docs/agent/guides/open-ended-html.mdx b/docs/content/docs/agent/guides/open-ended-html.mdxnew file mode 100644index 000000000..8744566ca--- /dev/null+++ b/docs/content/docs/agent/guides/open-ended-html.mdx@@ -0,0 +1,60 @@+---+title: Open-ended HTML+description: Generate self-contained HTML experiences and render them in an AgentInterface detailed view.+---++OpenUI usually asks the model to compose components from a library. For open-ended generation, the model can instead produce a complete HTML/CSS/JavaScript experience as the props of one OpenUI component.++[View the complete example on GitHub →](https://github.com/thesysdev/openui/tree/main/examples/html-artifact)++## How it works++The example defines a small library: a `Response` root, a `Markdown` component for normal replies, and an `HtmlArtifact` component the model uses only when asked to build something interactive.++```tsx+const HtmlArtifactSchema = z.object({+ title: z.string(),+ document: z.string(),+});++export const HtmlArtifact = defineComponent({+ name: "HtmlArtifact",+ description: "Renders a self-contained HTML/CSS/JavaScript experience.",+ props: HtmlArtifactSchema,+ component: HtmlArtifactRenderer,+});++export const library = createLibrary({+ root: "Response",+ components: [Response, Markdown, HtmlArtifact],+});+```++The model decides per reply: most responses are a `Response` with a single `Markdown` child; a request like "build me a sorting visualizer" produces an `HtmlArtifact`.++`HtmlArtifactRenderer` uses the existing chat stream:++1. `useIsStreaming()` tracks whether the document is still arriving.+2. A compact preview remains inline in the conversation.+3. `DetailedViewPanel` opens the result on the right.+4. The **Raw** tab shows the incoming source.+5. The **Rendered** tab shows a loading state, then switches to a sandboxed iframe when the stream completes.++No additional streaming endpoint or tool call is required.++## Teach the model++Generate the system prompt with `openui generate`. Prompt rules should tell the model to:++- use `Markdown` for normal conversation and `HtmlArtifact` only when asked to build something interactive;+- produce a self-contained HTML document or fragment;+- use inline CSS and JavaScript;+- avoid external scripts, styles, fonts, images, and network requests;+- omit Markdown fences;+- correctly escape the HTML inside the OpenUI Lang string.++See the example's [`library.tsx`](https://github.com/thesysdev/openui/blob/main/examples/html-artifact/src/library.tsx) for the complete prompt options.++## Before production++Generated HTML is untrusted content. Normalize and validate the document, enforce a Content Security Policy, restrict network access, keep the iframe sandbox narrow, and validate any messages crossing the iframe boundary.diff --git a/docs/content/docs/agent/meta.json b/docs/content/docs/agent/meta.jsonindex 08d543204..4b60ec4f5 100644--- a/docs/content/docs/agent/meta.json+++ b/docs/content/docs/agent/meta.json@@ -23,6 +23,7 @@"reference/components","reference/self-hosting","---Guides---",+ "guides/open-ended-html","guides/custom-artifacts","guides/migrating"]diff --git a/docs/public/AGENTS.md b/docs/public/AGENTS.mdindex e6f5163f2..8ab2e9a17 100644--- a/docs/public/AGENTS.md+++ b/docs/public/AGENTS.md@@ -470,6 +470,19 @@ actions (`@Set`, `@Run`, `@ToAssistant`). Helpers: `useFormName`,`useGetFieldValue`, `useSetFieldValue`, `useIsQueryLoading`, `useIsStreaming`.Form state is tracked automatically and saved with the thread.+### Open-ended HTML++For generated HTML apps, define one OpenUI component with `title` and `document`+props and add it to your component library (not as the root), so the model+chats normally and emits the artifact only when asked to build something+interactive. Keep a compact status preview inline, then use+`DetailedViewPanel` for Raw and Rendered tabs. Raw displays the incoming source;+Rendered shows a loading state and switches to a sandboxed `iframe srcDoc` when+the stream completes. Use the existing assistant stream—no second endpoint or+tool is required. See the+[guide](https://www.openui.com/docs/agent/guides/open-ended-html) and+[`examples/html-artifact`](https://github.com/thesysdev/openui/tree/main/examples/html-artifact).+## ArtifactsAn artifact is a durable output (report, slide deck, dashboard, code file): andiff --git a/examples/html-artifact/.dockerignore b/examples/html-artifact/.dockerignorenew file mode 100644index 000000000..999ffc10a--- /dev/null+++ b/examples/html-artifact/.dockerignore@@ -0,0 +1,39 @@+# Node+node_modules+.pnpm-store+npm-debug.log*+yarn-debug.log*+yarn-error.log*+pnpm-debug.log*++# Next.js+.next+out++# Git+.git+.gitignore++# Logs+logs+*.log++# Env files+.env+.env.*+!.env.example++# OS files+.DS_Store+Thumbs.db++# Build / cache+dist+build+.turbo+.cache+coverage++# Editor+.vscode+.idea\ No newline at end of filediff --git a/examples/html-artifact/.gitignore b/examples/html-artifact/.gitignorenew file mode 100644index 000000000..5ef6a5207--- /dev/null+++ b/examples/html-artifact/.gitignore@@ -0,0 +1,41 @@+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.++# dependencies+/node_modules+/.pnp+.pnp.*+.yarn/*+!.yarn/patches+!.yarn/plugins+!.yarn/releases+!.yarn/versions++# testing+/coverage++# next.js+/.next/+/out/++# production+/build++# misc+.DS_Store+*.pem++# debug+npm-debug.log*+yarn-debug.log*+yarn-error.log*+.pnpm-debug.log*++# env files (can opt-in for committing if needed)+.env*++# vercel+.vercel++# typescript+*.tsbuildinfo+next-env.d.tsdiff --git a/examples/html-artifact/README.md b/examples/html-artifact/README.mdnew file mode 100644index 000000000..f1d770cf0--- /dev/null+++ b/examples/html-artifact/README.md@@ -0,0 +1,43 @@+This example uses [OpenUI](https://openui.com) to generate self-contained HTML/CSS/JavaScript experiences. The model chats normally with markdown and only emits an `HtmlArtifact` when asked to build something interactive. The `HtmlArtifact` component keeps a compact status preview inline and opens a detailed right panel with Raw and Rendered tabs. Raw displays the incoming source; Rendered shows a loading state, then a sandboxed iframe when the stream completes.++This is intentionally a minimal example. Before using generated HTML in production, normalize and validate it, enforce a Content Security Policy, restrict network access, and validate iframe messages.++## Getting Started++First, create a `.env` file:++```env+OPENAI_API_KEY=sk-your-key-here+OPENAI_MODEL=gpt-5.5+```++Then run the development server:++```bash+pnpm dev+```++Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.++The generated component is defined in `src/html-artifact.tsx`, its OpenUI library and prompt rules are in `src/library.tsx`, and the model route is in `src/app/api/chat/route.ts`.++## OpenAI-compatible APIs++The example chat app supports OpenAI-compatible APIs through the optional `OPENAI_BASE_URL` environment variable.++Example using OpenRouter:++```env+OPENAI_API_KEY=sk-or-v1-...+OPENAI_BASE_URL=https://openrouter.ai/api/v1+OPENAI_MODEL=openai/gpt-5.5+```++This also works with other OpenAI-compatible providers.++## Learn More++To learn more about OpenUI, take a look at the following resources:++- [OpenUI Documentation](https://openui.com/docs) - learn about OpenUI features and API.+- [OpenUI GitHub repository](https://github.com/thesysdev/openui) - your feedback and contributions are welcome!diff --git a/examples/html-artifact/eslint.config.mjs b/examples/html-artifact/eslint.config.mjsnew file mode 100644index 000000000..05e726d1b--- /dev/null+++ b/examples/html-artifact/eslint.config.mjs@@ -0,0 +1,18 @@+import { defineConfig, globalIgnores } from "eslint/config";+import nextVitals from "eslint-config-next/core-web-vitals";+import nextTs from "eslint-config-next/typescript";++const eslintConfig = defineConfig([+ ...nextVitals,+ ...nextTs,+ // Override default ignores of eslint-config-next.+ globalIgnores([+ // Default ignores of eslint-config-next:+ ".next/**",+ "out/**",+ "build/**",+ "next-env.d.ts",+ ]),+]);++export default eslintConfig;diff --git a/examples/html-artifact/next.config.ts b/examples/html-artifact/next.config.tsnew file mode 100644index 000000000..7e1f0ae21--- /dev/null+++ b/examples/html-artifact/next.config.ts@@ -0,0 +1,8 @@+import type { NextConfig } from "next";++const nextConfig: NextConfig = {+ output: "standalone",+ turbopack: {},+};++export default nextConfig;diff --git a/examples/html-artifact/package.json b/examples/html-artifact/package.jsonnew file mode 100644index 000000000..047001e70--- /dev/null+++ b/examples/html-artifact/package.json@@ -0,0 +1,34 @@+{+ "name": "html-artifact",+ "version": "0.1.0",+ "private": true,+ "scripts": {+ "generate:prompt": "pnpm --filter @openuidev/cli build && pnpm exec openui generate src/library.tsx --out src/generated/system-prompt.txt",+ "dev": "pnpm generate:prompt && next dev",+ "build": "next build",+ "start": "next start",+ "lint": "eslint"+ },+ "dependencies": {+ "@openuidev/react-headless": "workspace:*",+ "@openuidev/react-lang": "workspace:*",+ "@openuidev/react-ui": "workspace:*",+ "lucide-react": "^0.575.0",+ "next": "16.2.6",+ "openai": "^6.22.0",+ "react": "19.2.3",+ "react-dom": "19.2.3",+ "zod": "catalog:"+ },+ "devDependencies": {+ "@openuidev/cli": "workspace:*",+ "@tailwindcss/postcss": "^4",+ "@types/node": "catalog:",+ "@types/react": "^19",+ "@types/react-dom": "^19",+ "eslint": "^9",+ "eslint-config-next": "16.2.6",+ "tailwindcss": "^4",+ "typescript": "^5"+ }+}diff --git a/examples/html-artifact/postcss.config.mjs b/examples/html-artifact/postcss.config.mjsnew file mode 100644index 000000000..61e36849c--- /dev/null+++ b/examples/html-artifact/postcss.config.mjs@@ -0,0 +1,7 @@+const config = {+ plugins: {+ "@tailwindcss/postcss": {},+ },+};++export default config;diff --git a/examples/html-artifact/src/app/api/chat/route.ts b/examples/html-artifact/src/app/api/chat/route.tsnew file mode 100644index 000000000..866aa59c6--- /dev/null+++ b/examples/html-artifact/src/app/api/chat/route.ts@@ -0,0 +1,44 @@+import { readFileSync } from "fs";+import { NextRequest } from "next/server";+import OpenAI from "openai";+import type { ChatCompletionMessageParam } from "openai/resources/chat/completions.mjs";+import { join } from "path";++const systemPrompt = readFileSync(join(process.cwd(), "src/generated/system-prompt.txt"), "utf-8");++const SSE_HEADERS = {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache, no-transform",+ Connection: "keep-alive",+} as const;++export async function POST(req: NextRequest) {+ const { messages } = (await req.json()) as { messages: ChatCompletionMessageParam[] };++ const client = new OpenAI({+ apiKey: process.env.OPENAI_API_KEY,+ baseURL: process.env.OPENAI_BASE_URL || undefined,+ });++ const stream = await client.chat.completions.create({+ model: process.env.OPENAI_MODEL || "gpt-5.5",+ messages: [{ role: "system", content: systemPrompt }, ...messages],+ stream: true,+ });++ const encoder = new TextEncoder();+ const readable = new ReadableStream({+ async start(controller) {+ try {+ for await (const chunk of stream) {+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));+ }+ } finally {+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));+ controller.close();+ }+ },+ });++ return new Response(readable, { headers: SSE_HEADERS });+}diff --git a/examples/html-artifact/src/app/globals.css b/examples/html-artifact/src/app/globals.cssnew file mode 100644index 000000000..d41e3795a--- /dev/null+++ b/examples/html-artifact/src/app/globals.css@@ -0,0 +1,3 @@+@import "tailwindcss";+@import "@openuidev/react-ui/styles/index.css";+diff --git a/examples/html-artifact/src/app/layout.tsx b/examples/html-artifact/src/app/layout.tsxnew file mode 100644index 000000000..64ccf6afe--- /dev/null+++ b/examples/html-artifact/src/app/layout.tsx@@ -0,0 +1,22 @@+import { ThemeProvider } from "@/hooks/use-system-theme";+import type { Metadata } from "next";+import "./globals.css";++export const metadata: Metadata = {+ title: "OpenUI HTML Artifact",+ description: "Open-ended HTML generation with OpenUI",+};++export default function RootLayout({+ children,+}: Readonly<{+ children: React.ReactNode;+}>) {+ return (+ <html lang="en">+ <body>+ <ThemeProvider>{children}</ThemeProvider>+ </body>+ </html>+ );+}diff --git a/examples/html-artifact/src/app/page.tsx b/examples/html-artifact/src/app/page.tsxnew file mode 100644index 000000000..b1ba9381f--- /dev/null+++ b/examples/html-artifact/src/app/page.tsx@@ -0,0 +1,61 @@+"use client";++import { useTheme } from "@/hooks/use-system-theme";+import { library } from "@/library";+import {+ AgentInterface,+ openAIAdapter,+ openAIMessageFormat,+ type ChatLLM,+} from "@openuidev/react-ui";+import { useMemo } from "react";++export default function Page() {+ const mode = useTheme();++ const llm = useMemo<ChatLLM>(+ () => ({+ send: ({ messages, signal }) =>+ fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ messages: openAIMessageFormat.toApi(messages) }),+ signal,+ }),+ streamProtocol: openAIAdapter(),+ }),+ [],+ );++ return (+ <div className="h-screen w-screen overflow-hidden relative">+ <AgentInterface+ llm={llm}+ componentLibrary={library}+ agentName="HTML Artifact"+ theme={{ mode }}+ starterVariant="short"+ starters={[+ {+ displayText: "Physics simulator",+ prompt:+ "Build an interactive orbital decay simulator with controls for altitude and satellite mass.",+ },+ {+ displayText: "Sorting visualizer",+ prompt:+ "Build an animated sorting algorithm visualizer that compares bubble sort and quicksort.",+ },+ {+ displayText: "Mortgage calculator",+ prompt: "Build an interactive mortgage calculator with a payment breakdown chart.",+ },+ {+ displayText: "Music sequencer",+ prompt: "Build a playful 8-step browser drum sequencer with tempo controls.",+ },+ ]}+ />+ </div>+ );+}diff --git a/examples/html-artifact/src/generated/system-prompt.txt b/examples/html-artifact/src/generated/system-prompt.txtnew file mode 100644index 000000000..5a3b01b97--- /dev/null+++ b/examples/html-artifact/src/generated/system-prompt.txt@@ -0,0 +1,63 @@+You are an AI assistant that responds using openui-lang, a declarative UI language. Your ENTIRE response must be valid openui-lang code — no markdown, no explanations, just openui-lang.++## Syntax Rules++1. Each statement is on its own line: `identifier = Expression`+2. `root` is the entry point — every program must define `root = Response(...)`+3. Expressions are: strings ("..."), numbers, booleans (true/false), null, arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)+4. Use references for readability: define `name = ...` on one line, then use `name` later+5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.+6. Arguments are POSITIONAL (order matters, not names). Write `Stack([children], "row", "l")` NOT `Stack([children], direction: "row", gap: "l")` — colon syntax is NOT supported and silently breaks+7. Optional arguments can be omitted from the end+- Strings use double quotes with backslash escaping++## Component Signatures++Arguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming.++Response(children: (Markdown | HtmlArtifact)[]) — Root container for every reply. Children stack vertically.+Markdown(text: string) — Renders conversational markdown text. Use this for normal replies.+HtmlArtifact(title: string, document: string) — Renders a bespoke, self-contained HTML/CSS/JavaScript experience from a complete document or HTML fragment.++## Hoisting & Streaming (CRITICAL)++openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.++During streaming, the output is re-parsed on every chunk. Undefined references are temporarily unresolved and appear once their definitions stream in. This creates a progressive top-down reveal — structure first, then data fills in.++**Recommended statement order for optimal streaming:**+1. `root = Response(...)` — UI shell appears immediately+2. Component definitions — fill in as they stream+3. Data values — leaf content last++Always write the root = Response(...) statement first so the UI shell appears immediately, even before child data has streamed in.++## Examples++Example 1 — a normal reply:++root = Response([answer])+answer = Markdown("Hi! I can chat normally, or build you an interactive HTML experience — try asking for a game, simulator, or visualizer.")++Example 2 — an interactive artifact:++root = Response([intro, artifact])+intro = Markdown("Here's a simple click counter:")+artifact = HtmlArtifact("Interactive counter", "<!doctype html><html><head><style>body{font-family:system-ui;padding:2rem}button{padding:.5rem 1rem}</style></head><body><h1>Counter</h1><button id='count'>0</button><script>let count=0;document.querySelector('#count').addEventListener('click',event=>{event.currentTarget.textContent=String(++count)})</script></body></html>")++## Important Rules+- When asked about data, generate realistic/plausible data+- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)++## Final Verification+Before finishing, walk your output and verify:+1. root = Response(...) is the FIRST line (for optimal streaming).+2. Every referenced name is defined. Every defined name (other than root) is reachable from root.++- Use Markdown for normal conversation. Most replies are a Response with a single Markdown child.+- Only use HtmlArtifact when the user explicitly asks you to build something interactive — an app, game, simulation, visualization, or similar experience.+- When you use HtmlArtifact, generate a self-contained HTML/CSS/JavaScript experience in the document argument. It may be a complete HTML document or a fragment.+- Inside an HtmlArtifact document: use inline CSS and JavaScript only. Do not depend on external scripts, stylesheets, fonts, images, or network requests.+- Do not wrap the document in Markdown fences.+- Keep each statement on one line. Encode line breaks as \n inside the document string.+- The document is a double-quoted openui-lang string. Prefer single quotes inside HTML and JavaScript, and escape any double quotes or backslashes.diff --git a/examples/html-artifact/src/hooks/use-system-theme.tsx b/examples/html-artifact/src/hooks/use-system-theme.tsxnew file mode 100644index 000000000..7c110c21d--- /dev/null+++ b/examples/html-artifact/src/hooks/use-system-theme.tsx@@ -0,0 +1,41 @@+"use client";++import { createContext, useContext, useLayoutEffect, useState } from "react";++type ThemeMode = "light" | "dark";++interface ThemeContextType {+ mode: ThemeMode;+}++const ThemeContext = createContext<ThemeContextType | undefined>(undefined);++function getSystemMode(): ThemeMode {+ if (typeof window === "undefined") return "light";+ return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";+}++export function ThemeProvider({ children }: { children: React.ReactNode }) {+ const [mode, setMode] = useState<ThemeMode>(getSystemMode);++ useLayoutEffect(() => {+ const mq = window.matchMedia("(prefers-color-scheme: dark)");+ const handler = (e: MediaQueryListEvent) => setMode(e.matches ? "dark" : "light");+ mq.addEventListener("change", handler);+ return () => mq.removeEventListener("change", handler);+ }, []);++ useLayoutEffect(() => {+ document.body.setAttribute("data-theme", mode);+ }, [mode]);++ return <ThemeContext.Provider value={{ mode }}>{children}</ThemeContext.Provider>;+}++export function useTheme(): ThemeMode {+ const ctx = useContext(ThemeContext);+ if (!ctx) {+ throw new Error("useTheme must be used within a ThemeProvider");+ }+ return ctx.mode;+}diff --git a/examples/html-artifact/src/html-artifact.tsx b/examples/html-artifact/src/html-artifact.tsxnew file mode 100644index 000000000..2168e6e10--- /dev/null+++ b/examples/html-artifact/src/html-artifact.tsx@@ -0,0 +1,108 @@+"use client";++import { defineComponent, useIsStreaming, type ComponentRenderProps } from "@openuidev/react-lang";+import {+ Button,+ DetailedViewPanel,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+ useDetailedView,+} from "@openuidev/react-ui";+import { useEffect, useId, useState } from "react";+import { z } from "zod/v4";++const HtmlArtifactSchema = z.object({+ title: z.string(),+ document: z.string(),+});++function HtmlArtifactRenderer({ props }: ComponentRenderProps<z.infer<typeof HtmlArtifactSchema>>) {+ const isStreaming = useIsStreaming();+ const [selectedView, setSelectedView] = useState<"raw" | "rendered">("raw");+ const viewId = useId();+ const { open } = useDetailedView(viewId);++ useEffect(() => {+ open();+ }, [open]);++ useEffect(() => {+ if (!isStreaming) {+ const frame = requestAnimationFrame(() => setSelectedView("rendered"));+ return () => cancelAnimationFrame(frame);+ }+ }, [isStreaming]);++ // Example only. Before production, normalize and validate the HTML,+ // enforce a CSP, restrict network access, and validate iframe messages.+ return (+ <>+ {isStreaming ? (+ <div className="w-full rounded-xl border border-neutral-200 bg-white px-4 py-3 text-neutral-700">+ Generating artifact {props.title}…+ </div>+ ) : (+ <Button+ type="button"+ variant="secondary"+ onClick={open}+ className="w-full justify-between"+ >+ <span className="font-medium text-neutral-900">{props.title}</span>+ <span className="text-sm text-neutral-500">Open artifact</span>+ </Button>+ )}++ <DetailedViewPanel viewId={viewId} title={props.title}>+ <Tabs+ value={selectedView}+ onValueChange={(value) => setSelectedView(value as "raw" | "rendered")}+ className="min-h-0 flex-1 gap-0"+ >+ <TabsList aria-label="Artifact view">+ <TabsTrigger value="raw" text="Raw" />+ <TabsTrigger value="rendered" text="Rendered" />+ </TabsList>++ <TabsContent+ value="raw"+ className="min-h-0 flex-1 overflow-hidden p-0! [&>.openui-tabs-content-inner]:h-full [&>.openui-tabs-content-inner]:gap-0"+ >+ <pre className="h-full overflow-auto whitespace-pre-wrap bg-neutral-950 p-4 text-xs leading-relaxed text-neutral-300">+ <code>{props.document}</code>+ </pre>+ </TabsContent>++ <TabsContent+ value="rendered"+ className="min-h-0 flex-1 overflow-hidden p-0! [&>.openui-tabs-content-inner]:h-full [&>.openui-tabs-content-inner]:gap-0"+ >+ {isStreaming ? (+ <div className="flex h-full items-center justify-center text-neutral-500">+ Generating artifact…+ </div>+ ) : (+ <iframe+ title={props.title}+ sandbox="allow-scripts"+ referrerPolicy="no-referrer"+ srcDoc={props.document}+ className="h-full w-full border-0 bg-white"+ />+ )}+ </TabsContent>+ </Tabs>+ </DetailedViewPanel>+ </>+ );+}++export const HtmlArtifact = defineComponent({+ name: "HtmlArtifact",+ description:+ "Renders a bespoke, self-contained HTML/CSS/JavaScript experience from a complete document or HTML fragment.",+ props: HtmlArtifactSchema,+ component: HtmlArtifactRenderer,+});diff --git a/examples/html-artifact/src/library.tsx b/examples/html-artifact/src/library.tsxnew file mode 100644index 000000000..dea89409a--- /dev/null+++ b/examples/html-artifact/src/library.tsx@@ -0,0 +1,59 @@+"use client";++import { createLibrary, defineComponent, type PromptOptions } from "@openuidev/react-lang";+import { Card, MarkDownRenderer } from "@openuidev/react-ui";+import { z } from "zod/v4";+import { HtmlArtifact } from "./html-artifact";++const Markdown = defineComponent({+ name: "Markdown",+ description: "Renders conversational markdown text. Use this for normal replies.",+ props: z.object({+ text: z.string(),+ }),+ component: ({ props }) => <MarkDownRenderer textMarkdown={props.text} />,+});++const Response = defineComponent({+ name: "Response",+ description: "Root container for every reply. Children stack vertically.",+ props: z.object({+ children: z.array(z.union([Markdown.ref, HtmlArtifact.ref])),+ }),+ component: ({ props, renderNode }) => (+ <Card+ width="full"+ style={{ display: "flex", flexDirection: "column", gap: "var(--openui-space-m)" }}+ >+ {renderNode(props.children)}+ </Card>+ ),+});++export const library = createLibrary({+ root: "Response",+ components: [Response, Markdown, HtmlArtifact],+});++export const promptOptions: PromptOptions = {+ additionalRules: [+ "Use Markdown for normal conversation. Most replies are a Response with a single Markdown child.",+ "Only use HtmlArtifact when the user explicitly asks you to build something interactive — an app, game, simulation, visualization, or similar experience.",+ "When you use HtmlArtifact, generate a self-contained HTML/CSS/JavaScript experience in the document argument. It may be a complete HTML document or a fragment.",+ "Inside an HtmlArtifact document: use inline CSS and JavaScript only. Do not depend on external scripts, stylesheets, fonts, images, or network requests.",+ "Do not wrap the document in Markdown fences.",+ "Keep each statement on one line. Encode line breaks as \\n inside the document string.",+ "The document is a double-quoted openui-lang string. Prefer single quotes inside HTML and JavaScript, and escape any double quotes or backslashes.",+ ],+ examples: [+ `Example 1 — a normal reply:++root = Response([answer])+answer = Markdown("Hi! I can chat normally, or build you an interactive HTML experience — try asking for a game, simulator, or visualizer.")`,+ `Example 2 — an interactive artifact:++root = Response([intro, artifact])+intro = Markdown("Here's a simple click counter:")+artifact = HtmlArtifact("Interactive counter", "<!doctype html><html><head><style>body{font-family:system-ui;padding:2rem}button{padding:.5rem 1rem}</style></head><body><h1>Counter</h1><button id='count'>0</button><script>let count=0;document.querySelector('#count').addEventListener('click',event=>{event.currentTarget.textContent=String(++count)})</script></body></html>")`,+ ],+};diff --git a/examples/html-artifact/tsconfig.json b/examples/html-artifact/tsconfig.jsonnew file mode 100644index 000000000..cf9c65d3e--- /dev/null+++ b/examples/html-artifact/tsconfig.json@@ -0,0 +1,34 @@+{+ "compilerOptions": {+ "target": "ES2017",+ "lib": ["dom", "dom.iterable", "esnext"],+ "allowJs": true,+ "skipLibCheck": true,+ "strict": true,+ "noEmit": true,+ "esModuleInterop": true,+ "module": "esnext",+ "moduleResolution": "bundler",+ "resolveJsonModule": true,+ "isolatedModules": true,+ "jsx": "react-jsx",+ "incremental": true,+ "plugins": [+ {+ "name": "next"+ }+ ],+ "paths": {+ "@/*": ["./src/*"]+ }+ },+ "include": [+ "next-env.d.ts",+ "**/*.ts",+ "**/*.tsx",+ ".next/types/**/*.ts",+ ".next/dev/types/**/*.ts",+ "**/*.mts"+ ],+ "exclude": ["node_modules"]+}diff --git a/packages/react-ui/src/index.ts b/packages/react-ui/src/index.tsindex 0583f076a..5e2ffa9f8 100644--- a/packages/react-ui/src/index.ts+++ b/packages/react-ui/src/index.ts@@ -54,8 +54,14 @@ export {// Shared Collapsible primitive + built-in web-search renderer.export { Collapsible } from "./components/_shared/Collapsible";-// Detailed-view exports (DetailedViewPanel/DetailedViewPortalTarget)+// Detailed-view exportsexport { useActiveDetailedView, useDetailedView } from "@openuidev/react-headless";+export {+ DetailedViewPanel,+ DetailedViewPortalTarget,+ type DetailedViewPanelProps,+ type DetailedViewPortalTargetProps,+} from "./components/AgentInterface/_shared/detailed-view";export * from "./components/Button";export * from "./components/Buttons";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex cce384ce4..85b7b0b3e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -563,6 +563,64 @@ importers:specifier: ^5version: 5.9.3+ examples/html-artifact:+ dependencies:+ '@openuidev/react-headless':+ specifier: workspace:*+ version: link:../../packages/react-headless+ '@openuidev/react-lang':+ specifier: workspace:*+ version: link:../../packages/react-lang+ '@openuidev/react-ui':+ specifier: workspace:*+ version: link:../../packages/react-ui+ lucide-react:+ specifier: ^0.575.0+ version: 0.575.0([email protected])+ next:+ specifier: 16.2.6+ version: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])+ openai:+ specifier: ^6.22.0+ version: 6.39.0([email protected])([email protected])+ react:+ specifier: 19.2.3+ version: 19.2.3+ react-dom:+ specifier: 19.2.3+ version: 19.2.3([email protected])+ zod:+ specifier: 'catalog:'+ version: 4.3.6+ devDependencies:+ '@openuidev/cli':+ specifier: workspace:*+ version: link:../../packages/openui-cli+ '@tailwindcss/postcss':+ specifier: ^4+ version: 4.2.1+ '@types/node':+ specifier: 'catalog:'+ version: 22.19.19+ '@types/react':+ specifier: ^19+ version: 19.2.14+ '@types/react-dom':+ specifier: ^19+ version: 19.2.3(@types/[email protected])+ eslint:+ specifier: ^9+ version: 9.29.0([email protected])+ eslint-config-next:+ specifier: 16.2.6+ version: 16.2.6(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ tailwindcss:+ specifier: ^4+ version: 4.2.1+ typescript:+ specifier: ^5+ version: 5.9.3+examples/langchain-chat:dependencies:'@ag-ui/core':diff --git a/skills/openui/SKILL.md b/skills/openui/SKILL.mdindex a85c9affb..5457efe6d 100644--- a/skills/openui/SKILL.md+++ b/skills/openui/SKILL.md@@ -44,6 +44,7 @@ Choose the package for the target runtime. For backend-only parsing or prompt/sc- If the user wants a new OpenUI/GenUI app, use `@openuidev/cli`; it is the easiest scaffolding path.- If the user wants to integrate OpenUI into an existing React/Next agent or chat app and wants an out-of-box component library, use `@openuidev/react-ui` with `AgentInterface`, `openuiLibrary`, or `openuiChatLibrary`.- If the user wants OpenUI Lang rendering in an existing React project without the full React UI surface, use `@openuidev/react-lang`.+- If the user wants open-ended generation, generated HTML apps, sandboxed iframes, or Raw/Rendered previews, read [references/open-ended-html.md](references/open-ended-html.md).- If the host app is Vue or Svelte, use `@openuidev/vue-lang` or `@openuidev/svelte-lang`. Use `@openuidev/lang-core` for framework-agnostic parsing, prompt generation, schemas, or backend/runtime work.## OpenUI Cloud Capabilitiesdiff --git a/skills/openui/references/open-ended-html.md b/skills/openui/references/open-ended-html.mdnew file mode 100644index 000000000..55c52a86c--- /dev/null+++ b/skills/openui/references/open-ended-html.md@@ -0,0 +1,35 @@+# Open-ended HTML++Use this pattern when the user wants full generative UI, generated mini-apps, raw HTML, or a sandboxed iframe rather than a fixed component catalog.++The canonical implementation is [`examples/html-artifact`](../../../examples/html-artifact).++## Pattern++1. Define one OpenUI component with `title` and `document` string props.+2. Put it alongside any library (the example uses a minimal one with just a markdown/text component and a plain container root) — the model chooses per reply whether to emit an artifact. Do NOT make the artifact the root: that forces every reply to be an HTML page.+3. Generate the system prompt with `openui generate`.+4. Pass that library to `AgentInterface.componentLibrary`.+5. Use `useIsStreaming()` to distinguish incoming source from the completed document.+6. Keep only a compact status preview inline.+7. Open a `DetailedViewPanel` containing Raw and Rendered tabs.+8. Show source in Raw, a loading state in Rendered while streaming, and a sandboxed `iframe srcDoc` when complete.++Use the existing assistant response stream. Do not add another streaming endpoint or a tool unless the user's application independently requires one.++## Prompt contract++Tell the model to:++- use the markdown component for normal conversation, and the artifact only when asked to build something interactive;+- emit a self-contained HTML document or fragment;+- use inline CSS and JavaScript;+- avoid external resources and network requests;+- omit Markdown fences;+- escape newlines, quotes, and backslashes for the OpenUI Lang string.++Keep one valid example in `promptOptions.examples`, then regenerate the checked-in system prompt.++## Security++Treat generated HTML as untrusted. Before production, normalize and validate it, enforce a Content Security Policy, restrict network access, keep iframe sandbox permissions narrow, and validate iframe messages.