Skip to content

The Open Standard for Generative UI

Agent Interface SDK (#692)

Ankit Das17c1dc85f684
diff --git a/docs/app/docs/chat/page.tsx b/docs/app/docs/chat/page.tsx
deleted file mode 100644
index 86243152e..000000000
--- a/docs/app/docs/chat/page.tsx
+++ /dev/null
@@ -1,193 +0,0 @@
-import { Button } from "@/components/button";
-import {
- CodeBlock,
- FeatureCard,
- FeatureCards,
- Separator,
- SimpleCard,
-} from "@/components/overview-components";
-import {
- Code2,
- Database,
- Layout,
- Maximize2,
- MessageCircle,
- MessageSquare,
- PanelRightOpen,
- Zap,
- type LucideIcon,
-} from "lucide-react";
-import Link from "next/link";
-
-export const metadata = {
- title: "OpenUI Chat SDK",
- description:
- "Production-ready chat UI for AI agents. Drop-in layouts, streaming, and state management.",
-};
-
-const headlessCode = `import { useChat } from '@openuidev/react';
-
-function CustomChat() {
- const { messages, append, isLoading } = useChat();
-
- return (
- <div>
- {messages.map(m => (
- <div key={m.id}>
- {m.content}
- </div>
- ))}
-
- <input
- onChange={e => append(e.target.value)}
- />
- </div>
- );
-}`;
-
-const layoutOptions = [
- {
- icon: <PanelRightOpen />,
- title: "Copilot",
- description: "A sidebar assistant that lives alongside your main application content.",
- href: "/docs/chat/copilot",
- },
- {
- icon: <Maximize2 />,
- title: "Full Screen",
- description: "A standalone, immersive chat page similar to ChatGPT or Claude.",
- href: "/docs/chat/fullscreen",
- },
- {
- icon: <MessageCircle />,
- title: "Bottom Tray",
- description: "A floating support-style widget that expands from the bottom corner.",
- href: "/docs/chat/bottom-tray",
- },
-] as const;
-
-const capabilities = [
- {
- icon: <MessageSquare />,
- title: "Streaming Native",
- description: "Handles text deltas, optimistic updates, loading states, and partial responses.",
- },
- {
- icon: <Database />,
- title: "Thread Persistence",
- description: "Save and restore conversation history with straightforward API contracts.",
- },
- {
- icon: <Zap />,
- title: "Composable State",
- description: "Use the same primitives across prebuilt layouts and fully custom chat surfaces.",
- },
-] as const;
-
-function SectionHeader({
- icon: Icon,
- title,
- description,
-}: {
- icon: LucideIcon;
- title: string;
- description: string;
-}) {
- return (
- <div className="mb-6 flex items-start gap-3 sm:mb-8 sm:gap-4">
- <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-fd-muted sm:size-12">
- <Icon className="size-5 text-fd-foreground sm:size-6" />
- </div>
- <div>
- <h2 className="mb-1 text-2xl font-bold sm:mb-2 sm:text-3xl">{title}</h2>
- <p className="text-sm text-fd-muted-foreground sm:text-base">{description}</p>
- </div>
- </div>
- );
-}
-
-export default function ChatOverviewPage() {
- return (
- <div className="mx-auto max-w-4xl px-3 py-8 font-sans text-slate-900 sm:px-4 sm:py-12 lg:px-8 dark:text-slate-100">
- <section className="mb-12 space-y-6 sm:mb-16">
- <h1 className="docs-page-title max-w-3xl">OpenUI Chat SDK</h1>
- <p className="max-w-2xl text-base leading-7 text-fd-muted-foreground sm:text-lg">
- Production-ready chat UI for AI agents. Start with prebuilt layouts for fast integration,
- then drop down to headless hooks when you need full control over behavior and rendering.
- </p>
- <div className="flex flex-wrap gap-3">
- <Button href="/docs/chat/installation" text="Installation" variant="primary" />
- <Button href="/docs/chat/copilot" text="Explore Layouts" variant="secondary" />
- </div>
- </section>
-
- <Separator className="my-8 sm:my-12" />
-
- <section>
- <SectionHeader
- icon={Layout}
- title="Batteries-Included Layouts"
- description="Choose the surface that matches your product and customize from there."
- />
-
- <FeatureCards>
- {layoutOptions.map((item) => (
- <FeatureCard
- key={item.href}
- icon={item.icon}
- title={item.title}
- description={item.description}
- href={item.href}
- />
- ))}
- </FeatureCards>
- </section>
-
- <Separator className="my-8 sm:my-12" />
-
- <section className="grid gap-10 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)] lg:items-start">
- <div className="space-y-8">
- <SectionHeader
- icon={Zap}
- title="Core Capabilities"
- description="The SDK handles the stateful parts so you can focus on UX, product logic, and polish."
- />
-
- <FeatureCards direction="horizontal">
- {capabilities.map((item) => (
- <FeatureCard
- key={item.title}
- direction="horizontal"
- icon={item.icon}
- title={item.title}
- description={item.description}
- />
- ))}
- </FeatureCards>
- </div>
-
- <div className="space-y-6">
- <SectionHeader
- icon={Code2}
- title="Go Headless"
- description="Use the same chat primitives without the prebuilt layouts when you need a fully custom surface."
- />
-
- <SimpleCard className="space-y-4 p-4 sm:p-5">
- <p className="text-sm leading-6 text-fd-muted-foreground">
- The `useChat` hook gives you message state, append helpers, and loading semantics
- without locking you into a specific UI.
- </p>
- <CodeBlock code={headlessCode} title="CustomChat.tsx" />
- <Link
- href="/docs/chat/headless-intro"
- className="inline-flex items-center text-sm font-medium text-fd-foreground transition-colors hover:text-fd-muted-foreground"
- >
- Read the Headless Guide
- </Link>
- </SimpleCard>
- </div>
- </section>
- </div>
- );
-}
diff --git a/docs/components/docs-navbar.tsx b/docs/components/docs-navbar.tsx
index c0efddf28..59ca8731e 100644
--- a/docs/components/docs-navbar.tsx
+++ b/docs/components/docs-navbar.tsx
@@ -12,16 +12,19 @@ import styles from "./docs-navbar.module.css";
import { SiteHeaderFrame } from "./site-header";
import { ThemeToggle } from "./theme-toggle";
-const tabs = [
+const tabs: { title: string; url: string; match?: string }[] = [
{ title: "OpenUI", url: "/docs/openui-lang" },
- { title: "Chat", url: "/docs/chat" },
+ { title: "Agent Interface", url: "/docs/agent/getting-started/introduction", match: "/docs/agent" },
{ title: "API Reference", url: "/docs/api-reference" },
-] as const;
+];
function activeTabUrl(pathname: string): string {
- const sorted = [...tabs].sort((a, b) => b.url.length - a.url.length);
+ const sorted = [...tabs].sort((a, b) => (b.match ?? b.url).length - (a.match ?? a.url).length);
return (
- sorted.find((t) => pathname === t.url || pathname.startsWith(`${t.url}/`))?.url ?? tabs[0].url
+ sorted.find((t) => {
+ const prefix = t.match ?? t.url;
+ return pathname === prefix || pathname.startsWith(`${prefix}/`);
+ })?.url ?? tabs[0].url
);
}
diff --git a/docs/components/overview-components/chat-modal.css b/docs/components/overview-components/chat-modal.css
index c98c21cfd..5fbd3cbbe 100644
--- a/docs/components/overview-components/chat-modal.css
+++ b/docs/components/overview-components/chat-modal.css
@@ -69,14 +69,14 @@
height: 100%;
}
-/* Override Shell container sizing to fit within the modal */
-.chat-modal-body .openui-shell-container {
+/* Override AgentInterface container sizing to fit within the modal */
+.chat-modal-body .openui-agent-container {
height: 100% !important;
width: 100% !important;
}
/* Hide the sidebar in the modal */
-.chat-modal-body .openui-shell-sidebar-container {
+.chat-modal-body .openui-agent-sidebar-container {
display: none !important;
}
diff --git a/docs/components/overview-components/chat-modal.tsx b/docs/components/overview-components/chat-modal.tsx
index 29934194f..f45cffbfb 100644
--- a/docs/components/overview-components/chat-modal.tsx
+++ b/docs/components/overview-components/chat-modal.tsx
@@ -8,12 +8,16 @@ import "./chat-modal.css";
import { DemoCreditsDialog } from "@/components/DemoCreditsDialog";
import { isDemoCreditsErrorPayload } from "@/lib/demo-credits";
-import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
+import {
+ AgentInterface,
+ openAIAdapter,
+ openAIMessageFormat,
+ type ChatLLM,
+} from "@openuidev/react-ui";
import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
import { X } from "lucide-react";
import { useTheme } from "next-themes";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
interface ChatModalProps {
@@ -40,6 +44,41 @@ export function ChatModal({ onClose }: ChatModalProps) {
};
}, [handleKey]);
+ // The backend call — including the demo-credits error handling — is unchanged;
+ // only the chat surface moved from FullScreen to AgentInterface. AgentInterface
+ // uses its built-in in-memory thread storage (wiped on reload).
+ const llm = useMemo<ChatLLM>(
+ () => ({
+ send: async ({ messages, signal }) => {
+ const response = await fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ messages: openAIMessageFormat.toApi(messages),
+ }),
+ signal,
+ });
+
+ if (!response.ok) {
+ const err = await response
+ .clone()
+ .json()
+ .catch(() => ({}));
+ if (isDemoCreditsErrorPayload((err as { error?: unknown }).error)) {
+ setShowOverviewCreditsDialog(true);
+ return new Response("data: [DONE]\n\n", {
+ headers: { "Content-Type": "text/event-stream" },
+ });
+ }
+ }
+
+ return response;
+ },
+ streamProtocol: openAIAdapter(),
+ }),
+ [],
+ );
+
return createPortal(
<div className="chat-modal-overlay" onClick={onClose}>
<div className="chat-modal-container" onClick={(e) => e.stopPropagation()}>
@@ -47,63 +86,37 @@ export function ChatModal({ onClose }: ChatModalProps) {
<X size={20} />
</button>
<div className="chat-modal-body">
- <FullScreen
- welcomeMessage={{ title: "Hello, how can I help you today?" }}
- processMessage={async ({ messages, abortController }) => {
- const response = await fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
-
- if (!response.ok) {
- const err = await response
- .clone()
- .json()
- .catch(() => ({}));
- if (isDemoCreditsErrorPayload((err as { error?: unknown }).error)) {
- setShowOverviewCreditsDialog(true);
- return new Response("data: [DONE]\n\n", {
- headers: { "Content-Type": "text/event-stream" },
- });
- }
- }
-
- return response;
- }}
- streamProtocol={openAIAdapter()}
+ <AgentInterface
+ llm={llm}
componentLibrary={openuiChatLibrary}
agentName="OpenUI Chat"
theme={{ mode: (resolvedTheme as "light" | "dark") ?? "light" }}
- conversationStarters={{
- variant: "short",
- options: [
- {
- displayText: "Revenue dashboard",
- prompt:
- "Build a revenue dashboard with a bar chart showing monthly revenue for Q4, key metrics, and a summary table.",
- },
- {
- displayText: "Signup form",
- prompt:
- "Create a user registration form with name, email, password, and country fields with validation.",
- },
- {
- displayText: "Compare React vs Vue",
- prompt:
- "Show me a comparison of React and Vue frameworks using tabs with pros, cons, and a feature comparison table.",
- },
- {
- displayText: "Travel destinations",
- prompt:
- "Show me a carousel of 3 popular travel destinations with images, descriptions, and best time to visit.",
- },
- ],
- }}
- />
+ starterVariant="short"
+ starters={[
+ {
+ displayText: "Revenue dashboard",
+ prompt:
+ "Build a revenue dashboard with a bar chart showing monthly revenue for Q4, key metrics, and a summary table.",
+ },
+ {
+ displayText: "Signup form",
+ prompt:
+ "Create a user registration form with name, email, password, and country fields with validation.",
+ },
+ {
+ displayText: "Compare React vs Vue",
+ prompt:
+ "Show me a comparison of React and Vue frameworks using tabs with pros, cons, and a feature comparison table.",
+ },
+ {
+ displayText: "Travel destinations",
+ prompt:
+ "Show me a carousel of 3 popular travel destinations with images, descriptions, and best time to visit.",
+ },
+ ]}
+ >
+ <AgentInterface.Welcome title="Hello, how can I help you today?" />
+ </AgentInterface>
</div>
<DemoCreditsDialog
open={showOverviewCreditsDialog}
diff --git a/docs/components/overview-components/overview-page.tsx b/docs/components/overview-components/overview-page.tsx
index 3303366e6..ebae10889 100644
--- a/docs/components/overview-components/overview-page.tsx
+++ b/docs/components/overview-components/overview-page.tsx
@@ -178,7 +178,6 @@ export function AssistantMessage({ content, isStreaming }) {
<div className="mt-4 flex flex-col gap-3 sm:mt-6 sm:flex-row">
<Button href="/docs/openui-lang" text="Get Started with OpenUI Lang" variant="primary" />
- <Button href="/docs/chat" text="Usage with OpenUI Chat" variant="secondary" />
</div>
</div>
@@ -199,25 +198,26 @@ export function AssistantMessage({ content, isStreaming }) {
</div>
<p className="mb-4 text-sm text-slate-600 sm:mb-6 sm:text-base dark:text-slate-400">
- Pre-built chat layouts (Copilot, Fullscreen, Bottom Tray) or build custom UIs with
- headless hooks. Fully themeable and accessible out of the box.
+ Drop in <code>AgentInterface</code> — a production-ready artifact chat surface with thread
+ history, conversation starters, and streaming — or build custom UIs with headless hooks.
+ Fully themeable and accessible out of the box.
</p>
<FeatureCards direction="horizontal" cols={3} className="mb-6">
<FeatureCard
direction="horizontal"
- title="Copilot"
- description="Floating widget for AI assistants"
+ title="Artifact Interface"
+ description="Drop-in chat surface with artifacts"
/>
<FeatureCard
direction="horizontal"
- title="Fullscreen"
- description="Full-page chat interface"
+ title="Thread History"
+ description="Persisted sidebar via pluggable storage"
/>
<FeatureCard
direction="horizontal"
- title="Bottom Tray"
- description="Slide-up mobile tray"
+ title="Headless Hooks"
+ description="Build a fully custom UI"
/>
</FeatureCards>
@@ -254,25 +254,31 @@ export function AssistantMessage({ content, isStreaming }) {
<CodeBlock
title="Quick example"
code={`import "@openuidev/react-ui/components.css";
-import "@openuidev/react-ui/styles/index.css";
-import { FullScreen, openuiLibrary } from "@openuidev/react-ui";
-
-<FullScreen
- apiUrl="/api/chat"
- componentLibrary={openuiLibrary}
+import {
+ AgentInterface,
+ openAIAdapter,
+ openAIMessageFormat,
+} from "@openuidev/react-ui";
+import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
+
+const llm = {
+ send: ({ messages, signal }) =>
+ fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ messages: openAIMessageFormat.toApi(messages) }),
+ signal,
+ }),
+ streamProtocol: openAIAdapter(),
+};
+
+<AgentInterface
+ llm={llm}
+ componentLibrary={openuiChatLibrary}
/>
`}
/>
</div>
-
- <div className="flex gap-3">
- <Button
- href="/docs/chat/quick-start"
- text="Get Started with OpenUI Chat"
- variant="primary"
- />
- <Button href="/docs/chat" text="View Components" variant="secondary" />
- </div>
</div>
<Separator className="my-8 sm:my-16" />
@@ -349,12 +355,28 @@ const customLibrary = createLibrary({
<TabsContent value="usage-with-chat" className="mt-4">
<CodeBlock
title="Using with Chat UI"
- code={`import { Copilot, openuiLibrary } from '@openuidev/react-ui';
+ code={`import {
+ AgentInterface,
+ openuiLibrary,
+ openAIAdapter,
+ openAIMessageFormat,
+} from '@openuidev/react-ui';
+
+const llm = {
+ send: ({ messages, signal }) =>
+ fetch('/api/chat', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ messages: openAIMessageFormat.toApi(messages) }),
+ signal,
+ }),
+ streamProtocol: openAIAdapter(),
+};
function App() {
return (
- <Copilot
- apiUrl="/api/chat"
+ <AgentInterface
+ llm={llm}
componentLibrary={openuiLibrary}
/>
);
diff --git a/docs/content/docs/agent/core-concepts/artifacts.mdx b/docs/content/docs/agent/core-concepts/artifacts.mdx
new file mode 100644
index 000000000..c9ec10d37
--- /dev/null
+++ b/docs/content/docs/agent/core-concepts/artifacts.mdx
@@ -0,0 +1,44 @@
+---
+title: Artifacts
+description: Durable, first-class conversation outputs like slides, reports, and apps that the user can open and return to.
+---
+
+An **artifact** is a first-class output of a conversation. Slides, reports, dashboards, a small app: things the user opens, reads, and returns to. An artifact is not a chat message and not a tool result. Once it exists, it stands on its own.
+
+On OpenUI Cloud, the agent produces **slides and reports** for you, with nothing to wire.
+
+## Where an artifact shows up
+
+The same renderer drives two surfaces:
+
+- **Preview:** a compact, inline view shown inside the chat message as the artifact is produced.
+- **Actual:** the full view, opened in a panel or on its own page.
+
+<video
+ src="/videos/agent/artifact-inline-to-side-panel.mp4"
+ autoPlay
+ loop
+ muted
+ playsInline
+ className="w-full rounded-lg border"
+/>
+
+## Static vs live
+
+Static and live describe how an artifact behaves, not two different APIs.
+
+**Static** content is frozen at generation. A report, a slide deck, generated code, a document. Re-open it next week and you see exactly what was produced.
+
+**Live** content is data-backed and interactive. A dashboard re-fetches current numbers on open. A small app exposes filters and controls and can write edits back.
+
+If the user expects a fixed record, it is static. If they expect fresh data, it is live. There is no `static: true` or `live: true` flag. It is how the renderer is written.
+
+## Custom artifacts
+
+To render an artifact, like an interactive app or a domain-specific view, you register a renderer for it through the `artifactRenderers` prop.
+
+```tsx
+<AgentInterface llm={llm} artifactRenderers={[myRenderer]} />
+```
+
+See [Custom artifacts](/docs/agent/guides/custom-artifacts) for `defineArtifactRenderer`, the preview and actual views, and persisting edits.
diff --git a/docs/content/docs/agent/core-concepts/conversations.mdx b/docs/content/docs/agent/core-concepts/conversations.mdx
new file mode 100644
index 000000000..56c224dbc
--- /dev/null
+++ b/docs/content/docs/agent/core-concepts/conversations.mdx
@@ -0,0 +1,38 @@
+---
+title: Conversations
+description: How to persist conversations and make them accessible to Agent Interface.
+---
+
+Every conversation with `AgentInterface` is stored through a `storage` adapter. Each message is persisted (its content, any extra context, and the complete response including text and tool calls), and `AgentInterface` reloads the threads and messages of the selected conversation automatically.
+
+On OpenUI Cloud, `useOpenuiCloudStorage` is that adapter. Cloud stores and reloads every conversation, so you run no database and write no persistence logic.
+
+This persistence lets users return to previous conversations, and the full history informs the agent's future responses.
+
+## What gets stored
+
+- **Threads:** the containers for a conversation. Each has an `id`, a title, and metadata like `createdAt`.
+- **Messages:** the turns inside a thread. Each has a `role` (`user`, `assistant`, or `tool`) and its content, including any [generative UI](/docs/agent/core-concepts/generative-ui) or [artifacts](/docs/agent/core-concepts/artifacts) the assistant produced.
+
+<img
+ src="/images/agent/conversation-history-sidebar.png"
+ alt="The sidebar thread list showing several saved conversations, illustrating persisted history"
+ className="w-full rounded-lg border"
+/>
+
+## Accessing conversations
+
+To build your own thread switcher or history view, read the data with hooks instead of touching storage. `useThread` selects from the current thread; `useThreadList` selects from all threads.
+
+```tsx
+import { useThread, useThreadList } from "@openuidev/react-ui";
+
+function ChatCount() {
+ const count = useThreadList((s) => s.threads.length);
+ return <span>{count} chats</span>;
+}
+```
+
+Both are selector hooks: pass a function that picks the slice you need, and the component re-renders only when that slice changes. They work anywhere inside `AgentInterface`. See [Hooks](/docs/agent/reference/hooks) for the full state.
+
+<Callout type="info">**Self-hosted:** the scaffold stores conversations in a local store it generates. To use your own database, implement the storage contract. See [Adapters & formats](/docs/agent/reference/adapters-and-formats).</Callout>
diff --git a/docs/content/docs/agent/core-concepts/generative-ui.mdx b/docs/content/docs/agent/core-concepts/generative-ui.mdx
new file mode 100644
index 000000000..e3bb03293
--- /dev/null
+++ b/docs/content/docs/agent/core-concepts/generative-ui.mdx
@@ -0,0 +1,48 @@
+---
+title: Generative UI
+description: "Render interactive components inline in chat messages: tables, forms, charts, and cards, not just markdown."
+---
+
+An assistant message is normally markdown text. **Generative UI (GenUI)** lets the agent render real components instead: tables, forms, charts, and cards, inline in the message and streaming as the reply arrives.
+
+Turn it on with one prop. On OpenUI Cloud, the components and model instructions are managed for you.
+
+```tsx
+import { AgentInterface } from "@openuidev/react-ui";
+import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
+
+<AgentInterface llm={llm} componentLibrary={openuiLibrary} />;
+```
+
+`openuiLibrary` covers layout, content, tables, charts, forms, and buttons, enough for most agents. To define your own components, see the [OpenUI Lang overview](/docs/openui-lang/overview).
+
+<video
+ src="/videos/agent/generative-ui-chart-inline.mp4"
+ autoPlay
+ loop
+ muted
+ playsInline
+ className="w-full rounded-lg border"
+/>
+
+## Interactivity
+
+Generated components are interactive, and the runtime wires up the behavior. When a user fills a form or clicks a button, one of two things happens:
+
+- **It continues the conversation.** The interaction goes back to the agent as the next turn, carrying the current field values.
+- **It updates in place.** The component refreshes data, changes a value, or opens a link, with no round trip to the model.
+
+Form state is tracked automatically and saved with the thread, so a half-filled form survives a reload. See [Interactivity](/docs/openui-lang/interactivity) for the details.
+
+<video
+ src="/videos/agent/generative-ui-form-interaction.mp4"
+ autoPlay
+ loop
+ muted
+ playsInline
+ className="w-full rounded-lg border"
+/>
+
+## GenUI vs artifacts
+
+Use 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.
diff --git a/docs/content/docs/agent/core-concepts/tools.mdx b/docs/content/docs/agent/core-concepts/tools.mdx
new file mode 100644
index 000000000..0b6bd4b8f
--- /dev/null
+++ b/docs/content/docs/agent/core-concepts/tools.mdx
@@ -0,0 +1,67 @@
+---
+title: Tools
+description: Let the agent call functions to fetch data and take actions, with your own tools or OpenUI Cloud's built-ins.
+---
+
+A chat model can only produce text. A **tool** is a function you give the agent so it can do more: fetch the weather, query your database, file a ticket. The result folds back into the conversation.
+
+The loop:
+
+1. The model proposes a tool: a **name** plus **arguments**.
+2. **Your code runs it.** It calls an API, reads a database, or does whatever the tool does.
+3. The **result returns to the conversation**, and the agent continues, usually turning it into a final answer.
+
+```
+user: "What's the weather in Tokyo?"
+ └─ model proposes: get_weather({ city: "Tokyo" })
+ └─ your code runs it → { tempC: 22, sky: "clear" }
+ └─ result returns to the agent
+ └─ agent: "It's 22°C and clear in Tokyo right now."
+```
+
+The trust boundary stays in your code. The model only proposes which tool to call and with what arguments. Execution, provider keys, and the tool implementations live on the server and never reach the browser.
+
+<video
+ src="/videos/agent/tool-call-web-search.mp4"
+ autoPlay
+ loop
+ muted
+ playsInline
+ className="w-full rounded-lg border"
+/>
+
+## Integrate your own tool
+
+A tool is a **name**, a **description**, and a **JSON Schema** for its arguments. The model uses the description and schema to decide when and how to call it, so write them like prompts.
+
+```ts
+const tools = [
+ {
+ type: "function",
+ name: "get_weather",
+ description: "Get the current weather for a city.",
+ parameters: {
+ type: "object",
+ properties: {
+ city: { type: "string", description: "City name, e.g. 'Tokyo'" },
+ },
+ required: ["city"],
+ additionalProperties: false,
+ },
+ },
+];
+```
+
+That declaration is what the model sees. The implementation, the code that actually fetches the weather, stays private and runs only when the agent calls the tool.
+
+This declaration is the same on OpenUI Cloud and self-hosted. Your code always runs your own tools. Only the built-in tools below run inside Cloud.
+
+<Callout type="info">**Self-hosted:** you run the loop in your own route. Call the provider, execute any tool it asks for, append the result, and call again until the model returns text with no more tool calls. See [Self-hosting](/docs/agent/reference/self-hosting).</Callout>
+
+## Built-in tools (OpenUI Cloud)
+
+OpenUI Cloud ships tools you enable without writing any implementation. Cloud holds the keys and runs them. For example, `image_search` lets the agent pull in relevant images.
+
+## Tools and artifacts
+
+A tool call is also one way an [artifact](/docs/agent/core-concepts/artifacts) gets produced. When the agent calls something like `generate_report`, the interface matches a renderer to that tool by name and draws the result in its own panel. The tool call is the mechanism; the artifact is the output. Many tool calls, like `get_weather`, produce no artifact at all. See [Custom artifacts](/docs/agent/guides/custom-artifacts) to render a tool's result as an artifact.
diff --git a/docs/content/docs/agent/customize/message-rendering.mdx b/docs/content/docs/agent/customize/message-rendering.mdx
new file mode 100644
index 000000000..e1cd8bd51
--- /dev/null
+++ b/docs/content/docs/agent/customize/message-rendering.mdx
@@ -0,0 +1,78 @@
+---
+title: Message rendering
+description: Replace how user and assistant messages render with your own React components, the escape hatch beyond Generative UI.
+---
+
+By default, `AgentInterface` renders each message for you: markdown for assistant text, the user's text as sent, tool calls inline. [Generative UI](/docs/agent/core-concepts/generative-ui) goes further, letting the model emit rich components inside an assistant message. In both, `AgentInterface` owns the rendering.
+
+The `components` prop is the escape hatch past both. Hand `AgentInterface` your own `AssistantMessage` and `UserMessage` and they render every assistant and user message: markdown, layout, avatars, all of it.
+
+```tsx
+import { AgentInterface } from "@openuidev/react-ui";
+
+<AgentInterface
+ llm={llm}
+ components={{ AssistantMessage: MyAssistantMessage, UserMessage: MyUserMessage }}
+/>;
+```
+
+Both keys are optional and independent. Override just one and the other keeps its default rendering.
+
+## What a component receives
+
+A message component renders once per message it handles and receives that message as a `message` prop. An `AssistantMessage` also gets an `isStreaming` boolean, `true` while it is the in-flight reply. Assistant `content` is empty until the first token arrives, so guard it.
+
+```tsx
+import type { AssistantMessage } from "@openuidev/react-ui";
+
+function MyAssistantMessage({
+ message,
+ isStreaming,
+}: {
+ message: AssistantMessage;
+ isStreaming: boolean;
+}) {
+ return <div className="assistant">{message.content ?? ""}</div>;
+}
+```
+
+The component re-renders as the reply streams in, with `content` growing token by token. A `UserMessage` works the same way without `isStreaming`. Its `content` may be a string or, for multimodal input, an array.
+
+## A custom AssistantMessage
+
+A complete renderer that adds a copy button while still rendering markdown:
+
+```tsx
+import { AgentInterface, type AssistantMessage } from "@openuidev/react-ui";
+import ReactMarkdown from "react-markdown";
+
+function CustomAssistantMessage({ message }: { message: AssistantMessage }) {
+ const text = message.content ?? "";
+ return (
+ <div className="prose">
+ <ReactMarkdown>{text}</ReactMarkdown>
+ <button onClick={() => navigator.clipboard.writeText(text)}>Copy</button>
+ </div>
+ );
+}
+
+<AgentInterface llm={llm} components={{ AssistantMessage: CustomAssistantMessage }} />;
+```
+
+The markdown library is your choice; nothing is imposed once you have taken over.
+
+<img
+ src="/images/agent/custom-assistant-message.png"
+ alt="A custom assistant message bubble with a Copy button, beside the default rendering of the same reply"
+ className="w-full rounded-lg border"
+/>
+
+## Precedence
+
+When a message renders, `AgentInterface` picks the first matching renderer:
+
+1. **`components`:** your explicit override, when set for that message.
+2. **`componentLibrary` (GenUI):** rich rendering so the model can emit components inline.
+3. **Built-in default:** markdown for assistant, plain text for user, tool calls inline.
+
+The props compose. Set `components.AssistantMessage` and your component wins for assistant messages, while user messages still flow through GenUI or the default.
\ No newline at end of file
diff --git a/docs/content/docs/agent/customize/sidebar.mdx b/docs/content/docs/agent/customize/sidebar.mdx
new file mode 100644
index 000000000..8943e77b8
--- /dev/null
+++ b/docs/content/docs/agent/customize/sidebar.mdx
@@ -0,0 +1,98 @@
+---
+title: Sidebar
+description: Add your own nav items to the left sidebar, or replace it entirely through the Sidebar slot.
+---
+
+The left sidebar holds the header, the thread list, and (when artifact storage is configured) an artifact entry. Add a couple of your own links above the threads, or take over the whole region.
+
+Both go through the `Sidebar` slot. Its children replace the sidebar's inner content, so you re-include the default pieces you want to keep. `SidebarContent` and `SidebarSeparator` are primitives you compose inside the slot, not slots themselves.
+
+## Add nav items above the thread list
+
+The common case: a few of your own links, the default thread list underneath. Pass children to the `Sidebar` slot and re-include `SidebarHeader`, `ArtifactNav`, and `ThreadList`.
+
+```tsx
+import { AgentInterface } from "@openuidev/react-ui";
+import { Home, LayoutDashboard } from "lucide-react";
+
+<AgentInterface llm={llm} storage={storage} logoUrl="/logo.svg" agentName="Acme">
+ <AgentInterface.Sidebar>
+ <AgentInterface.SidebarHeader />
+ <AgentInterface.SidebarContent>
+ <AgentInterface.SidebarItem icon={<Home size={14} />} path="home">
+ Home
+ </AgentInterface.SidebarItem>
+ <AgentInterface.SidebarItem icon={<LayoutDashboard size={14} />} path="dashboard">
+ Dashboard
+ </AgentInterface.SidebarItem>
+
+ <AgentInterface.SidebarSeparator />
+
+ {/* keep the defaults */}
+ <AgentInterface.ArtifactNav />
+ <AgentInterface.ThreadList />
+ </AgentInterface.SidebarContent>
+ </AgentInterface.Sidebar>
+</AgentInterface>
+```
+
+A `SidebarItem` with `path` navigates. Without one, handle the click yourself via `onClick`. When `path` is set, the item highlights while its route is active, and clicking it calls the router. Your `onClick` runs first; call `event.preventDefault()` to suppress navigation.
+
+<img
+ src="/images/agent/sidebar-custom-nav-items.png"
+ alt="The sidebar with two custom nav items (Home and Dashboard) above the thread list"
+ className="w-full rounded-lg border"
+/>
+
+## Wire items to pages
+
+A navigating item only changes the route. Pair it with a `Route` to render something there.
+
+```tsx
+<AgentInterface.SidebarItem path="dashboard">Dashboard</AgentInterface.SidebarItem>
+
+<AgentInterface.Route path="dashboard">
+ <YourDashboard />
+</AgentInterface.Route>
+```
+
+When the path matches, the route replaces the thread region; clicking a thread returns to the conversation.
+
+## Replace the whole sidebar
+
+For full control over header placement, section order, and dividers, compose every piece yourself. Nothing default is rendered; you own the structure.
+
+```tsx
+import { AgentInterface } from "@openuidev/react-ui";
+import { Home, LifeBuoy } from "lucide-react";
+
+<AgentInterface llm={llm} storage={storage} logoUrl="/logo.svg" agentName="Acme">
+ <AgentInterface.Sidebar>
+ <AgentInterface.SidebarHeader />
+ <AgentInterface.SidebarContent>
+ <AgentInterface.NewChatButton />
+ <AgentInterface.SidebarSeparator />
+
+ <AgentInterface.SidebarItem icon={<Home size={14} />} path="home">
+ Home
+ </AgentInterface.SidebarItem>
+
+ <AgentInterface.SidebarSeparator />
+ <AgentInterface.ArtifactNav />
+ <AgentInterface.ThreadList />
+ <AgentInterface.SidebarSeparator />
+
+ <AgentInterface.SidebarItem
+ icon={<LifeBuoy size={14} />}
+ onClick={() => window.open("https://docs.example.com", "_blank")}
+ >
+ Help & docs
+ </AgentInterface.SidebarItem>
+ </AgentInterface.SidebarContent>
+ </AgentInterface.Sidebar>
+</AgentInterface>
+```
+
+<Callout type="info">`ArtifactNav` renders nothing unless `storage.artifact` is configured. It auto-appears in the default sidebar and stays safe to include in a custom one regardless. With [artifact categories](/docs/agent/core-concepts/artifacts) it renders one entry per category, otherwise a single "Artifacts" item.</Callout>
+
+Put `SidebarHeader` inside the slot, not at the top level. When you replace the sidebar, you compose the header there too. `NewChatButton` is not part of the default sidebar content (it lives in the mobile header), so place it yourself if you want it on desktop.
diff --git a/docs/content/docs/agent/customize/welcome-and-starters.mdx b/docs/content/docs/agent/customize/welcome-and-starters.mdx
new file mode 100644
index 000000000..2ace35ef0
--- /dev/null
+++ b/docs/content/docs/agent/customize/welcome-and-starters.mdx
@@ -0,0 +1,87 @@
+---
+title: Welcome & starters
+description: Customize the empty-state welcome screen and the conversation starters that prime a new thread.
+---
+
+When a thread has no messages, `AgentInterface` shows an empty state: a **Welcome** screen with **conversation starters**, clickable prompts that kick off the conversation. Both are configurable, from a one-line greeting to a fully custom panel. The empty state disappears once the first message lands.
+
+## Conversation starters
+
+A starter is a clickable chip with display text and the prompt it sends. Pass an array via the `starters` prop:
+
+```tsx
+import { AgentInterface, fetchLLM, agUIAdapter } from "@openuidev/react-ui";
+
+const llm = fetchLLM({ url: "/api/chat", streamAdapter: agUIAdapter() });
+
+const starters = [
+ {
+ displayText: "Summarize my latest report",
+ prompt: "Summarize the key findings from my most recent quarterly report.",
+ },
+ {
+ displayText: "Build a revenue dashboard",
+ prompt: "Build a dashboard with a bar chart of monthly revenue and a total summary card.",
+ },
+];
+
+export default function App() {
+ return <AgentInterface llm={llm} starters={starters} starterVariant="long" />;
+}
+```
+
+Each entry is `{ displayText, prompt, icon? }`. Clicking a starter sends its `prompt` as a user message, exactly as if the user typed it, so write `prompt` as a full instruction. Omit `icon` for a default lightbulb, pass a React node for a custom glyph, or pass `<></>` for none. `starterVariant` is `"short"` (compact pills) or `"long"` (a vertical list with icons).
+
+<Callout type="info">`starters` and `starterVariant` set on `AgentInterface` flow down to the Welcome and Composer slots. Each slot can override with its own value. Pass `[]` to a slot to suppress inherited starters there.</Callout>
+
+## The Welcome slot
+
+`AgentInterface.Welcome` is the greeting area above the composer. Pass props to keep the default layout with your own content:
+
+```tsx
+<AgentInterface llm={llm}>
+ <AgentInterface.Welcome
+ title="What can I help you build?"
+ description="Ask about your reports and dashboards, or pick a starter below."
+ image={{ url: "/logo.svg" }}
+ starters={starters}
+ starterVariant="long"
+ />
+</AgentInterface>
+```
+
+The `image` prop takes `{ url: string }` or any React node. `starters` set here overrides the inherited value.
+
+### Replace it entirely
+
+Pass children to take over the whole welcome area. `title`, `description`, `image`, `starters`, and `starterVariant` are then ignored. A custom Welcome does not render starters for you, so to send a message from your own button, call `processMessage` from `useThread`:
+
+```tsx
+import { AgentInterface, useThread } from "@openuidev/react-ui";
+
+function Starter({ label, prompt }: { label: string; prompt: string }) {
+ const processMessage = useThread((s) => s.processMessage);
+ return (
+ <button onClick={() => processMessage({ role: "user", content: prompt })}>
+ {label}
+ </button>
+ );
+}
+
+<AgentInterface llm={llm}>
+ <AgentInterface.Welcome>
+ <div className="my-welcome">
+ <h1>What can I help you build?</h1>
+ <Starter label="Build a dashboard" prompt="Build a revenue dashboard for the last six months." />
+ </div>
+ </AgentInterface.Welcome>
+</AgentInterface>;
+```
+
+`processMessage({ role: "user", content })` sends a user message and starts the run, the same as typing in the composer.
+
+<img
+ src="/images/agent/welcome-and-starters.png"
+ alt="The empty state showing the Welcome title and logo above starter chips"
+ className="w-full rounded-lg border"
+/>
diff --git a/docs/content/docs/agent/getting-started/introduction.mdx b/docs/content/docs/agent/getting-started/introduction.mdx
new file mode 100644
index 000000000..a38a4ee66
--- /dev/null
+++ b/docs/content/docs/agent/getting-started/introduction.mdx
@@ -0,0 +1,48 @@
+---
+title: Agent Interface
+description: "A generative-UI toolkit for building agent interfaces in React: interactive components and artifacts inside a complete, streaming chat, on OpenUI Cloud or your own backend."
+---
+
+Agent Interface helps developers ship production agent UIs. Your agent renders interactive components and artifacts (dashboards, slides, reports) inside a complete, streaming chat, on OpenUI Cloud or your own backend.
+
+<video
+ src="/videos/agent/agent-interface-hero.mp4"
+ autoPlay
+ loop
+ muted
+ playsInline
+ className="w-full rounded-lg border"
+/>
+
+## Why Agent Interface?
+
+Building an agent UI from scratch is a lot of work before you ship a single feature. You wire up streaming and thread history, render every message, build the interactive components your agent returns, add panels for richer outputs, theme it all, and make it work on mobile.
+
+Agent Interface gives you that in one component. Give it a component library and your agent renders those components inline, streaming their props as they arrive. Durable outputs like dashboards, slides, and reports become artifacts your users can open, revisit, and edit. Connect it to OpenUI Cloud and it handles conversations, generative UI, and artifacts for you. You can also run it on your own backend.
+
+```tsx
+import { AgentInterface, fetchLLM, openAIResponsesAdapter, openAIConversationMessageFormat } from "@openuidev/react-ui";
+import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
+
+// Point the llm adapter at your backend route.
+const llm = fetchLLM({
+ url: "/api/chat",
+ streamAdapter: openAIResponsesAdapter(),
+ messageFormat: openAIConversationMessageFormat,
+});
+
+export default function App() {
+ return <AgentInterface llm={llm} componentLibrary={openuiLibrary} />;
+}
+```
+
+That is the whole integration. `AgentInterface` renders the streaming chat with generative UI on. Point `storage` at OpenUI Cloud (or your own backend) to add conversation history and artifacts.
+
+## What's included
+
+- **`<AgentInterface>`:** a complete chat UI out of the box, with a sidebar, thread list, composer, streaming, and a responsive layout.
+- **Generative UI:** your agent renders rich, interactive components inline in the conversation instead of plain text.
+- **Artifacts:** durable outputs like dashboards, slides, and reports, opened in side panels and full pages.
+- **Fully customizable:** override any slot, theme with design tokens, and swap in your own message rendering.
+- **OpenUI Cloud or self-hosted:** managed conversations, generative UI, and artifacts, or run it on your own backend.
+
diff --git a/docs/content/docs/agent/getting-started/openui-cloud.mdx b/docs/content/docs/agent/getting-started/openui-cloud.mdx
new file mode 100644
index 000000000..f57c865ec
--- /dev/null
+++ b/docs/content/docs/agent/getting-started/openui-cloud.mdx
@@ -0,0 +1,60 @@
+---
+title: OpenUI Cloud
+description: "The managed backend for Agent Interface: conversation history, production-grade generative UI, and prebuilt presentation and report artifacts."
+---
+
+OpenUI Cloud is the managed backend for Agent Interface. It is built on the open-source OpenUI rendering engine and adds the production layers on top, so you point your app at it and ship instead of operating that infrastructure yourself.
+
+<img
+ src="/images/agent/cloud-interface-with-artifacts.png"
+ alt="A Cloud-rendered, on-brand interface beside a report and presentation artifact it generated"
+ className="w-full rounded-lg border"
+/>
+
+## What you get
+
+- **Conversation history.** Threads and messages are stored and reloaded for you. No database to run, no endpoints to write.
+- **Production-grade generative UI.** A pre-tested, responsive, accessible component set. Invalid model output is detected and corrected before the user sees it, and a middleware layer normalizes model quirks so generation stays consistent across providers and model versions.
+- **Prebuilt artifacts.** Reports and presentations the agent generates and renders out of the box, with no renderer to build.
+- **Theming and white-labeling.** Fonts, colors, spacing, and component styles are configurable, so every agent-rendered UI is on-brand by default. Multiple brand configurations are supported.
+- **Production hardening.** Model fallbacks and a degraded mode when a provider is slow or down, version pinning and rollback to a known-good setup, and observability with an audit trail: render success, latency, token usage, and a record of what was rendered for whom.
+
+## Connect
+
+`AgentInterface` connects to Cloud through two props, both wired by the scaffold (or by hand, following the `openui-cloud` example in the repo):
+
+- **`llm`** points at a thin `/api/chat` route in your app that proxies to Cloud's Responses endpoint. Your `THESYS_API_KEY` stays on that route and never reaches the browser. On the client it uses `openAIResponsesAdapter()` with `openAIConversationMessageFormat`.
+- **`storage`** is `useOpenuiCloudStorage()` from `@openuidev/thesys`. It reads conversations and artifacts from Cloud directly, authenticated by a short-lived frontend token your app mints from a `/api/frontend-token` route (so the server key never reaches the browser).
+
+The component set (`chatLibrary`), artifact renderers, and categories also come from `@openuidev/thesys`.
+
+Add your server-side key:
+
+```bash
+THESYS_API_KEY=sk-th-your-key
+```
+
+Generate a key in the [Thesys console](https://console.thesys.dev/keys). See [Quickstart](/docs/agent/getting-started/quickstart) to scaffold a Cloud app.
+
+## OpenUI vs OpenUI Cloud
+
+| | OpenUI (open source) | OpenUI Cloud |
+|---|---|---|
+| Generative UI rendering | ✓ | ✓ |
+| Streaming and progressive rendering | ✓ | ✓ |
+| Production-grade components | Basic | Optimized, cross-browser tested |
+| Prebuilt report and presentation artifacts | ✗ | ✓ |
+| Theming and white-labeling | ✗ | ✓ |
+| Error detection and correction | ✗ | ✓ |
+| Cross-model consistency | ✗ | ✓ |
+| Fallbacks, versioning, observability | ✗ | ✓ |
+
+## Roadmap
+
+Coming next:
+
+- **Document exports.** Download reports and presentations as PDF, DOCX, and PPT.
+- **Live dashboards.** Dashboards backed by your business-specific data.
+- **Manual editing.** Edit generated reports and presentations by hand.
+- **Insights.** See what users ask, where they hit dead ends, and which usage patterns to build for next.
+- **Continual learning and memory.** Cloud learns how individual users prefer information presented and adapts over time.
diff --git a/docs/content/docs/agent/getting-started/quickstart.mdx b/docs/content/docs/agent/getting-started/quickstart.mdx
new file mode 100644
index 000000000..8ef1f7186
--- /dev/null
+++ b/docs/content/docs/agent/getting-started/quickstart.mdx
@@ -0,0 +1,84 @@
+---
+title: Quickstart
+description: Scaffold a working streaming chat agent (conversation history, tools, artifacts, and generative UI) in a few minutes with the OpenUI CLI.
+---
+
+The CLI scaffolds a complete Next.js app: a streaming chat with a sidebar, thread list, composer, and generative UI on by default. You write no boilerplate: create, connect, run.
+
+## 1. Create
+
+Run the create command and answer the prompts. One prompt asks **OpenUI Cloud or self-hosted?** Your choice decides which backend the scaffold wires up.
+
+<Tabs groupId="pkg" items={["npx", "pnpm", "yarn", "bun"]} persist>
+ <Tab value="npx">```bash npx @openuidev/cli@latest create ```</Tab>
+ <Tab value="pnpm">```bash pnpm dlx @openuidev/cli@latest create ```</Tab>
+ <Tab value="yarn">```bash yarn dlx @openuidev/cli@latest create ```</Tab>
+ <Tab value="bun">```bash bunx @openuidev/cli@latest create ```</Tab>
+</Tabs>
+
+When it finishes, move into the project:
+
+```bash
+cd my-agent
+```
+
+## 2. Connect
+
+<Tabs groupId="deploy" items={["OpenUI Cloud", "Self-hosted"]} persist>
+ <Tab value="OpenUI Cloud">
+
+Connect the scaffold to OpenUI Cloud. Generate an API key in the [Thesys console](https://console.thesys.dev/keys) and add it to `.env.local`:
+
+```bash
+THESYS_API_KEY=sk-th-your-key-here
+```
+
+The scaffold's `/api/chat` route proxies to Cloud with this key, so it stays on the server. Cloud manages conversation history, artifacts, and built-in tools, so there's no database or renderers to run. See [OpenUI Cloud](/docs/agent/getting-started/openui-cloud).
+
+ </Tab>
+ <Tab value="Self-hosted">
+
+The scaffold generates an `/api/chat` route that calls OpenAI on the server. Add your key to `.env.local`:
+
+```bash
+OPENAI_API_KEY=sk-your-key-here
+```
+
+The key stays on the server. The browser only ever talks to your route, never the provider.
+
+ </Tab>
+</Tabs>
+
+## 3. Run
+
+Start the dev server:
+
+<Tabs groupId="pkg" items={["npx", "pnpm", "yarn", "bun"]} persist>
+ <Tab value="npx">```bash npm run dev ```</Tab>
+ <Tab value="pnpm">```bash pnpm dev ```</Tab>
+ <Tab value="yarn">```bash yarn dev ```</Tab>
+ <Tab value="bun">```bash bun dev ```</Tab>
+</Tabs>
+
+Open [http://localhost:3000](http://localhost:3000) and send a message. The response streams in token by token, and the assistant can render rich, interactive components inline.
+
+<video
+ src="/videos/agent/quickstart-inline-generative-ui.mp4"
+ autoPlay
+ loop
+ muted
+ playsInline
+ className="w-full rounded-lg border"
+/>
+
+## What you get
+
+A working agent out of the box:
+
+- **Streaming chat:** responses render token by token in a full layout (sidebar, thread list, composer).
+- **Conversation history that persists:** past threads are saved and reloadable, not reset on refresh. See [Conversations](/docs/agent/core-concepts/conversations).
+- **Tool calling:** the agent can call tools mid-response, including built-in Cloud tools like `image_search` (no code to enable). See [Tools](/docs/agent/core-concepts/tools).
+- **An example artifact:** the scaffold ships a slides/report artifact you can prompt for and open in the workspace. See [Artifacts](/docs/agent/core-concepts/artifacts).
+- **Generative UI, on by default:** the assistant renders interactive components inside messages. See [Generative UI](/docs/agent/core-concepts/generative-ui).
+
+The difference is only in the backing: **OpenUI Cloud** manages history, artifacts, and built-in tools for you, while **self-hosted** uses your own OpenAI route and a local store the scaffold generates.
diff --git a/docs/content/docs/agent/guides/custom-artifacts.mdx b/docs/content/docs/agent/guides/custom-artifacts.mdx
new file mode 100644
index 000000000..0fa7a993b
--- /dev/null
+++ b/docs/content/docs/agent/guides/custom-artifacts.mdx
@@ -0,0 +1,102 @@
+---
+title: Custom artifacts
+description: "Add a custom artifact type beyond Cloud's built-in slides and reports: produce the data, write a renderer, register it."
+---
+
+OpenUI Cloud ships built-in artifact types (slides, reports) already wired to render. When your agent produces something they don't cover, like a code snippet or a custom app, you add your own type: a tool returns the data, a renderer turns it into UI, and the `artifactRenderers` prop registers it. The same renderer draws the artifact whether it just streamed in or was loaded from storage.
+
+This guide builds one custom artifact end to end: a code snippet the agent generates. For the concept, see [Artifacts](/docs/agent/core-concepts/artifacts). For every renderer field and edge case, see [defineArtifactRenderer](/docs/agent/reference/define-artifact-renderer).
+
+## 1. Produce the artifact
+
+An artifact reaches the UI as the result of a [tool call](/docs/agent/core-concepts/tools). Your agent calls a `create_code_artifact` tool, and its arguments are the artifact's data. The renderer below matches that tool by name and draws the result, the same way on OpenUI Cloud or your own backend.
+
+Keep that shape identical to whatever you persist, so one renderer covers both the freshly-streamed and the loaded-from-storage cases. For this example the data is:
+
+```ts
+interface CodeArtifact {
+ language: string;
+ title: string;
+ code: string;
+}
+```
+
+## 2. Write the renderer
+
+A renderer is keyed to an artifact `type`, not to a tool. A tool call is just one way the data arrives. You describe it with `defineArtifactRenderer`: a `parser` that reads the raw envelope into typed props, a `preview` (the inline card in the chat), and an `actual` (the full view in a side panel or page).
+
+The rule that matters most: the `parser` must never throw. It runs on every stream update, including before the result exists, so read `response` as the source of truth, fall back to a tolerant parse of `args` for an early preview, and bail with `null` until you have enough to draw.
+
+```tsx
+import { defineArtifactRenderer, CodeBlock } from "@openuidev/react-ui";
+
+const codeArtifactRenderer = defineArtifactRenderer({
+ type: "code_artifact",
+ toolName: "create_code_artifact",
+
+ parser: ({ args, response }, { isStreaming }) => {
+ // Storage path: args is undefined, response is the persisted content.
+ // Tool-call path: response is null until the result lands; args streams
+ // in first as a partial JSON string.
+ const data = (response as CodeArtifact | null) ?? tryParse(args);
+ if (!data?.title) return null; // not enough to draw yet
+
+ return {
+ props: data,
+ // Don't register in the workspace until the result is final.
+ meta: isStreaming
+ ? null
+ : { id: `code:${data.title}`, version: 1, heading: data.title },
+ };
+ },
+
+ preview: (props, controls) => (
+ <button
+ type="button"
+ onClick={controls.open}
+ data-active={controls.isActive}
+ className="code-card"
+ >
+ <span className="code-card__title">{props.title}</span>
+ <span className="code-card__lang">
+ {props.language}
+ {controls.isStreaming ? " · building…" : ""}
+ </span>
+ </button>
+ ),
+
+ actual: (props) => (
+ <div className="code-artifact">
+ <CodeBlock language={props.language || "text"} codeString={props.code} />
+ </div>
+ ),
+});
+
+// Best-effort parse of a possibly-partial JSON arg string.
+function tryParse(args: unknown): CodeArtifact | null {
+ if (typeof args !== "string") return null;
+ try {
+ return JSON.parse(args) as CodeArtifact;
+ } catch {
+ return null; // still mid-stream
+ }
+}
+```
+
+A few things to notice:
+
+- **`preview` vs `actual`:** `preview` is the compact card inline in the message; keep it small and give it an affordance that calls `controls.open()`. `actual` is the full view in the detailed-view panel or the artifact page. Here it uses the built-in `CodeBlock` component.
+- **`meta`:** return `meta: null` while streaming so the artifact joins the workspace only once complete; return `{ id, version, heading }` on the final pass to register it. Keep `id` stable across re-runs of the same artifact.
+- **`controls.isStreaming`:** the same component instance is reused across the streaming-to-complete transition, so this is a state swap, not a remount.
+
+## 3. Register it
+
+Hand your renderer to `<AgentInterface>` through the `artifactRenderers` prop. Pass as many as you like:
+
+```tsx
+import { AgentInterface } from "@openuidev/react-ui";
+
+<AgentInterface llm={llm} artifactRenderers={[codeArtifactRenderer]} />;
+```
+
+The interface indexes each renderer by `toolName` (the tool-call path) and by `type` (the storage path), so a `create_code_artifact` call renders as an inline card that opens a full panel, and any `code_artifact` loaded from storage renders through the same code. On a duplicate `toolName` or `type`, the first registration wins, so put your custom renderers before any built-in defaults.
diff --git a/docs/content/docs/agent/guides/migrating.mdx b/docs/content/docs/agent/guides/migrating.mdx
new file mode 100644
index 000000000..4c8f7f59e
--- /dev/null
+++ b/docs/content/docs/agent/guides/migrating.mdx
@@ -0,0 +1,225 @@
+---
+title: Migrating from flat-props ChatProvider
+description: Move from the legacy flat-props chat component to AgentInterface and its two adapter objects — with a complete old-to-new mapping and the behavior changes to watch for.
+---
+
+The legacy chat component took its backend wiring as a flat bag of props — `apiUrl`, `streamProtocol`, `processMessage`, `threadApiUrl`, `fetchThreadList`, `loadThread`, and a dozen more — directly on the component. `AgentInterface` replaces all of that with **two adapter objects**: an `llm` for producing replies and a `storage` for persistence. The component's prop surface shrinks to something small and stable, and each adapter is testable in isolation — you can unit-test a `ChatLLM` or `ChatStorage` without rendering anything.
+
+The whole migration, in one idea: the flat backend props are **removed** (not deprecated), and their values move into `fetchLLM({ ... })` for the LLM and `restStorage({ ... })` for threads.
+
+<Callout type="info">Everything imports from `@openuidev/react-ui`: `AgentInterface`, the `fetchLLM` / `restStorage` / `defineArtifactRenderer` factories, the stream adapters, the message formats, and hooks like `useArtifactList`.</Callout>
+
+## The whole diff
+
+If you were on the common setup — POST to a route, REST-backed threads — the migration is: build two adapters, pass two props.
+
+**Before:**
+
+```tsx
+// legacy flat-props chat component
+<LegacyChat
+ apiUrl="/api/chat"
+ streamProtocol="openai"
+ messageFormat="openai"
+ threadApiUrl="/api/threads"
+/>;
+```
+
+**After:**
+
+```tsx
+import { AgentInterface, fetchLLM, restStorage, openAIAdapter, openAIMessageFormat } from "@openuidev/react-ui";
+
+const llm = fetchLLM({
+ url: "/api/chat",
+ streamAdapter: openAIAdapter(),
+ messageFormat: openAIMessageFormat,
+});
+
+const storage = restStorage({
+ baseUrl: "/api/threads",
+ messageFormat: openAIMessageFormat,
+});
+
+<AgentInterface llm={llm} storage={storage} />;
+```
+
+Your route handler doesn't change: `fetchLLM` POSTs the same `{ threadId, messages }` to `url`, and `restStorage` calls the same thread endpoints `threadApiUrl` did. Everything else on this page is the field-by-field mapping behind those two factory calls.
+
+## Old → new at a glance
+
+| Legacy flat prop | New home | Notes |
+|------------------|----------|-------|
+| `apiUrl` | `fetchLLM({ url })` | The LLM endpoint moves into the factory's `url`. |
+| `streamProtocol` | `fetchLLM({ streamAdapter })` | String enum → a stream-adapter **factory call** (`openAIAdapter()`). |
+| `messageFormat` | `fetchLLM({ messageFormat })` *(and `restStorage({ messageFormat })`)* | String enum → a `MessageFormat` value (`openAIMessageFormat`). |
+| `processMessage` | `ChatLLM.send` | Custom send logic becomes a `send` implementation. `abortController` → the `signal` you receive. |
+| `threadApiUrl` | `restStorage({ baseUrl })` | The thread REST root moves into `restStorage`. |
+| `fetchThreadList` | `storage.thread.listThreads` | Now takes an optional cursor; returns `{ threads, nextCursor? }`. |
+| `createThread` | `storage.thread.createThread` | Receives the first `UserMessage`, returns the new `Thread`. |
+| `updateThread` | `storage.thread.updateThread` | Takes a full `Thread`, returns the updated `Thread`. |
+| `deleteThread` | `storage.thread.deleteThread` | Takes an id. |
+| `loadThread` | `storage.thread.getMessages` | Renamed; takes a `threadId`, returns `Message[]`. |
+| `appRenderers` | `artifactRenderers` | Prop rename; array of renderer configs. |
+| `defineAppRenderer` | `defineArtifactRenderer` | `kind` → `type`; `toolName` is `string \| string[]`; parser returns `{ props, meta }`. |
+| `useAppList` | `useArtifactList` | Hook rename; per-thread artifact registry. |
+| `Artifact*` panel APIs | `DetailedView*` | The in-thread panel hooks were renamed around "detailed view." |
+| legacy chat component | `AgentInterface` | Component rename, same package. |
+
+## LLM props → `llm`
+
+Four old props collapse into one `fetchLLM` call. Two things change beyond the renames:
+
+- **`streamProtocol` was a string; `streamAdapter` is a factory call.** Pick the adapter matching your provider's wire format and **call it** — `openAIAdapter()`, not the bare reference. The options are `agUIAdapter`, `openAIAdapter`, `openAIReadableStreamAdapter`, `openAIResponsesAdapter`, and `langGraphAdapter`.
+- **`messageFormat` was a string; it's now a value.** Use `openAIMessageFormat`, `openAIConversationMessageFormat` (the one that pairs with `openAIResponsesAdapter()`), `langGraphMessageFormat`, or `identityMessageFormat` (the default — the canonical `Message` array, unchanged).
+
+### `processMessage` → a custom `ChatLLM`
+
+If `processMessage` did something `fetchLLM` can't express — a non-`fetch` transport, a websocket, bespoke request shaping — implement the `ChatLLM` interface directly instead of calling `fetchLLM`.
+
+**Before** — `processMessage` received an `abortController`:
+
+```tsx
+<LegacyChat
+ streamProtocol="openai"
+ processMessage={async (messages, { abortController }) => {
+ return fetch("/api/chat", {
+ method: "POST",
+ body: JSON.stringify({ messages }),
+ signal: abortController.signal,
+ });
+ }}
+/>;
+```
+
+**After** — `send` receives the `signal` directly, and the parser moves onto the object as `streamProtocol`:
+
+```tsx
+import { AgentInterface, type ChatLLM, openAIAdapter } from "@openuidev/react-ui";
+
+const llm: ChatLLM = {
+ streamProtocol: openAIAdapter(),
+ async send({ threadId, messages, signal }) {
+ return fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ threadId, messages }),
+ signal, // was abortController.signal
+ });
+ },
+};
+
+<AgentInterface llm={llm} />;
+```
+
+The behavior change to internalize: **you no longer create or own an `AbortController`.** `AgentInterface` owns it and hands you the `signal` — wired to the UI's stop control — in every `send` call. Just forward it.
+
+## Thread props → `storage`
+
+`threadApiUrl` plus the per-operation callbacks become a single `ChatStorage` whose `thread` member holds five methods.
+
+### The REST case → `restStorage`
+
+If your old setup pointed `threadApiUrl` at a REST backend, the migration is one factory call:
+
+```tsx
+import { restStorage } from "@openuidev/react-ui";
+
+const storage = restStorage({ baseUrl: "/api/threads" }); // was threadApiUrl
+
+<AgentInterface llm={llm} storage={storage} />;
+```
+
+`restStorage` hits the exact endpoints the old `threadApiUrl` prop did — `GET {baseUrl}/get`, `POST {baseUrl}/create`, `GET {baseUrl}/get/{threadId}`, `PATCH {baseUrl}/update/{id}`, `DELETE {baseUrl}/delete/{id}` — so an existing backend keeps working. Pass `messageFormat` here too if your backend stores messages in a provider shape.
+
+<Callout type="info">If you pass no `storage` at all, `AgentInterface` uses an internal in-memory store — fine for prototyping, but wiped on reload.</Callout>
+
+### Custom thread callbacks → `storage.thread.*`
+
+If you supplied individual thread callbacks, each maps to a method on `storage.thread`:
+
+```tsx
+import { AgentInterface, type ChatStorage } from "@openuidev/react-ui";
+
+const storage: ChatStorage = {
+ thread: {
+ listThreads: fetchThreadList, // now takes an optional cursor, returns { threads, nextCursor? }
+ createThread, // receives the first UserMessage, returns the new Thread
+ getMessages: loadThread, // was loadThread — takes threadId, returns Message[]
+ updateThread, // takes a full Thread, returns the updated Thread
+ deleteThread, // takes an id
+ },
+};
+
+<AgentInterface llm={llm} storage={storage} />;
+```
+
+Two renames carry behavior changes: **`fetchThreadList` → `listThreads`** now takes an optional `cursor` and must return `{ threads, nextCursor? }` (cursor pagination for the sidebar's "load more"); **`loadThread` → `getMessages`** is the same job, just renamed for symmetry. If your callbacks already match these shapes, hand them over directly; otherwise wrap them.
+
+## Renderers: `appRenderers` → `artifactRenderers`
+
+The "app renderer" concept was renamed to **artifact renderer** throughout — the prop, the factory, and the parser contract all changed.
+
+```tsx
+import { AgentInterface, defineArtifactRenderer } from "@openuidev/react-ui";
+
+const codeArtifactRenderer = defineArtifactRenderer({
+ type: "code_artifact", // was kind
+ toolName: "create_code_artifact", // now string | string[]
+ parser: ({ args, response }, { isStreaming }) => {
+ const data = response as CodeArtifact | null;
+ if (!data) return null; // tolerate partial data while streaming
+ return {
+ props: data, // props AND meta now come from one return value
+ meta: isStreaming ? null : { id: `code:${data.title}`, version: 1, heading: data.title },
+ };
+ },
+ preview: (props, controls) => <CodeCard {...props} onOpen={controls.open} />,
+ actual: (props) => <CodeBlock language={props.language} codeString={props.code} />,
+});
+
+<AgentInterface llm={llm} artifactRenderers={[codeArtifactRenderer]} />;
+```
+
+The behavior changes inside the renderer:
+
+- **`kind` → `type`.** A literal string that links the renderer to its stored artifacts' `type`.
+- **`toolName` is now `string | string[]`.** Register one renderer for several tools by passing an array. Names are **literal only** — no RegExp. First registration wins on a duplicate `toolName`.
+- **The parser returns `{ props, meta }` (or `null`), not props alone.** `meta` is `{ id, version, heading } | null`: return the object to render *and* register the artifact in the thread (so it appears in the Workspace rail and artifact lists); return `null` for `meta` to render without registering (the common move while streaming). Returning `null` from the parser entirely skips rendering.
+- **The parser must tolerate partial data.** It's called on every stream update — `response` is `null` until the result lands, and `args` may be a partial JSON string. Guard accordingly.
+
+## Hooks and panel APIs
+
+`useAppList()` → **`useArtifactList(filter?)`**, imported from `@openuidev/react-ui`. It returns the per-thread artifact registry, optionally filtered by `type`:
+
+```tsx
+import { useArtifactList } from "@openuidev/react-ui";
+
+const artifacts = useArtifactList();
+const codeArtifacts = useArtifactList({ type: ["code_artifact"] });
+```
+
+The in-thread panel hooks that used to be named around "Artifact" are now named around **detailed view**: `useActiveDetailedView()`, `useDetailedView(viewId)`, `useDetailedViewStore()`, `useDetailedViewPortalTarget()`. If you reached into the old `Artifact*` panel hooks, swap to these.
+
+<Callout type="info">"Artifact" now consistently means the durable output (a dashboard, report, app); "detailed view" means the in-thread panel that shows one. The old "app" / "Artifact panel" naming conflated the two.</Callout>
+
+## Migration checklist
+
+1. Rename the legacy chat component → `AgentInterface` (same `@openuidev/react-ui` package).
+2. Build `llm = fetchLLM({ url, streamAdapter, messageFormat })` from your old `apiUrl` / `streamProtocol` / `messageFormat`. **Call** the adapter (`openAIAdapter()`).
+3. If you had a custom `processMessage`, implement `ChatLLM` directly and forward the `signal` — drop your own `AbortController`.
+4. Build `storage = restStorage({ baseUrl })` from `threadApiUrl`, **or** assemble `storage.thread.*` from your `fetchThreadList` (→ `listThreads`), `createThread`, `updateThread`, `deleteThread`, and `loadThread` (→ `getMessages`).
+5. Pass `llm` (required) and `storage` (optional) to `AgentInterface`.
+6. Rename `appRenderers` → `artifactRenderers` and `defineAppRenderer` → `defineArtifactRenderer`; change `kind` → `type`, allow `toolName` arrays, and return `{ props, meta }` from each parser.
+7. Rename `useAppList` → `useArtifactList` and any `Artifact*` panel hooks → `DetailedView*`.
+8. Delete every remaining flat backend prop — they're gone. If TypeScript flags an unknown prop, find it in the table above and move it into the right adapter.
+
+## Related
+
+<Cards>
+ <Card title="AgentInterface props" href="/docs/agent/reference/agentinterface-props">The presentation props that stay flat on the component.</Card>
+ <Card title="Adapters & formats" href="/docs/agent/reference/adapters-and-formats">Reference for `fetchLLM`, `restStorage`, stream adapters, and message formats.</Card>
+ <Card title="defineArtifactRenderer" href="/docs/agent/reference/define-artifact-renderer">The renderer config, parser contract, and `meta` shape.</Card>
+ <Card title="Conversations" href="/docs/agent/core-concepts/conversations">How `llm` and `storage` drive a thread end to end.</Card>
+ <Card title="Hooks" href="/docs/agent/reference/hooks">`useArtifactList`, the `DetailedView*` hooks, and more.</Card>
+</Cards>
diff --git a/docs/content/docs/agent/meta.json b/docs/content/docs/agent/meta.json
new file mode 100644
index 000000000..08d543204
--- /dev/null
+++ b/docs/content/docs/agent/meta.json
@@ -0,0 +1,29 @@
+{
+ "title": "Agent Interface",
+ "root": true,
+ "pages": [
+ "---Getting Started---",
+ "getting-started/introduction",
+ "getting-started/quickstart",
+ "getting-started/openui-cloud",
+ "---Core Concepts---",
+ "core-concepts/generative-ui",
+ "core-concepts/conversations",
+ "core-concepts/tools",
+ "core-concepts/artifacts",
+ "---Customize---",
+ "customize/welcome-and-starters",
+ "customize/sidebar",
+ "customize/message-rendering",
+ "---Reference---",
+ "reference/agentinterface-props",
+ "reference/adapters-and-formats",
+ "reference/define-artifact-renderer",
+ "reference/hooks",
+ "reference/components",
+ "reference/self-hosting",
+ "---Guides---",
+ "guides/custom-artifacts",
+ "guides/migrating"
+ ]
+}
diff --git a/docs/content/docs/agent/reference/adapters-and-formats.mdx b/docs/content/docs/agent/reference/adapters-and-formats.mdx
new file mode 100644
index 000000000..a1e47f4cb
--- /dev/null
+++ b/docs/content/docs/agent/reference/adapters-and-formats.mdx
@@ -0,0 +1,532 @@
+---
+title: Adapters & formats
+description: Complete reference for AgentInterface's backend channels — the ChatLLM/ChatStorage/ThreadStorage/ArtifactStorage interfaces, the fetchLLM and restStorage factories, the Thread type, the bundled stream adapters, and the message formats.
+---
+
+`AgentInterface` talks to your backend through two independent channels, each an *adapter* you supply:
+
+- **`llm`** — a `ChatLLM` that produces replies. **Required.**
+- **`storage`** — a `ChatStorage` that persists threads, messages, and (optionally) artifacts. Optional; defaults to an internal in-memory store that's wiped on reload.
+
+This page is the exhaustive reference for both channels, the factories that build them (`fetchLLM`, `restStorage`), the `Thread` record, the bundled **stream adapters** that parse provider wire formats, and the **message formats** that translate message shapes. For the task-oriented walkthroughs, see [Conversations](/docs/agent/core-concepts/conversations) and [Self-hosting](/docs/agent/reference/self-hosting).
+
+## Import sources
+
+Everything on this page imports from `@openuidev/react-ui`: `AgentInterface`, `useNav`, the `fetchLLM` and `restStorage` factories, the adapter and storage types, the stream adapters, and the message formats.
+
+```ts
+// Factories + types
+import {
+ fetchLLM,
+ restStorage,
+ type ChatLLM,
+ type ChatStorage,
+ type ThreadStorage,
+ type ArtifactStorage,
+ type Thread,
+ type MessageFormat,
+ type StreamProtocolAdapter,
+} from "@openuidev/react-ui";
+
+// Stream adapters + message formats
+import {
+ agUIAdapter,
+ openAIAdapter,
+ openAIReadableStreamAdapter,
+ openAIResponsesAdapter,
+ langGraphAdapter,
+ openAIMessageFormat,
+ openAIConversationMessageFormat,
+ langGraphMessageFormat,
+ identityMessageFormat,
+} from "@openuidev/react-ui";
+```
+
+<Callout type="warn">All five stream adapters are **factory functions** — always call them with `()`. `streamAdapter: openAIAdapter()` is correct; a bare `streamAdapter: openAIAdapter` is wrong.</Callout>
+
+## The two channels
+
+```tsx
+import { AgentInterface } from "@openuidev/react-ui";
+
+<AgentInterface
+ llm={chatLLM} // required — ChatLLM
+ storage={chatStorage} // optional — ChatStorage
+/>;
+```
+
+`llm` and `storage` are wholly separate. You can run a real LLM with ephemeral storage, or persistent storage with a placeholder LLM — they're configured and resolved independently.
+
+---
+
+## `ChatLLM`
+
+The object `AgentInterface` calls when the user sends a message.
+
+```ts
+interface ChatLLM {
+ send(params: {
+ threadId: string;
+ messages: Message[];
+ signal: AbortSignal;
+ }): Promise<Response>;
+ streamProtocol: StreamProtocolAdapter;
+}
+```
+
+- **`send`** receives the current `threadId`, the full `messages` array, and an `AbortSignal` wired to the UI's stop/cancel control. It returns a streaming `Response` (a standard `fetch` `Response` whose body is a readable stream).
+- **`streamProtocol`** is the [stream adapter](#stream-adapters) that parses the returned `Response` body into the canonical AG-UI events the UI renders (`TEXT_MESSAGE_*`, `TOOL_CALL_START` / `TOOL_CALL_ARGS` / `TOOL_CALL_END`, `TOOL_CALL_RESULT`, `RUN_ERROR`).
+
+Most apps never construct a `ChatLLM` by hand — `fetchLLM` builds one for the common "POST to my route, parse the stream" case. Implement the interface directly only when you need to call `send` in a way `fetchLLM` doesn't cover (e.g. a non-`fetch` transport).
+
+### `fetchLLM`
+
+Builds a `ChatLLM` that POSTs a JSON body to a URL and parses the streamed reply.
+
+```ts
+function fetchLLM(options: {
+ url: string;
+ streamAdapter: StreamProtocolAdapter;
+ messageFormat?: MessageFormat;
+ headers?: Record<string, string>;
+ fetch?: typeof fetch;
+}): ChatLLM;
+```
+
+| Option | Type | Required | What it does |
+|-----------------|----------------------------|----------|-----------------------------------------------------------------------------------------|
+| `url` | `string` | Yes | The endpoint `fetchLLM` POSTs to (your own route — never the provider directly). |
+| `streamAdapter` | `StreamProtocolAdapter` | Yes | Parses the streamed response into UI events. Becomes the `ChatLLM`'s `streamProtocol`. |
+| `messageFormat` | `MessageFormat` | No | Converts outgoing `messages` to your provider's shape. Defaults to `identityMessageFormat`. |
+| `headers` | `Record<string, string>` | No | Extra headers merged into every request (e.g. a session token). **Browser-visible.** |
+| `fetch` | `typeof fetch` | No | Override `fetch` (auth wrappers, instrumentation, tests). |
+
+**Request body.** `fetchLLM` POSTs JSON `{ threadId, messages }`, where `messages` is run through `messageFormat.toApi`, and threads the `AbortSignal` from the UI:
+
+```ts
+// Inside fetchLLM — shown for reference; you don't write this.
+fetch(url, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...headers },
+ body: JSON.stringify({ threadId, messages: messageFormat.toApi(messages) }),
+ signal, // wired to the UI's cancel/stop control
+});
+```
+
+Your route therefore always receives `{ threadId, messages }` and must return a streaming `Response`. `fetchLLM` runs that response through `streamAdapter`.
+
+```tsx
+import { fetchLLM, openAIReadableStreamAdapter, openAIMessageFormat } from "@openuidev/react-ui";
+
+const llm = fetchLLM({
+ url: "/api/chat",
+ streamAdapter: openAIReadableStreamAdapter(),
+ messageFormat: openAIMessageFormat,
+});
+```
+
+<Callout type="warn">`headers` are headers on the browser's request to *your* route. Use them for things like a session token or CSRF token — never a provider API key. The provider key lives only in your server-side route handler.</Callout>
+
+---
+
+## `ChatStorage`
+
+The persistence channel. A `ChatStorage` is an object with a required `thread` member and an optional `artifact` member:
+
+```ts
+interface ChatStorage {
+ thread: ThreadStorage;
+ artifact?: ArtifactStorage;
+}
+```
+
+- **`thread`** persists conversations — the thread list, message history, renames, and deletes.
+- **`artifact`** persists durable artifacts (dashboards, reports, presentations, apps) and powers the artifact browser. Optional and independent of `thread`. See [`ArtifactStorage`](#artifactstorage-optional) below and [Artifacts](/docs/agent/core-concepts/artifacts).
+
+Omit `storage` entirely and `AgentInterface` uses an internal in-memory store — fine for prototyping, but ephemeral.
+
+### `ThreadStorage`
+
+The five methods that back thread management. Implement these and the default sidebar's thread list, "New chat" button, thread switching, and deletion all operate against your backend.
+
+```ts
+interface ThreadStorage {
+ listThreads(cursor?: string): Promise<{ threads: Thread[]; nextCursor?: string }>;
+ createThread(firstMessage: UserMessage): Promise<Thread>;
+ getMessages(threadId: string): Promise<Message[]>;
+ updateThread(thread: Thread): Promise<Thread>;
+ deleteThread(id: string): Promise<void>;
+}
+```
+
+| Method | Returns | When `AgentInterface` calls it |
+|--------|---------|--------------------------------|
+| `listThreads(cursor?)` | `{ threads, nextCursor? }` | Populating the thread list; loading more when `nextCursor` exists and the user scrolls. |
+| `createThread(firstMessage)` | the new `Thread` | The user sends the first message of a new chat. |
+| `getMessages(threadId)` | `Message[]` | The user opens a thread. |
+| `updateThread(thread)` | the updated `Thread` | A thread changes (e.g. a rename). |
+| `deleteThread(id)` | `void` | The user deletes a thread. |
+
+Implement these directly when your storage doesn't fit the REST shape `restStorage` expects — a different route layout, GraphQL, or a client-side store like IndexedDB:
+
+```ts
+import type { ChatStorage } from "@openuidev/react-ui";
+
+export const storage: ChatStorage = {
+ thread: {
+ async listThreads(cursor) {
+ const res = await fetch(`/threads?cursor=${cursor ?? ""}`);
+ return res.json(); // { threads, nextCursor? }
+ },
+ async createThread(firstMessage) {
+ const res = await fetch("/threads", {
+ method: "POST",
+ body: JSON.stringify({ firstMessage }),
+ });
+ return res.json(); // a Thread
+ },
+ async getMessages(threadId) {
+ const res = await fetch(`/threads/${threadId}/messages`);
+ return res.json(); // Message[]
+ },
+ async updateThread(thread) {
+ const res = await fetch(`/threads/${thread.id}`, {
+ method: "PUT",
+ body: JSON.stringify(thread),
+ });
+ return res.json(); // the updated Thread
+ },
+ async deleteThread(id) {
+ await fetch(`/threads/${id}`, { method: "DELETE" });
+ },
+ },
+};
+```
+
+`restStorage` is itself just a `ChatStorage` built this way for the common REST case.
+
+### `Thread`
+
+The thread record at the storage boundary.
+
+```ts
+type Thread = {
+ id: string;
+ title: string;
+ createdAt: string | number;
+ isPending?: boolean;
+};
+```
+
+| Field | Type | Notes |
+|-------|------|-------|
+| `id` | `string` | Stable thread identifier. |
+| `title` | `string` | Shown in the sidebar thread list. |
+| `createdAt` | `string \| number` | ISO string or epoch — used for ordering/display. |
+| `isPending` | `boolean` (optional) | Marks a thread that's being created (e.g. optimistic insert before the create call resolves). |
+
+---
+
+## `restStorage`
+
+Builds a `ChatStorage` wired to a fixed set of REST endpoints under one `baseUrl`. The fastest path to durable history — you implement the endpoints, the factory does the wiring.
+
+```ts
+function restStorage(options: {
+ baseUrl: string;
+ messageFormat?: MessageFormat;
+ headers?: Record<string, string>;
+ fetch?: typeof fetch;
+}): ChatStorage;
+```
+
+| Option | Type | Required | What it does |
+|-----------------|----------------------------|----------|-------------------------------------------------------------------------------------------|
+| `baseUrl` | `string` | Yes | Root path for the endpoints below (e.g. `/api/threads`). |
+| `messageFormat` | `MessageFormat` | No | Converts messages to/from your stored shape. Defaults to `identityMessageFormat`. |
+| `headers` | `Record<string, string>` | No | Sent on every request (e.g. a tenant or session header). |
+| `fetch` | `typeof fetch` | No | Override `fetch` (auth, instrumentation, tests). |
+
+```tsx
+import { restStorage, openAIMessageFormat } from "@openuidev/react-ui";
+
+const storage = restStorage({
+ baseUrl: "/api/threads",
+ messageFormat: openAIMessageFormat, // optional
+ headers: { "x-tenant": "acme" }, // optional, sent on every request
+});
+```
+
+### Endpoint contract
+
+Each `ThreadStorage` operation maps to exactly one HTTP call under `baseUrl`. The paths are literal — these are the exact five endpoints you implement.
+
+| Operation | Method | Path | Request body | Response |
+|-----------|--------|------|--------------|----------|
+| List threads | `GET` | `{baseUrl}/get` — or `{baseUrl}/get?cursor={cursor}` when paginating | — | `{ threads: Thread[]; nextCursor?: string }` |
+| Create thread | `POST` | `{baseUrl}/create` | `{ messages: messageFormat.toApi([firstMessage]) }` | the new `Thread` |
+| Get messages | `GET` | `{baseUrl}/get/{threadId}` | — | `Message[]` (run through `messageFormat.fromApi`) |
+| Update thread | `PATCH` | `{baseUrl}/update/{thread.id}` | the `Thread` | the updated `Thread` |
+| Delete thread | `DELETE` | `{baseUrl}/delete/{id}` | — | — |
+
+With `baseUrl: "/api/threads"` the concrete paths are `/api/threads/get`, `/api/threads/create`, `/api/threads/get/{threadId}`, `/api/threads/update/{thread.id}`, and `/api/threads/delete/{id}`.
+
+### Message format application
+
+`messageFormat` applies at exactly two points:
+
+- **Create** — the request body's `messages` is `messageFormat.toApi([firstMessage])`.
+- **Get messages** — the `{baseUrl}/get/{threadId}` response is run through `messageFormat.fromApi` on the way back.
+
+With the default `identityMessageFormat`, messages cross the wire as the canonical `Message` type unchanged. Pass a provider-specific format (e.g. `openAIMessageFormat`) when your backend stores messages in that provider's shape.
+
+### Error behavior
+
+`restStorage` throws a **descriptive error on any non-`ok` response** (HTTP status outside 200–299). A failing endpoint surfaces clearly rather than being silently swallowed, so a misconfigured route or a backend error propagates to your error boundary instead of leaving the UI in a stuck state.
+
+---
+
+## `ArtifactStorage` (optional)
+
+The optional `artifact` member of `ChatStorage`. Configure it to store durable artifacts and enable the artifact browser. Summarized here for completeness — the task-oriented coverage is in [Artifacts](/docs/agent/core-concepts/artifacts).
+
+```ts
+interface ArtifactStorage {
+ list(params?: {
+ name?: string;
+ type?: string[];
+ cursor?: string;
+ limit?: number;
+ }): Promise<{ artifacts: ArtifactSummary[]; nextCursor?: string }>;
+ get(id: string): Promise<Artifact>;
+ update(patch: { id: string; content: unknown }): Promise<ArtifactSummary>;
+}
+
+interface ArtifactSummary {
+ id: string;
+ title: string;
+ type: string;
+ threadId: string; // required — every artifact belongs to a thread
+ updatedAt?: string | number;
+}
+
+interface Artifact extends ArtifactSummary {
+ content: unknown;
+}
+```
+
+- **`list`** — `name` and `type` filtering is **server-side**; the factory passes them through so your backend does the filtering. Paginated via `cursor` / `nextCursor`.
+- **`get`** — returns the full `Artifact`, including `content`.
+- **`update`** — persists an edit to an editable artifact's `content`; returns the updated summary.
+
+Attach it alongside `thread`:
+
+```ts
+const storage: ChatStorage = {
+ thread: threadStorage,
+ artifact: artifactStorage, // optional
+};
+```
+
+---
+
+## Stream adapters
+
+A **stream adapter** parses the streamed `Response` your route returns into the AG-UI events the UI renders. There is one per response *wire format*. It's a factory returning a `StreamProtocolAdapter`:
+
+```ts
+interface StreamProtocolAdapter {
+ parse(response: Response): AsyncIterable<AGUIEvent>;
+}
+```
+
+`fetchLLM` calls `parse` on the `Response` your route returns and consumes the yielded AG-UI events. All five bundled adapters are factories you call to get an instance — `agUIAdapter()`, `openAIAdapter()`, `openAIReadableStreamAdapter()`, `openAIResponsesAdapter()`, `langGraphAdapter()`; only `langGraphAdapter()` accepts options.
+
+<Callout type="info">A malformed line in the stream is logged to the console and skipped — it does not abort the whole stream. Provider-level failures should be surfaced as a `RUN_ERROR` event (the OpenAI Responses and LangGraph adapters do this for their error events).</Callout>
+
+### Selection guide
+
+Start from your provider and how the route streams its reply. The stream adapter and message format are independent knobs — pick the adapter to match how your backend *streams*, and the format to match how it represents *stored* messages — but they typically pair up as below.
+
+| Your backend streams… | Stream adapter | Pair with message format |
+|------------------------------------------------------------------------|---------------------------------|--------------------------------------|
+| OpenAI **Chat Completions** SSE (`data: {…}` lines) | `openAIAdapter()` | `openAIMessageFormat` |
+| OpenAI SDK `stream.toReadableStream()` (NDJSON, no `data:` prefix) | `openAIReadableStreamAdapter()` | `openAIMessageFormat` |
+| OpenAI **Responses / Conversations** API SSE | `openAIResponsesAdapter()` | `openAIConversationMessageFormat` |
+| **LangGraph** named-event SSE (`event: messages\ndata: …`) | `langGraphAdapter()` | `langGraphMessageFormat` |
+| Already AG-UI events (your route emits AG-UI SSE directly) | `agUIAdapter()` | `identityMessageFormat` (default) |
+
+Wrapping Anthropic, or any provider with no bundled adapter? You have two paths: translate to AG-UI events server-side and use `agUIAdapter()`, or re-emit your provider's stream as OpenAI Completions SSE and use `openAIAdapter()`. See [Migrating](/docs/agent/guides/migrating).
+
+### `agUIAdapter`
+
+```ts
+import { agUIAdapter } from "@openuidev/react-ui";
+
+const llm = fetchLLM({ url: "/api/chat", streamAdapter: agUIAdapter() });
+```
+
+- **Wire shape:** Server-Sent Events whose `data:` payload is already a serialized AG-UI event (`data: {"type":"TEXT_MESSAGE_CONTENT",…}`). `[DONE]` sentinels and blank lines are ignored.
+- **When to use:** Your route does the provider translation itself and emits AG-UI events directly. This is the lowest-overhead option when you control the backend — no per-provider parsing in the browser. It pairs naturally with `identityMessageFormat`, since both sides already speak AG-UI.
+
+### `openAIAdapter`
+
+```ts
+import { openAIAdapter } from "@openuidev/react-ui";
+
+const llm = fetchLLM({
+ url: "/api/chat",
+ streamAdapter: openAIAdapter(),
+ messageFormat: openAIMessageFormat,
+});
+```
+
+- **Wire shape:** OpenAI **Chat Completions** streaming SSE — the raw `data: {…}` chunk format from `chat.completions.create({ stream: true })` (each line is a `ChatCompletionChunk`).
+- **What it emits:** `TEXT_MESSAGE_START` on the first content/role delta, `TEXT_MESSAGE_CONTENT` per content delta, `TOOL_CALL_START` / `TOOL_CALL_ARGS` for streamed tool calls (indexed by `tool_calls[].index`), and end events driven by `finish_reason` (`stop` → `TEXT_MESSAGE_END`, `tool_calls` → `TOOL_CALL_END` for each open call).
+- **When to use:** Your route forwards the OpenAI Completions stream as-is (the most common OpenAI setup). Pair with `openAIMessageFormat`.
+
+### `openAIReadableStreamAdapter`
+
+```ts
+import { openAIReadableStreamAdapter } from "@openuidev/react-ui";
+
+const llm = fetchLLM({
+ url: "/api/chat",
+ streamAdapter: openAIReadableStreamAdapter(),
+ messageFormat: openAIMessageFormat,
+});
+```
+
+- **Wire shape:** **NDJSON** — one JSON object per line with no `data:` SSE prefix. This is exactly what the OpenAI SDK's `Stream.toReadableStream()` produces.
+- **When to use:** Your route returns `stream.toReadableStream()` from the OpenAI SDK directly, instead of re-serializing it as SSE. Same Completions chunk semantics as `openAIAdapter()` (same emitted events), only the line framing differs — it buffers partial lines across chunks rather than splitting on `data: `. Pair with `openAIMessageFormat`.
+
+<Callout type="info">`openAIAdapter()` and `openAIReadableStreamAdapter()` read the same OpenAI chunk objects — they differ only in framing (`data:` SSE vs. bare NDJSON lines). Match the one your route actually writes; using the wrong one will fail to parse every line.</Callout>
+
+### `openAIResponsesAdapter`
+
+```ts
+import { openAIResponsesAdapter } from "@openuidev/react-ui";
+
+const llm = fetchLLM({
+ url: "/api/chat",
+ streamAdapter: openAIResponsesAdapter(),
+ messageFormat: openAIConversationMessageFormat,
+});
+```
+
+- **Wire shape:** OpenAI **Responses API** (and Conversations API) streaming SSE — the item-based `ResponseStreamEvent` stream from `responses.create({ stream: true })`.
+- **What it handles:** `response.output_item.added` (assistant message start, `function_call` start, and server-side `function_call_output` → `TOOL_CALL_RESULT`), `response.output_text.delta` / `.done` for text, `response.function_call_arguments.delta` / `.done` for tool-call arguments (mapping `item_id` → `call_id`), and `error` / `response.failed` → `RUN_ERROR`. Lifecycle/metadata events (`response.created`, `response.completed`, etc.) are ignored.
+- **When to use:** You call the newer Responses or Conversations API rather than Chat Completions. Pair with `openAIConversationMessageFormat`.
+
+### `langGraphAdapter`
+
+```ts
+import { langGraphAdapter } from "@openuidev/react-ui";
+
+const llm = fetchLLM({
+ url: "/api/langgraph",
+ streamAdapter: langGraphAdapter({
+ onInterrupt: (payload) => {
+ // Called when a LangGraph __interrupt__ appears in an `updates` event.
+ console.log("interrupt", payload);
+ },
+ }),
+ messageFormat: langGraphMessageFormat,
+});
+```
+
+- **Wire shape:** LangGraph **named-event** SSE — `event: <type>\ndata: <json>\n\n` blocks, in the `messages` stream mode. Handles the `messages`, `metadata`, `updates`, `error`, and `end` event types; other event types (`values`, `debug`, `tasks`, `checkpoints`, `custom`) are ignored.
+- **What it handles:** AI message chunks → `TEXT_MESSAGE_*`; both streamed (`tool_call_chunks`) and complete (`tool_calls`) tool calls → `TOOL_CALL_*`; `error` events → `RUN_ERROR`. It closes out any open message/tool calls on the `end` event (or at stream end if no `end` arrives).
+- **Options** (`LangGraphAdapterOptions`):
+ - `onInterrupt?: (interrupt: unknown) => void` — invoked with the `__interrupt__` payload when a LangGraph interrupt surfaces in an `updates` event. This is the only adapter that takes options.
+- **When to use:** Your backend streams from a LangGraph deployment. Pair with `langGraphMessageFormat`.
+
+### AG-UI event vocabulary
+
+Every stream adapter normalizes its provider's stream into the same set of **AG-UI events** — the agent↔UI event protocol OpenUI streams internally (from the `@ag-ui/core` package). These events progressively build the assistant message as they arrive.
+
+| Event | Role |
+|-------|------|
+| `TEXT_MESSAGE_START` | Begins an assistant text message. |
+| `TEXT_MESSAGE_CONTENT` | Appends a chunk of text to the in-progress message. |
+| `TEXT_MESSAGE_END` | Closes the assistant text message. |
+| `TOOL_CALL_START` | Begins a tool call (carries the tool name / call id). |
+| `TOOL_CALL_ARGS` | Appends a chunk of the tool call's streamed arguments. |
+| `TOOL_CALL_END` | Closes the tool call's arguments. |
+| `TOOL_CALL_RESULT` | Carries the result of a server-executed tool call. |
+| `RUN_ERROR` | Signals a provider/run-level failure; surfaces as an error in the UI. |
+
+---
+
+## Message formats
+
+A **message format** converts between the canonical `Message` type at the boundary and your provider's message shape, in both directions. There is one per provider *message shape*:
+
+```ts
+interface MessageFormat {
+ /** Canonical Message[] → your provider's shape (outbound). */
+ toApi(messages: Message[]): unknown;
+ /** Your provider/storage shape → canonical Message[] (inbound). */
+ fromApi(data: unknown): Message[];
+}
+```
+
+Both methods operate on **arrays**, so formats where one canonical message maps to several provider items (e.g. the Responses API, where tool calls are sibling items of the assistant message) work the same as 1-to-1 formats.
+
+Where formats are used:
+
+- **`fetchLLM`** runs `messageFormat.toApi(messages)` on the outgoing request body. (The reply is parsed by the *stream adapter*, not the message format.)
+- **`restStorage`** uses `toApi` when creating a thread and `fromApi` when loading a thread's messages — so the same format keeps your stored history and your live requests consistent.
+
+If you omit `messageFormat`, both default to `identityMessageFormat`.
+
+### `identityMessageFormat` (default)
+
+```ts
+import { identityMessageFormat } from "@openuidev/react-ui";
+```
+
+- **Conversion:** none — messages pass through as-is in canonical AG-UI form (`toApi` returns the array unchanged; `fromApi` casts it back to `Message[]`).
+- **When to use:** Your backend already speaks the canonical `Message` shape. This is the default, so you can simply omit `messageFormat`. Natural partner for `agUIAdapter()`.
+
+### `openAIMessageFormat`
+
+```ts
+import { openAIMessageFormat } from "@openuidev/react-ui";
+```
+
+- **Shape:** OpenAI **Chat Completions** messages (`ChatCompletionMessageParam[]`). 1-to-1: each canonical message becomes exactly one Completions message and vice versa.
+- **Conversions:** strips/regenerates `id`; `toolCalls` ↔ `tool_calls`; `toolCallId` ↔ `tool_call_id`; multipart user `content` ↔ OpenAI content parts (binary parts become `image_url`). `reasoning`/`activity` messages have no Completions equivalent and map to an empty `system` message outbound.
+- **When to use:** Pair with `openAIAdapter()` or `openAIReadableStreamAdapter()`.
+
+### `openAIConversationMessageFormat`
+
+```ts
+import { openAIConversationMessageFormat } from "@openuidev/react-ui";
+```
+
+- **Shape:** OpenAI's item-based format for the **Responses API** and **Conversations API**. `toApi` returns `ResponseInputItem[]` (accepted by both `responses.create({ input })` and `conversations.items.create({ items })`); `fromApi` reads `ConversationItem[]` / `ResponseItem[]`.
+- **Conversions:** assistant messages are *flattened* into sibling items — a text `message` plus one `function_call` item per tool call; tool results become `function_call_output` items. Inbound, adjacent assistant `message` + `function_call` items are regrouped into one `AssistantMessage`, and Conversations-specific content parts (`reasoning_text`, `summary_text`, `refusal`, …) are folded into text.
+- **When to use:** Pair with `openAIResponsesAdapter()`.
+
+### `langGraphMessageFormat`
+
+```ts
+import { langGraphMessageFormat } from "@openuidev/react-ui";
+```
+
+- **Shape:** LangChain-style messages as used by LangGraph's thread-state API — discriminated by `type` (`"human"`, `"ai"`, `"tool"`, `"system"`) rather than `role`, with snake_case fields.
+- **Conversions:** `role` ↔ `type` (`user` ↔ `human`, `assistant` ↔ `ai`); tool-call `arguments` JSON string ↔ args object; `toolCallId` ↔ `tool_call_id`; missing `id` is generated inbound. (`developer` maps to `system`.)
+- **When to use:** Pair with `langGraphAdapter()`.
+
+---
+
+## Related
+
+<Cards>
+ <Card title="AgentInterface props" href="/docs/agent/reference/agentinterface-props">Where llm and storage are passed.</Card>
+ <Card title="Conversations" href="/docs/agent/core-concepts/conversations">How threads, messages, and persistence fit together.</Card>
+ <Card title="Artifacts" href="/docs/agent/core-concepts/artifacts">Persisting durable artifacts and the browser.</Card>
+ <Card title="Migrating" href="/docs/agent/guides/migrating">Choosing an adapter for a provider without a bundled one.</Card>
+ <Card title="Self-hosting" href="/docs/agent/reference/self-hosting">Implementing the adapters against your own backend.</Card>
+</Cards>
diff --git a/docs/content/docs/agent/reference/agentinterface-props.mdx b/docs/content/docs/agent/reference/agentinterface-props.mdx
new file mode 100644
index 000000000..2b2135a5c
--- /dev/null
+++ b/docs/content/docs/agent/reference/agentinterface-props.mdx
@@ -0,0 +1,183 @@
+---
+title: "<AgentInterface> props"
+description: Complete prop reference for AgentInterfaceProps — adapters, rendering, theme, branding, starters, routing, and children.
+---
+
+`AgentInterface` from `@openuidev/react-ui` is the only chat component you mount. It owns the full layout — sidebar, thread list, composer, routing, and the workspace rail — and you configure all of it through `AgentInterfaceProps`. This page is the complete prop reference, grouped by what each prop controls, with links to the relevant concept and how-to pages for each area.
+
+The only required prop is `llm`. Everything else is optional and falls back to a sensible default.
+
+## At a glance
+
+| Prop | Type | Required | Default |
+|-----------------------|---------------------------------------------------|----------|-------------------------------|
+| `llm` | `ChatLLM` | **Yes** | — |
+| `storage` | `ChatStorage` | No | internal in-memory (ephemeral)|
+| `artifactRenderers` | `ReadonlyArray<ArtifactRendererConfig<any>>` | No | none |
+| `artifactCategories` | `ArtifactCategory[]` | No | none (single "Artifacts" item)|
+| `componentLibrary` | `Library` | No | none (markdown rendering) |
+| `components` | `{ AssistantMessage?; UserMessage? }` | No | none |
+| `theme` | `ThemeProps` | No | built-in theme |
+| `disableThemeProvider`| `boolean` | No | `false` |
+| `logoUrl` | `string` | No | none |
+| `agentName` | `string` | No | none |
+| `starters` | `ConversationStarterProps[]` | No | none |
+| `starterVariant` | `"short" \| "long"` | No | — |
+| `path` | `string` | No | — (uncontrolled) |
+| `defaultPath` | `string` | No | thread view (`undefined`) |
+| `onNavigate` | `(next: string \| undefined) => void` | No | — (uncontrolled) |
+| `children` | `ReactNode` | No | none |
+
+The rest of this page explains each group.
+
+## Adapters
+
+These two props connect `AgentInterface` to your backend. They are independent channels: `llm` produces replies, `storage` persists threads and artifacts.
+
+| Prop | Type | Required | Default | Description |
+|-----------|---------------|----------|--------------------------------|------------------------------------------------------------------------|
+| `llm` | `ChatLLM` | **Yes** | — | Sends messages to your backend and streams the reply. |
+| `storage` | `ChatStorage` | No | internal in-memory (ephemeral) | Persists thread history (and, optionally, artifacts). |
+
+`llm` is a `ChatLLM` — usually built with `fetchLLM()`, which POSTs `{ threadId, messages }` to your route and parses the streamed response. See [Conversations](/docs/agent/core-concepts/conversations) for the model, and the [Adapters & formats reference](/docs/agent/reference/adapters-and-formats) for the full `ChatLLM` / `fetchLLM()` surface and the stream adapters that parse each provider's stream.
+
+`storage` is a `ChatStorage` — `{ thread: ThreadStorage; artifact?: ArtifactStorage }`. Omit it and conversations live only in memory: a page refresh clears everything. Build one with `restStorage()`, or implement the interfaces yourself. The full adapter interfaces (`ChatLLM`, `ChatStorage`, `ThreadStorage`, `ArtifactStorage`, `fetchLLM`, `restStorage`) are in the [Adapters & formats reference](/docs/agent/reference/adapters-and-formats).
+
+<Callout type="info">The provider API call always happens on your server. `fetchLLM()` only ever talks to your own route, so provider keys never reach the browser.</Callout>
+
+## Rendering
+
+These props control how the assistant's output is rendered — both durable artifacts (dashboards, reports, presentations, apps) and the inline message body.
+
+| Prop | Type | Required | Default | Description |
+|----------------------|-----------------------------------------------|----------|---------|-----------------------------------------------------------------------------|
+| `artifactRenderers` | `ReadonlyArray<ArtifactRendererConfig<any>>` | No | none | Renderers that display artifacts (from a tool call or from stored content). |
+| `artifactCategories` | `ArtifactCategory[]` | No | none | User-defined groupings for the artifact browser and workspace rail. |
+| `componentLibrary` | `Library` | No | none | Turns on Generative UI — rich interactive components rendered inline in chat.|
+| `components` | `{ AssistantMessage?; UserMessage? }` | No | none | Replace the assistant/user message components entirely. |
+
+### `artifactRenderers`
+
+Each entry is built with `defineArtifactRenderer` and links a tool name (or names) to a `preview` (inline in the message) and an `actual` (full view in the workspace panel or a full-page artifact view). The registry indexes by both `toolName` and `type`. See [Artifacts](/docs/agent/core-concepts/artifacts) and the [`defineArtifactRenderer` reference](/docs/agent/reference/define-artifact-renderer).
+
+```tsx
+import { AgentInterface, defineArtifactRenderer } from "@openuidev/react-ui";
+
+const codeArtifact = defineArtifactRenderer({
+ type: "code_artifact",
+ toolName: "create_code_artifact",
+ parser: (raw, ctx) => /* ... */ null,
+ preview: (props, controls) => /* ... */ null,
+ actual: (props, controls) => /* ... */ null,
+});
+
+<AgentInterface llm={llm} artifactRenderers={[codeArtifact]} />;
+```
+
+### `artifactCategories`
+
+Categories are **user-defined organization** for the artifact browser — they are orthogonal to whether an artifact is static or live. Each is `{ name: string; filter: { type: string[] } }`. Without categories, the sidebar shows a single "Artifacts" item; with them, one item per category. See [Artifacts](/docs/agent/core-concepts/artifacts).
+
+```tsx
+<AgentInterface
+ llm={llm}
+ storage={storage}
+ artifactCategories={[
+ { name: "Code", filter: { type: ["code_artifact"] } },
+ { name: "Reports", filter: { type: ["th_report"] } },
+ ]}
+/>;
+```
+
+### `componentLibrary`
+
+Pass a library (e.g. `openuiLibrary` from `@openuidev/react-ui/genui-lib`) to enable Generative UI: the LLM renders rich, interactive components **inline in chat messages**, beyond markdown. This is distinct from artifacts (durable outputs in panels and pages). See [Generative UI](/docs/agent/core-concepts/generative-ui).
+
+```tsx
+import { AgentInterface } from "@openuidev/react-ui";
+import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
+
+<AgentInterface llm={llm} componentLibrary={openuiLibrary} />;
+```
+
+### `components`
+
+Override the message components directly: `{ AssistantMessage?, UserMessage? }`. Message rendering precedence is **`components` > `componentLibrary` > built-in default** — an explicit `components` entry always wins. See [Message rendering](/docs/agent/customize/message-rendering).
+
+## Theme
+
+| Prop | Type | Required | Default | Description |
+|------------------------|--------------|----------|----------------|---------------------------------------------------------------------|
+| `theme` | `ThemeProps` | No | built-in theme | Customizes colors, radii, and typography. |
+| `disableThemeProvider` | `boolean` | No | `false` | Skip the built-in theme provider when your app already supplies one.|
+
+Set `disableThemeProvider` to `true` when `AgentInterface` is mounted inside an app that already wraps it in a compatible theme provider, to avoid nesting two.
+
+## Branding
+
+| Prop | Type | Required | Default | Description |
+|-------------|----------|----------|---------|----------------------------------------------------------|
+| `logoUrl` | `string` | No | none | Logo shown in the sidebar header and the mobile header. |
+| `agentName` | `string` | No | none | Agent name shown next to the logo. |
+
+These feed the default `SidebarHeader` and `MobileHeader`. To go further, replace those slots. See [Sidebar](/docs/agent/customize/sidebar).
+
+## Starters
+
+Conversation starters are the suggested prompts shown on the welcome screen and in the composer.
+
+| Prop | Type | Required | Default | Description |
+|------------------|-------------------------------|----------|---------|--------------------------------------------------------------|
+| `starters` | `ConversationStarterProps[]` | No | none | Suggested prompts to seed a conversation. |
+| `starterVariant` | `"short" \| "long"` | No | — | Layout variant for how starters are presented. |
+
+Each starter is `{ displayText: string; prompt: string; icon?: ReactNode }` — `displayText` is the label on the suggestion chip and `prompt` is the message sent when it is clicked. These props set the defaults for the `Welcome` and `Composer` slots; either slot can also take its own `starters` / `starterVariant`. See [Welcome & starters](/docs/agent/customize/welcome-and-starters).
+
+## Routing
+
+`AgentInterface` has a built-in router. `undefined` is the thread view; non-`undefined` paths select Routes and the artifact browser.
+
+| Prop | Type | Required | Default | Description |
+|---------------|----------------------------------------|----------|--------------------------|--------------------------------------------------------------|
+| `path` | `string` | No | — (uncontrolled) | Controlled current route. |
+| `defaultPath` | `string` | No | thread view (`undefined`)| Uncontrolled initial route. |
+| `onNavigate` | `(next: string \| undefined) => void` | No | — (uncontrolled) | Navigation callback; **its presence selects controlled mode**.|
+
+Controlled mode is chosen by the **presence of `onNavigate`**, not by `path !== undefined` — because `undefined` is a meaningful path (the thread view). In controlled mode, drive `path` from your own router and update it inside `onNavigate`. In uncontrolled mode, set an initial route with `defaultPath` and let the component manage navigation internally.
+
+Controlled consumers must round-trip the reserved artifact-browser paths (`artifacts/{category}` and `artifacts/{category}/{id}`), which are matched before your own `AgentInterface.Route` entries. Read the current route and navigate from anywhere inside the component with the `useNav()` hook (from `@openuidev/react-ui`).
+
+```tsx
+// Uncontrolled: open on a specific route at mount.
+<AgentInterface llm={llm} defaultPath="settings" />;
+
+// Controlled: drive the route from your own state/router.
+<AgentInterface llm={llm} path={path} onNavigate={setPath} />;
+```
+
+## Children
+
+| Prop | Type | Required | Default | Description |
+|------------|-------------|----------|---------|---------------------------------------------------|
+| `children` | `ReactNode` | No | none | Slots, primitives, Routes, and free content. |
+
+`children` is where composition happens. Pass the compound statics on `AgentInterface` — slots (`AgentInterface.Sidebar`, `.Welcome`, `.Composer`, `.Workspace`, …), primitives (`AgentInterface.SidebarItem`, `.ThreadList`, `.Messages`, …), and `AgentInterface.Route` for multi-page content. Slots not provided fall back to their built-in defaults. See the [Components reference](/docs/agent/reference/components).
+
+```tsx
+<AgentInterface llm={llm}>
+ <AgentInterface.Welcome
+ title="What can I help with?"
+ description="Ask about your data, generate a report, or build a dashboard."
+ />
+ <AgentInterface.Route path="settings">
+ <SettingsPanel />
+ </AgentInterface.Route>
+</AgentInterface>;
+```
+
+## Related references
+
+- [Adapters & formats](/docs/agent/reference/adapters-and-formats) — `ChatLLM`, `ChatStorage`, `ThreadStorage`, `ArtifactStorage`, `fetchLLM`, `restStorage`, the stream adapters, and the message formats used to build `llm` and `storage`.
+- [`defineArtifactRenderer`](/docs/agent/reference/define-artifact-renderer) — the shape of each `artifactRenderers` entry.
+- [Hooks](/docs/agent/reference/hooks) — `useNav`, `useThread`, `useArtifactStorage`, and the rest.
+- [Components](/docs/agent/reference/components) — the slots and primitives you pass as `children`.
diff --git a/docs/content/docs/agent/reference/components.mdx b/docs/content/docs/agent/reference/components.mdx
new file mode 100644
index 000000000..71b7c346a
--- /dev/null
+++ b/docs/content/docs/agent/reference/components.mdx
@@ -0,0 +1,346 @@
+---
+title: Components
+description: Reference for the slots and primitive statics on AgentInterface — Sidebar, ThreadHeader, Welcome, Composer, Workspace, SidebarItem, Route, and the rest.
+---
+
+Every customizable region of `AgentInterface` is exposed as a **compound static** — a component hung off `AgentInterface` (e.g. `AgentInterface.Welcome`, `AgentInterface.SidebarItem`). You compose the interface by placing these as children:
+
+```tsx
+import { AgentInterface } from "@openuidev/react-ui";
+
+<AgentInterface llm={llm}>
+ <AgentInterface.Welcome title="Ask me anything" />
+ <AgentInterface.Sidebar>
+ <AgentInterface.SidebarHeader />
+ <AgentInterface.SidebarItem path="settings" icon={<GearIcon />}>
+ Settings
+ </AgentInterface.SidebarItem>
+ <AgentInterface.SidebarSeparator />
+ <AgentInterface.ThreadList />
+ </AgentInterface.Sidebar>
+</AgentInterface>
+```
+
+There are two kinds:
+
+- **Slots** — named regions of the layout (`Sidebar`, `Welcome`, `Composer`, …). `AgentInterface` matches them **by component reference** (not by position or string), routes each into the right region, and treats anything unrecognized as free content. Order doesn't matter. Slots support a subset of three override modes:
+ - **A — omit:** the built-in default renders.
+ - **B — props:** the default structure renders with your values swapped into specific pieces.
+ - **C — children:** your children replace the region entirely (children win over props; a dev warning fires if you pass both).
+- **Primitives / statics** — building blocks you place *inside* slots (or, for `Route`, at the top level) to assemble custom layouts: `SidebarItem`, `SidebarContent`, `SidebarSeparator`, `ArtifactNav`, `Route`, `NewChatButton`, `ThreadList`, `Messages`, `MessageLoading`, `ScrollArea`.
+
+All of these are also reachable as named exports from `@openuidev/react-ui`, but the compound-static form (`AgentInterface.X`) is the documented usage.
+
+## Slots
+
+Pass these at the top level of `<AgentInterface>` to override a layout region. The **Modes** column lists which of the three override modes (A — omit, B — props, C — children) each slot supports.
+
+| Slot | Region | Modes |
+|------|--------|-------|
+| `AgentInterface.Sidebar` | The entire left sidebar | A, C |
+| `AgentInterface.SidebarHeader` | Header at the top of the sidebar | A, B, C |
+| `AgentInterface.MobileHeader` | Top bar shown on mobile in place of the sidebar | A, B, C |
+| `AgentInterface.ThreadHeader` | Header above the active conversation | A, C |
+| `AgentInterface.Welcome` | Empty-state screen shown before a thread starts | A, B, C |
+| `AgentInterface.Composer` | Message input at the bottom of the thread | A, B, C |
+| `AgentInterface.Workspace` | Per-thread right rail listing the thread's artifacts | A, C |
+
+### `AgentInterface.Sidebar`
+
+The whole left sidebar. **Modes A, C.**
+
+- **A — omit:** the default sidebar renders (`SidebarHeader` + `SidebarContent` containing `ArtifactNav` when `storage.artifact` is configured, a `SidebarSeparator`, and `ThreadList`).
+- **C — children:** your children replace the sidebar's inner content. You compose `SidebarHeader`, `SidebarItem`, `SidebarSeparator`, `ThreadList`, etc. as you like.
+
+```tsx
+<AgentInterface.Sidebar>
+ <AgentInterface.SidebarHeader />
+ <AgentInterface.SidebarContent>
+ <AgentInterface.SidebarItem path="dashboard">Dashboard</AgentInterface.SidebarItem>
+ <AgentInterface.SidebarSeparator />
+ <AgentInterface.ThreadList />
+ </AgentInterface.SidebarContent>
+</AgentInterface.Sidebar>
+```
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `children` | `ReactNode` | Mode C — replaces the sidebar's inner content. |
+
+<Callout type="info">
+When you provide `<AgentInterface.Sidebar>`, a `<AgentInterface.SidebarHeader>` placed at the **top level** (outside `Sidebar`) is ignored with a dev warning — put it inside `Sidebar`.
+</Callout>
+
+### `AgentInterface.SidebarHeader`
+
+The header strip at the top of the sidebar — brand logo, agent name, and the collapse button. **Modes A, B, C.**
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `logo` | `ReactNode` | Defaults to `logoUrl` from `<AgentInterface>`. |
+| `agentName` | `ReactNode` | Defaults to `agentName` from `<AgentInterface>`. |
+| `collapseButton` | `ReactNode \| false` | Pass `false` to hide the collapse control. |
+| `children` | `ReactNode` | Mode C — replaces the header body. |
+| `className` | `string` | |
+
+### `AgentInterface.MobileHeader`
+
+The top bar shown on mobile viewports in place of the (collapsed) sidebar. **Modes A, B, C.**
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `logo` | `ReactNode` | |
+| `agentName` | `ReactNode` | |
+| `menuButton` | `ReactNode \| false` | Opens the mobile sidebar drawer. Pass `false` to hide. |
+| `newChatButton` | `ReactNode \| false` | Pass `false` to hide. |
+| `actions` | `ReactNode` | Extra controls, right-aligned. |
+| `children` | `ReactNode` | Mode C — replaces the header. |
+| `className` | `string` | |
+
+### `AgentInterface.ThreadHeader`
+
+Header bar above the active conversation. **Modes A, C.**
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `children` | `ReactNode` | Mode C — replaces the header. |
+| `className` | `string` | |
+
+### `AgentInterface.Welcome`
+
+The empty-state screen shown before the first message of a thread. **Modes A, B, C.** As with every slot, `children` (mode C) win over the content props (mode B) and a dev warning fires if you pass both.
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `title` | `string` | Greeting/title text. |
+| `description` | `string` | Sub-text under the title. |
+| `image` | `{ url: string } \| ReactNode` | `{ url }` renders a styled 64×64 rounded `<img>`; a `ReactNode` is rendered as-is. |
+| `starters` | `ConversationStarterProps[]` | Conversation starters. Inherits from `<AgentInterface starters>` when omitted. |
+| `starterVariant` | `"short" \| "long"` | Layout for the starters. Inherits from `<AgentInterface starterVariant>`. |
+| `children` | `ReactNode` | Mode C — replaces the screen; when passed, `title`/`description`/`image`/`starters` are ignored (dev warning). |
+| `className` | `string` | |
+
+```tsx
+<AgentInterface.Welcome
+ title="Ask me anything"
+ description="I can pull reports, build dashboards, and answer questions."
+ image={{ url: "/logo.png" }}
+ starters={[{ displayText: "Summarize Q3 revenue", prompt: "Summarize Q3 revenue" }]}
+ starterVariant="short"
+/>
+```
+
+Each entry in `starters` is a `ConversationStarterProps`: `{ displayText: string; prompt: string; icon?: ReactNode }`. See [Welcome & starters](/docs/agent/customize/welcome-and-starters) for the full guide.
+
+### `AgentInterface.Composer`
+
+The message input at the bottom of the thread. **Modes A, B, C.**
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `placeholder` | `string` | Input placeholder. |
+| `starters` | `ConversationStarterProps[]` | Starter chips shown above the input when the chat is empty. Inherits from `<AgentInterface starters>`. |
+| `starterVariant` | `"short" \| "long"` | Inherits from `<AgentInterface starterVariant>`. |
+| `children` | `ReactNode` | Mode C — fully replaces the composer area; auto-starter rendering is then disabled. |
+| `className` | `string` | |
+
+### `AgentInterface.Workspace`
+
+The per-thread right rail listing the artifacts registered in the active thread. **Modes A, C.**
+
+- **Auto-shows on the first registered artifact** and renders nothing while the thread's registry is empty — drop-in users with no artifact renderers never see it.
+- Sections are driven by the `artifactCategories` configured on `<AgentInterface>`; a single "Artifacts" section lists everything when no categories are configured.
+- Clicking an item opens the corresponding artifact's detailed view.
+- Rendered **only in the thread view** — hidden on `Route` pages and the artifact browser. Hidden on mobile.
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `children` | `ReactNode` | Mode C — replaces the entire rail (you own its chrome and visibility). |
+| `className` | `string` | |
+
+See [Artifacts](/docs/agent/core-concepts/artifacts) for the artifact model the Workspace surfaces.
+
+## Primitives & statics
+
+Place these inside slots — or, for `Route`, at the top level — to build custom layouts. Unlike slots, primitives are not matched by reference into a region; they render wherever you put them.
+
+| Primitive | Role |
+|-----------|------|
+| `AgentInterface.SidebarContent` | Scrollable body region of the sidebar. |
+| `AgentInterface.SidebarSeparator` | Styled divider between sidebar groups. |
+| `AgentInterface.SidebarItem` | Clickable nav row, optionally path-bound. |
+| `AgentInterface.ArtifactNav` | Sidebar nav into the global artifact browser. |
+| `AgentInterface.Route` | Top-level exact-path view that replaces the thread region. |
+| `AgentInterface.NewChatButton` | Button that starts a fresh thread. |
+| `AgentInterface.ThreadList` | List of the user's threads from `storage.thread`. |
+| `AgentInterface.Messages` | The active thread's messages + streaming message. |
+| `AgentInterface.MessageLoading` | Default "assistant is thinking" indicator. |
+| `AgentInterface.ScrollArea` | Bottom-pinned scroll container for thread content. |
+
+### `AgentInterface.SidebarContent`
+
+The scrollable body region of the sidebar — where nav items and the thread list live. Place it inside `<AgentInterface.Sidebar>` to wrap your sidebar content.
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `children` | `ReactNode` | The content to render. |
+| `className` | `string` | |
+
+### `AgentInterface.SidebarSeparator`
+
+A styled divider rule for visually grouping sidebar sections. Takes no props; drop it between groups inside the sidebar.
+
+```tsx
+<AgentInterface.SidebarItem path="reports">Reports</AgentInterface.SidebarItem>
+<AgentInterface.SidebarSeparator />
+<AgentInterface.ThreadList />
+```
+
+### `AgentInterface.SidebarItem`
+
+A styled clickable row for use inside the sidebar. Visually matches `ThreadList` rows so custom nav blends in with the thread list. Spreads remaining props onto the underlying `<button>`.
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `icon` | `ReactNode` | Leading icon. |
+| `trailing` | `ReactNode` | Right-aligned trailing content (badges, counts). |
+| `path` | `string` | When set, clicking calls `navigate(path)`; the item auto-selects when the current path matches. Works in controlled and uncontrolled `<AgentInterface>`. |
+| `selected` | `boolean` | Active state. Defaults to `currentPath === path` when `path` is set; pass explicitly to override. |
+| `children` | `ReactNode` | The label. (Required.) |
+| `...buttonProps` | `ComponentPropsWithoutRef<"button">` | `onClick`, `disabled`, `aria-*`, etc. |
+
+**Click order with `path`:** your `onClick` fires first (call `preventDefault()` to suppress navigation) → then `navigate(path)` → then the mobile sidebar closes.
+
+```tsx
+<AgentInterface.SidebarItem
+ path="settings"
+ icon={<GearIcon />}
+ trailing={<Badge>3</Badge>}
+>
+ Settings
+</AgentInterface.SidebarItem>
+```
+
+Pair with [`AgentInterface.Route`](#agentinterfaceroute) to render a view at that path. See [Sidebar](/docs/agent/customize/sidebar).
+
+### `AgentInterface.ArtifactNav`
+
+Sidebar navigation for the global artifact browser. Renders one `SidebarItem` per configured `artifactCategories` entry — or a single "Artifacts" item when no categories are configured. Each item navigates to the reserved `artifacts/{category}` path, which `AgentInterface` renders as the searchable artifact browser in the thread region.
+
+- **Included automatically** in the default sidebar when `storage.artifact` is configured.
+- **Renders nothing** when `storage.artifact` is not configured.
+- When you build a custom `<AgentInterface.Sidebar>`, add it back manually where you want it.
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `icon` | `ReactNode` | Leading icon for every category item. Defaults to a boxes icon. |
+| `className` | `string` | |
+
+```tsx
+<AgentInterface.Sidebar>
+ <AgentInterface.SidebarHeader />
+ <AgentInterface.SidebarContent>
+ <AgentInterface.ArtifactNav />
+ <AgentInterface.SidebarSeparator />
+ <AgentInterface.ThreadList />
+ </AgentInterface.SidebarContent>
+</AgentInterface.Sidebar>
+```
+
+See [Artifacts](/docs/agent/core-concepts/artifacts).
+
+### `AgentInterface.Route`
+
+Declares a routable view. Placed at the **top level** of `<AgentInterface>` (not inside a slot). When the current nav path **exactly matches** `path`, the Route's children **replace the entire thread region** — `MobileHeader`, `ThreadHeader`, the message scroll area, and `Composer` are all hidden. When no Route matches, the thread region renders normally.
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `path` | `string` | Exact string match — **no wildcards or params**. |
+| `children` | `ReactNode` | Content shown in the thread region when active. |
+
+```tsx
+<AgentInterface llm={llm}>
+ <AgentInterface.SidebarItem path="settings">Settings</AgentInterface.SidebarItem>
+ <AgentInterface.Route path="settings">
+ <SettingsPanel />
+ </AgentInterface.Route>
+</AgentInterface>
+```
+
+Use multiple `<AgentInterface.Route>` siblings to define separate views. The paths `artifacts/{category}` and `artifacts/{category}/{id}` are reserved by the artifact browser and matched before your Routes.
+
+### `AgentInterface.NewChatButton`
+
+A styled button that starts a fresh thread (clears the active thread and returns to the empty/welcome state). Drop it anywhere inside the sidebar or a custom header.
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `className` | `string` | |
+
+```tsx
+<AgentInterface.SidebarHeader />
+<AgentInterface.NewChatButton />
+```
+
+### `AgentInterface.ThreadList`
+
+Renders the list of the user's threads from `storage.thread` (one row per thread). Clicking a row opens that thread and **auto-clears the current path** (returning to the thread view from any Route or the artifact browser).
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `className` | `string` | |
+
+```tsx
+<AgentInterface.SidebarContent>
+ <AgentInterface.ThreadList />
+</AgentInterface.SidebarContent>
+```
+
+### `AgentInterface.Messages`
+
+Renders the active thread's messages, including the in-flight streaming message and the loading indicator. Used inside a custom thread region (typically wrapped in `ScrollArea`).
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `loader` | `ReactNode` | Custom loading indicator shown while a response is pending. Defaults to `MessageLoading`. |
+| `assistantMessage` | component | Override for rendering assistant messages. Mirrors `components.AssistantMessage` on `<AgentInterface>`. |
+| `userMessage` | component | Override for rendering user messages. Mirrors `components.UserMessage`. |
+| `className` | `string` | |
+
+```tsx
+<AgentInterface.ScrollArea>
+ <AgentInterface.Messages loader={<MyLoader />} />
+</AgentInterface.ScrollArea>
+```
+
+For full control over per-message rendering, see [Message rendering](/docs/agent/customize/message-rendering).
+
+### `AgentInterface.MessageLoading`
+
+The default "assistant is thinking" indicator. Render it standalone, or pass it (or your own) to `Messages` via the `loader` prop. Takes no props.
+
+```tsx
+<AgentInterface.Messages loader={<AgentInterface.MessageLoading />} />
+```
+
+### `AgentInterface.ScrollArea`
+
+A scroll container that keeps the conversation pinned to the bottom as messages stream in. Wrap `Messages` (or any thread content) in it when composing a custom thread region.
+
+| Prop | Type | Notes |
+|------|------|-------|
+| `scrollVariant` | `ScrollVariant` | Controls the scroll-to-bottom behavior when the last message is added. |
+| `userMessageSelector` | `string` | CSS selector identifying the user message element (used to anchor scrolling). |
+| `children` | `ReactNode` | Scrollable content. |
+| `className` | `string` | |
+
+```tsx
+<AgentInterface.ScrollArea>
+ <AgentInterface.Messages />
+</AgentInterface.ScrollArea>
+```
+
+## See also
+
+- [Sidebar](/docs/agent/customize/sidebar) — building custom sidebars with `SidebarItem`, `ArtifactNav`, and `ThreadList`.
+- [`<AgentInterface>` props](/docs/agent/reference/agentinterface-props) — the top-level props (`logoUrl`, `agentName`, `starters`, `path`/`onNavigate`, …) that these components inherit from.
diff --git a/docs/content/docs/agent/reference/define-artifact-renderer.mdx b/docs/content/docs/agent/reference/define-artifact-renderer.mdx
new file mode 100644
index 000000000..3eb5e6b80
--- /dev/null
+++ b/docs/content/docs/agent/reference/define-artifact-renderer.mdx
@@ -0,0 +1,294 @@
+---
+title: defineArtifactRenderer
+description: Full reference for the artifact-renderer config — type, toolName, the parser contract, preview/actual, controls, and registry matching.
+---
+
+A **renderer** describes how one kind of artifact — a dashboard, a report, a slide deck, a code file — turns into UI: an inline preview inside the chat message and a full view in a side panel or page. You build one with `defineArtifactRenderer(config)` and pass the results to `<AgentInterface>` through the [`artifactRenderers`](/docs/agent/reference/agentinterface-props#artifactrenderers) prop.
+
+```tsx
+import { defineArtifactRenderer } from "@openuidev/react-ui";
+
+const codeArtifactRenderer = defineArtifactRenderer({
+ type: "code_artifact",
+ toolName: "create_code_artifact",
+ parser: ({ response }) => {
+ const data = response as CodeArtifact | null;
+ if (!data) return null;
+ return { props: data, meta: { id: `code:${data.title}`, version: 1, heading: data.title } };
+ },
+ preview: (props, controls) => <CodeCard title={props.title} onOpen={controls.open} />,
+ actual: (props) => <CodeBlock language={props.language} codeString={props.code} />,
+});
+```
+
+`defineArtifactRenderer` returns its argument unchanged. Its only job is type inference: it infers the `Props` type from the `parser`'s return value, so `preview` and `actual` receive a fully-typed `props` without you annotating anything by hand. (Without it you'd have to write `const r: ArtifactRendererConfig<CodeArtifact> = { ... }`.)
+
+For a walkthrough of building a renderer end to end, see [Custom artifacts](/docs/agent/guides/custom-artifacts). This page is the precise contract.
+
+## Config type
+
+```ts
+function defineArtifactRenderer<Props>(
+ config: ArtifactRendererConfig<Props>,
+): ArtifactRendererConfig<Props>;
+
+interface ArtifactRendererConfig<Props = unknown> {
+ type: string;
+ toolName: string | string[];
+ parser: (
+ raw: { args: unknown; response: unknown },
+ ctx: { isStreaming: boolean },
+ ) => ParsedArtifact<Props> | null;
+ preview: (props: Props, controls: ArtifactRendererControls) => ReactNode;
+ actual: (props: Props, controls: ArtifactRendererControls) => ReactNode;
+}
+
+interface ParsedArtifact<Props> {
+ props: Props;
+ meta: { id: string; version: number; heading: string } | null;
+}
+
+interface ArtifactRendererControls {
+ isActive: boolean;
+ isStreaming: boolean;
+ open: () => void;
+ close: () => void;
+ toggle: () => void;
+}
+```
+
+All five fields (`type`, `toolName`, `parser`, `preview`, `actual`) are required.
+
+| Field | Type | Purpose |
+| --- | --- | --- |
+| `type` | `string` | The artifact kind — the key for the storage path and for category filters. |
+| `toolName` | `string \| string[]` | The tool call(s) this renderer matches on the tool-call path. |
+| `parser` | `(raw, ctx) => ParsedArtifact \| null` | Converts the raw envelope into typed `props` plus an optional `meta` registry entry. |
+| `preview` | `(props, controls) => ReactNode` | The compact inline view rendered in the chat message. |
+| `actual` | `(props, controls) => ReactNode` | The full view rendered in the detailed-view panel or full-page browser. |
+
+## `type`
+
+```ts
+type: string;
+```
+
+The artifact kind — a literal string like `"code_artifact"` or `"code_block"`. It links three things together:
+
+- **this renderer**, for the storage path (the artifact browser looks up a renderer by `type`);
+- any [`artifactCategories`](/docs/agent/reference/agentinterface-props#artifactcategories) whose `filter.type` includes it;
+- **stored artifacts**, whose `ArtifactSummary.type` is matched against it.
+
+`type` is orthogonal to the static/live distinction — it is just an identifier you choose. On a duplicate `type` across renderers, the first registration wins (see [Registry behavior](#registry-behavior)).
+
+## `toolName`
+
+```ts
+toolName: string | string[];
+```
+
+The tool call(s) this renderer matches on the tool-call path. Literal strings only — **no `RegExp`, no wildcards, no patterns**. A single string matches one tool; an array registers the *same* renderer for several tool names (e.g. a create and an edit tool that both yield the same artifact):
+
+```ts
+toolName: ["presentation:create", "presentation:edit"],
+```
+
+On a duplicate `toolName` across renderers, the first registration wins.
+
+## `parser`
+
+```ts
+parser: (
+ raw: { args: unknown; response: unknown },
+ ctx: { isStreaming: boolean },
+) => { props: Props; meta: { id; version; heading } | null } | null;
+```
+
+The parser converts the raw envelope into typed `props` plus an optional `meta` registry entry. The SDK **does not pre-parse JSON** — `args` and `response` arrive exactly as the backend emitted them (typically a JSON *string* for `args`, the raw deserialized value for `response`, depending on your stream adapter). Your parser owns deserialization and validation.
+
+### Two invocation paths
+
+The same parser is called on both paths, with different inputs:
+
+| | `args` | `response` | `ctx.isStreaming` |
+| --- | --- | --- | --- |
+| **Tool-call path** (matched by `toolName`) | the call's arguments, as emitted | the tool result, or `null` until it arrives | `true` while args stream in; `false` once the result lands |
+| **Storage path** (matched by `type`) | `undefined` | `artifact.content` | always `false` |
+
+Concretely, the storage path always calls:
+
+```ts
+parser({ args: undefined, response: artifact.content }, { isStreaming: false });
+```
+
+Two consequences your parser must respect:
+
+1. **It is called on every update during streaming.** While `ctx.isStreaming` is `true`, `args` may be a *partial* JSON string (the LLM is still emitting it) and `response` may be `null` (the tool result hasn't paired in yet). Tolerate both — wrap JSON parsing in `try/catch`, and bail with `return null` until you have enough to render.
+2. **Read everything you need out of `response`, not `args`.** Only the tool-call path populates `args`, and only the storage path guarantees a complete `response`. Treat `args` as a streaming nicety (useful for an early preview) and `response` as the source of truth. To make one renderer work on both paths, ensure whatever your tool *returns* has the same shape as whatever you *persist* as `artifact.content`.
+
+### Return value
+
+| Return | Effect |
+| --- | --- |
+| `null` (outer) | Skip rendering this call entirely — no preview, no actual, no registry entry. |
+| `{ props, meta: { id, version, heading } }` | Render `preview`/`actual` with `props`, **and** register an entry in the per-thread ThreadContext. |
+| `{ props, meta: null }` | Render `preview`/`actual` with `props`, but do **not** register in ThreadContext. |
+
+`meta` controls the [per-thread artifact registry](/docs/agent/reference/hooks#useartifactlist) — the list backing `useArtifactList` and the [Workspace](/docs/agent/reference/components#agentinterfaceworkspace) rail:
+
+- **`meta.id`** — a stable identifier for this logical entry. It should not change across re-runs of the same artifact.
+- **`meta.version`** — bump it when the content changes. When the `(id, version)` pair changes, the entry is re-registered.
+- **`meta.heading`** — the display label shown in workspace/registry lists.
+
+A common pattern is to return `meta: null` while `ctx.isStreaming` is `true`, then a real `meta` once the result arrives — so the entry only appears in the registry after the artifact is complete:
+
+```ts
+parser: ({ args, response }, { isStreaming }) => {
+ const partial = safeParse(args); // tolerate partial JSON
+ if (!partial) return null; // not enough to draw yet
+ if (isStreaming || !response) {
+ return { props: partial, meta: null }; // render a skeleton, don't register
+ }
+ const data = response as CodeArtifact;
+ return { props: data, meta: { id: `code:${data.title}`, version: 1, heading: data.title } };
+},
+```
+
+## `preview`
+
+```ts
+preview: (props: Props, controls: ArtifactRendererControls) => ReactNode;
+```
+
+The compact view rendered **inline in the chat message** — typically a card or chip with a button that opens the full view via `controls.open()`. Receives the `props` your parser produced and the [`controls`](#controls).
+
+## `actual`
+
+```ts
+actual: (props: Props, controls: ArtifactRendererControls) => ReactNode;
+```
+
+The **full view** of the artifact. It renders in one of two places depending on how the artifact was opened:
+
+- the in-thread **detailed-view panel** (the side panel opened by `controls.open()`), or
+- the **full-page artifact view** in the artifact browser (`artifacts/{category}/{id}`).
+
+Same `props`, same `controls` signature as `preview`.
+
+## `controls`
+
+Both `preview` and `actual` receive a `controls` object:
+
+```ts
+interface ArtifactRendererControls {
+ isActive: boolean; // this renderer's detailed view is the currently active one
+ isStreaming: boolean; // true while the tool call is still streaming; always false for storage-opened artifacts
+ open: () => void; // activate this renderer's detailed view
+ close: () => void; // close this renderer's detailed view if active
+ toggle: () => void; // toggle this renderer's detailed view
+}
+```
+
+| Field | Meaning |
+| --- | --- |
+| `isActive` | `true` when this renderer's detailed view is the currently active one. Lets a preview reflect that its panel is already open (e.g. highlight the card). |
+| `isStreaming` | Mirrors the `ctx.isStreaming` your parser saw — `true` while arguments arrive incrementally and no tool result has paired in, then `false` once the result lands. Always `false` for storage-opened artifacts. |
+| `open` | Activate this renderer's detailed view. |
+| `close` | Close this renderer's detailed view if active. |
+| `toggle` | Toggle this renderer's detailed view. |
+
+The **same component instance is reused** across the streaming → completed transition (no remount), so you can swap UI states off `isStreaming` — a skeleton or "streaming…" badge during partial args, then the final view once the result lands.
+
+## Registry behavior
+
+Pass an array of configs to `<AgentInterface artifactRenderers={[...]}>`. The interface builds a registry once at mount and indexes each renderer **two ways**:
+
+- **by `toolName`** — used on the tool-call path. A renderer with an array of tool names is indexed once per name.
+- **by `type`** — used on the storage path (the artifact browser rendering stored artifacts).
+
+```tsx
+<AgentInterface
+ llm={llm}
+ artifactRenderers={[codeArtifactRenderer, presentationRenderer, codeBlockRenderer]}
+/>
+```
+
+**First-wins on duplicates.** If two renderers register the same `toolName`, the first one in the array wins and the later one is ignored (with a dev-mode `console.warn`). The same rule applies independently to `type`. Because the rules are independent, a renderer whose `type` collides with an earlier one is still indexed under its own (non-colliding) `toolName`s — only the type-based lookup is deduped. **Put your custom renderers before any SDK defaults** so yours win.
+
+<Callout type="warn">
+The registry is built once and stays stable for the provider's lifetime; later changes to the `artifactRenderers` prop are ignored (with a dev-mode warning). Pass a stable array — don't construct a fresh `artifactRenderers` value on every render expecting it to swap renderers in.
+</Callout>
+
+### Looking renderers up at runtime
+
+Resolve the matched renderer for a tool name with [`useArtifactRenderer`](/docs/agent/reference/hooks#useartifactrenderer):
+
+```ts
+import { useArtifactRenderer } from "@openuidev/react-ui";
+
+const renderer = useArtifactRenderer("create_code_artifact"); // ArtifactRendererConfig | null
+```
+
+It returns `null` on a miss (and when no `artifactRenderers` were provided). This is the normal way to resolve a renderer.
+
+#### Advanced: the raw registry
+
+For custom dispatching — when you need to iterate every registered renderer, or do your own matching rather than looking up a single tool name — [`useArtifactRendererRegistry`](/docs/agent/reference/hooks#useartifactrendererregistry) is the escape hatch. It returns the whole `ArtifactRendererRegistry` (or `null` when no `artifactRenderers` were provided):
+
+```ts
+import { useArtifactRendererRegistry } from "@openuidev/react-ui";
+
+const registry = useArtifactRendererRegistry();
+// registry: { byToolName: Map<string, ArtifactRendererConfig>;
+// byType: Map<string, ArtifactRendererConfig> } | null
+```
+
+The two indexes mirror the [two-way indexing](#registry-behavior) above: `byToolName` is keyed on every registered tool name (a renderer with an array of tool names appears once per name) and `byType` is keyed on each renderer's `type`. The `lookupArtifactRenderer` (by tool name) and `lookupArtifactRendererByType` (by type) helpers do a single lookup against a registry object directly, without a hook. Reach for the registry only when the single-tool `useArtifactRenderer` lookup isn't enough.
+
+## Full example
+
+```tsx
+import { defineArtifactRenderer } from "@openuidev/react-ui";
+
+type CodeBlockProps = { language: string; title: string; codeString: string };
+
+const isCodeBlockProps = (v: unknown): v is CodeBlockProps =>
+ !!v &&
+ typeof v === "object" &&
+ typeof (v as CodeBlockProps).language === "string" &&
+ typeof (v as CodeBlockProps).title === "string" &&
+ typeof (v as CodeBlockProps).codeString === "string";
+
+export const codeBlockRenderer = defineArtifactRenderer({
+ type: "code_block",
+ toolName: "create_code_block",
+
+ parser: ({ args }) => {
+ if (typeof args !== "string") return null; // tolerate non-string / partial args
+ try {
+ const parsed = JSON.parse(args);
+ if (!isCodeBlockProps(parsed)) return null;
+ return {
+ props: parsed,
+ meta: { id: parsed.title, version: 1, heading: parsed.title },
+ };
+ } catch {
+ return null; // partial JSON mid-stream
+ }
+ },
+
+ preview: (props, { open, isActive }) => (
+ <InlinePreview {...props} open={open} isActive={isActive} />
+ ),
+
+ actual: (props) => <ArtifactView {...props} />,
+});
+```
+
+## See also
+
+- [Custom artifacts](/docs/agent/guides/custom-artifacts) — the build-it walkthrough, including the storage path and `artifactCategories`.
+- [Artifacts](/docs/agent/core-concepts/artifacts) — what artifacts are and where they show up.
+- [Hooks](/docs/agent/reference/hooks) — `useArtifactRenderer`, `useArtifactRendererRegistry`, `useArtifactList`.
+- [`<AgentInterface>` props](/docs/agent/reference/agentinterface-props) — `artifactRenderers`, `artifactCategories`.
+- [Components](/docs/agent/reference/components#agentinterfaceworkspace) — the Workspace rail backed by the registry.
diff --git a/docs/content/docs/agent/reference/hooks.mdx b/docs/content/docs/agent/reference/hooks.mdx
new file mode 100644
index 000000000..f44fe5dca
--- /dev/null
+++ b/docs/content/docs/agent/reference/hooks.mdx
@@ -0,0 +1,313 @@
+---
+title: Hooks
+description: Reference for every AgentInterface hook — navigation, artifact storage and registry, threads and messages, and the detailed-view system.
+---
+
+These hooks let your own components read and drive the state inside `<AgentInterface>` — the current route, the artifact storage adapter, the per-thread artifact registry, the active thread and message, and the detailed-view panel system. They're the same hooks the built-in UI uses, so anything the default chrome does, your components can do too.
+
+Two rules apply to **all** of them:
+
+- **They only work inside `<AgentInterface>`.** Each reads from a context that the component provides. Call one outside that tree and you get either a thrown error or a `null`/empty result (noted per hook below). Renderer `preview`/`actual` functions, slot children, message components, and `Route` children are all inside the tree, so all of these are valid call sites.
+- **Import from `@openuidev/react-ui`.** Every hook on this page is exported from `@openuidev/react-ui`.
+
+```tsx
+import {
+ useNav,
+ useArtifactStorage,
+ useArtifactCategories,
+ useArtifactList,
+ useArtifactRenderer,
+ useArtifactRendererRegistry,
+ useThread,
+ useThreadList,
+ useMessage,
+ useActiveDetailedView,
+ useDetailedView,
+ useDetailedViewStore,
+ useDetailedViewPortalTarget,
+ useThreadContextStore,
+} from "@openuidev/react-ui";
+```
+
+---
+
+## Navigation
+
+### `useNav`
+
+```ts
+function useNav(): {
+ path: string | undefined;
+ navigate: (next: string | undefined) => void;
+};
+```
+
+**Imported from `@openuidev/react-ui`.** Reads the current route and lets you change it. `path` is the current route string (or `undefined`, which means the thread view). `navigate(next)` moves to a route; `navigate(undefined)` returns to the thread view.
+
+In controlled mode (when you pass `onNavigate` to `AgentInterface`), `navigate` ultimately calls back through your `onNavigate` handler — the hook respects whichever mode the component is in. **Throws if called outside `<AgentInterface>`.**
+
+```tsx
+function GoToSettings() {
+ const { path, navigate } = useNav();
+ return <button onClick={() => navigate("settings")}>Settings</button>;
+}
+```
+
+Reserved `artifacts/…` paths are matched before your own Routes.
+
+---
+
+## Artifact storage & registry
+
+These cover the two distinct artifact surfaces: the **storage adapter** (the global, cross-thread browser backed by `storage.artifact`) and the **per-thread registry** (the artifacts a renderer registered while rendering the current thread). See [Artifacts](/docs/agent/core-concepts/artifacts) for how the two relate.
+
+### `useArtifactStorage`
+
+```ts
+function useArtifactStorage(): ArtifactStorage | null;
+```
+
+Returns the `ArtifactStorage` adapter you configured via `storage.artifact`, or `null` when no artifact storage is configured. Use it to `list`/`get`/`update` artifacts from your own components — most commonly to **save an edited artifact** from a renderer's `actual` view. Always guard for `null` before calling.
+
+```tsx
+function SaveButton({ id, content }: { id: string; content: unknown }) {
+ const storage = useArtifactStorage();
+ if (!storage) return null;
+ return <button onClick={() => storage.update({ id, content })}>Save</button>;
+}
+```
+
+For the full `ArtifactStorage` shape see [Adapters & formats](/docs/agent/reference/adapters-and-formats).
+
+### `useArtifactCategories`
+
+```ts
+function useArtifactCategories(): ArtifactCategory[];
+```
+
+Returns the `artifactCategories` you passed to `AgentInterface` (each `{ name, filter: { type: string[] } }`), or an empty array if you passed none. Use it to render your own category-aware UI — a custom artifact nav, a filtered picker, grouping logic — instead of relying on the built-in `ArtifactNav`.
+
+```tsx
+function CategoryTabs() {
+ const categories = useArtifactCategories();
+ return categories.map((c) => <Tab key={c.name}>{c.name}</Tab>);
+}
+```
+
+### `useArtifactList`
+
+```ts
+function useArtifactList(filter?: { type?: string[] }): Record<
+ string,
+ ArtifactEntry[]
+>;
+// ArtifactEntry = { id: string; version: number; heading: string; type: string }
+```
+
+Returns the **per-thread artifact registry** — the artifacts a renderer registered while rendering the *current* thread, keyed for grouping (the same data that powers the per-thread Workspace rail). Pass `filter.type` to limit to specific artifact types. This is the in-thread registry, **not** the global storage browser — it reflects what the open conversation produced and works even with ephemeral storage.
+
+```tsx
+function ThreadArtifacts() {
+ const groups = useArtifactList({ type: ["code_artifact"] });
+ return Object.values(groups)
+ .flat()
+ .map((a) => <li key={a.id}>{a.heading}</li>);
+}
+```
+
+### `useArtifactRenderer`
+
+```ts
+function useArtifactRenderer(toolName: string): ArtifactRendererConfig | null;
+```
+
+Looks up a registered artifact renderer by its `toolName`, or `null` if none is registered for that name. Use it when you need to reach a renderer's config directly — for example, to render an artifact's `preview`/`actual` in a custom surface outside the default flow.
+
+```tsx
+// `controls` is the same { isActive, isStreaming, open, close, toggle }
+// object the framework passes to a renderer's preview/actual.
+function CustomPreview({ toolName, props, controls }) {
+ const renderer = useArtifactRenderer(toolName);
+ if (!renderer) return null;
+ return renderer.preview(props, controls);
+}
+```
+
+The registry indexes renderers by both `toolName` and `type`; see [defineArtifactRenderer](/docs/agent/reference/define-artifact-renderer).
+
+### `useArtifactRendererRegistry`
+
+```ts
+function useArtifactRendererRegistry(): ArtifactRendererRegistry | null;
+// ArtifactRendererRegistry = {
+// byToolName: Map<string, ArtifactRendererConfig>;
+// byType: Map<string, ArtifactRendererConfig>;
+// }
+```
+
+An **advanced escape hatch** that returns the whole renderer registry, indexed both by `toolName` and by artifact `type`, or `null` when none is configured. Normal lookups should use `useArtifactRenderer(toolName)` above — reach for the registry only when you need custom dispatching (for example, resolving a renderer by `type` rather than by `toolName`). The standalone helpers `lookupArtifactRenderer` and `lookupArtifactRendererByType` resolve a single config against the same registry.
+
+```tsx
+function RendererByType({ type }: { type: string }) {
+ const registry = useArtifactRendererRegistry();
+ const renderer = registry?.byType.get(type);
+ if (!renderer) return null;
+ return <span>{renderer.toolName}</span>;
+}
+```
+
+---
+
+## Threads & messages
+
+### `useThread`
+
+```ts
+function useThread<T>(selector: (state: ThreadState) => T): T;
+```
+
+A selector hook scoped to the **current thread** inside `<AgentInterface>`. Pass a function that picks the slice you need; the component only re-renders when that slice changes. The thread state exposes the running state — most notably `isRunning` (a reply is in flight) — along with a way to cancel the in-flight message. Select narrowly.
+
+```tsx
+function StopButton() {
+ const isRunning = useThread((s) => s.isRunning);
+ const cancelMessage = useThread((s) => s.cancelMessage);
+ if (!isRunning) return null;
+ return <button onClick={cancelMessage}>Stop</button>;
+}
+```
+
+See [Conversations](/docs/agent/core-concepts/conversations) for the run lifecycle, `isRunning`, and cancellation.
+
+### `useThreadList`
+
+```ts
+function useThreadList<T>(selector: (state: ThreadListState) => T): T;
+```
+
+A selector hook for the **list of threads** (the data behind `AgentInterface.ThreadList`) — loaded threads, pending state, and the actions for creating, selecting, and deleting threads. Like `useThread`, pass a selector so you only re-render on the slice you read. Use it to build a custom thread switcher or sidebar.
+
+```tsx
+function ThreadCount() {
+ const count = useThreadList((s) => s.threads.length);
+ return <span>{count} chats</span>;
+}
+```
+
+### `useMessage`
+
+```ts
+function useMessage(): Message;
+```
+
+Returns the canonical `Message` for the **current message row** — the same hook the built-in message renderer uses, so you never thread the message through props. Because it returns the live message, your component re-renders as the reply streams in (`content` grows token by token). **Throws if called outside a message component** — it only works inside the components you pass via the `components` prop or inside `AgentInterface.Messages`.
+
+```tsx
+function AssistantMessage() {
+ const message = useMessage();
+ return <div className="bubble">{message.content}</div>;
+}
+```
+
+See [Message rendering](/docs/agent/customize/message-rendering) for custom message components.
+
+---
+
+## Detailed views
+
+The **detailed view** is the in-thread panel that opens when a user expands an artifact (the renderer's `actual` rendered in a side panel rather than inline). These hooks drive that system — they're for advanced custom surfaces; most apps never touch them directly because the renderer `controls` (`open`/`close`/`toggle`) and the Workspace rail handle the common cases.
+
+### `useActiveDetailedView`
+
+```ts
+function useActiveDetailedView(): /* the currently open detailed view, or null */;
+```
+
+Returns the detailed view that's currently open, or a null/empty value when none is open. Use it to react to whichever view is active — e.g. a header that reflects the open artifact.
+
+```tsx
+const active = useActiveDetailedView();
+```
+
+### `useDetailedView`
+
+```ts
+function useDetailedView(viewId: string): /* the detailed view for that id */;
+```
+
+Looks up a specific detailed view by its id. Use it when you hold a known view id and need its state.
+
+```tsx
+const view = useDetailedView(viewId);
+```
+
+### `useDetailedViewStore`
+
+```ts
+function useDetailedViewStore(): /* the detailed-view store */;
+```
+
+Returns the underlying store backing the detailed-view system — the registry of views plus the actions to open and close them. Use it to drive the panel programmatically from a custom surface.
+
+```tsx
+const store = useDetailedViewStore();
+```
+
+### `useDetailedViewPortalTarget`
+
+```ts
+function useDetailedViewPortalTarget(): /* the portal mount target */;
+```
+
+Returns the DOM target the detailed-view panel portals into. Use it when you render custom panel content that must mount into the same target as the built-in detailed view.
+
+```tsx
+const target = useDetailedViewPortalTarget();
+```
+
+### `useThreadContextStore`
+
+```ts
+function useThreadContextStore(): /* the thread-context store */;
+```
+
+Returns the store holding the **thread context** — the per-thread registry of artifacts a renderer registered (via its `parser` returning non-null `meta`). This is the source the Workspace rail and `useArtifactList` read from. Use it directly only when you need lower-level access than `useArtifactList` provides.
+
+```tsx
+const ctx = useThreadContextStore();
+```
+
+<Callout type="info">The exact return shapes of the detailed-view hooks and `useThreadContextStore` are internal store/view objects. For the common cases — opening the full view, listing a thread's artifacts — prefer the renderer `controls` ([defineArtifactRenderer](/docs/agent/reference/define-artifact-renderer)) and `useArtifactList` over reaching into these stores.</Callout>
+
+---
+
+## Where each hook can be called
+
+| Hook | Call site | Outside `<AgentInterface>` |
+|------|-----------|----------------------------|
+| `useNav` | anywhere in the tree | throws |
+| `useArtifactStorage` | anywhere in the tree | returns `null` |
+| `useArtifactCategories` | anywhere in the tree | empty array |
+| `useArtifactList` | inside a thread | empty / per-thread |
+| `useArtifactRenderer` | anywhere in the tree | `null` |
+| `useArtifactRendererRegistry` | anywhere in the tree | `null` |
+| `useThread` | inside a thread | n/a |
+| `useThreadList` | anywhere in the tree | n/a |
+| `useMessage` | inside a message component only | throws |
+| `useActiveDetailedView` · `useDetailedView` · `useDetailedViewStore` · `useDetailedViewPortalTarget` | inside a thread | n/a |
+| `useThreadContextStore` | inside a thread | n/a |
+
+<Cards>
+ <Card title="<AgentInterface> props" href="/docs/agent/reference/agentinterface-props">
+ Every prop AgentInterface accepts.
+ </Card>
+ <Card title="Adapters & formats" href="/docs/agent/reference/adapters-and-formats">
+ The storage and LLM adapter shapes hooks read from.
+ </Card>
+ <Card title="defineArtifactRenderer" href="/docs/agent/reference/define-artifact-renderer">
+ Register renderers and their preview/actual controls.
+ </Card>
+ <Card title="Components" href="/docs/agent/reference/components">
+ The composable subcomponents of AgentInterface.
+ </Card>
+</Cards>
diff --git a/docs/content/docs/agent/reference/self-hosting.mdx b/docs/content/docs/agent/reference/self-hosting.mdx
new file mode 100644
index 000000000..469143c10
--- /dev/null
+++ b/docs/content/docs/agent/reference/self-hosting.mdx
@@ -0,0 +1,509 @@
+---
+title: Self-hosting
+description: Run your own backend instead of OpenUI Cloud — connect your LLM with a streaming route, persist threads and artifacts against your own storage, on any server framework.
+---
+
+OpenUI Cloud handles the backend for you: the provider call, streaming, conversation history, and artifact storage all run behind a single managed endpoint, and `<AgentInterface>` just points at it (see [OpenUI Cloud](/docs/agent/getting-started/openui-cloud)). This page is for the **self-hosted** variant — you run the backend yourself, against your own provider keys, database, and server framework.
+
+Everything `<AgentInterface>` needs from a backend flows through two independent interfaces:
+
+- **`llm`** — a `ChatLLM` that produces replies. The browser-side [`fetchLLM`](/docs/agent/reference/adapters-and-formats) factory builds one for you.
+- **`storage`** — a `ChatStorage` that persists threads (and optionally artifacts). The [`restStorage`](/docs/agent/reference/adapters-and-formats) factory builds one for you.
+
+They are configured separately. You can run a real `llm` with ephemeral (in-memory) storage, or persistent storage with a placeholder `llm`. For the full type signatures of every interface and factory named here, see [Adapters & formats](/docs/agent/reference/adapters-and-formats); this page is the worked-example home for wiring them against your own backend.
+
+<Callout type="info">The provider key **always** lives server-side. `fetchLLM` only ever talks to your own origin (e.g. `/api/chat`), never directly to `api.openai.com`. The key is read from `process.env` inside your route and is never bundled into the browser.</Callout>
+
+## 1. Connect your LLM
+
+The `llm` channel is two halves of one loop:
+
+- **Browser half** — `fetchLLM({ url, streamAdapter, messageFormat })` POSTs `{ threadId, messages }` to your route and parses the streamed reply.
+- **Server half** — a route handler that receives `{ threadId, messages }`, calls your provider with streaming on, and returns the stream.
+
+```tsx
+import { AgentInterface, fetchLLM, openAIReadableStreamAdapter, openAIMessageFormat } from "@openuidev/react-ui";
+
+const llm = fetchLLM({
+ url: "/api/chat", // your route handler
+ streamAdapter: openAIReadableStreamAdapter(), // how to parse the streamed response
+ messageFormat: openAIMessageFormat, // how to shape outgoing messages
+});
+
+export default function App() {
+ return <AgentInterface llm={llm} agentName="Acme Assistant" />;
+}
+```
+
+Your route always receives a JSON body of `{ threadId, messages }` and returns a streaming `Response`. `fetchLLM` runs that response through `streamAdapter` to turn the bytes into the AG-UI events the UI renders.
+
+`threadId` is in the body so your route can scope context, log, or attach per-thread state. The minimal route can ignore it.
+
+### Choosing `streamAdapter` and `messageFormat`
+
+`streamAdapter` governs the **response** (how the streamed bytes are decoded); `messageFormat` governs the **request** (how outgoing `messages` are shaped). They are chosen independently but pair up by provider. Each adapter is a factory — **call it**: `openAIAdapter()`, not the bare reference.
+
+| Provider / route output | `streamAdapter` | `messageFormat` |
+|---|---|---|
+| OpenAI Chat Completions, NDJSON from `stream.toReadableStream()` | `openAIReadableStreamAdapter()` | `openAIMessageFormat` |
+| OpenAI Chat Completions, raw SSE (`data: {…}\n\n`, `data: [DONE]`) | `openAIAdapter()` | `openAIMessageFormat` |
+| OpenAI **Responses / Conversations** API stream | `openAIResponsesAdapter()` | `openAIConversationMessageFormat` |
+| LangGraph stream (named SSE events) | `langGraphAdapter()` | `langGraphMessageFormat` |
+| A backend that already emits AG-UI events | `agUIAdapter()` | depends on what your route expects |
+
+The full catalogue and the precise wire format each adapter expects are in [Adapters & formats](/docs/agent/reference/adapters-and-formats).
+
+### Recipe: OpenAI
+
+With `openAIMessageFormat` on the client, `messages` already arrives in OpenAI's chat shape, so you forward it straight to the SDK. `stream.toReadableStream()` emits NDJSON, which `openAIReadableStreamAdapter()` parses on the client.
+
+```ts
+// app/api/chat/route.ts
+import OpenAI from "openai";
+
+const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); // server-side only
+
+export async function POST(req: Request) {
+ const { threadId, messages } = await req.json();
+
+ const stream = await openai.chat.completions.create({
+ model: "gpt-4o",
+ stream: true, // ← the part that makes it stream
+ messages, // already OpenAI-shaped via openAIMessageFormat
+ });
+
+ // openAIReadableStreamAdapter() parses exactly this NDJSON output.
+ return new Response(stream.toReadableStream(), {
+ headers: { "Content-Type": "text/event-stream" },
+ });
+}
+```
+
+**Variant — forward raw SSE.** If you proxy another OpenAI-compatible service that emits SSE, return the SSE bytes unchanged and switch the client to `openAIAdapter()`:
+
+```ts
+export async function POST(req: Request) {
+ const { messages } = await req.json();
+ const upstream = await fetch("https://api.openai.com/v1/chat/completions", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
+ },
+ body: JSON.stringify({ model: "gpt-4o", stream: true, messages }),
+ });
+ return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream" } });
+}
+```
+
+### Recipe: Anthropic (translate to AG-UI)
+
+Anthropic streams its own format, and OpenUI has **no built-in adapter for it**. Rather than invent one, the route translates Anthropic's stream into **AG-UI events** as it goes, and the client uses `agUIAdapter()`. AG-UI events are emitted as Server-Sent Events: each event is a line `data: {json}\n\n`, and the JSON's `type` field names the event. This is the general pattern for any provider OpenUI lacks a native adapter for.
+
+The events a text reply needs:
+
+| Event `type` | Fields | Meaning |
+|---|---|---|
+| `TEXT_MESSAGE_START` | `messageId` | An assistant text message begins. |
+| `TEXT_MESSAGE_CONTENT` | `messageId`, `delta` | A chunk of assistant text. |
+| `TEXT_MESSAGE_END` | `messageId` | The text message is complete. |
+| `RUN_ERROR` | `message` | The turn failed; surfaces as an error in the UI. |
+
+```ts
+// app/api/chat/route.ts
+import Anthropic from "@anthropic-ai/sdk";
+
+const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); // server-side only
+
+export async function POST(req: Request) {
+ const { messages } = await req.json(); // { threadId, messages } from fetchLLM
+
+ // Anthropic takes `system` as a top-level field, not a message role.
+ const system = messages
+ .filter((m: any) => m.role === "system")
+ .map((m: any) => m.content)
+ .join("\n");
+ const turns = messages.filter((m: any) => m.role !== "system");
+
+ const stream = new ReadableStream({
+ async start(controller) {
+ const sse = (event: object) =>
+ controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify(event)}\n\n`));
+ const messageId = crypto.randomUUID();
+
+ try {
+ const anthropicStream = anthropic.messages.stream({
+ model: "claude-3-5-sonnet-latest",
+ max_tokens: 1024,
+ system: system || undefined,
+ messages: turns,
+ });
+
+ sse({ type: "TEXT_MESSAGE_START", messageId });
+ for await (const chunk of anthropicStream) {
+ if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
+ sse({ type: "TEXT_MESSAGE_CONTENT", messageId, delta: chunk.delta.text });
+ }
+ }
+ sse({ type: "TEXT_MESSAGE_END", messageId });
+ } catch (err) {
+ sse({ type: "RUN_ERROR", message: err instanceof Error ? err.message : "Anthropic call failed" });
+ } finally {
+ controller.close(); // flips the UI loading state off — leave it open and the loader never disappears
+ }
+ },
+ });
+
+ return new Response(stream, {
+ headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" },
+ });
+}
+```
+
+Paired client — `agUIAdapter()` because the route emits AG-UI events; `openAIMessageFormat` shapes the outgoing `role` / `content` turns:
+
+```tsx
+import { agUIAdapter, openAIMessageFormat } from "@openuidev/react-ui";
+
+const llm = fetchLLM({
+ url: "/api/chat",
+ streamAdapter: agUIAdapter(),
+ messageFormat: openAIMessageFormat,
+});
+```
+
+To let the model call tools, declare provider-format tools on the request, run the ones it asks for, and emit the matching `TOOL_CALL_START` / `TOOL_CALL_ARGS` / `TOOL_CALL_END` / `TOOL_CALL_RESULT` events between the text events, looping back to the provider with each result until it returns a turn with no tool calls. (`TOOL_CALL_RESULT.content` is always a string.) See [Tools](/docs/agent/core-concepts/tools).
+
+## 2. Stream — your route must stream
+
+Streaming is a property of your **backend route**, not of `<AgentInterface>`. The frontend reads whatever the route sends; if the route buffers the full answer and returns it in one shot, the UI has nothing to stream. Two rules:
+
+1. **Enable the provider's streaming mode** (`stream: true` for OpenAI, `messages.stream(...)` for Anthropic) and return the streamed body — never an `await`-ed full completion sent as JSON.
+2. **Close the stream when generation finishes.** The client's `isRunning` flips back to `false` only when the stream **closes**. A stream left open hangs the loader forever.
+
+If responses arrive all-at-once, the cause is almost always one of two things: the route isn't actually streaming, or `streamAdapter` doesn't match the route's wire format (an adapter that can't decode the bytes can't render them incrementally). Check the network tab: if the response body trickles in gradually, the route streams and the problem is the adapter; if it completes in one shot after a pause, the problem is the route.
+
+### Honor the abort signal
+
+Every run is backed by an `AbortController`. `fetchLLM` threads the UI's `AbortSignal` into its `fetch`, so when the user hits stop, the HTTP request to your route is aborted. To stop the **upstream provider call** too, pass that request's signal into the provider SDK. Without it, the UI stops consuming the stream but the provider may keep generating server-side. A cancelled run is treated as intentional — it does not surface a thread error.
+
+## 3. Persist conversations
+
+Add a `storage` adapter and the default sidebar's thread list, "New chat" button, thread switching, and deletion all operate against your backend — conversations survive reloads. The fastest path is `restStorage`, which maps each `ChatStorage` operation to one HTTP call under a `baseUrl`:
+
+```tsx
+import { AgentInterface, fetchLLM, restStorage, agUIAdapter } from "@openuidev/react-ui";
+
+const llm = fetchLLM({ url: "/api/chat", streamAdapter: agUIAdapter() });
+const storage = restStorage({ baseUrl: "/api/threads" });
+
+export default function App() {
+ return <AgentInterface storage={storage} llm={llm} agentName="Acme Assistant" />;
+}
+```
+
+That's the whole frontend change — one prop. You implement the five endpoints `restStorage` calls; the sidebar's thread lifecycle comes for free. With `baseUrl: "/api/threads"`:
+
+| Operation | Method | Path | Request body | Returns |
+|---|---|---|---|---|
+| List threads | `GET` | `/api/threads/get` | — (append `?cursor={cursor}` to paginate) | `{ threads, nextCursor? }` |
+| Create thread | `POST` | `/api/threads/create` | `{ messages: [...] }` (first user message via the message format) | the new `Thread` |
+| Get messages | `GET` | `/api/threads/get/{threadId}` | — | the thread's `Message[]` |
+| Update thread | `PATCH` | `/api/threads/update/{threadId}` | the full `Thread` | the updated `Thread` |
+| Delete thread | `DELETE` | `/api/threads/delete/{threadId}` | — | nothing |
+
+`restStorage` throws a descriptive error on any non-`ok` response. The `Thread` shape at the boundary is `{ id, title, createdAt: string | number, isPending? }`. By default `restStorage` uses the identity message format; pass `messageFormat` (and optional `headers` / `fetch`) if your backend stores a provider-specific shape — it is applied to the `create` body (`toApi`) and the `get/{threadId}` response (`fromApi`).
+
+```tsx
+import { openAIMessageFormat } from "@openuidev/react-ui";
+
+const storage = restStorage({
+ baseUrl: "/api/threads",
+ messageFormat: openAIMessageFormat,
+ headers: { "x-tenant": "acme" }, // sent on every request
+});
+```
+
+A minimal Next.js App Router implementation, lining up exactly with the table:
+
+```ts
+// app/api/threads/get/route.ts — list threads (and paginate)
+export async function GET(req: NextRequest) {
+ const cursor = req.nextUrl.searchParams.get("cursor") ?? undefined;
+ const { threads, nextCursor } = await db.listThreads({ cursor, limit: 20 });
+ return NextResponse.json({ threads, nextCursor });
+}
+
+// app/api/threads/create/route.ts — create from the first message
+export async function POST(req: NextRequest) {
+ const { messages } = await req.json();
+ const thread = await db.createThread({
+ title: deriveTitle(messages[0]), // e.g. first ~40 chars of user text
+ createdAt: Date.now(),
+ messages,
+ });
+ return NextResponse.json(thread); // the new Thread
+}
+
+// app/api/threads/get/[threadId]/route.ts — load one thread's messages
+export async function GET(_req: NextRequest, { params }: { params: { threadId: string } }) {
+ return NextResponse.json(await db.getMessages(params.threadId)); // Message[]
+}
+
+// app/api/threads/update/[threadId]/route.ts — update (e.g. rename)
+export async function PATCH(req: NextRequest, { params }: { params: { threadId: string } }) {
+ const thread = await req.json(); // the full Thread
+ return NextResponse.json(await db.updateThread(params.threadId, thread));
+}
+
+// app/api/threads/delete/[threadId]/route.ts — delete
+export async function DELETE(_req: NextRequest, { params }: { params: { threadId: string } }) {
+ await db.deleteThread(params.threadId);
+ return new NextResponse(null, { status: 204 });
+}
+```
+
+`db` is a stand-in for your persistence layer — Postgres, SQLite, Redis, a cloud KV store, anything. The endpoints are thin: read/write threads and messages, return the shapes the table describes.
+
+### Custom `ChatStorage` instead
+
+If the REST endpoint shape doesn't fit your backend — GraphQL, a client-side store like IndexedDB, a SaaS SDK, or just a different URL layout — implement `ChatStorage` directly. It's an object with a `thread` member satisfying `ThreadStorage` (five methods) plus an optional `artifact` member. `restStorage` is itself just a `ChatStorage` built this way for the common REST case.
+
+```ts
+import type { ChatStorage } from "@openuidev/react-ui";
+import { gql } from "@/lib/graphql";
+
+export const storage: ChatStorage = {
+ thread: {
+ async listThreads(cursor) {
+ const { threads, nextCursor } = await gql(LIST_THREADS, { cursor });
+ return { threads, nextCursor };
+ },
+ async createThread(firstMessage) {
+ const { thread } = await gql(CREATE_THREAD, { firstMessage });
+ return thread; // a Thread: { id, title, createdAt }
+ },
+ async getMessages(threadId) {
+ const { messages } = await gql(GET_MESSAGES, { threadId });
+ return messages; // Message[]
+ },
+ async updateThread(thread) {
+ const { updated } = await gql(UPDATE_THREAD, { thread });
+ return updated; // the updated Thread
+ },
+ async deleteThread(id) {
+ await gql(DELETE_THREAD, { id });
+ },
+ },
+};
+```
+
+The five methods map one-to-one onto the sidebar:
+
+| Method | When it runs |
+|---|---|
+| `listThreads(cursor?)` | Populating the thread list; loading more on scroll. |
+| `createThread(firstMessage)` | User sends the first message of a new chat. Receives the `UserMessage`. |
+| `getMessages(threadId)` | User opens a thread. Returns its `Message[]`. |
+| `updateThread(thread)` | A thread changes (e.g. rename). Returns the updated `Thread`. |
+| `deleteThread(id)` | User deletes a thread. |
+
+## 4. Store artifacts
+
+Adding an optional `artifact` channel to your storage makes every dashboard, report, and presentation the agent produces a durable, searchable, cross-thread record — and `<AgentInterface>` renders the entire artifact browser (sidebar entry → searchable list → full-page view) for you. `ArtifactStorage` is three methods:
+
+```ts
+interface ArtifactStorage {
+ // name/type filtering is SERVER-SIDE; cursor-paginated
+ list(params?: { name?: string; type?: string[]; cursor?: string; limit?: number }):
+ Promise<{ artifacts: ArtifactSummary[]; nextCursor?: string }>;
+ get(id: string): Promise<Artifact>;
+ update(patch: { id: string; content: unknown }): Promise<ArtifactSummary>; // for editable artifacts
+}
+```
+
+```ts
+import type { ChatStorage, ArtifactStorage } from "@openuidev/react-ui";
+
+const artifact: ArtifactStorage = {
+ async list({ name, type, cursor, limit } = {}) {
+ const params = new URLSearchParams();
+ if (name) params.set("name", name);
+ if (type) type.forEach((t) => params.append("type", t));
+ if (cursor) params.set("cursor", cursor);
+ if (limit) params.set("limit", String(limit));
+ const res = await fetch(`/api/artifacts?${params}`);
+ if (!res.ok) throw new Error(`list artifacts failed: ${res.status}`);
+ return res.json(); // { artifacts: ArtifactSummary[], nextCursor?: string }
+ },
+ async get(id) {
+ const res = await fetch(`/api/artifacts/${id}`);
+ if (!res.ok) throw new Error(`get artifact failed: ${res.status}`);
+ return res.json(); // Artifact (includes content)
+ },
+ async update({ id, content }) {
+ const res = await fetch(`/api/artifacts/${id}`, {
+ method: "PATCH",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ content }),
+ });
+ if (!res.ok) throw new Error(`update artifact failed: ${res.status}`);
+ return res.json(); // ArtifactSummary
+ },
+};
+
+const storage: ChatStorage = {
+ thread: restStorage({ baseUrl: "/api/threads" }).thread, // reuse the REST thread channel
+ artifact,
+};
+```
+
+Four things to keep right (full contract in [Adapters & formats](/docs/agent/reference/adapters-and-formats)):
+
+- **`list` filters on the server.** `name` (partial-match search on `title`) and `type` go to your backend, not applied client-side — the browser's search box and category tabs become these params, paginated via `cursor` / `nextCursor`.
+- **`get` returns the full record** including `content`, which the renderer needs to draw the full view. On the storage path a renderer's `parser` is called as `parser({ args: undefined, response: artifact.content }, { isStreaming: false })`, so make your parser tolerate `args` being `undefined` and read the artifact's data from `response`.
+- **`update` is for editable artifacts.** A renderer reaches storage via the `useArtifactStorage()` hook (returns `ArtifactStorage | null` — guard for `null`) and calls `update({ id, content })` to persist.
+- **`threadId` is required on every `ArtifactSummary`.** It powers the "go to thread" jump from the artifact view back to the conversation that produced it.
+
+The matching Next.js backend — filtering and pagination live on the server:
+
+```ts
+// app/api/artifacts/route.ts — list (search + type filter + paginate)
+export async function GET(req: NextRequest) {
+ const sp = req.nextUrl.searchParams;
+ const name = sp.get("name") ?? undefined; // search box
+ const type = sp.getAll("type"); // category filter (repeatable)
+ const cursor = sp.get("cursor") ?? undefined; // pagination
+ const limit = Number(sp.get("limit") ?? 20);
+ const { artifacts, nextCursor } = await db.listArtifacts({
+ name, type: type.length ? type : undefined, cursor, limit,
+ });
+ // each artifact MUST include threadId
+ return NextResponse.json({ artifacts, nextCursor });
+}
+
+// app/api/artifacts/[id]/route.ts — get (full content) + update
+export async function GET(_req: NextRequest, { params }: { params: { id: string } }) {
+ return NextResponse.json(await db.getArtifact(params.id)); // Artifact (with content)
+}
+export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
+ const { content } = await req.json();
+ return NextResponse.json(await db.updateArtifact(params.id, content)); // ArtifactSummary
+}
+```
+
+The artifact `type` you store must match the `type` a registered renderer declares — it's the contract linking a stored artifact to the renderer that draws it. How artifacts get *written* (a tool call, a background job, a direct write) is up to your agent; the browser only reads, gets, and updates. For organizing the browser into groups and the per-thread Workspace rail (which does **not** require storage), see [Artifacts](/docs/agent/core-concepts/artifacts) and [`<AgentInterface>` props](/docs/agent/reference/agentinterface-props).
+
+## 5. Framework-agnostic (plain Web `Request`/`Response`)
+
+None of the above is Next.js-specific. The only thing `ChatLLM.send` must return is a standard **Web `Response`** with a streaming body — the primitive that Next.js route handlers, Hono, Bun, Deno, and Cloudflare Workers all speak natively, and that Express can be adapted to in a few lines. Write the handler once, mount it anywhere.
+
+```ts
+// chat-handler.ts — pure Web platform, no framework imports
+import OpenAI from "openai";
+
+const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); // server-side only
+
+export async function handleChat(req: Request): Promise<Response> {
+ const { threadId, messages } = await req.json();
+ const stream = await openai.chat.completions.create({
+ model: "gpt-4o",
+ stream: true,
+ messages,
+ });
+ return new Response(stream.toReadableStream(), {
+ headers: { "Content-Type": "text/event-stream" },
+ });
+}
+```
+
+Mounting it differs only at the edges:
+
+```ts
+// Next.js App Router — app/api/chat/route.ts
+import { handleChat } from "@/chat-handler";
+export const POST = (req: Request) => handleChat(req);
+```
+
+```ts
+// Hono
+import { Hono } from "hono";
+import { handleChat } from "./chat-handler";
+const app = new Hono();
+app.post("/api/chat", (c) => handleChat(c.req.raw)); // c.req.raw is a Web Request
+export default app;
+```
+
+```ts
+// Bun / Deno / Cloudflare Workers — the runtime hands you a Request directly
+export default {
+ fetch(req: Request) {
+ const url = new URL(req.url);
+ if (req.method === "POST" && url.pathname === "/api/chat") return handleChat(req);
+ return new Response("Not found", { status: 404 });
+ },
+};
+```
+
+```ts
+// Express — bridge req/res to Web Request/Response
+import express from "express";
+import { handleChat } from "./chat-handler";
+const app = express();
+app.post("/api/chat", express.json(), async (req, res) => {
+ const webReq = new Request("http://local/api/chat", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(req.body),
+ });
+ const webRes = await handleChat(webReq);
+ res.status(webRes.status);
+ webRes.headers.forEach((v, k) => res.setHeader(k, v));
+ const reader = webRes.body!.getReader();
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
+ res.write(chunk.value);
+ }
+ res.end();
+});
+```
+
+The handler is identical across all four — the framework only routes the request to it.
+
+On the client, a fully custom `llm` is an object with `send` (returns a streaming `Response`, **forwards the `signal`**) and `streamProtocol` (the adapter matching your body's wire format):
+
+```tsx
+import { type ChatLLM, type ChatStorage, openAIReadableStreamAdapter } from "@openuidev/react-ui";
+
+const llm: ChatLLM = {
+ async send({ threadId, messages, signal }) {
+ return fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ threadId, messages }),
+ signal, // forward it so the stop button actually aborts the request
+ });
+ },
+ streamProtocol: openAIReadableStreamAdapter(),
+};
+```
+
+Because `send` is just a function returning a `Response`, you can layer logic around the request — a retry on 503, a fresh auth token per attempt, telemetry — without a proxy. It still runs in the browser, so it must call your **own** origin, never a provider API directly. The factory path and the custom path are the same two interfaces; they mix freely (e.g. `restStorage` for threads plus a custom `llm`), and `<AgentInterface>` can't tell the difference.
+
+## What you have now
+
+A self-hosted `<AgentInterface>`: a model reply that streams (key server-side), durable threads and artifacts against your own storage, on any server framework — because the contract is two small interfaces over plain Web `Request`/`Response`.
+
+<Cards>
+ <Card title="Adapters & formats" href="/docs/agent/reference/adapters-and-formats">
+ The full `ChatLLM`, `ChatStorage`, `ThreadStorage`, `ArtifactStorage` interfaces and the `fetchLLM` / `restStorage` factories, plus every stream adapter and message format.
+ </Card>
+ <Card title="<AgentInterface> props" href="/docs/agent/reference/agentinterface-props">
+ The `llm`, `storage`, `artifactRenderers`, and `artifactCategories` props in full.
+ </Card>
+ <Card title="Conversations" href="/docs/agent/core-concepts/conversations">
+ How threads, messages, and streaming fit together.
+ </Card>
+ <Card title="Artifacts" href="/docs/agent/core-concepts/artifacts">
+ The artifact browser, Workspace rail, and how stored artifacts render.
+ </Card>
+</Cards>
diff --git a/docs/content/docs/api-reference/cli.mdx b/docs/content/docs/api-reference/cli.mdx
index 25d9c6f9b..86a6c1c92 100644
--- a/docs/content/docs/api-reference/cli.mdx
+++ b/docs/content/docs/api-reference/cli.mdx
@@ -167,9 +167,6 @@ openui generate ./src/library.ts --out src/generated/system-prompt.txt
## See also
<Cards>
- <Card title="Quick Start" href="/docs/chat/quick-start">
- Scaffold and run a new OpenUI chat app with `openui create` in under 5 minutes.
- </Card>
<Card title="@openuidev/react-lang" href="/docs/api-reference/react-lang">
`createLibrary`, `PromptOptions`, and the `Library` interface that `openui generate` reads.
</Card>
diff --git a/docs/content/docs/api-reference/index.mdx b/docs/content/docs/api-reference/index.mdx
index 7f16e3d4c..1819f2e7d 100644
--- a/docs/content/docs/api-reference/index.mdx
+++ b/docs/content/docs/api-reference/index.mdx
@@ -11,7 +11,7 @@ The OpenUI SDK is split into packages that build on each other:
- **`@openuidev/react-headless`** — Headless chat state management. Provides `ChatProvider`, thread/message hooks, streaming protocol adapters (OpenAI, AG-UI), and message format converters. Use this when you want full control over your chat UI.
-- **`@openuidev/react-ui`** — Prebuilt chat layouts (`Copilot`, `FullScreen`, `BottomTray`) and two ready-to-use component libraries (general-purpose and chat-optimized). Depends on both packages above. Use this for the fastest path to a working chat interface.
+- **`@openuidev/react-ui`** — `AgentInterface`, a ready-to-use artifact chat surface with thread history, plus two built-in component libraries (general-purpose and chat-optimized). Depends on both packages above. Use this for the fastest path to a working chat interface.
- **`@openuidev/react-email`** — Pre-built email component library and prompt options for model-generated emails that can be rendered to HTML with React Email.
@@ -55,8 +55,8 @@ The OpenUI SDK is split into packages that build on each other:
format converters.
</Card>
<Card title="@openuidev/react-ui" href="/docs/api-reference/react-ui">
- Copilot, FullScreen, BottomTray chat layouts, and two built-in component libraries
- (general-purpose and chat-optimized).
+ AgentInterface, a ready-to-use artifact chat surface with thread history, and two built-in
+ component libraries (general-purpose and chat-optimized).
</Card>
<Card title="@openuidev/react-email" href="/docs/api-reference/react-email">
API reference for the pre-built email templates library and prompt options.
diff --git a/docs/content/docs/api-reference/react-ui.mdx b/docs/content/docs/api-reference/react-ui.mdx
index 86a960d7f..3fcbdc5e3 100644
--- a/docs/content/docs/api-reference/react-ui.mdx
+++ b/docs/content/docs/api-reference/react-ui.mdx
@@ -1,66 +1,54 @@
---
title: "@openuidev/react-ui"
-description: API reference for prebuilt chat layouts and default component library exports.
+description: API reference for the AgentInterface chat surface and default component library exports.
---
-Use this package for prebuilt chat UIs and default component library primitives.
+Use this package for the prebuilt `AgentInterface` chat surface and default component library primitives.
## Import
```ts
-import { Copilot, FullScreen, BottomTray } from "@openuidev/react-ui";
+import { AgentInterface } from "@openuidev/react-ui";
```
-## Layout components
+## Chat interface
-These layouts are documented in Chat UI guides and are all wrapped with `ChatProvider`.
+`AgentInterface` is the package's chat surface — a full-page artifact chat with a thread-history sidebar, composer, and per-thread artifact workspace. It wraps `ChatProvider`, so it accepts the provider's `storage` + `llm` props alongside the shared UI props below.
-### `Copilot`
+### `AgentInterface`
-Sidebar chat layout.
-
-```ts
-type CopilotProps = ChatLayoutProps;
-```
-
-### `FullScreen`
-
-Full-page chat layout with thread sidebar.
-
-```ts
-type FullScreenProps = ChatLayoutProps;
-```
-
-### `BottomTray`
-
-Floating/collapsible tray layout.
+```tsx
+import { AgentInterface, openAIAdapter, type ChatLLM } from "@openuidev/react-ui";
+import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
-```ts
-type BottomTrayProps = ChatLayoutProps & {
- isOpen?: boolean;
- onOpenChange?: (isOpen: boolean) => void;
- defaultOpen?: boolean;
+const llm: ChatLLM = {
+ send: ({ messages, signal }) =>
+ fetch("/api/chat", { method: "POST", body: JSON.stringify({ messages }), signal }),
+ streamProtocol: openAIAdapter(),
};
+
+<AgentInterface llm={llm} componentLibrary={openuiChatLibrary} />;
```
-## Shared layout props (`ChatLayoutProps`)
+## Props (`AgentInterfaceProps`)
-All three layouts accept:
+`AgentInterface` extends `ChatProviderProps` (minus `children`) and adds the shared UI + theme props:
-- Chat provider props: `apiUrl`/`processMessage`, thread APIs, `streamProtocol`, `messageFormat`
+- Chat provider props (from `@openuidev/react-headless`):
+ - `storage?: ChatStorage` — thread (and optional artifact) persistence; defaults to in-memory
+ - `llm: ChatLLM` — required; `{ send({ threadId, messages, signal }), streamProtocol }`
+ - `artifactRenderers?: ArtifactRendererConfig[]`
+ - `artifactCategories?: ArtifactCategory[]`
- Shared UI props:
+ - `componentLibrary?: Library` (from `@openuidev/react-lang`) — drives auto-GenUI rendering
+ - `components?: AgentInterfaceComponents` — `{ AssistantMessage?, UserMessage? }` overrides
- `logoUrl?: string`
- `agentName?: string`
- - `messageLoading?: React.ComponentType`
+ - `labels?: AgentInterfaceLabels`
+ - `starters?: ConversationStarterProps[]`
+ - `starterVariant?: ConversationStarterVariant`
- `scrollVariant?: ScrollVariant`
- - `isArtifactActive?: boolean`
- - `renderArtifact?: () => React.ReactNode`
- - `welcomeMessage?: WelcomeMessageConfig`
- - `conversationStarters?: ConversationStartersConfig`
- - `assistantMessage?: AssistantMessageComponent`
- - `userMessage?: UserMessageComponent`
- - `composer?: ComposerComponent`
- - `componentLibrary?: Library` (from `@openuidev/react-lang`)
+ - `scrollOnLoad?: boolean`
- Theme wrapper props:
- `theme?: ThemeProps`
- `disableThemeProvider?: boolean`
@@ -117,7 +105,7 @@ import {
} from "@openuidev/react-ui/genui-lib";
```
-**`openuiChatLibrary`** — Root is `Card` (vertical, no layout params). Includes chat-specific components: `FollowUpBlock`, `ListBlock`, `SectionBlock`. Does not include `Stack`. Use with `FullScreen` / `BottomTray` / `Copilot` chat interfaces.
+**`openuiChatLibrary`** — Root is `Card` (vertical, no layout params). Includes chat-specific components: `FollowUpBlock`, `ListBlock`, `SectionBlock`. Does not include `Stack`. Use with the `AgentInterface` chat surface.
**`openuiLibrary`** — Root is `Stack`. Full layout suite with `Stack`, `Tabs`, `Carousel`, `Accordion`, `Modal`, etc. Use with the standalone `Renderer` or any non-chat layout (e.g., playground, embedded widgets, dashboards).
@@ -131,7 +119,7 @@ npx @openuidev/cli@latest generate ./src/library.ts --out src/generated/system-p
```tsx
// Chat interface — system prompt stays on the server
-<FullScreen componentLibrary={openuiChatLibrary} ... />
+<AgentInterface componentLibrary={openuiChatLibrary} ... />
// Standalone renderer
<Renderer response={message} library={openuiLibrary} />
diff --git a/docs/content/docs/chat/api-contract.mdx b/docs/content/docs/chat/api-contract.mdx
deleted file mode 100644
index bcb4ff8eb..000000000
--- a/docs/content/docs/chat/api-contract.mdx
+++ /dev/null
@@ -1,108 +0,0 @@
----
-title: The API Contract
-description: JSON contract for threads, messages, and streaming.
----
-
-OpenUI Chat can work with any backend stack as long as the API contract is respected.
-
-This page is the reference source for request and response shapes. Use [Connecting to LLM](/docs/chat/connecting) for decision guidance and [Connect Thread History](/docs/chat/persistence) for the setup flow.
-
-## Chat endpoint contract
-
-When you pass `apiUrl`, OpenUI sends a `POST` request with this shape:
-
-```json
-{
- "threadId": "thread_123",
- "messages": [{ "id": "msg_1", "role": "user", "content": "Hello" }]
-}
-```
-
-- `threadId` is the selected thread ID when persistence is enabled, or `"ephemeral"` when no thread storage is configured.
-- `messages` is converted through `messageFormat.toApi(messages)` before the request is sent.
-
-If your backend already accepts the default AG-UI message shape, each message can stay in this form:
-
-```json
-{ "id": "msg_1", "role": "user", "content": "Hello" }
-```
-
-### Stream response
-
-Your response stream must match one of these cases:
-
-| Backend response shape | Frontend config |
-| :--------------------------------------- | :----------------------------------------------- |
-| OpenUI Protocol | No `streamProtocol` needed |
-| Raw OpenAI Chat Completions SSE | `streamProtocol={openAIAdapter()}` |
-| OpenAI SDK `toReadableStream()` / NDJSON | `streamProtocol={openAIReadableStreamAdapter()}` |
-| OpenAI Responses API | `streamProtocol={openAIResponsesAdapter()}` |
-
-## Default thread API contract
-
-When using `threadApiUrl="/api/threads"`, OpenUI expects the base URL plus these default path segments:
-
-| Action | Method | URL | Request body | Response |
-| :------------ | :------- | :------------------------ | :------------- | :---------------------------------------- |
-| List threads | `GET` | `/api/threads/get` | — | `{ threads: Thread[], nextCursor?: any }` |
-| Create thread | `POST` | `/api/threads/create` | `{ messages }` | `Thread` |
-| Update thread | `PATCH` | `/api/threads/update/:id` | `Thread` | `Thread` |
-| Delete thread | `DELETE` | `/api/threads/delete/:id` | — | empty response is fine |
-| Load messages | `GET` | `/api/threads/get/:id` | — | message array in your backend format |
-
-`messages` in the create request is the first user message, already converted through `messageFormat.toApi([firstMessage])`.
-
-## Thread shape
-
-```ts
-type Thread = {
- id: string;
- title: string;
- createdAt: string | number;
-};
-```
-
-## Message format contract
-
-`messageFormat` controls both directions:
-
-- `toApi()` shapes the `messages` array sent to `apiUrl` and `threadApiUrl/create`
-- `fromApi()` shapes the array returned from `threadApiUrl/get/:id`
-
-OpenUI ships with these built-in message converters:
-
-| Converter | Use when your backend expects or returns... |
-| :-------------------------------- | :------------------------------------------ |
-| Default | AG-UI message objects |
-| `openAIMessageFormat` | OpenAI chat completion messages |
-| `openAIConversationMessageFormat` | OpenAI Responses conversation items |
-
-Every persisted message should include a unique `id`. Without stable message IDs, history hydration and message updates become unreliable.
-
-## Example custom converter
-
-```ts
-const myCustomFormat = {
- toApi(messages) {
- return messages.map((message) => ({
- speaker: message.role,
- text: message.content,
- }));
- },
- fromApi(items) {
- return items.map((item) => ({
- id: item.id,
- role: item.speaker,
- content: item.text,
- }));
- },
-};
-```
-
-{/* add visual: flow-chart showing how messageFormat.toApi affects outgoing chat and thread-create requests, and how messageFormat.fromApi affects thread loading */}
-
-## Related guides
-
-- [Next.js Implementation](/docs/chat/nextjs)
-- [Connect Thread History](/docs/chat/persistence)
-- [Providers](/docs/chat/providers)
diff --git a/docs/content/docs/chat/artifacts.mdx b/docs/content/docs/chat/artifacts.mdx
deleted file mode 100644
index 0114d01f9..000000000
--- a/docs/content/docs/chat/artifacts.mdx
+++ /dev/null
@@ -1,173 +0,0 @@
----
-title: Artifacts
-description: Add side-panel content that opens from inline previews in chat.
----
-
-Artifacts let a component render a compact inline preview inside the chat message and expand into a full side panel when clicked. Use them for code viewers, document previews, embedded frames, or any content that benefits from a larger canvas.
-
-```tsx
-import { defineComponent } from "@openuidev/react-lang";
-import { Artifact } from "@openuidev/react-ui";
-import { z } from "zod";
-
-const ArtifactCodeBlock = defineComponent({
- name: "ArtifactCodeBlock",
- props: z.object({
- language: z.string(),
- title: z.string(),
- codeString: z.string(),
- }),
- description: "Code block that opens in the artifact side panel",
- component: Artifact({
- title: (props) => props.title,
- preview: (props, { open, isActive }) => (
- <CodeChip title={props.title} language={props.language} onClick={open} isActive={isActive} />
- ),
- panel: (props) => (
- <SyntaxHighlighter language={props.language}>{props.codeString}</SyntaxHighlighter>
- ),
- }),
-});
-```
-
-## How it works
-
-An artifact component has two parts:
-
-- **Preview** — a compact element rendered inline in the chat message. It receives an `open` callback to activate the side panel.
-- **Panel** — the full content rendered inside `ArtifactPanel`, portaled into the `ArtifactPortalTarget` in your layout. Only one panel is visible at a time.
-
-`Artifact()` is a factory function that wires these together. It generates a `ComponentRenderer` that handles ID generation, artifact state, and panel portaling internally. Pass the result as the `component` field of `defineComponent`.
-
-## `Artifact()` config
-
-```ts
-import { Artifact } from "@openuidev/react-ui";
-
-Artifact({
- title, // string | (props) => string
- preview, // (props, controls) => ReactNode
- panel, // (props, controls) => ReactNode
- panelProps, // optional — className, errorFallback, header
-});
-```
-
-| Option | Type | Description |
-| ------------ | ----------------------------------------------------- | -------------------------------------------------------- |
-| `title` | `string \| (props: P) => string` | Panel header title. Static string or derived from props. |
-| `preview` | `(props: P, controls: ArtifactControls) => ReactNode` | Inline preview rendered in the chat message. |
-| `panel` | `(props: P, controls: ArtifactControls) => ReactNode` | Content rendered inside the side panel. |
-| `panelProps` | `{ className?, errorFallback?, header? }` | Optional overrides forwarded to `ArtifactPanel`. |
-
-Both `preview` and `panel` receive the full Zod-inferred props as the first argument and `ArtifactControls` as the second.
-
-## `ArtifactControls`
-
-The controls object passed to `preview` and `panel` render functions.
-
-```ts
-interface ArtifactControls {
- isActive: boolean; // whether this artifact's panel is currently open
- open: () => void; // activate this artifact
- close: () => void; // deactivate this artifact
- toggle: () => void; // toggle open/close
-}
-```
-
-The preview typically uses `open` and `isActive` to show a click-to-expand button. The panel can use `close` to render a dismiss button inside the panel body.
-
-## Layout setup
-
-Built-in layouts (`FullScreen`, `Copilot`, `BottomTray`) mount `ArtifactPortalTarget` automatically. Artifact panels render into this target with no extra setup.
-
-If you build a custom layout with the headless hooks, mount one `ArtifactPortalTarget` in your layout where the panel should appear.
-
-```tsx
-import { ArtifactPortalTarget } from "@openuidev/react-ui";
-
-function Layout() {
- return (
- <div className="flex h-screen">
- <main className="flex-1">{/* chat area */}</main>
- <ArtifactPortalTarget className="w-[480px]" />
- </div>
- );
-}
-```
-
-Only one `ArtifactPortalTarget` should be mounted at a time. All artifact panels portal into this single element.
-
-## Headless hooks
-
-For custom layouts or advanced control, use the artifact hooks from `@openuidev/react-headless`.
-
-### `useArtifact(id)`
-
-Binds a component to a specific artifact by ID. Returns activation state and actions.
-
-```ts
-import { useArtifact } from "@openuidev/react-headless";
-
-const { isActive, open, close, toggle } = useArtifact(artifactId);
-```
-
-### `useActiveArtifact()`
-
-Returns global artifact state — whether any artifact is open, and a close action. Use this in layout components that resize or show overlays when any artifact is active.
-
-```ts
-import { useActiveArtifact } from "@openuidev/react-headless";
-
-const { isArtifactActive, activeArtifactId, closeArtifact } = useActiveArtifact();
-```
-
-Both hooks require a `ChatProvider` ancestor in the component tree.
-
-## Manual wiring
-
-If `Artifact()` does not fit your use case, wire the pieces directly. This is the escape hatch for full control.
-
-```tsx
-import { defineComponent } from "@openuidev/react-lang";
-import { ArtifactPanel } from "@openuidev/react-ui";
-import { useArtifact } from "@openuidev/react-headless";
-import { useId } from "react";
-
-const CustomArtifact = defineComponent({
- name: "CustomArtifact",
- props: CustomSchema,
- description: "Artifact with full manual control",
- component: ({ props }) => {
- const artifactId = useId();
- const { isActive, open, close } = useArtifact(artifactId);
-
- return (
- <>
- <button onClick={open}>{isActive ? "Viewing" : "Open"}</button>
- <ArtifactPanel artifactId={artifactId} title="Custom">
- <div>{/* panel content */}</div>
- </ArtifactPanel>
- </>
- );
- },
-});
-```
-
-`ArtifactPanel` accepts `artifactId`, `title`, `children`, `className`, `errorFallback`, and `header` (boolean or custom ReactNode). It renders nothing when the artifact is inactive.
-
-## Related guides
-
-<Cards>
- <Card title="Defining Components" href="/docs/openui-lang/defining-components">
- Create custom openui-lang components with `defineComponent`.
- </Card>
- <Card title="Custom UI Guide" href="/docs/chat/custom-ui-guide">
- Build a fully custom chat UI with headless hooks.
- </Card>
- <Card title="Headless Hooks" href="/docs/chat/hooks">
- Full reference for all headless hooks.
- </Card>
- <Card title="Theming" href="/docs/chat/theming">
- Adjust colors, mode, and theme overrides.
- </Card>
-</Cards>
diff --git a/docs/content/docs/chat/bottom-tray.mdx b/docs/content/docs/chat/bottom-tray.mdx
deleted file mode 100644
index 7f5e3419d..000000000
--- a/docs/content/docs/chat/bottom-tray.mdx
+++ /dev/null
@@ -1,50 +0,0 @@
----
-title: BottomTray
-description: A floating support-style chat widget.
----
-
-`BottomTray` provides a floating chat widget instead of a full-page chat surface.
-
-This page covers the widget-style layout for support flows, product assistants, and experiences where chat stays collapsed until a user opens it.
-
-```tsx
-import { BottomTray } from "@openuidev/react-ui";
-
-export function App() {
- return (
- <>
- <main>{/* Your app */}</main>
- <BottomTray apiUrl="/api/chat" agentName="Support" />
- </>
- );
-}
-```
-
-![BottomTray widget in collapsed and expanded states](/docs/images/chat/bottom-tray.gif)
-
-## Controlled open state
-
-```tsx
-<BottomTray apiUrl="/api/chat" isOpen={isOpen} onOpenChange={setIsOpen} />
-```
-
-Use the same backend configuration props as the other layouts. The only layout-specific props are the open-state controls.
-
-That means you can start with `BottomTray` for the UI and still reuse the same `apiUrl`, `processMessage`, `streamProtocol`, and `threadApiUrl` setup from the other layouts.
-
-## Related guides
-
-<Cards>
- <Card title="Connecting to LLM" href="/docs/chat/connecting">
- Configure endpoint, adapters, and auth headers.
- </Card>
- <Card title="Connect Thread History" href="/docs/chat/persistence">
- Load saved threads and previous messages into the widget.
- </Card>
- <Card title="Welcome & Starters" href="/docs/chat/welcome">
- Configure the empty-state content and starter prompts.
- </Card>
- <Card title="Theming" href="/docs/chat/theming">
- Adjust mode and theme overrides.
- </Card>
-</Cards>
diff --git a/docs/content/docs/chat/connecting.mdx b/docs/content/docs/chat/connecting.mdx
deleted file mode 100644
index 25eb95f35..000000000
--- a/docs/content/docs/chat/connecting.mdx
+++ /dev/null
@@ -1,130 +0,0 @@
----
-title: Connecting to LLM
-description: Configure apiUrl, streamProtocol adapters, and authentication.
----
-
-Every chat layout needs a backend connection, but there are a few separate pieces involved:
-
-- how the frontend sends the request
-- how the backend streams the response
-- what message shape the backend expects
-
-This page introduces each one first, then shows how to choose the right combination for your backend.
-
-## `apiUrl`
-
-`apiUrl` is the simplest connection option. Use it when your frontend can call one backend endpoint directly and you do not need custom request logic on the client.
-
-```tsx
-import { FullScreen } from "@openuidev/react-ui";
-
-<FullScreen apiUrl="/api/chat" agentName="Assistant" />;
-```
-
-With `apiUrl`, OpenUI sends the message history to your endpoint for you. If your backend expects a different message format, configure `messageFormat`. If you need custom headers, extra fields, or a different request body, use `processMessage` instead.
-
-## `processMessage`
-
-`processMessage` gives you full control over the request. Use it when you need to:
-
-- add auth headers
-- build a dynamic URL
-- include extra request fields
-- convert `messages` before sending them
-
-```tsx
-import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
-
-<FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${getToken()}`,
- },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIReadableStreamAdapter()}
- componentLibrary={openuiLibrary}
- agentName="Assistant"
-/>;
-```
-
-`processMessage` receives `threadId`, `messages`, and `abortController`, and must return a standard `Response` from your backend call.
-
-## `streamProtocol`
-
-`streamProtocol` tells OpenUI how to parse the response stream. By default, OpenUI expects the OpenUI Protocol, so only set this when your backend streams a different format.
-
-| Backend output | Frontend config |
-| :--------------------------------------- | :----------------------------------------------- |
-| OpenUI Protocol | No adapter required |
-| Raw OpenAI Chat Completions SSE | `streamProtocol={openAIAdapter()}` |
-| OpenAI SDK `toReadableStream()` / NDJSON | `streamProtocol={openAIReadableStreamAdapter()}` |
-| OpenAI Responses API | `streamProtocol={openAIResponsesAdapter()}` |
-
-```tsx
-import { openAIReadableStreamAdapter } from "@openuidev/react-headless";
-
-<FullScreen
- apiUrl="/api/chat"
- streamProtocol={openAIReadableStreamAdapter()}
- agentName="Assistant"
-/>;
-```
-
-## `messageFormat`
-
-`messageFormat` controls the shape of the `messages` array sent to your backend and the shape expected when loading thread history.
-
-| Backend message shape | Frontend config |
-| :---------------------------------- | :------------------------------------------------ |
-| AG-UI message shape | No converter required |
-| OpenAI chat completions messages | `messageFormat={openAIMessageFormat}` |
-| OpenAI Responses conversation items | `messageFormat={openAIConversationMessageFormat}` |
-
-```tsx
-import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-
-<FullScreen
- apiUrl="/api/chat"
- streamProtocol={openAIReadableStreamAdapter()}
- messageFormat={openAIMessageFormat}
- agentName="Assistant"
-/>;
-```
-
-Use `messageFormat` whenever your backend expects or returns a non-default message shape. This is especially important if you store messages for thread history.
-
-## How to choose
-
-Once you know what each prop does, the decision becomes:
-
-1. Start with `apiUrl`.
-2. Switch to `processMessage` only if you need auth, extra fields, dynamic URLs, or request conversion.
-3. Add `streamProtocol` only if your backend does not stream the default OpenUI Protocol.
-4. Add `messageFormat` only if your backend expects or returns a non-default message shape.
-
-{/* add visual: flow-chart showing the decision between apiUrl and processMessage, then mapping backend stream output to the correct streamProtocol adapter and messageFormat choice */}
-
-## Rules summary
-
-- `apiUrl` is the simplest path when one endpoint can handle the request as-is.
-- `processMessage` is the right choice when you need auth, extra fields, or payload conversion.
-- `streamProtocol` parses the response stream.
-- `messageFormat` converts request messages and loaded thread history.
-
-## Related guides
-
-- [Next.js Implementation](/docs/chat/nextjs)
-- [The API Contract](/docs/chat/api-contract)
-- [Providers](/docs/chat/providers)
-- [Connect Thread History](/docs/chat/persistence)
diff --git a/docs/content/docs/chat/copilot.mdx b/docs/content/docs/chat/copilot.mdx
deleted file mode 100644
index 2b4608d66..000000000
--- a/docs/content/docs/chat/copilot.mdx
+++ /dev/null
@@ -1,58 +0,0 @@
----
-title: Copilot
-description: The sidebar assistant layout for in-app chat experiences.
----
-
-`Copilot` provides a sidebar assistant layout that stays visible alongside the rest of your application.
-
-This layout keeps the main app screen in view while chat stays available at the side. For a full-page chat surface, see [FullScreen](/docs/chat/fullscreen). For a floating widget, see [BottomTray](/docs/chat/bottom-tray).
-
-```tsx
-import { Copilot } from "@openuidev/react-ui";
-
-export function App() {
- return (
- <div className="flex h-screen w-full">
- <main className="flex-1">{/* Your app */}</main>
- <Copilot apiUrl="/api/chat" agentName="Assistant" />
- </div>
- );
-}
-```
-
-![Copilot sidebar layout example](/docs/images/chat/video2.gif)
-
-## Common configuration
-
-```tsx
-<Copilot
- apiUrl="/api/chat"
- threadApiUrl="/api/threads"
- agentName="Support Assistant"
- logoUrl="/logo.png"
-/>
-```
-
-`Copilot` only handles the UI layer. It is a good fit for support panels, assistant sidebars, and workflows where users need to keep the main screen visible while chatting.
-
-Set up your backend connection in [Connecting to LLM](/docs/chat/connecting), connect thread history in [Connect Thread History](/docs/chat/persistence), and customize the empty state in [Welcome & Starters](/docs/chat/welcome).
-
-## Related guides
-
-<Cards>
- <Card title="Connecting to LLM" href="/docs/chat/connecting">
- Configure `apiUrl`, adapters, and auth.
- </Card>
- <Card title="Connect Thread History" href="/docs/chat/persistence">
- Load thread lists and previous messages from your backend.
- </Card>
- <Card title="Welcome & Starters" href="/docs/chat/welcome">
- Configure the empty-state experience.
- </Card>
- <Card title="Theming" href="/docs/chat/theming">
- Adjust colors, mode, and theme overrides.
- </Card>
- <Card title="Custom Chat Components" href="/docs/chat/custom-chat-components">
- Override assistant, user, and composer UI.
- </Card>
-</Cards>
diff --git a/docs/content/docs/chat/custom-chat-components.mdx b/docs/content/docs/chat/custom-chat-components.mdx
deleted file mode 100644
index 91e5638fb..000000000
--- a/docs/content/docs/chat/custom-chat-components.mdx
+++ /dev/null
@@ -1,71 +0,0 @@
----
-title: Custom Chat Components
-description: Override the composer, assistant messages, and user messages.
----
-
-You can customize specific UI surfaces without rebuilding the full chat stack:
-
-- `composer`
-- `assistantMessage`
-- `userMessage`
-
-These props replace the built-in UI entirely for that surface. If you override them, your component becomes responsible for rendering the message or composer state correctly.
-
-Use these props when you want to swap a specific surface while keeping the built-in layout and state model. If you need to redesign the whole chat shell, use the headless APIs instead.
-
-## Custom composer
-
-```tsx
-function MyComposer({ onSend, onCancel, isRunning }) {
- // your UI
-}
-
-<Copilot apiUrl="/api/chat" composer={MyComposer} />;
-```
-
-### `ComposerProps`
-
-```ts
-type ComposerProps = {
- onSend: (message: string) => void;
- onCancel: () => void;
- isRunning: boolean;
- isLoadingMessages: boolean;
-};
-```
-
-Call `onSend(text)` when the user submits. Use `onCancel()` to stop a running response.
-
-Even a simple custom composer should still account for both `isRunning` and `isLoadingMessages`, because the composer may need to disable input while streaming or while history is still loading.
-
-## Custom assistant and user messages
-
-```tsx
-function AssistantBubble({ message }) {
- return <div>{message.content}</div>;
-}
-
-function UserBubble({ message }) {
- return <div>{String(message.content)}</div>;
-}
-
-<Copilot apiUrl="/api/chat" assistantMessage={AssistantBubble} userMessage={UserBubble} />;
-```
-
-The `message` prop is the full `AssistantMessage` or `UserMessage` object from `@openuidev/react-headless`.
-
-## Important behavior notes
-
-- `assistantMessage` replaces the default assistant wrapper, including the avatar/container UI.
-- `userMessage` replaces the default user bubble wrapper.
-- If you pass `componentLibrary` and also pass `assistantMessage`, your custom component takes priority. That means you are responsible for rendering any structured assistant content yourself.
-- `composer` should handle both `isRunning` and `isLoadingMessages` so the input behaves correctly while streaming or loading history.
-- If your custom assistant renderer only handles plain text, document that constraint in your app and avoid assuming `message.content` is always a simple string.
-
-{/* add visual: image showing the default assistant bubble beside a custom assistant bubble implementation */}
-
-## Related guides
-
-- [Headless Intro](/docs/chat/headless-intro)
-- [Custom UI Guide](/docs/chat/custom-ui-guide)
-- [GenUI](/docs/chat/genui)
diff --git a/docs/content/docs/chat/custom-ui-guide.mdx b/docs/content/docs/chat/custom-ui-guide.mdx
deleted file mode 100644
index 2932964f3..000000000
--- a/docs/content/docs/chat/custom-ui-guide.mdx
+++ /dev/null
@@ -1,139 +0,0 @@
----
-title: Custom UI Guide
-description: Build a chat interface from scratch using headless hooks.
----
-
-This guide shows a complete headless composition with:
-
-1. `ChatProvider` for backend configuration
-2. `useThreadList()` for the sidebar
-3. `useThread()` for messages and the composer
-
-The goal is to show how those pieces fit together in one working example, not to prescribe a specific visual design.
-
-```tsx
-import { useState } from "react";
-import {
- ChatProvider,
- openAIMessageFormat,
- openAIReadableStreamAdapter,
- useThread,
- useThreadList,
-} from "@openuidev/react-headless";
-
-function ThreadSidebar() {
- const { threads, selectedThreadId, isLoadingThreads, selectThread, switchToNewThread } =
- useThreadList();
-
- return (
- <aside>
- <button onClick={switchToNewThread}>New chat</button>
- {isLoadingThreads ? <p>Loading threads...</p> : null}
- {threads.map((thread) => (
- <button
- key={thread.id}
- onClick={() => selectThread(thread.id)}
- aria-pressed={thread.id === selectedThreadId}
- >
- {thread.title}
- </button>
- ))}
- </aside>
- );
-}
-
-function MessageList() {
- const { messages, isRunning } = useThread();
-
- return (
- <div>
- {messages.map((message) => (
- <div key={message.id}>
- <strong>{message.role}:</strong> {String(message.content ?? "")}
- </div>
- ))}
- {isRunning ? <p>Thinking...</p> : null}
- </div>
- );
-}
-
-function Composer() {
- const { processMessage, cancelMessage, isRunning } = useThread();
- const [input, setInput] = useState("");
-
- return (
- <form
- onSubmit={(event) => {
- event.preventDefault();
- if (!input.trim() || isRunning) return;
- processMessage({ role: "user", content: input });
- setInput("");
- }}
- >
- <input
- value={input}
- onChange={(event) => setInput(event.target.value)}
- placeholder="Ask anything..."
- />
- {isRunning ? (
- <button type="button" onClick={cancelMessage}>
- Stop
- </button>
- ) : (
- <button type="submit">Send</button>
- )}
- </form>
- );
-}
-
-function CustomChat() {
- return (
- <div className="chat-app">
- <ThreadSidebar />
- <main>
- <MessageList />
- <Composer />
- </main>
- </div>
- );
-}
-
-export default function App() {
- return (
- <ChatProvider
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- threadApiUrl="/api/threads"
- streamProtocol={openAIReadableStreamAdapter()}
- messageFormat={openAIMessageFormat}
- >
- <CustomChat />
- </ChatProvider>
- );
-}
-```
-
-This example uses the same backend assumptions as the built-in layouts:
-
-- `openAIMessageFormat.toApi(messages)` is called explicitly in `processMessage` to convert messages to OpenAI format — the `messageFormat` prop does not transform messages for `processMessage`
-- `messageFormat={openAIMessageFormat}` is still needed here because `threadApiUrl` is set — it tells the UI how to convert messages when loading saved thread history
-- `openAIReadableStreamAdapter()` matches `response.toReadableStream()`
-- `threadApiUrl` enables saved thread history
-
-If you want Generative UI in a headless build, you also need to render structured assistant content yourself instead of relying on the built-in `componentLibrary` behavior from the layout components.
-
-{/* add visual: flow-chart showing ChatProvider feeding ThreadSidebar, MessageList, and Composer through useThreadList and useThread */}
-
-## Related guides
-
-- [Headless Intro](/docs/chat/headless-intro)
-- [Hooks & State](/docs/chat/hooks)
-- [Connecting to LLM](/docs/chat/connecting)
diff --git a/docs/content/docs/chat/from-scratch.mdx b/docs/content/docs/chat/from-scratch.mdx
deleted file mode 100644
index a26e15f1d..000000000
--- a/docs/content/docs/chat/from-scratch.mdx
+++ /dev/null
@@ -1,196 +0,0 @@
----
-title: End-to-End Guide
-description: Build a complete OpenUI Chat setup from an existing app.
----
-
-This guide shows a complete OpenUI Chat setup in an existing Next.js App Router project.
-
-This path covers:
-
-- a built-in chat layout
-- an OpenAI-backed route handler
-- frontend request wiring with `processMessage`
-- the correct stream adapter and message format
-- optional thread history
-- optional headless customization
-
-{/* add visual: flow-chart showing frontend page -> processMessage -> /api/chat route -> OpenAI -> toReadableStream() -> openAIReadableStreamAdapter() -> rendered UI with componentLibrary */}
-
-## Prerequisites
-
-Complete [Installation](/docs/chat/installation) first, then return here to wire the chat flow.
-
-## 1. Generate the system prompt
-
-If you want Generative UI, generate a system prompt from the component library. The backend loads this prompt and sends it to the model with each request.
-
-If you only want plain text chat, you can skip this step and omit `componentLibrary` in the next examples.
-
-```bash
-npx @openuidev/cli@latest generate ./src/library.ts --out src/generated/system-prompt.txt
-```
-
-Where `src/library.ts` exports your library:
-
-```ts
-export {
- openuiLibrary as library,
- openuiPromptOptions as promptOptions,
-} from "@openuidev/react-ui/genui-lib";
-```
-
-Add this as a prebuild step in `package.json`:
-
-```json
-"scripts": {
- "generate:prompt": "openui generate src/library.ts --out src/generated/system-prompt.txt",
- "dev": "pnpm generate:prompt && next dev",
- "build": "pnpm generate:prompt && next build"
-}
-```
-
-This prompt tells the model which UI components it is allowed to emit.
-
-## 2. Create the streaming backend route
-
-Create `app/api/chat/route.ts`:
-
-```ts
-import { readFileSync } from "fs";
-import { join } from "path";
-import { NextRequest } from "next/server";
-import OpenAI from "openai";
-
-const client = new OpenAI();
-const systemPrompt = readFileSync(join(process.cwd(), "src/generated/system-prompt.txt"), "utf-8");
-
-export async function POST(req: NextRequest) {
- try {
- const { messages } = await req.json();
-
- const response = await client.chat.completions.create({
- model: "gpt-5.2",
- messages: [{ role: "system", content: systemPrompt }, ...messages],
- stream: true,
- });
-
- return new Response(response.toReadableStream(), {
- headers: {
- "Content-Type": "text/event-stream",
- "Cache-Control": "no-cache, no-transform",
- Connection: "keep-alive",
- },
- });
- } catch (err) {
- console.error(err);
- const message = err instanceof Error ? err.message : "Unknown error";
- return new Response(JSON.stringify({ error: message }), {
- status: 500,
- headers: { "Content-Type": "application/json" },
- });
- }
-}
-```
-
-The system prompt is loaded from the file generated by the CLI. The route only receives messages from the frontend — the prompt never leaves the server.
-
-## 3. Render a layout and connect it to the route
-
-`FullScreen` is a good baseline because it includes both the thread list and the main chat surface.
-
-This guide uses `processMessage` instead of `apiUrl` so the request body stays explicit.
-
-```tsx
-import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
-
-export default function Page() {
- return (
- <div className="h-screen">
- <FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIReadableStreamAdapter()}
- componentLibrary={openuiLibrary}
- agentName="Assistant"
- />
- </div>
- );
-}
-```
-
-Why this setup matters:
-
-- `processMessage` gives you control over the request body
-- `openAIMessageFormat.toApi(messages)` converts messages to OpenAI format before sending
-- `openAIReadableStreamAdapter()` matches `response.toReadableStream()`
-- `componentLibrary={openuiLibrary}` lets the UI render structured responses
-
-### Checkpoint
-
-At this point, you should be able to send a message and receive streamed responses in the UI.
-
-Guides: [Connecting to LLM](/docs/chat/connecting), [Next.js Implementation](/docs/chat/nextjs), [Providers](/docs/chat/providers)
-
-## 4. Connect Thread History (optional)
-
-Stop here if you only need a working streamed chat UI.
-
-Continue with this section only if your app also needs saved threads and message history from the backend.
-
-If you want the UI to load saved threads and previous messages, add `threadApiUrl` and implement the default thread contract described in [Connect Thread History](/docs/chat/persistence).
-
-```tsx
-<FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- threadApiUrl="/api/threads"
- streamProtocol={openAIReadableStreamAdapter()}
- messageFormat={openAIMessageFormat}
- componentLibrary={openuiLibrary}
- agentName="Assistant"
-/>
-```
-
-When using `processMessage`, you must call `openAIMessageFormat.toApi(messages)` explicitly in the request body — the `messageFormat` prop does not transform messages for `processMessage`. The `messageFormat={openAIMessageFormat}` prop here is for `threadApiUrl`: it tells the UI how to convert messages when loading saved thread history from the backend.
-
-## 5. Switch layouts or go headless (optional)
-
-This step does not change your backend contract. It only changes the UI layer that sits on top of the same chat and thread wiring.
-
-Once the backend contract is working, you can keep the same chat wiring and swap the UI layer.
-
-- Use [Copilot](/docs/chat/copilot) for a sidebar layout
-- Use [BottomTray](/docs/chat/bottom-tray) for a floating widget
-- Use [Headless Intro](/docs/chat/headless-intro) and [Custom UI Guide](/docs/chat/custom-ui-guide) for full UI control
-
-## You now have
-
-- a streaming `/api/chat` route
-- a connected chat layout
-- the correct OpenAI message conversion and stream adapter
-- optional GenUI support
-- a clear path to thread history and headless customization
-
-## Next steps
-
-- [Connect Thread History](/docs/chat/persistence)
-- [GenUI](/docs/chat/genui)
-- [Custom UI Guide](/docs/chat/custom-ui-guide)
diff --git a/docs/content/docs/chat/fullscreen.mdx b/docs/content/docs/chat/fullscreen.mdx
deleted file mode 100644
index 7798557c8..000000000
--- a/docs/content/docs/chat/fullscreen.mdx
+++ /dev/null
@@ -1,55 +0,0 @@
----
-title: FullScreen
-description: The full-page, ChatGPT-style chat layout.
----
-
-`FullScreen` provides a full-page chat layout with the built-in thread list and main conversation area.
-
-This page covers the complete built-in layout. For a sidebar inside an existing app screen, see [Copilot](/docs/chat/copilot). For a floating widget, see [BottomTray](/docs/chat/bottom-tray).
-
-```tsx
-import { FullScreen } from "@openuidev/react-ui";
-
-export function App() {
- return (
- <div className="h-screen">
- <FullScreen apiUrl="/api/chat" agentName="Assistant" />
- </div>
- );
-}
-```
-
-![FullScreen layout example](/docs/images/chat/video1.gif)
-
-## Common configuration
-
-```tsx
-<FullScreen
- apiUrl="/api/chat"
- threadApiUrl="/api/threads"
- agentName="Data Assistant"
- logoUrl="/logo.png"
-/>
-```
-
-`FullScreen` is the best starting point for end-to-end setup because it exercises both the message surface and thread UI. See the [End-to-End Guide](/docs/chat/from-scratch) if you want to wire the whole flow manually.
-
-## Related guides
-
-<Cards>
- <Card title="Connecting to LLM" href="/docs/chat/connecting">
- Configure endpoint, streaming adapters, and auth.
- </Card>
- <Card title="Connect Thread History" href="/docs/chat/persistence">
- Load thread lists and message history from your backend.
- </Card>
- <Card title="Welcome & Starters" href="/docs/chat/welcome">
- Customize the empty-state experience.
- </Card>
- <Card title="Theming" href="/docs/chat/theming">
- Control colors, mode, and theme overrides.
- </Card>
- <Card title="Custom Chat Components" href="/docs/chat/custom-chat-components">
- Override the built-in composer and message rendering.
- </Card>
-</Cards>
diff --git a/docs/content/docs/chat/genui.mdx b/docs/content/docs/chat/genui.mdx
deleted file mode 100644
index 861590cca..000000000
--- a/docs/content/docs/chat/genui.mdx
+++ /dev/null
@@ -1,123 +0,0 @@
----
-title: GenUI
-description: Use Generative UI with Chat components.
----
-
-GenUI lets assistant messages render structured UI instead of plain text. To make it work, you need both sides of the setup:
-
-- `componentLibrary` on the frontend so OpenUI knows how to render components
-- a generated system prompt on the backend so the model knows what it is allowed to emit
-
-Passing `componentLibrary` alone is not enough.
-
-The frontend and backend have different jobs here:
-
-- the frontend renders structured responses through `componentLibrary`
-- the backend loads the generated system prompt and sends it to the model with each request
-
-If either side is missing, the model falls back to plain text or emits components the UI cannot render.
-
-Generate the system prompt with the CLI:
-
-```bash
-npx @openuidev/cli@latest generate ./src/library.ts --out src/generated/system-prompt.txt
-```
-
-The CLI auto-detects exported `PromptOptions` alongside your library, so examples and rules are included automatically. See [System Prompts](/docs/openui-lang/system-prompts) for details.
-
-## Use the chat library
-
-`openuiChatLibrary` is optimised for conversational chat: every response is wrapped in a `Card`, and it includes chat-specific components like `FollowUpBlock`, `ListBlock`, and `SectionBlock`.
-
-```tsx
-import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
-
-export default function Page() {
- return (
- <FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIAdapter()}
- componentLibrary={openuiChatLibrary}
- agentName="Assistant"
- />
- );
-}
-```
-
-In this setup:
-
-- The system prompt is generated at build time via the CLI and loaded by the backend
-- `openAIMessageFormat.toApi(messages)` converts messages before sending
-- `componentLibrary={openuiChatLibrary}` tells the UI how to render the model output
-- `openAIAdapter()` parses raw SSE chunks from the backend
-
-This is the minimal complete pattern for GenUI in a chat interface. For a non-chat renderer or custom layout, use `openuiLibrary` and `openuiPromptOptions` from the same import path.
-
-<div className="grid md:grid-cols-2 gap-6 my-6">
- <div>
- <p className="text-sm text-center font-medium mb-2">Plain text response</p>
- ![Plain text response](/docs/images/chat/genui-text-response.png)
- </div>
- <div>
- <p className="text-sm text-center font-medium mb-2">GenUI response</p>
- ![GenUI rendered response](/docs/images/chat/genui-response.png)
- </div>
-</div>
-
-## Use your own library
-
-If you need domain-specific components, keep the same request flow and swap in your own library definition:
-
-First, generate the system prompt from your custom library:
-
-```bash
-npx @openuidev/cli@latest generate ./src/lib/my-library.ts --out src/generated/system-prompt.txt
-```
-
-Then wire up the frontend — it only needs the component library for rendering:
-
-```tsx
-import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-import { myLibrary } from "@/lib/my-library";
-
-<FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIReadableStreamAdapter()}
- componentLibrary={myLibrary}
- agentName="Assistant"
-/>;
-```
-
-Your custom library needs two things:
-
-- a `createLibrary()` result, so the CLI can generate the system prompt and the frontend can render components
-- optional `PromptOptions` export for examples and rules (auto-detected by the CLI)
-
-Your backend loads the generated prompt file and sends it to the model alongside the message history.
-
-## Related guides
-
-- [End-to-End Guide](/docs/chat/from-scratch)
-- [Connecting to LLM](/docs/chat/connecting)
-- [Define Components](/docs/openui-lang/defining-components)
diff --git a/docs/content/docs/chat/headless-intro.mdx b/docs/content/docs/chat/headless-intro.mdx
deleted file mode 100644
index e1a54506a..000000000
--- a/docs/content/docs/chat/headless-intro.mdx
+++ /dev/null
@@ -1,51 +0,0 @@
----
-title: Headless Introduction
-description: Why and when to use headless mode with ChatProvider.
----
-
-This page introduces headless mode and the role of `ChatProvider` in a custom chat UI.
-
-The trade-off is simple: you get full control over rendering, but you become responsible for composing the sidebar, message list, and composer yourself.
-
-At the center is `ChatProvider`, which manages:
-
-- streaming state
-- thread list and selection
-- message sending/cancelation
-- thread-history hooks
-
-```tsx
-import { ChatProvider } from "@openuidev/react-headless";
-
-export function App() {
- return (
- <ChatProvider apiUrl="/api/chat" threadApiUrl="/api/threads">
- <MyCustomChat />
- </ChatProvider>
- );
-}
-```
-
-`ChatProvider` accepts the same backend props as the built-in layouts:
-
-- `apiUrl` or `processMessage`
-- `streamProtocol`
-- `messageFormat`
-- `threadApiUrl` or custom thread functions
-
-Thread history is not automatic. To load and save threads, you still need `threadApiUrl` or the custom thread handlers.
-
-The usual build order is:
-
-1. configure `ChatProvider` with your backend connection
-2. read state with `useThread()` and `useThreadList()`
-3. render your own sidebar, messages, and composer components
-
-{/* add visual: flow-chart showing ChatProvider at the center with hooks, backend config, and custom UI components around it */}
-
-## Related guides
-
-- [Hooks & State](/docs/chat/hooks)
-- [Custom UI Guide](/docs/chat/custom-ui-guide)
-- [Connecting to LLM](/docs/chat/connecting)
-- [Connect Thread History](/docs/chat/persistence)
diff --git a/docs/content/docs/chat/hooks.mdx b/docs/content/docs/chat/hooks.mdx
deleted file mode 100644
index 4b50fa8c6..000000000
--- a/docs/content/docs/chat/hooks.mdx
+++ /dev/null
@@ -1,166 +0,0 @@
----
-title: Hooks & State
-description: Deep dive into useThread, useThreadList, and related headless state hooks.
----
-
-All headless hooks must run inside `ChatProvider`.
-
-Use `useThread()` for the active conversation and `useThreadList()` for thread navigation. Most custom UIs need both.
-
-## Start with `ChatProvider`
-
-```tsx
-import {
- ChatProvider,
- openAIMessageFormat,
- openAIReadableStreamAdapter,
-} from "@openuidev/react-headless";
-
-export function App() {
- return (
- <ChatProvider
- apiUrl="/api/chat"
- threadApiUrl="/api/threads"
- streamProtocol={openAIReadableStreamAdapter()}
- messageFormat={openAIMessageFormat}
- >
- <MyCustomChat />
- </ChatProvider>
- );
-}
-```
-
-That provider owns the shared state. The hooks below read from and write to that state.
-
-## `useThread()`
-
-Use `useThread()` for the currently selected conversation: messages, send state, loading state, and message mutations.
-
-```tsx
-const {
- messages,
- isRunning,
- isLoadingMessages,
- threadError,
- processMessage,
- cancelMessage,
- appendMessages,
- updateMessage,
- setMessages,
- deleteMessage,
-} = useThread();
-```
-
-### Common send flow
-
-```tsx
-function Composer() {
- const { processMessage, cancelMessage, isRunning } = useThread();
- const [input, setInput] = useState("");
-
- return (
- <form
- onSubmit={(event) => {
- event.preventDefault();
- if (!input.trim() || isRunning) return;
- processMessage({ role: "user", content: input });
- setInput("");
- }}
- >
- <input value={input} onChange={(event) => setInput(event.target.value)} />
- {isRunning ? (
- <button type="button" onClick={cancelMessage}>
- Stop
- </button>
- ) : (
- <button type="submit">Send</button>
- )}
- </form>
- );
-}
-```
-
-Use `isLoadingMessages` to show a loading state when a saved thread is being hydrated, and use `threadError` to render request or load failures near the conversation surface.
-
-## `useThreadList()`
-
-Use `useThreadList()` for the sidebar: thread loading, selection, creation, pagination, and thread-level mutations.
-
-```tsx
-const {
- threads,
- isLoadingThreads,
- threadListError,
- selectedThreadId,
- hasMoreThreads,
- loadThreads,
- loadMoreThreads,
- switchToNewThread,
- createThread,
- selectThread,
- updateThread,
- deleteThread,
-} = useThreadList();
-```
-
-### Common sidebar flow
-
-```tsx
-function ThreadSidebar() {
- const {
- threads,
- selectedThreadId,
- hasMoreThreads,
- isLoadingThreads,
- loadMoreThreads,
- switchToNewThread,
- selectThread,
- deleteThread,
- } = useThreadList();
-
- return (
- <aside>
- <button onClick={switchToNewThread}>New chat</button>
-
- {threads.map((thread) => (
- <div key={thread.id}>
- <button
- onClick={() => selectThread(thread.id)}
- aria-pressed={thread.id === selectedThreadId}
- >
- {thread.title}
- </button>
- <button onClick={() => deleteThread(thread.id)}>Delete</button>
- </div>
- ))}
-
- {hasMoreThreads ? (
- <button onClick={() => loadMoreThreads()} disabled={isLoadingThreads}>
- Load more
- </button>
- ) : null}
- </aside>
- );
-}
-```
-
-`switchToNewThread()` clears the current selection so the next user message starts a new conversation. `updateThread()` is useful when you want to rename or otherwise patch thread metadata after creation.
-
-## Selectors
-
-Use selectors to minimize re-renders when you only need a small part of the store.
-
-```tsx
-const messages = useThread((state) => state.messages);
-const selectedThreadId = useThreadList((state) => state.selectedThreadId);
-```
-
-This is especially useful when your sidebar and message list are separate components and you do not want unrelated state updates to rerender both.
-
-{/* add visual: flow-chart showing how useThread maps to the active conversation and useThreadList maps to the thread sidebar */}
-
-## Related guides
-
-- [Headless Intro](/docs/chat/headless-intro)
-- [Custom UI Guide](/docs/chat/custom-ui-guide)
-- [Connect Thread History](/docs/chat/persistence)
diff --git a/docs/content/docs/chat/index.mdx b/docs/content/docs/chat/index.mdx
deleted file mode 100644
index 84b362efa..000000000
--- a/docs/content/docs/chat/index.mdx
+++ /dev/null
@@ -1,4 +0,0 @@
----
-title: Chat
-description: Production-ready chat UI for AI agents. Drop-in layouts, streaming from any LLM provider, and Generative UI — all in a few lines of code.
----
diff --git a/docs/content/docs/chat/installation.mdx b/docs/content/docs/chat/installation.mdx
deleted file mode 100644
index 0b49eaa82..000000000
--- a/docs/content/docs/chat/installation.mdx
+++ /dev/null
@@ -1,93 +0,0 @@
----
-title: Installation
-description: Add OpenUI Chat to an existing Next.js App Router application.
----
-
-This page covers package installation, style imports, and a basic render check for an existing Next.js App Router app.
-
-<Callout type="info">
- **Starting a new project?** Skip this guide and use our scaffold command instead: `npx
- @openuidev/cli@latest create --name my-app`
-</Callout>
-
-## Prerequisites
-
-This guide assumes:
-
-- Next.js App Router
-- React 18 or newer
-- a page where you can mount a chat layout
-
-## 1. Install dependencies
-
-Install the UI package, the headless core, and the icons package used by the built-in layouts.
-
-<Tabs items={["npm", "pnpm", "yarn", "bun"]}>
- <Tab value="npm">
- ```bash npm install @openuidev/react-ui @openuidev/react-headless lucide-react ```
- </Tab>
- <Tab value="pnpm">
- ```bash pnpm add @openuidev/react-ui @openuidev/react-headless lucide-react ```
- </Tab>
- <Tab value="yarn">
- ```bash yarn add @openuidev/react-ui @openuidev/react-headless lucide-react ```
- </Tab>
- <Tab value="bun">
- ```bash bun add @openuidev/react-ui @openuidev/react-headless lucide-react ```
- </Tab>
-</Tabs>
-
-## 2. Import the styles
-
-Import the component and theme styles in your root layout.
-
-```tsx
-import "@openuidev/react-ui/components.css";
-import "@openuidev/react-ui/styles/index.css";
-import "./globals.css";
-
-export default function RootLayout({ children }: { children: React.ReactNode }) {
- return (
- <html lang="en">
- <body>{children}</body>
- </html>
- );
-}
-```
-
-These imports give you the default chat layout styling and theme tokens.
-
-## 3. Render a layout to verify setup
-
-Render one of the built-in layouts on a page to confirm the package is installed correctly.
-
-```tsx
-// app/page.tsx
-import { FullScreen } from "@openuidev/react-ui";
-
-export default function Page() {
- return (
- <div className="h-screen">
- <FullScreen apiUrl="/api/chat" agentName="Assistant" />
- </div>
- );
-}
-```
-
-At this stage, the page should render the layout shell. It will not send working chat requests until you add a backend.
-
-![Expected baseline render after styles are imported](/docs/images/chat/fullscreen.png)
-
-## Related guides
-
-<Cards>
- <Card title="End-to-End Guide" href="/docs/chat/from-scratch">
- Add the backend route, message conversion, stream adapter, and optional persistence.
- </Card>
- <Card title="Explore Layouts" href="/docs/chat/fullscreen">
- Compare the built-in layouts and choose the one you want to ship.
- </Card>
- <Card title="Quick Start" href="/docs/chat/quick-start">
- Prefer a generated app instead of wiring everything manually.
- </Card>
-</Cards>
diff --git a/docs/content/docs/chat/meta.json b/docs/content/docs/chat/meta.json
deleted file mode 100644
index 062aa6803..000000000
--- a/docs/content/docs/chat/meta.json
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "title": "Chat",
- "root": true,
- "pages": [
- "---Introduction---",
- "index",
- "quick-start",
- "installation",
- "genui",
- "from-scratch",
- "---Chat Layouts---",
- "copilot",
- "fullscreen",
- "bottom-tray",
- "artifacts",
- "---Configurations---",
- "connecting",
- "persistence",
- "welcome",
- "theming",
- "custom-chat-components",
- "---Headless (Advanced)---",
- "headless-intro",
- "hooks",
- "custom-ui-guide",
- "---Backend & Integrations---",
- "api-contract",
- "nextjs",
- "providers"
- ]
-}
diff --git a/docs/content/docs/chat/nextjs.mdx b/docs/content/docs/chat/nextjs.mdx
deleted file mode 100644
index 9912a52a7..000000000
--- a/docs/content/docs/chat/nextjs.mdx
+++ /dev/null
@@ -1,102 +0,0 @@
----
-title: Next.js Implementation
-description: Build a Route Handler for streaming chat responses.
----
-
-This page covers the Route Handler pattern and matching frontend configuration for a Next.js App Router setup.
-
-If you want the full install-and-render walkthrough, use the [End-to-End Guide](/docs/chat/from-scratch) instead.
-
-This page focuses on one specific backend pattern:
-
-- `processMessage` on the frontend to send messages
-- `openAIMessageFormat` to send OpenAI chat messages
-- `openAIReadableStreamAdapter()` because `response.toReadableStream()` emits NDJSON, not raw SSE
-- the system prompt stays on the server, generated at build time by the CLI
-
-## Route handler
-
-Generate the system prompt at build time:
-
-```bash
-npx @openuidev/cli@latest generate ./src/library.ts --out src/generated/system-prompt.txt
-```
-
-Create `app/api/chat/route.ts`:
-
-```ts
-import { readFileSync } from "fs";
-import { join } from "path";
-import { NextRequest } from "next/server";
-import OpenAI from "openai";
-
-const client = new OpenAI();
-const systemPrompt = readFileSync(join(process.cwd(), "src/generated/system-prompt.txt"), "utf-8");
-
-export async function POST(req: NextRequest) {
- try {
- const { messages } = await req.json();
-
- const response = await client.chat.completions.create({
- model: "gpt-5.2",
- messages: [{ role: "system", content: systemPrompt }, ...messages],
- stream: true,
- });
-
- return new Response(response.toReadableStream(), {
- headers: {
- "Content-Type": "text/event-stream",
- "Cache-Control": "no-cache, no-transform",
- Connection: "keep-alive",
- },
- });
- } catch (err) {
- console.error(err);
- const message = err instanceof Error ? err.message : "Unknown error";
- return new Response(JSON.stringify({ error: message }), {
- status: 500,
- headers: { "Content-Type": "application/json" },
- });
- }
-}
-```
-
-The system prompt is loaded from the file generated by the CLI. It never leaves the server.
-
-## Matching frontend configuration
-
-Because `toReadableStream()` produces newline-delimited JSON, pair it with `openAIReadableStreamAdapter()` on the frontend.
-
-When using `processMessage`, you must convert messages yourself with `openAIMessageFormat.toApi(messages)` before sending. The `messageFormat` prop only applies automatically for the `apiUrl` flow.
-
-```tsx
-import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
-
-<FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIReadableStreamAdapter()}
- componentLibrary={openuiLibrary}
- agentName="Assistant"
-/>;
-```
-
-Use `openAIAdapter()` only if your backend emits raw SSE chunks instead of the OpenAI SDK readable stream.
-
-{/* add visual: flow-chart showing request from FullScreen -> /api/chat route -> OpenAI chat completions -> toReadableStream() -> openAIReadableStreamAdapter() -> rendered assistant message */}
-
-## Related guides
-
-- [Connecting to LLM](/docs/chat/connecting)
-- [Providers](/docs/chat/providers)
-- [End-to-End Guide](/docs/chat/from-scratch)
diff --git a/docs/content/docs/chat/persistence.mdx b/docs/content/docs/chat/persistence.mdx
deleted file mode 100644
index 4135d7459..000000000
--- a/docs/content/docs/chat/persistence.mdx
+++ /dev/null
@@ -1,111 +0,0 @@
----
-title: Connect Thread History
-description: Configure threadApiUrl and load thread lists and message history.
----
-
-This page explains how to connect thread lists and previous messages from a backend.
-
-To connect thread history, either:
-
-- pass `threadApiUrl` and implement the default endpoint contract used by OpenUI
-- provide custom thread functions if your API shape is different
-
-This config only affects thread history. Your live chat request still comes from `apiUrl` or `processMessage`.
-
-## Default `threadApiUrl` contract
-
-When you pass `threadApiUrl="/api/threads"`, OpenUI appends its own path segments. The default requests look like this:
-
-| Action | Method | URL | Request body | Expected response |
-| :------------ | :------- | :------------------------ | :------------- | :---------------------------------------- |
-| List threads | `GET` | `/api/threads/get` | — | `{ threads: Thread[], nextCursor?: any }` |
-| Create thread | `POST` | `/api/threads/create` | `{ messages }` | `Thread` |
-| Update thread | `PATCH` | `/api/threads/update/:id` | `Thread` | `Thread` |
-| Delete thread | `DELETE` | `/api/threads/delete/:id` | — | empty response is fine |
-| Load messages | `GET` | `/api/threads/get/:id` | — | message array in your backend format |
-
-```tsx
-import { FullScreen } from "@openuidev/react-ui";
-
-<FullScreen apiUrl="/api/chat" threadApiUrl="/api/threads" agentName="Assistant" />;
-```
-
-`createThread` sends the first user message as `messages`, already converted through your current `messageFormat`. `loadThread` expects the response body to be something `messageFormat.fromApi()` can read.
-
-## When to add `messageFormat`
-
-If your thread API stores messages in OpenUI's default shape, you do not need any extra config.
-
-If your thread API stores messages in OpenAI chat format, add `messageFormat={openAIMessageFormat}` so both chat requests and thread loading stay aligned.
-
-In other words:
-
-- `apiUrl` or `processMessage` handles sending new chat requests
-- `threadApiUrl` handles listing threads and loading saved messages
-- `messageFormat` keeps both paths aligned when your backend does not use the default AG-UI message shape
-
-```tsx
-import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-
-<FullScreen
- apiUrl="/api/chat"
- threadApiUrl="/api/threads"
- streamProtocol={openAIReadableStreamAdapter()}
- messageFormat={openAIMessageFormat}
- agentName="Assistant"
-/>;
-```
-
-## Use custom thread functions when your API differs
-
-If your backend already uses a different shape, such as:
-
-- REST routes like `/api/threads/:id/messages`
-- GraphQL
-- auth-protected endpoints with custom headers
-- a different request body for creating threads
-
-then provide the individual thread functions instead of relying on the default `threadApiUrl` behavior.
-
-```tsx
-<FullScreen
- apiUrl="/api/chat"
- fetchThreadList={async (cursor) => {
- const res = await fetch(`/api/conversations?cursor=${cursor ?? ""}`);
- return res.json();
- }}
- createThread={async (firstMessage) => {
- const res = await fetch("/api/conversations", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ firstMessage }),
- });
- return res.json();
- }}
- updateThread={async (thread) => {
- const res = await fetch(`/api/conversations/${thread.id}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(thread),
- });
- return res.json();
- }}
- deleteThread={async (id) => {
- await fetch(`/api/conversations/${id}`, { method: "DELETE" });
- }}
- loadThread={async (threadId) => {
- const res = await fetch(`/api/conversations/${threadId}/messages`);
- return res.json();
- }}
- agentName="Assistant"
-/>
-```
-
-{/* add visual: flow-chart showing how threadApiUrl maps to list, create, update, delete, and load requests, and where messageFormat affects create/load payloads */}
-
-## Related guides
-
-- [The API Contract](/docs/chat/api-contract)
-- [Connecting to LLM](/docs/chat/connecting)
-- [End-to-End Guide](/docs/chat/from-scratch)
diff --git a/docs/content/docs/chat/providers.mdx b/docs/content/docs/chat/providers.mdx
deleted file mode 100644
index 034f27343..000000000
--- a/docs/content/docs/chat/providers.mdx
+++ /dev/null
@@ -1,119 +0,0 @@
----
-title: Providers
-description: Provider-specific setup for OpenAI, Vercel AI SDK, and LangGraph.
----
-
-Choose config based on the stream format and message shape your backend emits, not just the provider name.
-
-This page maps common provider and backend patterns to the matching `streamProtocol` and `messageFormat` configuration.
-
-For the core connection concepts, see [Connecting to LLM](/docs/chat/connecting).
-
-## Common mappings
-
-| Backend pattern | `streamProtocol` | `messageFormat` | Use this when... |
-| :--------------------------------------- | :------------------------------ | :-------------------------------------------- | :------------------------------------------------------------------------------- |
-| OpenUI Protocol | none | none | Your backend already emits the default OpenUI stream and accepts OpenUI messages |
-| Raw OpenAI Chat Completions SSE | `openAIAdapter()` | `openAIMessageFormat` when needed | You forward raw `data:` SSE chunks from Chat Completions |
-| OpenAI SDK `toReadableStream()` / NDJSON | `openAIReadableStreamAdapter()` | `openAIMessageFormat` when needed | You return `response.toReadableStream()` from the OpenAI SDK |
-| OpenAI Responses API | `openAIResponsesAdapter()` | `openAIConversationMessageFormat` when needed | Your backend uses `openai.responses.create()` |
-
-Start with the backend output format. Then add `messageFormat` only if the request or stored-history message shape also differs from the OpenUI default.
-
-## OpenAI Chat Completions
-
-There are two common OpenAI Chat Completions patterns.
-
-### Raw SSE
-
-Use `openAIAdapter()` if your server forwards raw Chat Completions SSE events.
-
-```tsx
-import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-
-<FullScreen
- apiUrl="/api/chat"
- streamProtocol={openAIAdapter()}
- messageFormat={openAIMessageFormat}
- agentName="Assistant"
-/>;
-```
-
-### OpenAI SDK `toReadableStream()`
-
-Use `openAIReadableStreamAdapter()` if your route returns `response.toReadableStream()`.
-
-```tsx
-import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-
-<FullScreen
- apiUrl="/api/chat"
- streamProtocol={openAIReadableStreamAdapter()}
- messageFormat={openAIMessageFormat}
- agentName="Assistant"
-/>;
-```
-
-## OpenAI Responses API
-
-Use `openAIResponsesAdapter()` for the Responses API event stream.
-
-Add `openAIConversationMessageFormat` only if your backend also expects or stores Responses conversation items instead of the default AG-UI message shape.
-
-```tsx
-import { openAIConversationMessageFormat, openAIResponsesAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-
-<FullScreen
- apiUrl="/api/chat"
- streamProtocol={openAIResponsesAdapter()}
- messageFormat={openAIConversationMessageFormat}
- agentName="Assistant"
-/>;
-```
-
-## Vercel AI SDK
-
-Ignore the SDK name at first and inspect what your route actually returns.
-
-- If the route already speaks the OpenUI Protocol, `apiUrl` is usually enough.
-- If it returns a different stream format, keep `apiUrl` or switch to `processMessage`, then add the matching `streamProtocol`.
-- If the route expects a custom request body, use `processMessage`.
-
-## LangGraph
-
-Use the same decision rules:
-
-- start with `apiUrl` when the endpoint already matches the request and stream shape your frontend expects
-- switch to `processMessage` when you need auth headers, a custom body, dynamic routing, or provider-specific metadata
-
-`@openuidev/react-headless` ships `langGraphAdapter()` and `langGraphMessageFormat` for exactly this. Pair them with a `processMessage` that posts to a proxy route, converting messages with `langGraphMessageFormat.toApi`:
-
-```tsx
-import { langGraphAdapter, langGraphMessageFormat } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-
-<FullScreen
- processMessage={async ({ messages, abortController }) =>
- fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ messages: langGraphMessageFormat.toApi(messages) }),
- signal: abortController.signal,
- })
- }
- streamProtocol={langGraphAdapter()}
-/>;
-```
-
-For a complete, runnable version (including a multi-agent supervisor graph and the server-side proxy that hides your API key), see the [LangGraph Chat example](/docs/openui-lang/examples/langgraph-chat).
-
-{/* add visual: flow-chart showing provider choice splitting first by emitted stream format, then by whether messageFormat is needed */}
-
-## Related guides
-
-- [Connecting to LLM](/docs/chat/connecting)
-- [Next.js Implementation](/docs/chat/nextjs)
-- [The API Contract](/docs/chat/api-contract)
diff --git a/docs/content/docs/chat/quick-start.mdx b/docs/content/docs/chat/quick-start.mdx
deleted file mode 100644
index 41ba1a8e7..000000000
--- a/docs/content/docs/chat/quick-start.mdx
+++ /dev/null
@@ -1,108 +0,0 @@
----
-title: Quick Start
-description: Get a working chat UI running in under 5 minutes.
----
-
-This page shows the scaffolded setup for getting a working chat app running quickly.
-
-If you already have an existing Next.js app, use [Installation](/docs/chat/installation) or the [End-to-End Guide](/docs/chat/from-scratch) instead.
-
-## 1. Create your app
-
-Run the create command. This scaffolds a Next.js app with OpenUI Chat already wired to an OpenAI-backed route.
-
-<Tabs groupId="pkg" items={["npx", "pnpm", "yarn", "bun"]} persist>
- <Tab value="npx">```bash npx @openuidev/cli@latest create cd genui-chat-app ```</Tab>
- <Tab value="pnpm">```bash pnpm dlx @openuidev/cli@latest create cd genui-chat-app ```</Tab>
- <Tab value="yarn">```bash yarn dlx @openuidev/cli@latest create cd genui-chat-app ```</Tab>
- <Tab value="bun">```bash bunx @openuidev/cli@latest create cd genui-chat-app ```</Tab>
-</Tabs>
-
-## 2. Add your API key
-
-Create a `.env.local` file in the project root:
-
-```bash
-OPENAI_API_KEY=sk-your-key-here
-```
-
-## 3. Start the dev server
-
-<Tabs groupId="pkg" items={["npx", "pnpm", "yarn", "bun"]} persist>
- <Tab value="npx">```bash npm run dev ```</Tab>
- <Tab value="pnpm">```bash pnpm dev ```</Tab>
- <Tab value="yarn">```bash yarn dev ```</Tab>
- <Tab value="bun">```bash bun dev ```</Tab>
-</Tabs>
-
-Open [http://localhost:3000](http://localhost:3000) in your browser. You should see the default **FullScreen** chat. Try sending a message.
-
-You should see a full-page chat experience with streaming responses enabled.
-
-{/* add visual: gif showing the generated app launching, sending a message, and streaming a response in the default scaffold */}
-
-## What you just built
-
-The scaffold generates both the frontend and backend for you.
-
-You do not need to recreate these files during quick start. This section is here so you know what the scaffold already configured.
-
-### The Frontend (`app/page.tsx`)
-
-**The** frontend renders `FullScreen`, sends requests with `processMessage`, converts messages explicitly with `openAIMessageFormat.toApi(messages)`, and parses the OpenAI SDK readable stream correctly.
-
-```tsx
-import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
-
-export default function Page() {
- return (
- <FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIReadableStreamAdapter()}
- componentLibrary={openuiLibrary}
- agentName="OpenUI Chat"
- />
- );
-}
-```
-
-### The Backend (`app/api/chat/route.ts`)
-
-The scaffold also creates a Next.js route handler at `app/api/chat/route.ts`.
-
-That route:
-
-- loads the system prompt generated by the CLI at build time
-- receives OpenAI-format messages
-- prepends the system prompt
-- calls OpenAI Chat Completions with streaming enabled
-- returns `response.toReadableStream()`
-
-The scaffold includes a prebuild step (`openui generate`) that creates the system prompt from your component library. This keeps the prompt on the server — it is never sent from the frontend.
-
-## Next steps
-
-Now that the app is running, choose the next path based on what you want to change.
-
-<Cards>
- <Card title="End-to-End Guide" href="/docs/chat/from-scratch">
- Recreate the same flow in your own existing app.
- </Card>
- <Card title="Understand GenUI" href="/docs/chat/genui">
- Learn how the component library and system prompt work together.
- </Card>
- <Card title="Go Headless" href="/docs/chat/headless-intro">
- Build your own UI with `ChatProvider` and hooks.
- </Card>
-</Cards>
diff --git a/docs/content/docs/chat/theming.mdx b/docs/content/docs/chat/theming.mdx
deleted file mode 100644
index 945c060e1..000000000
--- a/docs/content/docs/chat/theming.mdx
+++ /dev/null
@@ -1,72 +0,0 @@
----
-title: Theming
-description: Customize colors, typography, and branding for Chat components.
----
-
-Built-in chat layouts mount their own `ThemeProvider` by default. Use the `theme` prop to control mode and token overrides, or disable the built-in provider if your app already wraps the UI in its own theme scope.
-
-There are two common theming paths:
-
-- set `theme.mode` when you only need light or dark mode
-- pass `lightTheme` and `darkTheme` when you need token-level visual customization
-
-## Set the mode
-
-```tsx
-import { FullScreen } from "@openuidev/react-ui";
-
-<FullScreen apiUrl="/api/chat" theme={{ mode: "dark" }} agentName="Assistant" />;
-```
-
-## Override theme tokens
-
-Use `lightTheme` and `darkTheme` inside the `theme` prop to override the built-in token sets.
-
-```tsx
-import { FullScreen, createTheme } from "@openuidev/react-ui";
-
-<FullScreen
- apiUrl="/api/chat"
- theme={{
- mode: "dark",
- lightTheme: createTheme({
- interactiveAccentDefault: "oklch(0.62 0.22 260)",
- }),
- darkTheme: createTheme({
- interactiveAccentDefault: "oklch(0.72 0.18 260)",
- }),
- }}
- agentName="Assistant"
-/>;
-```
-
-If you only pass `lightTheme`, those overrides are also used as the fallback for dark mode.
-
-## Use your own app-level theme provider
-
-If your app already wraps the page in `ThemeProvider`, disable the built-in wrapper on the chat layout.
-
-```tsx
-import { FullScreen } from "@openuidev/react-ui";
-
-<FullScreen apiUrl="/api/chat" disableThemeProvider agentName="Assistant" />;
-```
-
-`disableThemeProvider` only skips the wrapper. It does not remove any chat functionality.
-
-<div className="grid md:grid-cols-2 gap-6 my-6">
- <div>
- <p className="text-sm text-center font-medium mb-2">Light (default)</p>
- ![FullScreen light theme](/docs/images/chat/fullscreen.png)
- </div>
- <div>
- <p className="text-sm text-center font-medium mb-2">Dark</p>
- ![FullScreen dark theme](/docs/images/chat/fullscreen-dark.png)
- </div>
-</div>
-
-## Related guides
-
-- [FullScreen](/docs/chat/fullscreen)
-- [Copilot](/docs/chat/copilot)
-- [BottomTray](/docs/chat/bottom-tray)
diff --git a/docs/content/docs/chat/welcome.mdx b/docs/content/docs/chat/welcome.mdx
deleted file mode 100644
index ea6b7dc8b..000000000
--- a/docs/content/docs/chat/welcome.mdx
+++ /dev/null
@@ -1,91 +0,0 @@
----
-title: Welcome & Starters
-description: Configure the empty-state welcome message and conversation starters.
----
-
-When there are no messages yet, OpenUI Chat shows a welcome state. The same props work across the built-in layouts, including `Copilot`, `FullScreen`, and `BottomTray`.
-
-You can customize that empty state with:
-
-- `welcomeMessage`
-- `conversationStarters`
-
-## Basic welcome state
-
-```tsx
-import { Copilot } from "@openuidev/react-ui";
-
-<Copilot
- apiUrl="/api/chat"
- welcomeMessage={{
- title: "Hi there! 👋",
- description: "How can I help today?",
- }}
- conversationStarters={{
- options: [
- { displayText: "Track my order", prompt: "Where is my latest order?" },
- { displayText: "Billing help", prompt: "I have a billing question." },
- ],
- }}
-/>;
-```
-
-`displayText` is what users click. `prompt` is what gets sent to the model.
-
-## Custom welcome component
-
-If you want full control over the empty state, pass a React component instead of a config object.
-
-```tsx
-function CustomWelcome() {
- return (
- <div>
- <h2>Welcome back</h2>
- <p>Ask about orders, billing, or product recommendations.</p>
- </div>
- );
-}
-
-<Copilot apiUrl="/api/chat" welcomeMessage={CustomWelcome} agentName="Assistant" />;
-```
-
-## Conversation starter variants
-
-Use `variant="short"` for compact pill buttons or `variant="long"` for more descriptive list-style starters.
-
-```tsx
-<Copilot
- apiUrl="/api/chat"
- conversationStarters={{
- variant: "long",
- options: [
- {
- displayText: "Track my order",
- prompt: "Where is my latest order?",
- },
- {
- displayText: "Return an item",
- prompt: "How do I return a product?",
- },
- ],
- }}
- agentName="Assistant"
-/>
-```
-
-<div className="grid md:grid-cols-2 gap-6 my-6">
- <div>
- <p className="text-sm text-center font-medium mb-2">`"short"` variant</p>
- ![Short conversation starters](/docs/images/chat/starters-short.png)
- </div>
- <div>
- <p className="text-sm text-center font-medium mb-2">`"long"` variant</p>
- ![Long conversation starters](/docs/images/chat/starters-long.png)
- </div>
-</div>
-
-## Related guides
-
-- [Copilot](/docs/chat/copilot)
-- [FullScreen](/docs/chat/fullscreen)
-- [BottomTray](/docs/chat/bottom-tray)
diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.json
index ddc80b45a..0030f5227 100644
--- a/docs/content/docs/meta.json
+++ b/docs/content/docs/meta.json
@@ -1,4 +1,4 @@
{
"title": "OpenUI",
- "pages": ["openui-lang", "components", "chat", "api-reference"]
+ "pages": ["openui-lang", "components", "agent", "api-reference"]
}
diff --git a/docs/content/docs/openui-lang/examples/harnesses/pi-agent-harness.mdx b/docs/content/docs/openui-lang/examples/harnesses/pi-agent-harness.mdx
index fa422d7ce..171ae97cf 100644
--- a/docs/content/docs/openui-lang/examples/harnesses/pi-agent-harness.mdx
+++ b/docs/content/docs/openui-lang/examples/harnesses/pi-agent-harness.mdx
@@ -1,9 +1,9 @@
---
-title: Pi Agent Harness
-description: Chat with the Pi coding agent (a real read/bash/edit/write agent) and get its answers as live generative UI, bridged through the Pi SDK over an OpenAI-compatible stream.
+title: pi Agent Harness
+description: Chat with the pi coding agent (a real read/bash/edit/write agent) and get its answers as live generative UI, bridged through the pi SDK over an OpenAI-compatible stream.
---
-Anything that can stream text can drive OpenUI's renderer, including a full **coding agent**. This example connects [pi](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) (`@earendil-works/pi-coding-agent`), running its default `read` / `bash` / `edit` / `write` tools, to `<FullScreen>`. pi's [OpenUI Lang](/docs/openui-lang/overview) instructions are appended to its system prompt, so it emits component markup instead of markdown and its streamed answers render live as generative UI.
+Anything that can stream text can drive OpenUI's renderer, including a full **coding agent**. This example connects [pi](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) (`@earendil-works/pi-coding-agent`), running its default `read` / `bash` / `edit` / `write` tools, to `<AgentInterface>`. pi's [OpenUI Lang](/docs/openui-lang/overview) instructions are appended to its system prompt, so it emits component markup instead of markdown and its streamed answers render live as generative UI.
Its mid-turn activity (reasoning and tool runs) surfaces as cards too.
@@ -26,36 +26,42 @@ Its mid-turn activity (reasoning and tool runs) surfaces as cards too.
| Piece | File | Role |
| --- | --- | --- |
-| Frontend | `src/app/page.tsx` | A single `<FullScreen>` with `streamProtocol={openAIReadableStreamAdapter()}`. Generates the OpenUI Lang system prompt and sends it with each turn. |
-| Bridge route | `src/app/api/chat/route.ts` | Drives a Pi `AgentSession` and re-emits its events as NDJSON OpenAI chunks (`delta.content` is OpenUI Lang). |
+| Frontend | `src/app/page.tsx` | A single `<AgentInterface>` whose `llm.send` posts to the bridge with `streamProtocol: openAIReadableStreamAdapter()`. Generates the OpenUI Lang system prompt and sends it with each turn. |
+| Bridge route | `src/app/api/chat/route.ts` | Drives a pi `AgentSession` and re-emits its events as NDJSON OpenAI chunks (`delta.content` is OpenUI Lang). |
| Session registry | `src/lib/pi-session.ts` | One persistent `AgentSession` per chat thread, keyed by the `x-conversation-id` header. |
-| Agent | `@earendil-works/pi-coding-agent` | The Pi coding agent: `read` / `bash` / `edit` / `write` on the workspace you choose at launch. |
+| Agent | `@earendil-works/pi-coding-agent` | The pi coding agent: `read` / `bash` / `edit` / `write` on the workspace you choose at launch. |
-Everything runs in **one Next.js process**: the App-Router route _is_ the backend. The Pi SDK is embedded directly (no separate server), so there is no second service and no CORS. Each chat thread maps to one persistent Pi `AgentSession`, so multi-turn context is preserved.
+Everything runs in **one Next.js process**: the App-Router route _is_ the backend. The pi SDK is embedded directly (no separate server), so there is no second service and no CORS. Each chat thread maps to one persistent pi `AgentSession`, so multi-turn context is preserved.
## Connecting the frontend
-The client is a single `<FullScreen>`. It generates the OpenUI Lang system prompt from the component library, sends it with each turn, and parses the response with `openAIReadableStreamAdapter()` (NDJSON OpenAI chunks):
+The client is a single `<AgentInterface>` (the artifact chat surface with sidebar thread history). It generates the OpenUI Lang system prompt from the component library, sends it with each turn via its `llm.send`, and parses the response with `openAIReadableStreamAdapter()` (NDJSON OpenAI chunks):
```tsx
-import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
+import {
+ AgentInterface,
+ openAIMessageFormat,
+ openAIReadableStreamAdapter,
+ type ChatLLM,
+} from "@openuidev/react-ui";
import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
-<FullScreen
- // Each thread gets a stable id, so it maps to its own persistent Pi AgentSession.
- createThread={async () => ({ id: crypto.randomUUID(), title: "New chat", createdAt: Date.now() })}
- processMessage={async ({ threadId, messages, abortController }) =>
+const llm: ChatLLM = {
+ // threadId is stable per thread, so each thread maps to its own persistent pi AgentSession.
+ send: ({ threadId, messages, signal }) =>
fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json", "x-conversation-id": threadId },
body: JSON.stringify({ systemPrompt, messages: openAIMessageFormat.toApi(messages) }),
- signal: abortController.signal,
- })
- }
- streamProtocol={openAIReadableStreamAdapter()}
+ signal,
+ }),
+ streamProtocol: openAIReadableStreamAdapter(),
+};
+
+<AgentInterface
+ llm={llm}
componentLibrary={openuiLibrary}
agentName="OpenUI Agent Harness"
/>;
@@ -65,7 +71,7 @@ The `systemPrompt` generated here is the **same** string the backend injects int
## The bridge route
-The route keys a persistent `AgentSession` by the `x-conversation-id` header, injects the OpenUI Lang prompt via `appendSystemPrompt`, subscribes to the session's events, and re-emits them as NDJSON OpenAI chunks. Because Pi keeps its own transcript, only the newest user turn is sent to `session.prompt()`:
+The route keys a persistent `AgentSession` by the `x-conversation-id` header, injects the OpenUI Lang prompt via `appendSystemPrompt`, subscribes to the session's events, and re-emits them as NDJSON OpenAI chunks. Because pi keeps its own transcript, only the newest user turn is sent to `session.prompt()`:
```ts
// lib/pi-session.ts: one AgentSession per conversation
@@ -76,14 +82,14 @@ const loader = new DefaultResourceLoader({
cwd,
agentDir,
settingsManager,
- appendSystemPrompt: [systemPrompt], // makes Pi speak OpenUI Lang
+ appendSystemPrompt: [systemPrompt], // makes pi speak OpenUI Lang
});
await loader.reload();
const { session } = await createAgentSession({ cwd, agentDir, settingsManager, resourceLoader: loader });
```
```ts
-// app/api/chat/route.ts: translate Pi events into OpenAI NDJSON
+// app/api/chat/route.ts: translate pi events into OpenAI NDJSON
const unsubscribe = session.subscribe((event) => {
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
enqueue(ndjsonChunk({ content: event.assistantMessageEvent.delta }));
@@ -93,7 +99,7 @@ await session.prompt(lastUserText);
enqueue(ndjsonChunk({}, "stop"));
```
-The Pi SDK is ESM-only, so it is loaded with a native dynamic `import()` and marked as a webpack external in `next.config.ts` (the example runs with `--webpack`).
+The pi SDK is ESM-only, so it is loaded with a native dynamic `import()` and marked as a webpack external in `next.config.ts` (the example runs with `--webpack`).
## Thinking states
@@ -126,23 +132,23 @@ The agent's `read` / `bash` / `edit` / `write` tools act on that directory.
This example executes real code on your machine. The agent has the full `read` / `bash` / `edit` / `write` toolset, tools execute **without an approval prompt**, and the route is **unauthenticated**, so treat reaching the port as remote code execution.
-- Local, single-user use is equivalent to running the Pi CLI yourself.
+- Local, single-user use is equivalent to running the pi CLI yourself.
- For anything networked: set `PI_WEB_TOOLS=read-only`, put it behind auth, bind to loopback (`next start -H 127.0.0.1`), and sandbox the agent. `PI_AGENT_CWD` is a discovery root, **not** a sandbox: `bash` can escape it.
## Authentication
-The Pi SDK resolves a model from either an environment API key (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, ...) **or** an existing `~/.pi/agent` login from the Pi CLI. The Pi CLI is **not** required; an API key alone works.
+The pi SDK resolves a model from either an environment API key (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, ...) **or** an existing `~/.pi/agent` login from the pi CLI. The pi CLI is **not** required; an API key alone works.
## Project layout
```
examples/harnesses/pi-agent-harness/
-|- src/app/page.tsx # <FullScreen> wired to openAIReadableStreamAdapter()
-|- src/app/api/chat/route.ts # Pi event stream into NDJSON OpenAI chunks
-|- src/lib/pi-session.ts # one persistent Pi AgentSession per conversation
+|- src/app/page.tsx # <AgentInterface> wired to openAIReadableStreamAdapter()
+|- src/app/api/chat/route.ts # pi event stream into NDJSON OpenAI chunks
+|- src/lib/pi-session.ts # one persistent pi AgentSession per conversation
|- src/library.ts # the OpenUI component library (re-exported)
|- scripts/launch.mjs # picks the agent workspace, then starts Next
-|- next.config.ts # keeps the ESM-only Pi SDK external
+|- next.config.ts # keeps the ESM-only pi SDK external
```
## Run the example
@@ -153,7 +159,7 @@ From the repo root, install workspace deps once, then run the example pointed at
pnpm install
cd examples/harnesses/pi-agent-harness
-cp .env.example .env # set a provider API key (skip if you have a Pi login)
+cp .env.example .env # set a provider API key (skip if you have a pi login)
pnpm dev -- /path/to/your/project
```
diff --git a/docs/content/docs/openui-lang/examples/langgraph-chat.mdx b/docs/content/docs/openui-lang/examples/langgraph-chat.mdx
index fa1395c58..72df36075 100644
--- a/docs/content/docs/openui-lang/examples/langgraph-chat.mdx
+++ b/docs/content/docs/openui-lang/examples/langgraph-chat.mdx
@@ -3,7 +3,7 @@ title: LangGraph Chat
description: A multi-agent LangGraph supervisor that routes each message to a weather, finance, or research specialist and streams OpenUI Lang into live generative UI.
---
-OpenUI's renderer is transport-agnostic: it turns a stream of OpenUI Lang markup into interactive React components no matter how that stream is produced. This example produces it with a **multi-agent [LangGraph](https://langchain-ai.github.io/langgraphjs/) graph**: a supervisor routes each user message to one of three specialists (**weather**, **finance**, or **research**), and the chosen agent streams its answer as OpenUI Lang, which `<FullScreen>` renders into cards, tables, and charts as the tokens arrive.
+OpenUI's renderer is transport-agnostic: it turns a stream of OpenUI Lang markup into interactive React components no matter how that stream is produced. This example produces it with a **multi-agent [LangGraph](https://langchain-ai.github.io/langgraphjs/) graph**: a supervisor routes each user message to one of three specialists (**weather**, **finance**, or **research**), and the chosen agent streams its answer as OpenUI Lang, which `<AgentInterface>` renders into cards, tables, and charts as the tokens arrive.
Because every specialist shares the same OpenUI system prompt (generated from the component library), any agent you add automatically speaks generative UI.
@@ -35,32 +35,39 @@ The example runs **two processes**: the LangGraph server runs the graph (and the
## Connecting the frontend
-The client is a single `<FullScreen>`. `processMessage` posts the conversation to the proxy, and `langGraphAdapter()` parses the LangGraph SSE stream that comes back:
+The client is a single `<AgentInterface>` — the artifact chat interface. Its `llm.send` posts the conversation to the proxy, and `langGraphAdapter()` parses the LangGraph SSE stream that comes back:
```tsx
-import { langGraphAdapter, langGraphMessageFormat } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
+import {
+ AgentInterface,
+ langGraphAdapter,
+ langGraphMessageFormat,
+ type ChatLLM,
+} from "@openuidev/react-ui";
import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
-<FullScreen
- processMessage={async ({ messages, abortController }) =>
+const llm: ChatLLM = {
+ send: ({ messages, signal }) =>
fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
// Convert OpenUI messages to LangChain shape. The run is stateless,
// so the full history is sent each turn.
body: JSON.stringify({ messages: langGraphMessageFormat.toApi(messages) }),
- signal: abortController.signal,
- })
- }
- streamProtocol={langGraphAdapter()}
+ signal,
+ }),
+ streamProtocol: langGraphAdapter(),
+};
+
+<AgentInterface
+ llm={llm}
componentLibrary={openuiChatLibrary}
agentName="OpenUI + LangGraph Chat"
/>;
```
-- `processMessage`: posts the conversation to the proxy; `langGraphMessageFormat.toApi` converts OpenUI messages into the LangChain message shape the graph expects
-- `streamProtocol={langGraphAdapter()}`: parses LangGraph's `messages` SSE events back into streaming assistant text
+- `llm.send`: posts the conversation to the proxy; `langGraphMessageFormat.toApi` converts OpenUI messages into the LangChain message shape the graph expects
+- `llm.streamProtocol={langGraphAdapter()}`: parses LangGraph's `messages` SSE events back into streaming assistant text
- `componentLibrary={openuiChatLibrary}`: maps OpenUI Lang nodes to the built-in component set (cards, tables, charts, forms)
## The proxy route
@@ -136,7 +143,7 @@ Add a specialist by extending the `SPECIALISTS` map and wiring a matching `*_age
```
examples/langgraph-chat/
-|- src/app/page.tsx # <FullScreen> wired to langGraphAdapter()
+|- src/app/page.tsx # <AgentInterface> wired to langGraphAdapter()
|- src/app/api/chat/route.ts # Stateless proxy to the LangGraph server (SSE)
|- src/agent/graph.ts # Supervisor + specialist ReAct loops
|- src/agent/tools.ts # Mock weather / finance / research tools
@@ -184,5 +191,3 @@ LANGSMITH_API_KEY=lsv2-... # auth for the deployment
```
The SDK sends `LANGSMITH_API_KEY` as `x-api-key` from the server side only. Restart `pnpm dev` after changing `.env`.
-
-For the configuration-level decision between `apiUrl` and `processMessage` when wiring any LangGraph backend, see the [Providers guide](/docs/chat/providers#langgraph).
diff --git a/docs/content/docs/openui-lang/examples/shadcn-chat.mdx b/docs/content/docs/openui-lang/examples/shadcn-chat.mdx
index 77302a2b9..de299ec9c 100644
--- a/docs/content/docs/openui-lang/examples/shadcn-chat.mdx
+++ b/docs/content/docs/openui-lang/examples/shadcn-chat.mdx
@@ -64,8 +64,8 @@ See [Defining Components](/docs/openui-lang/defining-components) for the full `d
## Architecture
```
-Browser (FullScreen) -- POST /api/chat --> Next.js route --> OpenAI
- <-- SSE stream -- (OpenUI Lang + tool calls)
+Browser (AgentInterface) -- POST /api/chat --> Next.js route --> OpenAI
+ <-- SSE stream -- (OpenUI Lang + tool calls)
```
The client sends a conversation to `/api/chat`. The API route loads a generated `system-prompt.txt`, forwards the messages to the LLM with streaming and tool definitions, and returns SSE events. On the client, `openAIAdapter()` parses the SSE stream and `shadcnChatLibrary` maps each OpenUI Lang node to a shadcn/ui component that renders progressively as tokens arrive.
diff --git a/docs/content/docs/openui-lang/index.mdx b/docs/content/docs/openui-lang/index.mdx
index efa5eb440..0328507e7 100644
--- a/docs/content/docs/openui-lang/index.mdx
+++ b/docs/content/docs/openui-lang/index.mdx
@@ -48,9 +48,6 @@ OpenUI Lang was created to solve these core issues:
## What can you build?
<Cards>
- <Card title="Chat" href="/docs/chat">
- Conversational AI with generative UI responses, thread history, and prebuilt layouts.
- </Card>
<Card title="Dashboards & Apps" href="/docs/openui-lang/how-it-works">
Data-driven dashboards, CRUD interfaces, and monitoring tools, powered by live data from your
tools.
diff --git a/docs/content/docs/openui-lang/overview.mdx b/docs/content/docs/openui-lang/overview.mdx
index f1bd067b0..0457e1d2b 100644
--- a/docs/content/docs/openui-lang/overview.mdx
+++ b/docs/content/docs/openui-lang/overview.mdx
@@ -38,15 +38,14 @@ const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
Root component is `Card` (vertical container, no layout params). Adds chat-specific components like `FollowUpBlock`, `ListBlock`, and `SectionBlock`. Does not include `Stack`; responses are always single-card, vertically stacked.
-```ts
-import { openuiChatLibrary, openuiChatPromptOptions } from "@openuidev/react-ui/genui-lib";
-import { FullScreen } from "@openuidev/react-ui";
+```tsx
+import { AgentInterface, openAIAdapter } from "@openuidev/react-ui";
+import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
-// Use with a chat layout
-<FullScreen
+// Use with AgentInterface, the artifact chat interface with thread history
+<AgentInterface
+ llm={{ send, streamProtocol: openAIAdapter() }}
componentLibrary={openuiChatLibrary}
- processMessage={...}
- streamProtocol={openAIAdapter()}
/>
```
diff --git a/docs/content/docs/openui-lang/quickstart.mdx b/docs/content/docs/openui-lang/quickstart.mdx
index 11ae7f6aa..4224909f9 100644
--- a/docs/content/docs/openui-lang/quickstart.mdx
+++ b/docs/content/docs/openui-lang/quickstart.mdx
@@ -40,7 +40,7 @@ The CLI generates a Next.js app with everything wired up:
```
src/
app/
- page.tsx # FullScreen chat layout with the built-in component library
+ page.tsx # AgentInterface chat (thread history) with the built-in component library
api/chat/
route.ts # Backend route with OpenAI streaming + example tools
library.ts # Re-exports openuiChatLibrary and openuiChatPromptOptions
@@ -48,7 +48,7 @@ src/
system-prompt.txt # Auto-generated at build time via `openui generate`
```
-- **`page.tsx`**: Renders the `FullScreen` chat layout with `openuiChatLibrary` for Generative UI rendering and `openAIAdapter()` for streaming.
+- **`page.tsx`**: Renders the `AgentInterface` chat (an artifact chat surface with thread history) with `openuiChatLibrary` for Generative UI rendering. It provides an `llm` whose `send` posts messages to the route and whose `streamProtocol` is `openAIAdapter()`. Storage is optional — omit it and threads are kept in memory (wiped on reload).
- **`route.ts`**: A backend API route that sends the system prompt to the LLM and streams the response back.
- **`library.ts`**: Your component library entrypoint. The `openui generate` CLI reads this file to produce the system prompt.
diff --git a/docs/public/AGENTS.md b/docs/public/AGENTS.md
new file mode 100644
index 000000000..0ac348586
--- /dev/null
+++ b/docs/public/AGENTS.md
@@ -0,0 +1,776 @@
+# OpenUI Agent Interface: guide for coding agents
+
+OpenUI Agent Interface (`@openuidev/react-ui`) builds a complete streaming chat in
+React: generative-UI components rendered inline, durable artifacts (reports,
+slides, dashboards) in side panels, conversation history, and a mobile layout. It runs on **OpenUI Cloud** (a managed backend) or your **own backend**.
+
+This file is self-contained: everything needed to build an agent app is here.
+Everything imports from `@openuidev/react-ui`. Read the Rules first.
+
+## Rules
+
+- **Import everything from `@openuidev/react-ui`.** It re-exports the headless
+ package. Never import from `@openuidev/react-headless`.
+- **`<AgentInterface>` requires `llm`.** `storage` is optional (in-memory default,
+ wiped on reload). `componentLibrary` turns on generative UI.
+- **Stream adapters and message formats are factories. Call them.**
+ `openAIResponsesAdapter()`, never bare `openAIResponsesAdapter`.
+- **Pair the adapter with its message format.** `openAIResponsesAdapter()` with
+ `openAIConversationMessageFormat`; `openAIAdapter()` or
+ `openAIReadableStreamAdapter()` with `openAIMessageFormat`; `agUIAdapter()` with
+ `identityMessageFormat` (the default); `langGraphAdapter()` with
+ `langGraphMessageFormat`.
+- **OpenUI Cloud is two planes.** `llm` is a `ChatLLM` whose `send` posts to your
+ own `/api/chat` route, which proxies to Cloud with `THESYS_API_KEY`. `storage`
+ is `useOpenuiCloudStorage({ token: "/api/frontend-token" })`. `THESYS_API_KEY`
+ is server-side only, never in the browser.
+- **On Cloud, send only the latest message.** The Responses API replays history
+ from the conversation: `input: openAIConversationMessageFormat.toApi(messages.slice(-1))`.
+- **For Cloud, the component set, storage hook, and artifacts come from
+ `@openuidev/thesys`** (`chatLibrary`, `useOpenuiCloudStorage`,
+ `artifactRenderers`, `artifactCategories`); the server route uses
+ `@openuidev/thesys-server` (`artifactTool`, `createResponsesInstructions`).
+- **Send a message programmatically** with `useThread`:
+ `const send = useThread((s) => s.processMessage); send({ role: "user", content })`.
+- **An artifact `parser` must tolerate partial data.** While streaming, `args` is
+ a partial JSON string and `response` is `null` until the tool result lands.
+ Return `null` to skip.
+- **Build artifact props with `defineArtifactCategories(...)` and spread the
+ result** onto `<AgentInterface>`. Do not hand-write the `artifactCategories` array.
+- **Hooks only work inside `<AgentInterface>`**, and all import from
+ `@openuidev/react-ui` (including `useNav`).
+- **Import the CSS once.** `@openuidev/react-ui/components.css`, plus
+ `@openuidev/thesys/styles.css` on Cloud.
+
+## Install
+
+```bash
+npm install @openuidev/react-ui
+# OpenUI Cloud also:
+npm install @openuidev/thesys @openuidev/thesys-server
+# Authoring your own GenUI components:
+npm install @openuidev/react-lang zod
+# The `openui generate` CLI (build-time system-prompt generation):
+npm install -D @openuidev/cli
+```
+
+## Quickstart: OpenUI Cloud
+
+Three files: the client mount, a generation proxy, and a token mint.
+
+```tsx
+// app/page.tsx
+"use client";
+import "@openuidev/react-ui/components.css";
+import "@openuidev/thesys/styles.css";
+
+import {
+ AgentInterface,
+ openAIConversationMessageFormat,
+ openAIResponsesAdapter,
+ type ChatLLM,
+} from "@openuidev/react-ui";
+import {
+ chatLibrary,
+ useOpenuiCloudStorage,
+ artifactRenderers,
+ artifactCategories,
+} from "@openuidev/thesys";
+
+const llm: ChatLLM = {
+ // Cloud replays history from the conversation, so send only the latest message.
+ send: ({ threadId, messages, signal }) =>
+ fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ threadId,
+ input: openAIConversationMessageFormat.toApi(messages.slice(-1)),
+ }),
+ signal,
+ }),
+ streamProtocol: openAIResponsesAdapter(),
+};
+
+export default function App() {
+ const storage = useOpenuiCloudStorage({
+ token: "/api/frontend-token",
+ features: { artifact: true },
+ });
+
+ return (
+ <AgentInterface
+ llm={llm}
+ storage={storage}
+ componentLibrary={chatLibrary}
+ artifactRenderers={artifactRenderers}
+ artifactCategories={artifactCategories}
+ agentName="My Agent"
+ />
+ );
+}
+```
+
+```ts
+// app/api/chat/route.ts: proxies to OpenUI Cloud. THESYS_API_KEY stays server-side.
+import { artifactTool, createResponsesInstructions } from "@openuidev/thesys-server";
+
+export async function POST(req: Request) {
+ const { threadId, input } = await req.json();
+ const upstream = await fetch("https://api.thesys.dev/v1/embed/responses", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${process.env.THESYS_API_KEY}`,
+ },
+ body: JSON.stringify({
+ model: "openai/gpt-5",
+ conversation: threadId, // Cloud stores and replays the conversation
+ input,
+ stream: true,
+ store: true,
+ tools: [artifactTool()], // managed slides/report tool
+ instructions: createResponsesInstructions(),
+ }),
+ signal: req.signal, // forward browser aborts (stop button)
+ });
+ // Pipe the SSE stream straight through.
+ return new Response(upstream.body, {
+ headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache, no-transform" },
+ });
+}
+```
+
+```ts
+// app/api/frontend-token/route.ts: mints a short-lived browser token for storage reads.
+export async function POST() {
+ const res = await fetch("https://api.thesys.dev/v1/frontend-tokens", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${process.env.THESYS_API_KEY}`,
+ },
+ body: JSON.stringify({ user_id: "<your end-user id, from your own auth>" }),
+ });
+ const { token, expires_at } = await res.json();
+ return Response.json({ token, expires_at });
+}
+```
+
+```bash
+# .env.local
+THESYS_API_KEY=sk-th-your-key # server-side only
+```
+
+## Quickstart: self-hosted
+
+```tsx
+// app/page.tsx
+"use client";
+import "@openuidev/react-ui/components.css";
+import {
+ AgentInterface,
+ fetchLLM,
+ restStorage,
+ openAIReadableStreamAdapter,
+ openAIMessageFormat,
+} from "@openuidev/react-ui";
+import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
+
+const llm = fetchLLM({
+ url: "/api/chat",
+ streamAdapter: openAIReadableStreamAdapter(),
+ messageFormat: openAIMessageFormat,
+});
+const storage = restStorage({ baseUrl: "/api/threads" }); // optional; omit for in-memory
+
+export default function App() {
+ return <AgentInterface llm={llm} storage={storage} componentLibrary={openuiLibrary} />;
+}
+```
+
+```ts
+// app/api/chat/route.ts
+import OpenAI from "openai";
+import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
+
+const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
+const systemPrompt = openuiLibrary.prompt(openuiPromptOptions); // teaches the model the components
+
+export async function POST(req: Request) {
+ const { messages } = await req.json();
+ const stream = await openai.chat.completions.create({
+ model: "gpt-5",
+ messages: [{ role: "system", content: systemPrompt }, ...messages],
+ stream: true,
+ });
+ // openAIReadableStreamAdapter() parses this NDJSON.
+ return new Response(stream.toReadableStream(), {
+ headers: { "Content-Type": "application/x-ndjson" },
+ });
+}
+```
+
+`fetchLLM` POSTs `{ threadId, messages: messageFormat.toApi(messages) }` to `url`
+and forwards the abort signal. Here `messages` is the **full thread history** (the
+SDK loads it from `storage` and holds it client-side), so forward all of it to your
+provider. (Contrast Cloud, where you send only the latest because Cloud replays the
+conversation.) Your route must **stream** and **close the stream when done** (the
+client's `isRunning` flips back to `false` only on close).
+
+## `<AgentInterface>` props
+
+Required:
+- `llm: ChatLLM`: produces replies.
+
+Common:
+- `storage?: ChatStorage`: persistence (in-memory default, wiped on reload).
+- `componentLibrary?: Library`: turns on generative UI.
+- `artifactRenderers?: ArtifactRendererConfig[]`: custom artifact renderers.
+- `artifactCategories?: ArtifactCategory[]`: sidebar artifact nav groups.
+- `components?: { AssistantMessage?, UserMessage? }`: replace message rendering.
+- `agentName?: string`, `logoUrl?: string`, `labels?: AgentInterfaceLabels`.
+- `starters?: ConversationStarterProps[]`, `starterVariant?: "short" | "long"`.
+
+Routing and scroll:
+- `path?` / `defaultPath?` / `onNavigate?`: pass `onNavigate` for controlled nav.
+- `scrollVariant?: "always" | "user-message-anchor"` (default `user-message-anchor`).
+- `scrollOnLoad?: boolean` (default `true`).
+
+Children are slot overrides (see Customization).
+
+## Backends: `ChatLLM` and adapters
+
+The `llm` is a `ChatLLM`. `fetchLLM` builds one for the common case; for full
+control, write the object directly (this is what the Cloud quickstart does).
+
+```ts
+interface ChatLLM {
+ send(p: { threadId: string; messages: Message[]; signal: AbortSignal }): Promise<Response>;
+ streamProtocol: StreamProtocolAdapter; // the adapter that parses the response stream
+}
+
+// Factory for the common case:
+fetchLLM({ url, streamAdapter, messageFormat?, headers?, fetch? }): ChatLLM;
+```
+
+Stream adapters (all factories, call with `()`) and the message format each pairs with:
+
+| Adapter | Wire format | Message format |
+|---|---|---|
+| `agUIAdapter()` | AG-UI SSE (see AG-UI events) | `identityMessageFormat` (default) |
+| `openAIAdapter()` | OpenAI Chat Completions SSE | `openAIMessageFormat` |
+| `openAIReadableStreamAdapter()` | OpenAI SDK `toReadableStream()` NDJSON | `openAIMessageFormat` |
+| `openAIResponsesAdapter()` | OpenAI Responses SSE | `openAIConversationMessageFormat` |
+| `langGraphAdapter(opts?)` | LangGraph named SSE | `langGraphMessageFormat` |
+
+A `MessageFormat` is `{ toApi(messages): unknown; fromApi(data): Message[] }`.
+`toApi` shapes outgoing messages for your provider; `fromApi` parses stored
+messages back. `identityMessageFormat` passes `Message[]` through unchanged.
+
+## Storage
+
+`storage` is a `ChatStorage` with a required `thread` channel and an optional
+`artifact` channel.
+
+```ts
+interface ChatStorage { thread: ThreadStorage; artifact?: ArtifactStorage; }
+
+interface ThreadStorage {
+ listThreads(cursor?: string): Promise<{ threads: Thread[]; nextCursor?: string }>;
+ createThread(firstMessage: UserMessage): Promise<Thread>;
+ getMessages(threadId: string): Promise<Message[]>;
+ updateThread(thread: Thread): Promise<Thread>;
+ deleteThread(id: string): Promise<void>;
+}
+
+interface ArtifactStorage {
+ list(params?: ArtifactListParams): Promise<{ artifacts: ArtifactSummary[]; nextCursor?: string }>;
+ get(id: string): Promise<Artifact>;
+ update(patch: { id: string; content: unknown }): Promise<ArtifactSummary>;
+}
+
+// ArtifactSummary = { id, title, type, threadId, updatedAt? }
+// Artifact extends ArtifactSummary { content: unknown }
+// Thread = { id, title, createdAt: string | number, isPending? }
+```
+
+`Message` is a discriminated union on `role` (re-exported from `@ag-ui/core`); every
+message carries an `id`:
+
+```ts
+type Message =
+ | { id: string; role: "user"; content: string | InputContent[] } // array = multimodal
+ | { id: string; role: "assistant"; content?: string; toolCalls?: ToolCall[] }
+ | { id: string; role: "tool"; toolCallId: string; content: string }
+ | { id: string; role: "system" | "developer" | "reasoning"; content: string };
+```
+
+`restStorage({ baseUrl, messageFormat?, headers?, fetch? })` implements the
+`thread` channel against this fixed REST contract (no `artifact` channel):
+
+| Operation | Method + path | Body | Returns |
+|---|---|---|---|
+| List threads | `GET {baseUrl}/get` (`?cursor=` to paginate) | none | `{ threads, nextCursor? }` |
+| Create thread | `POST {baseUrl}/create` | `{ messages: [...] }` (first user message) | the new `Thread` |
+| Get messages | `GET {baseUrl}/get/{threadId}` | none | `Message[]` |
+| Update thread | `PATCH {baseUrl}/update/{threadId}` | the full `Thread` | the updated `Thread` |
+| Delete thread | `DELETE {baseUrl}/delete/{threadId}` | none | nothing |
+
+`restStorage` applies `messageFormat` to the `/create` body (`toApi`) and the
+`/get/{id}` response (`fromApi`), so it can match a backend that stores a
+provider-specific shape; the default is identity (no transform).
+
+For anything else, pass a hand-written `ChatStorage`. To add an artifact channel,
+supply `storage.artifact` yourself (restStorage does not).
+
+A minimal Next.js App Router backend for the `restStorage` contract (back the
+`Map` with your database):
+
+```ts
+// app/api/threads/[...path]/route.ts
+import type { Thread, Message } from "@openuidev/react-ui";
+
+const store = new Map<string, { thread: Thread; messages: Message[] }>(); // use your DB
+
+export async function GET(_req: Request, { params }: { params: Promise<{ path: string[] }> }) {
+ const { path } = await params;
+ if (path[0] === "get" && path[1]) return Response.json(store.get(path[1])?.messages ?? []);
+ return Response.json({ threads: [...store.values()].map((r) => r.thread) }); // list
+}
+export async function POST(req: Request) {
+ const { messages } = await req.json(); // create: body is { messages: [firstUserMessage] }
+ const thread: Thread = { id: crypto.randomUUID(), title: "New chat", createdAt: Date.now() };
+ store.set(thread.id, { thread, messages });
+ return Response.json(thread);
+}
+export async function PATCH(req: Request, { params }: { params: Promise<{ path: string[] }> }) {
+ const { path } = await params;
+ const thread: Thread = await req.json();
+ const row = store.get(path[1]);
+ if (row) row.thread = thread;
+ return Response.json(thread);
+}
+export async function DELETE(_req: Request, { params }: { params: Promise<{ path: string[] }> }) {
+ const { path } = await params;
+ store.delete(path[1]);
+ return new Response(null, { status: 204 });
+}
+```
+
+On Cloud, `useOpenuiCloudStorage({ token, features?, apiBaseUrl? })` provides both
+the thread and artifact channels. `features.artifact` defaults to `true` (omit
+`features` to keep artifacts on).
+
+## Generative UI
+
+The agent renders components from a `Library` inline, streaming their props as
+they arrive. Pass the library as `componentLibrary`.
+
+```tsx
+import { AgentInterface } from "@openuidev/react-ui";
+import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
+
+<AgentInterface llm={llm} componentLibrary={openuiLibrary} />;
+```
+
+`openuiLibrary` (web) / `openuiChatLibrary` cover layout, content, tables, charts,
+forms, and buttons. On Cloud use `chatLibrary` from `@openuidev/thesys`. Each
+library ships paired prompt options (`openuiPromptOptions`,
+`openuiChatPromptOptions`).
+
+The model must be told what components exist. Generate a system prompt from the
+library and send it to your provider (self-hosted): `library.prompt(promptOptions)`
+(see the self-hosted route above). On Cloud, `createResponsesInstructions()` does this.
+
+### Authoring your own components
+
+Use `@openuidev/react-lang`. A component is a Zod v4 schema (props) plus a React
+renderer. `createLibrary` bundles components into a `Library`.
+
+```tsx
+import { z } from "zod";
+import { defineComponent, createLibrary } from "@openuidev/react-lang";
+
+const StatCard = defineComponent({
+ name: "StatCard",
+ description: "A single KPI with a label, value, and optional delta percentage.",
+ props: z.object({
+ label: z.string(),
+ value: z.string(),
+ delta: z.number().optional(),
+ }),
+ component: ({ props }) => (
+ <div className="stat-card">
+ <span>{props.label}</span>
+ <strong>{props.value}</strong>
+ {props.delta != null && <em>{props.delta}%</em>}
+ </div>
+ ),
+});
+
+export const library = createLibrary({ components: [StatCard] });
+export const promptOptions = { additionalRules: ["Prefer StatCard for single metrics."] };
+```
+
+- Props **must be a Zod v4 object** (Zod 3 throws). `description` is what the model sees.
+- The renderer is `React.FC<{ props, renderNode, statementId? }>`. Because it contains JSX, name the library file `.tsx`.
+- **Nesting:** reference another component with `Child.ref` and render it with
+ `renderNode`:
+
+```tsx
+const Item = defineComponent({
+ name: "Item",
+ description: "A list row.",
+ props: z.object({ text: z.string() }),
+ component: ({ props }) => <li>{props.text}</li>,
+});
+
+const List = defineComponent({
+ name: "List",
+ description: "A bulleted list of Items.",
+ props: z.object({ children: z.array(Item.ref) }),
+ component: ({ props, renderNode }) => <ul>{renderNode(props.children)}</ul>,
+});
+```
+
+`createLibrary({ components, componentGroups?, root? })` returns a `Library` with
+`prompt(options?)`, `toSpec()`, and `toJSONSchema()`. `library.prompt(options)`
+takes `PromptOptions`:
+
+```ts
+interface PromptOptions {
+ preamble?: string;
+ additionalRules?: string[];
+ examples?: string[]; // static/layout patterns
+ toolExamples?: string[]; // shown when tools present
+ tools?: (string | ToolSpec)[];
+ editMode?: boolean; inlineMode?: boolean;
+ toolCalls?: boolean; // default true when tools provided
+ bindings?: boolean; // $variables/@Set/@Reset; default true if toolCalls
+}
+```
+
+Generate the system prompt at build time with the CLI:
+
+```bash
+openui generate src/library.tsx --out src/system-prompt.txt
+openui generate src/library.tsx --json-schema -o spec.json # component signatures
+```
+
+Mount your library: `componentLibrary={library}`, and feed
+`library.prompt(promptOptions)` to your model as the system prompt.
+
+### Interactivity
+
+Generated components can be interactive. From `@openuidev/react-lang`:
+`reactive(schema)` marks a prop as accepting a `$variable` binding;
+`useStateField(name, value?)` reads/writes form state; `useTriggerAction()` fires
+actions (`@Set`, `@Run`, `@ToAssistant`). Helpers: `useFormName`,
+`useGetFieldValue`, `useSetFieldValue`, `useIsQueryLoading`, `useIsStreaming`.
+Form state is tracked automatically and saved with the thread.
+
+## Artifacts
+
+An artifact is a durable output (report, slide deck, dashboard, code file): an
+inline preview in chat plus a full view in a side panel or page. A renderer
+matches a tool call by `toolName` and a stored artifact by `type`.
+
+```tsx
+import { defineArtifactRenderer } from "@openuidev/react-ui";
+
+const reportRenderer = defineArtifactRenderer({
+ type: "report",
+ toolName: "create_report", // string | string[]; first registration wins on a dup
+ parser: ({ args, response }, { isStreaming }) => {
+ const data = response as { id: string; title: string; body: string } | null;
+ if (!data) return null; // tolerate partial data while streaming
+ return {
+ props: data,
+ // meta null = render without registering in the thread (common while streaming)
+ meta: isStreaming ? null : { id: data.id, version: 1, heading: data.title },
+ };
+ },
+ preview: (props, controls) => <ReportCard title={props.title} onOpen={controls.open} />,
+ actual: (props) => <ReportView body={props.body} />,
+ icon: <ReportIcon />,
+ label: "Report",
+});
+```
+
+Parser contract (two paths, same renderer):
+- **Tool-call path:** `{ args, response }` exactly as the backend emitted them.
+ `args` is a partial JSON string while the LLM streams; `response` is `null`
+ until the tool result arrives (`isStreaming` is `true` until then). The SDK does
+ not pre-parse JSON.
+- **Storage path:** `{ args: undefined, response: artifact.content }`, `isStreaming`
+ false. Stored `content` must match the tool-call response shape.
+- Return `null` to skip. Return `meta: null` to render without registering.
+ `meta.id` must be stable across re-runs; `meta.type` overrides the static `type`
+ for registration. The same component instance is reused across the
+ streaming → complete transition (swap UI on `controls.isStreaming`, no remount).
+
+The parser returns `ParsedArtifact` (or `null`):
+
+```ts
+interface ParsedArtifact<Props> {
+ props: Props;
+ meta: { id: string; version: number; heading: string; type?: string } | null;
+}
+```
+
+- `id`: stable identity across re-runs. Supply it from the tool result (include an `id` field) or derive it from stable content (e.g. a slug of the title); it must not change when the same artifact re-renders.
+- `version`: bump when content changes for the same `id`; an `(id, version)` change re-registers the entry.
+- `heading`: label shown in the workspace and artifact lists.
+- `type?`: override the renderer's static `type` for this entry (one tool-owning renderer can register entries under different kinds).
+- `meta: null`: render preview/actual but skip thread registration (use while streaming).
+
+`controls` passed to `preview`/`actual`:
+`{ isActive, isStreaming, open(), close(), toggle() }`.
+
+Group renderers into sidebar categories with `defineArtifactCategories`. It
+returns both props (renderers and types deduped); spread them onto the component.
+
+```tsx
+import { AgentInterface, defineArtifactCategories } from "@openuidev/react-ui";
+
+const artifacts = defineArtifactCategories([
+ { name: "Reports", renderers: [reportRenderer], icon: <ReportIcon /> },
+ { name: "Dashboards", renderers: [dashboardRenderer], icon: <AppIcon /> },
+]);
+
+<AgentInterface llm={llm} {...artifacts} />;
+// artifacts === { artifactRenderers, artifactCategories }
+```
+
+On OpenUI Cloud, the agent produces **slides and reports** with no renderer to
+write: the managed `artifactTool()` (server) plus `artifactRenderers` /
+`artifactCategories` from `@openuidev/thesys` (client) cover them. To add your own
+artifact types on Cloud, compose: pass your custom renderers and categories
+alongside the managed ones (`artifactRenderers={[...artifactRenderers, myRenderer]}`,
+`artifactCategories={[...artifactCategories, ...myCategories]}`); a custom
+`componentLibrary` works the same way (all just `<AgentInterface>` props). The
+renderer side is reliable on Cloud. The tool that *produces* a custom artifact's
+content, though, is only fully worked in the self-hosted loop above: the managed
+`artifactTool()` generates slides/reports inside Cloud, but running your own
+artifact-producing tool on Cloud (catching its streamed call and returning the
+content into the conversation) is an advanced, less-trodden path.
+
+## Tools
+
+A tool is a `name`, a `description`, and a JSON Schema for its arguments. The model
+proposes a call; **your code runs it** (on Cloud and self-hosted alike, your code
+always runs your own tools); the result returns to the conversation. Only Cloud's
+built-in tools run inside Cloud.
+
+```ts
+const tools = [
+ {
+ type: "function",
+ name: "get_weather",
+ description: "Get the current weather for a city.",
+ parameters: {
+ type: "object",
+ properties: { city: { type: "string", description: "City name" } },
+ required: ["city"],
+ additionalProperties: false,
+ },
+ },
+];
+```
+
+**Self-hosted loop:** in your route, declare the tools to your provider, run the
+ones it asks for, append each result, and call the provider again until it returns
+a turn with no tool calls. If your route emits AG-UI events (with `agUIAdapter()`),
+emit `TOOL_CALL_START` / `TOOL_CALL_ARGS` / `TOOL_CALL_END` / `TOOL_CALL_RESULT`
+around each call between the text events (see AG-UI events).
+
+```ts
+// app/api/chat/route.ts (self-hosted, with tools)
+import OpenAI from "openai";
+const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
+
+const run: Record<string, (args: any) => Promise<unknown>> = {
+ get_weather: async ({ city }) => ({ tempC: 22, sky: "clear" }), // your real impl
+};
+
+export async function POST(req: Request) {
+ const { messages } = await req.json();
+ const convo = [...messages];
+ while (true) {
+ const res = await openai.chat.completions.create({ model: "gpt-5", messages: convo, tools });
+ const msg = res.choices[0].message;
+ if (!msg.tool_calls?.length) {
+ // No more tool calls: stream the final answer back to the client.
+ const final = await openai.chat.completions.create({ model: "gpt-5", messages: convo, stream: true });
+ return new Response(final.toReadableStream(), { headers: { "Content-Type": "application/x-ndjson" } });
+ }
+ convo.push(msg);
+ for (const call of msg.tool_calls) {
+ const out = await run[call.function.name](JSON.parse(call.function.arguments));
+ convo.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(out) });
+ }
+ }
+}
+```
+
+On Cloud, the managed `artifactTool()` runs inside Cloud. You can declare extra
+function tools in the `/api/chat` `tools` array, but executing them means catching
+the streamed tool call in your app and submitting the result back to Cloud's
+Responses API (an advanced pattern not worked here). For a fully worked custom-tool
+loop, use the self-hosted route above.
+
+A tool call is also how a custom artifact is produced: name the tool to match a
+renderer's `toolName`.
+
+## Customization (slots and primitives)
+
+Pass children to override regions. Every slot and primitive is a **static property
+of `AgentInterface`** (`<AgentInterface.Sidebar>`, `<AgentInterface.Welcome>`,
+`<AgentInterface.Route>`, and so on), not a separate import. **Slot markers**
+replace a whole region; **primitives** compose inside a slot. Omit a slot to get
+the default.
+
+Slot markers: `Sidebar`, `SidebarHeader`, `MobileHeader`, `ThreadHeader`,
+`Welcome`, `Composer`, `Workspace`, `Route`.
+Primitives: `SidebarItem`, `SidebarContent`, `SidebarSeparator`, `NewChatButton`,
+`ThreadList`, `ArtifactNav`, `Messages`, `MessageLoading`, `ScrollArea`.
+
+```tsx
+<AgentInterface llm={llm}>
+ <AgentInterface.Sidebar>
+ <AgentInterface.SidebarHeader agentName="Acme" />
+ <AgentInterface.NewChatButton />
+ <AgentInterface.SidebarItem icon={<HomeIcon />} path="/home">Home</AgentInterface.SidebarItem>
+ <AgentInterface.SidebarSeparator />
+ <AgentInterface.ThreadList />
+ </AgentInterface.Sidebar>
+
+ {/* exact-match custom route; its children replace the thread region */}
+ <AgentInterface.Route path="/home">
+ <MyHomePanel />
+ </AgentInterface.Route>
+</AgentInterface>
+```
+
+- **`Sidebar`**: omit for the default (header + new-chat + artifact nav + thread
+ list). With children, you compose the inner content from primitives.
+- **`SidebarItem`**: `{ icon?, trailing?, selected?, path?, children }`. With
+ `path`, clicking navigates and the item auto-selects when the route matches.
+- **`ArtifactNav`**: `{ className?, icon? }`. One item per `artifactCategories`
+ (or a single "Artifacts"). Renders nothing without `storage.artifact`.
+- **`Welcome`**: `{ title?, description?, image?, starters?, starterVariant? }`
+ XOR `{ children }`. Shown only while the thread is empty.
+- **`Composer`**: `{ className?, placeholder?, starters?, starterVariant?, children? }`.
+- **`Workspace`**: the artifact rail. Omit for the default; pass children to
+ replace. Hidden on mobile and on Route/artifact pages.
+- **`Route`**: `{ path, children }`, **exact match only**. Active route children
+ replace the thread region. Pair with `useNav()` to navigate.
+- **`Messages`**: `{ loader?, assistantMessage?, userMessage? }`.
+
+### Starters
+
+```tsx
+<AgentInterface
+ llm={llm}
+ starters={[{ displayText: "Summarize", prompt: "Summarize my latest report.", icon: <Bulb /> }]}
+ starterVariant="long" // "short" pills | "long" vertical list
+/>;
+```
+
+Each starter is `{ displayText, prompt, icon? }`. Clicking one sends `prompt` as a
+user message. Starters set on `AgentInterface` flow into Welcome and Composer; pass
+`[]` to a slot to suppress them there.
+
+### Custom message rendering
+
+```tsx
+import { AgentInterface, type AssistantMessage } from "@openuidev/react-ui";
+
+function CustomAssistantMessage({ message, isStreaming }: {
+ message: AssistantMessage;
+ isStreaming: boolean;
+}) {
+ return <div className="prose">{message.content ?? ""}</div>; // content empty until first token
+}
+
+<AgentInterface llm={llm} components={{ AssistantMessage: CustomAssistantMessage }} />;
+```
+
+`components.AssistantMessage` / `components.UserMessage` are independent; override
+one and the other keeps its default. When `componentLibrary` is set and you do not
+override `AssistantMessage`, assistant messages render through the library.
+
+## Hooks
+
+All import from `@openuidev/react-ui`. Call only inside `<AgentInterface>` (a
+renderer's `preview`/`actual`, slot children, message components, and `Route`
+children are all inside the tree).
+
+| Hook | Returns |
+|---|---|
+| `useNav()` | `{ path: string \| undefined; navigate(next): void }` |
+| `useThread(selector?)` | `{ messages, isRunning, isLoadingMessages, threadError, executingToolCallIds, processMessage, appendMessages, updateMessage, setMessages, deleteMessage, cancelMessage }` |
+| `useThreadList(selector?)` | `{ threads, isLoadingThreads, selectedThreadId, hasMoreThreads, loadThreads, loadMoreThreads, switchToNewThread, createThread, selectThread, updateThread, deleteThread }` |
+| `useMessage()` | `{ message: Message }` |
+| `useArtifactList(filter?)` | per-thread artifact registry, optionally filtered by `type` |
+| `useArtifactRenderer(toolName)` | the matched `ArtifactRendererConfig` or `null` |
+| `useArtifactRendererRegistry()` | `{ byToolName, byType } \| null` (escape hatch) |
+| `useArtifactStorage()` | the `ArtifactStorage` adapter or `null` |
+| `useArtifactCategories()` | `ArtifactCategory[]` |
+| `useDetailedView(viewId)` / `useActiveDetailedView()` | the detailed-view (side panel) system |
+| `useToolActivities(message, allMessages)` | `ToolActivity[]` for a message |
+
+`useThread` and `useThreadList` are selector hooks: pass a function that picks a
+slice; the component re-renders only when that slice changes. Send a message:
+`const send = useThread((s) => s.processMessage); send({ role: "user", content })`
+(`content` is a string, or an array for multimodal input).
+
+## AG-UI events (custom streaming backends)
+
+When your route streams AG-UI SSE (paired with `agUIAdapter()`), the SDK consumes
+this event subset. Emit them in order; a run ends when the stream closes.
+
+- `TEXT_MESSAGE_START` `{ messageId, role }`
+- `TEXT_MESSAGE_CONTENT` `{ messageId, delta }` (or `TEXT_MESSAGE_CHUNK`)
+- `TOOL_CALL_START` `{ toolCallId, toolCallName }`
+- `TOOL_CALL_ARGS` `{ toolCallId, delta }` (arguments stream as a partial JSON string)
+- `TOOL_CALL_END` `{ toolCallId }`
+- `TOOL_CALL_RESULT` `{ messageId, toolCallId, content }` (`content` is always a string)
+- `RUN_ERROR` `{ message, code? }`
+
+Tool status progresses `streaming → executing → complete | error`. The event types
+are re-exported from `@openuidev/react-ui` (originally `@ag-ui/core`).
+
+A `messageId` groups one assistant text message; a `toolCallId` groups one tool
+call (independent ids). For a turn that calls one tool, then replies:
+
+```
+TOOL_CALL_START { toolCallId: "t1", toolCallName: "get_weather" }
+TOOL_CALL_ARGS { toolCallId: "t1", delta: "{\"city\":\"Tokyo\"}" }
+TOOL_CALL_END { toolCallId: "t1" }
+TOOL_CALL_RESULT { messageId: "m1", toolCallId: "t1", content: "22C, clear" }
+TEXT_MESSAGE_START { messageId: "m2", role: "assistant" }
+TEXT_MESSAGE_CONTENT { messageId: "m2", delta: "It is 22C in Tokyo." }
+(then close the stream)
+```
+
+Tool and text events may interleave across rounds in one turn. Keep each tool's
+START/ARGS/END/RESULT together, and each text message's START/CONTENT under one
+`messageId`.
+
+## Factory and type reference
+
+```ts
+fetchLLM({ url, streamAdapter, messageFormat?, headers?, fetch? }): ChatLLM
+restStorage({ baseUrl, messageFormat?, headers?, fetch? }): ChatStorage // thread channel only
+defineArtifactRenderer(config): ArtifactRendererConfig
+defineArtifactCategories(groups: ArtifactCategoryGroup[]): { artifactRenderers, artifactCategories }
+
+interface ArtifactCategoryGroup { name: string; renderers: ArtifactRendererConfig[]; icon?: ReactNode; } // builder input
+interface ArtifactCategory { name: string; filter: { type: string[] }; icon?: ReactNode; } // builder output
+type CreateMessage = { role: "user"; content: string }; // processMessage input
+```
+
+Env: OpenUI Cloud uses `THESYS_API_KEY` (server-side only); self-hosted uses your
+provider key (e.g. `OPENAI_API_KEY`), also server-side only.
diff --git a/docs/public/docs/images/chat/bottom-tray.gif b/docs/public/docs/images/chat/bottom-tray.gif
deleted file mode 100644
index 951c01e1f..000000000
Binary files a/docs/public/docs/images/chat/bottom-tray.gif and /dev/null differ
diff --git a/docs/public/docs/images/chat/bottom-tray.png b/docs/public/docs/images/chat/bottom-tray.png
deleted file mode 100644
index 380ba596c..000000000
Binary files a/docs/public/docs/images/chat/bottom-tray.png and /dev/null differ
diff --git a/docs/public/docs/images/chat/copilot.png b/docs/public/docs/images/chat/copilot.png
deleted file mode 100644
index e3fa8d5e1..000000000
Binary files a/docs/public/docs/images/chat/copilot.png and /dev/null differ
diff --git a/docs/public/docs/images/chat/fullscreen-dark.png b/docs/public/docs/images/chat/fullscreen-dark.png
deleted file mode 100644
index d8c484aa9..000000000
Binary files a/docs/public/docs/images/chat/fullscreen-dark.png and /dev/null differ
diff --git a/docs/public/docs/images/chat/fullscreen.png b/docs/public/docs/images/chat/fullscreen.png
deleted file mode 100644
index 70259d49b..000000000
Binary files a/docs/public/docs/images/chat/fullscreen.png and /dev/null differ
diff --git a/docs/public/images/agent/cloud-interface-with-artifacts.png b/docs/public/images/agent/cloud-interface-with-artifacts.png
new file mode 100644
index 000000000..9914eb90d
Binary files /dev/null and b/docs/public/images/agent/cloud-interface-with-artifacts.png differ
diff --git a/docs/public/images/agent/conversation-history-sidebar.png b/docs/public/images/agent/conversation-history-sidebar.png
new file mode 100644
index 000000000..728e372e3
Binary files /dev/null and b/docs/public/images/agent/conversation-history-sidebar.png differ
diff --git a/docs/public/images/agent/custom-assistant-message.png b/docs/public/images/agent/custom-assistant-message.png
new file mode 100644
index 000000000..5c56b4aac
Binary files /dev/null and b/docs/public/images/agent/custom-assistant-message.png differ
diff --git a/docs/public/images/agent/sidebar-custom-nav-items.png b/docs/public/images/agent/sidebar-custom-nav-items.png
new file mode 100644
index 000000000..b959e444e
Binary files /dev/null and b/docs/public/images/agent/sidebar-custom-nav-items.png differ
diff --git a/docs/public/images/agent/welcome-and-starters.png b/docs/public/images/agent/welcome-and-starters.png
new file mode 100644
index 000000000..bc4cc65a7
Binary files /dev/null and b/docs/public/images/agent/welcome-and-starters.png differ
diff --git a/docs/public/images/chat/architecture.svg b/docs/public/images/chat/architecture.svg
deleted file mode 100644
index ba7831732..000000000
--- a/docs/public/images/chat/architecture.svg
+++ /dev/null
@@ -1,34 +0,0 @@
-<svg width="800" height="280" xmlns="http://www.w3.org/2000/svg">
- <rect width="800" height="280" rx="12" fill="#f4f4f5"/>
-
- <!-- Row 1: Your Backend -->
- <rect x="280" y="20" width="240" height="40" rx="8" fill="#e4e4e7"/>
- <text x="400" y="45" text-anchor="middle" font-family="system-ui, sans-serif" font-size="14" font-weight="600" fill="#3f3f46">Your Backend (any LLM)</text>
-
- <!-- Arrow -->
- <text x="400" y="75" text-anchor="middle" font-family="system-ui, sans-serif" font-size="13" fill="#a1a1aa">streams response</text>
-
- <!-- Row 2: Stream Adapter -->
- <rect x="240" y="90" width="320" height="40" rx="8" fill="#e4e4e7"/>
- <text x="400" y="115" text-anchor="middle" font-family="system-ui, sans-serif" font-size="14" font-weight="600" fill="#3f3f46">Stream Adapter (parses provider format)</text>
-
- <!-- Arrow -->
- <text x="400" y="145" text-anchor="middle" font-family="system-ui, sans-serif" font-size="13" fill="#a1a1aa">normalized events</text>
-
- <!-- Row 3: ChatProvider -->
- <rect x="200" y="160" width="400" height="40" rx="8" fill="#d4d4d8"/>
- <text x="400" y="185" text-anchor="middle" font-family="system-ui, sans-serif" font-size="14" font-weight="600" fill="#27272a">ChatProvider (messages, threads, streaming)</text>
-
- <!-- Arrow -->
- <text x="400" y="215" text-anchor="middle" font-family="system-ui, sans-serif" font-size="13" fill="#a1a1aa">React context</text>
-
- <!-- Row 4: Layout Components -->
- <rect x="120" y="230" width="170" height="36" rx="8" fill="#d4d4d8"/>
- <text x="205" y="253" text-anchor="middle" font-family="system-ui, sans-serif" font-size="13" font-weight="600" fill="#27272a">Copilot</text>
-
- <rect x="315" y="230" width="170" height="36" rx="8" fill="#d4d4d8"/>
- <text x="400" y="253" text-anchor="middle" font-family="system-ui, sans-serif" font-size="13" font-weight="600" fill="#27272a">FullScreen</text>
-
- <rect x="510" y="230" width="170" height="36" rx="8" fill="#d4d4d8"/>
- <text x="595" y="253" text-anchor="middle" font-family="system-ui, sans-serif" font-size="13" font-weight="600" fill="#27272a">BottomTray</text>
-</svg>
diff --git a/docs/public/images/chat/layouts.svg b/docs/public/images/chat/layouts.svg
deleted file mode 100644
index e489c6f8e..000000000
--- a/docs/public/images/chat/layouts.svg
+++ /dev/null
@@ -1,5 +0,0 @@
-<svg width="400" height="240" xmlns="http://www.w3.org/2000/svg">
- <rect width="400" height="240" rx="12" fill="#f4f4f5"/>
- <text x="200" y="110" text-anchor="middle" font-family="system-ui, sans-serif" font-size="18" fill="#71717a">[ Layouts Preview ]</text>
- <text x="200" y="140" text-anchor="middle" font-family="system-ui, sans-serif" font-size="13" fill="#a1a1aa">Copilot - Full Screen - Bottom Tray</text>
-</svg>
diff --git a/docs/public/videos/agent/agent-interface-hero.mp4 b/docs/public/videos/agent/agent-interface-hero.mp4
new file mode 100644
index 000000000..d151bbd0e
Binary files /dev/null and b/docs/public/videos/agent/agent-interface-hero.mp4 differ
diff --git a/docs/public/videos/agent/artifact-inline-to-side-panel.mp4 b/docs/public/videos/agent/artifact-inline-to-side-panel.mp4
new file mode 100644
index 000000000..07310434d
Binary files /dev/null and b/docs/public/videos/agent/artifact-inline-to-side-panel.mp4 differ
diff --git a/docs/public/videos/agent/generative-ui-chart-inline.mp4 b/docs/public/videos/agent/generative-ui-chart-inline.mp4
new file mode 100644
index 000000000..895bd76b1
Binary files /dev/null and b/docs/public/videos/agent/generative-ui-chart-inline.mp4 differ
diff --git a/docs/public/videos/agent/generative-ui-form-interaction.mp4 b/docs/public/videos/agent/generative-ui-form-interaction.mp4
new file mode 100644
index 000000000..4fd2ffbfa
Binary files /dev/null and b/docs/public/videos/agent/generative-ui-form-interaction.mp4 differ
diff --git a/docs/public/videos/agent/quickstart-inline-generative-ui.mp4 b/docs/public/videos/agent/quickstart-inline-generative-ui.mp4
new file mode 100644
index 000000000..ff75a1208
Binary files /dev/null and b/docs/public/videos/agent/quickstart-inline-generative-ui.mp4 differ
diff --git a/docs/public/videos/agent/tool-call-web-search.mp4 b/docs/public/videos/agent/tool-call-web-search.mp4
new file mode 100644
index 000000000..4fd4638e3
Binary files /dev/null and b/docs/public/videos/agent/tool-call-web-search.mp4 differ
diff --git a/examples/fastapi-backend/README.md b/examples/fastapi-backend/README.md
index 0288a639f..e974990a3 100644
--- a/examples/fastapi-backend/README.md
+++ b/examples/fastapi-backend/README.md
@@ -11,7 +11,7 @@ This is the first example in the repo using a non-Node.js backend — the same f
│ Vite + React │ POST │ FastAPI (Python) │
│ (port 5173) │ ──────► │ (port 8000) │
│ │ │ │
-│ • FullScreen UI │ │ • POST /api/chat │
+│ • AgentInterface UI │ │ • POST /api/chat │
│ • openAIReadable- │ NDJSON │ • OpenAI streaming │
│ StreamAdapter() │ ◄────── │ • AsyncOpenAI client │
└────────────────────────┘ └─────────────────────────┘
diff --git a/examples/fastapi-backend/frontend/package.json b/examples/fastapi-backend/frontend/package.json
index b59bfdcdd..9160dfafd 100644
--- a/examples/fastapi-backend/frontend/package.json
+++ b/examples/fastapi-backend/frontend/package.json
@@ -8,9 +8,9 @@
"preview": "vite preview"
},
"dependencies": {
- "@openuidev/react-headless": "latest",
- "@openuidev/react-lang": "latest",
- "@openuidev/react-ui": "latest",
+ "@openuidev/react-headless": "workspace:*",
+ "@openuidev/react-lang": "workspace:*",
+ "@openuidev/react-ui": "workspace:*",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
diff --git a/examples/fastapi-backend/frontend/src/App.jsx b/examples/fastapi-backend/frontend/src/App.jsx
index 83503dff2..6e0328280 100644
--- a/examples/fastapi-backend/frontend/src/App.jsx
+++ b/examples/fastapi-backend/frontend/src/App.jsx
@@ -1,31 +1,40 @@
import "@openuidev/react-ui/components.css";
import "@openuidev/react-ui/styles/index.css";
-import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
+import {
+ AgentInterface,
+ openAIMessageFormat,
+ openAIReadableStreamAdapter,
+} from "@openuidev/react-ui";
import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
+import { useMemo } from "react";
const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
export default function App() {
+ // Storage is AgentInterface's built-in in-memory default (wiped on reload). The
+ // backend call is unchanged — only the chat surface moved from FullScreen to
+ // AgentInterface.
+ const llm = useMemo(
+ () => ({
+ send: ({ messages, signal }) =>
+ fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ systemPrompt,
+ messages: openAIMessageFormat.toApi(messages),
+ }),
+ signal,
+ }),
+ streamProtocol: openAIReadableStreamAdapter(),
+ }),
+ [],
+ );
+
return (
<div className="h-screen w-screen overflow-hidden">
- <FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- systemPrompt,
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIReadableStreamAdapter()}
- componentLibrary={openuiLibrary}
- agentName="OpenUI Chat"
- />
+ <AgentInterface llm={llm} componentLibrary={openuiLibrary} agentName="OpenUI Chat" />
</div>
);
}
diff --git a/examples/form-generator/src/app/page.tsx b/examples/form-generator/src/app/page.tsx
index cc3cdba05..41ed70788 100644
--- a/examples/form-generator/src/app/page.tsx
+++ b/examples/form-generator/src/app/page.tsx
@@ -82,21 +82,16 @@ export default function Page() {
const assistantId = crypto.randomUUID();
+ const applyContent = (msg: Message) => {
+ draftContent = typeof msg.content === "string" ? msg.content : "";
+ setStreamingCode(draftContent);
+ };
+
await processStreamedMessage({
response,
adapter: openAIAdapter(),
- createMessage: (msg) => {
- draftContent = msg.content ?? "";
- setStreamingCode(draftContent);
- },
- updateMessage: (msg) => {
- draftContent = msg.content ?? "";
- setStreamingCode(draftContent);
- },
- deleteMessage: () => {
- draftContent = "";
- setStreamingCode("");
- },
+ createMessage: applyContent,
+ updateMessage: applyContent,
});
const assistantMsg: Message = {
diff --git a/examples/hands-on-table-chat/README.md b/examples/hands-on-table-chat/README.md
index 347c718e8..20c137b83 100644
--- a/examples/hands-on-table-chat/README.md
+++ b/examples/hands-on-table-chat/README.md
@@ -9,7 +9,7 @@ An AI-powered spreadsheet app that pairs a full-featured [Handsontable](https://
## Features
- **Live spreadsheet** — Handsontable grid with Excel-like editing, 386+ formula functions (via HyperFormula), context menus, column resizing, and CSV export
-- **AI chat panel** — OpenUI Copilot sidebar that understands the spreadsheet context and responds with rich UI (charts, tables, markdown)
+- **AI chat panel** — OpenUI `AgentInterface` chat surface (artifact rendering + thread history) that understands the spreadsheet context and responds with rich UI (charts, tables, markdown)
- **Bidirectional sync** — AI tool calls mutate the server-side table store, then push updates back to the grid via a `SpreadsheetTable` component
- **Formula-aware row operations** — Adding or deleting rows automatically shifts cell references in formulas (mirrors Excel/Sheets behavior)
- **Aggregate recalculation** — Total/Average/Sum/Count/Max/Min rows auto-update their formula ranges after structural changes
@@ -20,7 +20,7 @@ An AI-powered spreadsheet app that pairs a full-featured [Handsontable](https://
```
┌─────────────────────────────────┐ ┌──────────────────────────┐
│ Spreadsheet Panel │ │ Chat Panel │
-│ PersistentSpreadsheet.tsx │ │ OpenUI <Copilot /> │
+│ PersistentSpreadsheet.tsx │ │ OpenUI <AgentInterface> │
│ (Handsontable + HyperFormula) │ │ spreadsheet-library.tsx │
└──────────────┬──────────────────┘ └────────────┬─────────────┘
│ │
@@ -128,7 +128,7 @@ hands-on-table-chat/
| [`handsontable`](https://handsontable.com/) | Excel-like data grid |
| [`@handsontable/react-wrapper`](https://www.npmjs.com/package/@handsontable/react-wrapper) | React bindings for Handsontable |
| [`hyperformula`](https://hyperformula.handsontable.com/) | Formula engine (386+ Excel-compatible functions) |
-| [`@openuidev/react-ui`](https://openui.com/docs) | OpenUI chat Copilot component |
+| [`@openuidev/react-ui`](https://openui.com/docs) | OpenUI `AgentInterface` chat component |
| [`@openuidev/react-headless`](https://openui.com/docs) | OpenUI adapter and message formatting |
| [`@openuidev/react-lang`](https://openui.com/docs) | OpenUI Lang component library DSL |
| [`openai`](https://www.npmjs.com/package/openai) | OpenAI SDK for chat completions with tool calling |
diff --git a/examples/hands-on-table-chat/src/app/page.tsx b/examples/hands-on-table-chat/src/app/page.tsx
index c6867597a..fc3f3ea24 100644
--- a/examples/hands-on-table-chat/src/app/page.tsx
+++ b/examples/hands-on-table-chat/src/app/page.tsx
@@ -1,21 +1,42 @@
"use client";
-import { openAIMessageFormat, openAIAdapter } from "@openuidev/react-headless";
-import { Copilot } from "@openuidev/react-ui";
import { spreadsheetLibrary } from "@/lib/spreadsheet-library";
-import { TableProvider, useTableContext } from "./TableContext";
-import { useState, useEffect, useCallback } from "react";
+import {
+ AgentInterface,
+ openAIAdapter,
+ openAIMessageFormat,
+ type ChatLLM,
+} from "@openuidev/react-ui";
import { MessageSquare, PanelRightClose } from "lucide-react";
import dynamic from "next/dynamic";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { TableProvider, useTableContext } from "./TableContext";
-const PersistentSpreadsheet = dynamic(
- () => import("./PersistentSpreadsheet"),
- { ssr: false }
-);
+const PersistentSpreadsheet = dynamic(() => import("./PersistentSpreadsheet"), { ssr: false });
function ChatPanel({ onClose }: { onClose: () => void }) {
const { threadId } = useTableContext();
+ // AgentInterface uses its built-in in-memory storage default (wiped on reload).
+ // The backend call is unchanged — only the chat surface moved from Copilot to
+ // AgentInterface.
+ const llm = useMemo<ChatLLM>(
+ () => ({
+ send: ({ messages, signal }) =>
+ fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ messages: openAIMessageFormat.toApi(messages),
+ threadId,
+ }),
+ signal,
+ }),
+ streamProtocol: openAIAdapter(),
+ }),
+ [threadId],
+ );
+
return (
<div className="chat-panel">
<div className="chat-panel__close-row">
@@ -24,57 +45,43 @@ function ChatPanel({ onClose }: { onClose: () => void }) {
</button>
</div>
<div className="chat-panel__body">
- <Copilot
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- threadId,
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIAdapter()}
+ <AgentInterface
+ llm={llm}
componentLibrary={spreadsheetLibrary}
agentName="Spreadsheet AI"
- welcomeMessage={{
- title: "Spreadsheet AI",
- description:
- "I can help you analyze, visualize, and modify your product revenue data.",
- }}
- conversationStarters={{
- variant: "long",
- options: [
- {
- displayText: "Chart revenue by quarter",
- prompt:
- "Show me a bar chart comparing Q1 through Q4 revenue for all products.",
- },
- {
- displayText: "Add Vision Pro to the lineup",
- prompt:
- "Add a new product 'Vision Pro' in category 'Headsets' with Q1=8200, Q2=11500, Q3=14800, Q4=22000, Units Sold=450, Unit Price=3499, and a SUM formula for Annual Revenue.",
- },
- {
- displayText: "Add a profit margin column",
- prompt:
- "Add a new column called 'Profit Margin' that calculates 35% of the Annual Revenue for each product.",
- },
- {
- displayText: "Revenue breakdown by category",
- prompt:
- "Show me a pie chart of total annual revenue broken down by category (Laptops, Phones, Audio, etc.).",
- },
- {
- displayText: "Compare Q1 vs Q4 growth",
- prompt:
- "Show me a table comparing Q1 and Q4 revenue for each product with the percentage growth.",
- },
- ],
- }}
- />
+ starterVariant="long"
+ starters={[
+ {
+ displayText: "Chart revenue by quarter",
+ prompt: "Show me a bar chart comparing Q1 through Q4 revenue for all products.",
+ },
+ {
+ displayText: "Add Vision Pro to the lineup",
+ prompt:
+ "Add a new product 'Vision Pro' in category 'Headsets' with Q1=8200, Q2=11500, Q3=14800, Q4=22000, Units Sold=450, Unit Price=3499, and a SUM formula for Annual Revenue.",
+ },
+ {
+ displayText: "Add a profit margin column",
+ prompt:
+ "Add a new column called 'Profit Margin' that calculates 35% of the Annual Revenue for each product.",
+ },
+ {
+ displayText: "Revenue breakdown by category",
+ prompt:
+ "Show me a pie chart of total annual revenue broken down by category (Laptops, Phones, Audio, etc.).",
+ },
+ {
+ displayText: "Compare Q1 vs Q4 growth",
+ prompt:
+ "Show me a table comparing Q1 and Q4 revenue for each product with the percentage growth.",
+ },
+ ]}
+ >
+ <AgentInterface.Welcome
+ title="Spreadsheet AI"
+ description="I can help you analyze, visualize, and modify your product revenue data."
+ />
+ </AgentInterface>
</div>
</div>
);
@@ -101,11 +108,7 @@ export default function Home() {
{chatOpen && <ChatPanel onClose={closeChat} />}
{!chatOpen && (
- <button
- onClick={() => setChatOpen(true)}
- className="chat-fab"
- aria-label="Open chat"
- >
+ <button onClick={() => setChatOpen(true)} className="chat-fab" aria-label="Open chat">
<MessageSquare size={22} />
<span className="chat-fab__label">AI Chat</span>
</button>
diff --git a/examples/harnesses/pi-agent-harness/README.md b/examples/harnesses/pi-agent-harness/README.md
index 8e3bb842a..12a4a0522 100644
--- a/examples/harnesses/pi-agent-harness/README.md
+++ b/examples/harnesses/pi-agent-harness/README.md
@@ -14,7 +14,7 @@ launch — see **Security** below.
```
Browser (src/app/page.tsx)
- FullScreen chat ──POST /api/chat ({ systemPrompt, messages })──► route.ts (runtime=nodejs)
+ AgentInterface ──POST /api/chat ({ systemPrompt, messages })──► route.ts (runtime=nodejs)
+ openuiLibrary x-conversation-id: <threadId> │
renderer ◄──NDJSON OpenAI chunks (delta.content = OpenUI Lang)─────────┤
▼
diff --git a/examples/harnesses/pi-agent-harness/src/app/page.tsx b/examples/harnesses/pi-agent-harness/src/app/page.tsx
index 7e3d49e01..e6ec006d6 100644
--- a/examples/harnesses/pi-agent-harness/src/app/page.tsx
+++ b/examples/harnesses/pi-agent-harness/src/app/page.tsx
@@ -2,47 +2,46 @@
import "@openuidev/react-ui/components.css";
import "@openuidev/react-ui/styles/index.css";
-import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
+import {
+ AgentInterface,
+ openAIMessageFormat,
+ openAIReadableStreamAdapter,
+ type ChatLLM,
+} from "@openuidev/react-ui";
import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
+import { useMemo } from "react";
const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
export default function Home() {
+ // AgentInterface uses its built-in in-memory storage default (wiped on reload).
+ // Each new thread gets a stable client-generated id, so the per-thread
+ // x-conversation-id maps to an isolated pi AgentSession. The backend call is
+ // unchanged; only the chat surface moved from FullScreen to AgentInterface.
+ const llm = useMemo<ChatLLM>(
+ () => ({
+ send: ({ threadId, messages, signal }) =>
+ fetch("/api/chat", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ // Map each chat thread to its own persistent pi AgentSession.
+ "x-conversation-id": threadId,
+ },
+ body: JSON.stringify({
+ systemPrompt,
+ messages: openAIMessageFormat.toApi(messages),
+ }),
+ signal,
+ }),
+ streamProtocol: openAIReadableStreamAdapter(),
+ }),
+ [],
+ );
+
return (
<div className="h-screen w-screen overflow-hidden">
- <FullScreen
- // Without a thread backend, OpenUI sends a constant "ephemeral" id for
- // every chat, collapsing them onto one Pi session. Assign each new thread
- // a stable client-generated id so threads get isolated sessions and
- // "new chat" forks a fresh one.
- createThread={async (firstMessage) => {
- const content = (firstMessage as { content?: unknown }).content;
- const title =
- typeof content === "string" && content.trim()
- ? content.trim().slice(0, 50)
- : "New chat";
- return { id: crypto.randomUUID(), title, createdAt: Date.now() };
- }}
- processMessage={async ({ threadId, messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- // Map each chat thread to its own persistent Pi AgentSession.
- "x-conversation-id": threadId,
- },
- body: JSON.stringify({
- systemPrompt,
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIReadableStreamAdapter()}
- componentLibrary={openuiLibrary}
- agentName="OpenUI Agent Harness"
- />
+ <AgentInterface llm={llm} componentLibrary={openuiLibrary} agentName="OpenUI Agent Harness" />
</div>
);
}
diff --git a/examples/harnesses/vercel-eve/next-env.d.ts b/examples/harnesses/vercel-eve/next-env.d.ts
index c4b7818fb..9edff1c7c 100644
--- a/examples/harnesses/vercel-eve/next-env.d.ts
+++ b/examples/harnesses/vercel-eve/next-env.d.ts
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/dev/types/routes.d.ts";
+import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/examples/harnesses/vercel-eve/src/app/page.tsx b/examples/harnesses/vercel-eve/src/app/page.tsx
index aa56a1f70..df2df4eb7 100644
--- a/examples/harnesses/vercel-eve/src/app/page.tsx
+++ b/examples/harnesses/vercel-eve/src/app/page.tsx
@@ -1,45 +1,42 @@
"use client";
import { useTheme } from "@/hooks/use-system-theme";
-import { agUIAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
+import { AgentInterface } from "@openuidev/react-ui";
import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
import { useMemo } from "react";
import { createEveChatProps } from "../eve-chat";
export default function Page() {
const mode = useTheme();
- const chatProps = useMemo(() => createEveChatProps(), []);
+ const { llm, storage } = useMemo(() => createEveChatProps(), []);
return (
<div className="app-shell">
- <FullScreen
- {...chatProps}
- streamProtocol={agUIAdapter()}
+ <AgentInterface
+ llm={llm}
+ storage={storage}
componentLibrary={openuiChatLibrary}
agentName="Eve + OpenUI"
theme={{ mode }}
- conversationStarters={{
- variant: "short",
- options: [
- {
- displayText: "Launch checklist",
- prompt: "Create a launch checklist for a new AI feature.",
- },
- {
- displayText: "Project status",
- prompt: "Turn this into a project status brief with risks and next steps.",
- },
- {
- displayText: "Onboarding flow",
- prompt: "Design a customer onboarding flow for a B2B SaaS product.",
- },
- {
- displayText: "Support case",
- prompt: "Summarize a support case as an action dashboard.",
- },
- ],
- }}
+ starterVariant="short"
+ starters={[
+ {
+ displayText: "Launch checklist",
+ prompt: "Create a launch checklist for a new AI feature.",
+ },
+ {
+ displayText: "Project status",
+ prompt: "Turn this into a project status brief with risks and next steps.",
+ },
+ {
+ displayText: "Onboarding flow",
+ prompt: "Design a customer onboarding flow for a B2B SaaS product.",
+ },
+ {
+ displayText: "Support case",
+ prompt: "Summarize a support case as an action dashboard.",
+ },
+ ]}
/>
</div>
);
diff --git a/examples/harnesses/vercel-eve/src/eve-chat.ts b/examples/harnesses/vercel-eve/src/eve-chat.ts
index 31d3f7458..c5b8530a7 100644
--- a/examples/harnesses/vercel-eve/src/eve-chat.ts
+++ b/examples/harnesses/vercel-eve/src/eve-chat.ts
@@ -1,4 +1,9 @@
-import type { Message } from "@openuidev/react-headless";
+import {
+ agUIAdapter,
+ type ChatLLM,
+ type ChatStorage,
+ type Message,
+} from "@openuidev/react-headless";
import type { HandleMessageStreamEvent, SessionState } from "eve/client";
import { eveEventsToAGUI } from "./eve-stream";
import {
@@ -147,73 +152,66 @@ async function* runTurn(
/**
* Wires OpenUI's chat surface to an Eve agent over Eve's native session
- * protocol. `processMessage` delivers the latest user turn, maps Eve's events to
- * AG-UI, and persists the session cursor + transcript per thread. Pair with
- * `streamProtocol={agUIAdapter()}`.
+ * protocol. Returns the `llm` + `storage` adapters `<AgentInterface>` expects:
+ * `llm.send` delivers the latest user turn and maps Eve's events to AG-UI, while
+ * `storage.thread` persists the session cursor + transcript per thread.
*/
export function createEveChatProps(
storage: KVStorage = getClientStorage(),
store: ThreadStore = createThreadStore(storage),
-) {
- return {
- createThread: store.createThread,
- fetchThreadList: store.fetchThreadList,
- loadThread: store.loadThread,
- deleteThread: store.deleteThread,
- updateThread: store.updateThread,
- processMessage: async ({
- messages,
- threadId,
- abortController,
- }: {
- messages: Message[];
- threadId: string;
- abortController: AbortController;
- }): Promise<Response> => {
- store.saveMessages(threadId, messages);
-
- let nextSession = loadSession(storage, threadId);
- const turn = runTurn(
- nextSession,
- latestUserText(messages),
- abortController.signal,
- (state) => {
- nextSession = state;
- },
- );
-
- const encoder = new TextEncoder();
- let assistant = "";
-
- const body = new ReadableStream<Uint8Array>({
- async start(controller) {
- try {
- for await (const event of eveEventsToAGUI(turn)) {
- if (event.type === "TEXT_MESSAGE_CONTENT") {
- assistant += (event as { delta: string }).delta;
- }
- controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
+): { llm: ChatLLM; storage: ChatStorage } {
+ const send: ChatLLM["send"] = async ({ messages, threadId, signal }): Promise<Response> => {
+ store.saveMessages(threadId, messages);
+
+ let nextSession = loadSession(storage, threadId);
+ const turn = runTurn(nextSession, latestUserText(messages), signal, (state) => {
+ nextSession = state;
+ });
+
+ const encoder = new TextEncoder();
+ let assistant = "";
+
+ const body = new ReadableStream<Uint8Array>({
+ async start(controller) {
+ try {
+ for await (const event of eveEventsToAGUI(turn)) {
+ if (event.type === "TEXT_MESSAGE_CONTENT") {
+ assistant += (event as { delta: string }).delta;
}
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- controller.enqueue(
- encoder.encode(`data: ${JSON.stringify({ type: "RUN_ERROR", message })}\n\n`),
- );
- } finally {
- saveSession(storage, threadId, nextSession);
- if (assistant) {
- store.saveMessages(threadId, [
- ...messages,
- { id: crypto.randomUUID(), role: "assistant", content: assistant } as Message,
- ]);
- }
- controller.enqueue(encoder.encode("data: [DONE]\n\n"));
- controller.close();
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ controller.enqueue(
+ encoder.encode(`data: ${JSON.stringify({ type: "RUN_ERROR", message })}\n\n`),
+ );
+ } finally {
+ saveSession(storage, threadId, nextSession);
+ if (assistant) {
+ store.saveMessages(threadId, [
+ ...messages,
+ { id: crypto.randomUUID(), role: "assistant", content: assistant } as Message,
+ ]);
}
- },
- });
+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));
+ controller.close();
+ }
+ },
+ });
- return new Response(body, { headers: { "content-type": "text/event-stream" } });
+ return new Response(body, { headers: { "content-type": "text/event-stream" } });
+ };
+
+ return {
+ llm: { send, streamProtocol: agUIAdapter() },
+ storage: {
+ thread: {
+ listThreads: () => store.fetchThreadList(),
+ createThread: (firstMessage) => store.createThread(firstMessage),
+ getMessages: (threadId) => store.loadThread(threadId),
+ updateThread: (thread) => store.updateThread(thread),
+ deleteThread: (id) => store.deleteThread(id),
+ },
},
};
}
diff --git a/examples/langgraph-chat/README.md b/examples/langgraph-chat/README.md
index fa7f7613a..46bee444a 100644
--- a/examples/langgraph-chat/README.md
+++ b/examples/langgraph-chat/README.md
@@ -20,7 +20,7 @@ browser ──fetch /api/chat──▶ Next.js route ──@langchain/langgraph-
| Piece | File | Role |
| --- | --- | --- |
-| Frontend | `src/app/page.tsx` | `<FullScreen>` with `streamProtocol={langGraphAdapter()}`; converts messages with `langGraphMessageFormat.toApi`. |
+| Frontend | `src/app/page.tsx` | `<AgentInterface>` with `llm={{ send, streamProtocol: langGraphAdapter() }}`; converts messages with `langGraphMessageFormat.toApi`. |
| Proxy | `src/app/api/chat/route.ts` | Opens a stateless run on the LangGraph server and forwards its SSE. Keeps the API key + deployment URL server-side. |
| Graph | `src/agent/graph.ts` | Supervisor + specialist ReAct loops. Each specialist shares the generated OpenUI system prompt, so its output is OpenUI Lang. |
| Tools | `src/agent/tools.ts` | Mock `get_weather` / `get_stock_price` / `search_web` (no external keys needed). |
diff --git a/examples/langgraph-chat/src/app/page.tsx b/examples/langgraph-chat/src/app/page.tsx
index 6786d0d5e..41c2dfce7 100644
--- a/examples/langgraph-chat/src/app/page.tsx
+++ b/examples/langgraph-chat/src/app/page.tsx
@@ -2,50 +2,62 @@
import "@openuidev/react-ui/components.css";
import { useTheme } from "@/hooks/use-system-theme";
-import { langGraphAdapter, langGraphMessageFormat } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
+import {
+ AgentInterface,
+ langGraphAdapter,
+ langGraphMessageFormat,
+ type ChatLLM,
+} from "@openuidev/react-ui";
import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
+import { useMemo } from "react";
export default function Page() {
const mode = useTheme();
+ // Storage is optional; AgentInterface uses an in-memory default (wiped on
+ // reload). The backend call is unchanged — only the chat surface moved from
+ // FullScreen to AgentInterface.
+ const llm = useMemo<ChatLLM>(
+ () => ({
+ send: ({ messages, signal }) =>
+ fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ // Convert OpenUI messages to LangChain shape for the graph.
+ // The run is stateless: the full history is sent each turn.
+ messages: langGraphMessageFormat.toApi(messages),
+ }),
+ signal,
+ }),
+ streamProtocol: langGraphAdapter(),
+ }),
+ [],
+ );
+
return (
<div className="h-screen w-screen overflow-hidden relative">
- <FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- // Convert OpenUI messages to LangChain shape for the graph.
- // The run is stateless: the full history is sent each turn.
- messages: langGraphMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={langGraphAdapter()}
+ <AgentInterface
+ llm={llm}
componentLibrary={openuiChatLibrary}
agentName="OpenUI + LangGraph Chat"
theme={{ mode }}
- conversationStarters={{
- variant: "short",
- options: [
- {
- displayText: "Weather in Tokyo",
- prompt: "What's the weather like in Tokyo right now?",
- },
- { displayText: "AAPL stock price", prompt: "What's the current Apple stock price?" },
- {
- displayText: "Research a topic",
- prompt: "Give me a quick briefing on the James Webb Space Telescope.",
- },
- {
- displayText: "Compare cities",
- prompt: "Compare the weather in London and Sydney right now.",
- },
- ],
- }}
+ starterVariant="short"
+ starters={[
+ {
+ displayText: "Weather in Tokyo",
+ prompt: "What's the weather like in Tokyo right now?",
+ },
+ { displayText: "AAPL stock price", prompt: "What's the current Apple stock price?" },
+ {
+ displayText: "Research a topic",
+ prompt: "Give me a quick briefing on the James Webb Space Telescope.",
+ },
+ {
+ displayText: "Compare cities",
+ prompt: "Compare the weather in London and Sydney right now.",
+ },
+ ]}
/>
</div>
);
diff --git a/examples/mastra-chat/README.md b/examples/mastra-chat/README.md
index ce2f3c475..a0b49e879 100644
--- a/examples/mastra-chat/README.md
+++ b/examples/mastra-chat/README.md
@@ -4,7 +4,7 @@ An [OpenUI](https://openui.com) example showing how to wire a [Mastra](https://m
## What this demonstrates
-- Using `agUIAdapter()` as the `streamProtocol` on OpenUI's `<FullScreen />` component
+- Using `agUIAdapter()` as the `streamProtocol` in the `llm` config of OpenUI's `<AgentInterface />` component
- A Mastra `Agent` with `createTool` tools (weather and stock price) running in a Next.js API route
- Streaming AG-UI protocol events from the server to the client via SSE
@@ -34,7 +34,7 @@ Open [http://localhost:3000](http://localhost:3000) to see the chat interface.
The server (`src/app/api/chat/route.ts`) wraps a Mastra `Agent` with `@ag-ui/mastra`'s `MastraAgent`, which emits AG-UI protocol events. These events are serialized as SSE and streamed to the client.
-The frontend (`src/app/page.tsx`) uses `agUIAdapter()` from `@openuidev/react-headless` as the `streamProtocol` for the `<FullScreen />` component. The adapter parses the SSE stream into internal chat events that drive the UI.
+The frontend (`src/app/page.tsx`) renders OpenUI's `<AgentInterface />` (the artifact chat interface with thread history), passing it an `llm` whose `streamProtocol` is `agUIAdapter()` from `@openuidev/react-ui`. Storage is optional — `AgentInterface` defaults to in-memory storage (wiped on reload) — so no `storage` prop is needed. The adapter parses the SSE stream into internal chat events that drive the UI.
To add more tools, define them with `createTool` in `src/app/api/chat/route.ts` and pass them to the `Agent`.
diff --git a/examples/mastra-chat/src/app/page.tsx b/examples/mastra-chat/src/app/page.tsx
index a64566126..8571dbdfe 100644
--- a/examples/mastra-chat/src/app/page.tsx
+++ b/examples/mastra-chat/src/app/page.tsx
@@ -1,47 +1,54 @@
"use client";
import { useTheme } from "@/hooks/use-system-theme";
-import { agUIAdapter } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
+import { AgentInterface, agUIAdapter, type ChatLLM } from "@openuidev/react-ui";
import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
+import { useMemo } from "react";
export default function Page() {
const mode = useTheme();
+ // The backend call is unchanged — only the chat surface moved from FullScreen
+ // to AgentInterface. Storage is omitted, so AgentInterface uses its built-in
+ // in-memory default (wiped on reload).
+ const llm = useMemo<ChatLLM>(
+ () => ({
+ send: ({ messages, threadId, signal }) =>
+ fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ messages, threadId }),
+ signal,
+ }),
+ streamProtocol: agUIAdapter(),
+ }),
+ [],
+ );
+
return (
<div className="h-screen w-screen overflow-hidden relative">
- <FullScreen
- processMessage={async ({ messages, threadId, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ messages, threadId }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={agUIAdapter()}
+ <AgentInterface
+ llm={llm}
componentLibrary={openuiChatLibrary}
agentName="OpenUI + Mastra Chat"
theme={{ mode }}
- conversationStarters={{
- variant: "short",
- options: [
- {
- displayText: "Weather in Tokyo",
- prompt: "What's the weather like in Tokyo right now?",
- },
- { displayText: "AAPL stock price", prompt: "What's the current Apple stock price?" },
- {
- displayText: "Contact form",
- prompt: "Build me a contact form with name, email, topic, and message fields.",
- },
- {
- displayText: "Data table",
- prompt:
- "Show me a table of the top 5 programming languages by popularity with year created.",
- },
- ],
- }}
+ starterVariant="short"
+ starters={[
+ {
+ displayText: "Weather in Tokyo",
+ prompt: "What's the weather like in Tokyo right now?",
+ },
+ { displayText: "AAPL stock price", prompt: "What's the current Apple stock price?" },
+ {
+ displayText: "Contact form",
+ prompt: "Build me a contact form with name, email, topic, and message fields.",
+ },
+ {
+ displayText: "Data table",
+ prompt:
+ "Show me a table of the top 5 programming languages by popularity with year created.",
+ },
+ ]}
/>
</div>
);
diff --git a/examples/material-ui-chat/README.md b/examples/material-ui-chat/README.md
index 3a24912db..652e26e80 100644
--- a/examples/material-ui-chat/README.md
+++ b/examples/material-ui-chat/README.md
@@ -14,7 +14,14 @@ header = CardHeader("Q1 Sales")
tbl = Table([Col("Product"), Col("Revenue", "number")], [["Widget", 1200]])
```
-On the client, `<FullScreen />` from `@openuidev/react-ui` manages conversation state, streaming, input, and rendering. It parses the incoming SSE stream with `openAIAdapter()` and renders each OpenUI Lang node using `muiChatLibrary` — the custom component library defined in `src/lib/mui-genui/`.
+On the client, `<AgentInterface />` from `@openuidev/react-ui` provides the artifact chat interface — thread history, streaming, input, and rendering. It requires an `llm` object whose `send()` calls the backend and whose `streamProtocol` parses the incoming SSE stream with `openAIAdapter()`, and a `componentLibrary` (`muiChatLibrary` — the custom component library defined in `src/lib/mui-genui/`) used to render each OpenUI Lang node. `storage` is optional — threads live in memory by default and reset on reload.
+
+```tsx
+<AgentInterface
+ llm={{ send, streamProtocol: openAIAdapter() }}
+ componentLibrary={muiChatLibrary}
+/>
+```
## Architecture
@@ -22,14 +29,14 @@ On the client, `<FullScreen />` from `@openuidev/react-ui` manages conversation
┌────────────────────────────────────┐ ┌────────────────────────────────────┐
│ Browser │ HTTP │ Next.js API Route │
│ │ ──────►│ │
-│ • <FullScreen /> manages UI │ │ • Loads system-prompt.txt │
+│ • <AgentInterface /> manages UI │ │ • Loads system-prompt.txt │
│ • openAIAdapter() parses SSE │◄────── │ • Calls LLM with runTools │
│ • muiChatLibrary renders nodes │ SSE │ • Executes tools server-side │
│ • MUI ThemeProvider + CssBaseline │ │ • Streams response as SSE events │
└────────────────────────────────────┘ └────────────────────────────────────┘
```
-1. The user types a message. `<FullScreen />` calls `processMessage`, which `POST`s to `/api/chat` with the conversation history formatted via `openAIMessageFormat.toApi()`.
+1. The user types a message. `<AgentInterface />` invokes the `llm.send()` callback, which `POST`s to `/api/chat` with the conversation history formatted via `openAIMessageFormat.toApi()`.
2. The API route reads `src/generated/system-prompt.txt`, instantiates an OpenAI client, and calls `runTools` — the OpenAI SDK's multi-step tool-execution loop.
3. Tool calls run server-side; results are fed back to the model automatically and emitted as SSE events.
4. The LLM streams a final OpenUI Lang response. The stream ends with `data: [DONE]`.
@@ -43,7 +50,7 @@ material-ui-chat/
│ ├── library.ts # Entry the OpenUI CLI reads to generate the prompt
│ ├── app/
│ │ ├── api/chat/route.ts # Streaming chat endpoint (OpenAI SDK + SSE)
-│ │ ├── page.tsx # Mounts <FullScreen /> + color-mode toggle
+│ │ ├── page.tsx # Mounts <AgentInterface /> + color-mode toggle
│ │ ├── layout.tsx # Root layout with ColorModeProvider
│ │ └── globals.css # Minimal full-height reset
│ ├── hooks/
diff --git a/examples/material-ui-chat/next-env.d.ts b/examples/material-ui-chat/next-env.d.ts
index c4b7818fb..9edff1c7c 100644
--- a/examples/material-ui-chat/next-env.d.ts
+++ b/examples/material-ui-chat/next-env.d.ts
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/dev/types/routes.d.ts";
+import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/examples/material-ui-chat/src/app/page.tsx b/examples/material-ui-chat/src/app/page.tsx
index 5c1e43730..264e23e90 100644
--- a/examples/material-ui-chat/src/app/page.tsx
+++ b/examples/material-ui-chat/src/app/page.tsx
@@ -5,8 +5,13 @@ import LightModeIcon from "@mui/icons-material/LightMode";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import Tooltip from "@mui/material/Tooltip";
-import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
+import {
+ AgentInterface,
+ openAIAdapter,
+ openAIMessageFormat,
+ type ChatLLM,
+} from "@openuidev/react-ui";
+import { useMemo } from "react";
import { useColorMode } from "@/hooks/use-system-theme";
import { muiChatLibrary } from "@/lib/mui-genui";
@@ -14,61 +19,67 @@ import { muiChatLibrary } from "@/lib/mui-genui";
export default function Page() {
const { mode, toggle } = useColorMode();
+ 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 (
<Box sx={{ height: "100vh", width: "100vw", overflow: "hidden", position: "relative" }}>
<Box sx={{ position: "fixed", top: 12, right: 16, zIndex: 1300 }}>
<Tooltip title={mode === "dark" ? "Switch to light mode" : "Switch to dark mode"}>
<IconButton onClick={toggle} size="small" aria-label="Toggle color mode">
- {mode === "dark" ? <LightModeIcon fontSize="small" /> : <DarkModeIcon fontSize="small" />}
+ {mode === "dark" ? (
+ <LightModeIcon fontSize="small" />
+ ) : (
+ <DarkModeIcon fontSize="small" />
+ )}
</IconButton>
</Tooltip>
</Box>
- <FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIAdapter()}
+ <AgentInterface
+ llm={llm}
componentLibrary={muiChatLibrary}
agentName="Material UI Chat"
theme={{ mode }}
- conversationStarters={{
- variant: "short",
- options: [
- {
- displayText: "Startup dashboard",
- prompt:
- "Build a startup analytics dashboard with a CardHeader, Tabs (Revenue BarChart, Growth LineChart, Breakdown PieChart), a key metrics Table, a progress bar toward the annual goal, and follow-ups.",
- },
- {
- displayText: "Onboarding form",
- prompt:
- "Create an account onboarding form with an info Alert, then a Form containing inputs for name and email, a Select for plan, and a SwitchGroup for notification preferences. Add follow-ups.",
- },
- {
- displayText: "Project status",
- prompt:
- "Generate a project status report with a CardHeader, a warning Alert for blockers, a List of this week's tasks, an Accordion (Done, In progress, Blocked), and a BarChart of story points per engineer. Add follow-ups.",
- },
- {
- displayText: "Pricing comparison",
- prompt:
- "Show a pricing comparison with a CardHeader, a Table comparing three plans, a List of included features, and buttons to choose a plan. Add follow-ups.",
- },
- {
- displayText: "Chart showcase",
- prompt:
- "Build a 'Quarterly Report' with Tabs containing a grouped BarChart (revenue by region, 2 series), a LineChart (monthly active users, 2 series), and a donut PieChart (traffic sources, 4 slices). Below, add a summary Table and follow-ups.",
- },
- ],
- }}
+ starterVariant="short"
+ starters={[
+ {
+ displayText: "Startup dashboard",
+ prompt:
+ "Build a startup analytics dashboard with a CardHeader, Tabs (Revenue BarChart, Growth LineChart, Breakdown PieChart), a key metrics Table, a progress bar toward the annual goal, and follow-ups.",
+ },
+ {
+ displayText: "Onboarding form",
+ prompt:
+ "Create an account onboarding form with an info Alert, then a Form containing inputs for name and email, a Select for plan, and a SwitchGroup for notification preferences. Add follow-ups.",
+ },
+ {
+ displayText: "Project status",
+ prompt:
+ "Generate a project status report with a CardHeader, a warning Alert for blockers, a List of this week's tasks, an Accordion (Done, In progress, Blocked), and a BarChart of story points per engineer. Add follow-ups.",
+ },
+ {
+ displayText: "Pricing comparison",
+ prompt:
+ "Show a pricing comparison with a CardHeader, a Table comparing three plans, a List of included features, and buttons to choose a plan. Add follow-ups.",
+ },
+ {
+ displayText: "Chart showcase",
+ prompt:
+ "Build a 'Quarterly Report' with Tabs containing a grouped BarChart (revenue by region, 2 series), a LineChart (monthly active users, 2 series), and a donut PieChart (traffic sources, 4 slices). Below, add a summary Table and follow-ups.",
+ },
+ ]}
/>
</Box>
);
diff --git a/examples/openui-artifact-demo/.dockerignore b/examples/openui-artifact-demo/.dockerignore
deleted file mode 100644
index 999ffc10a..000000000
--- a/examples/openui-artifact-demo/.dockerignore
+++ /dev/null
@@ -1,39 +0,0 @@
-# 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 file
diff --git a/examples/openui-artifact-demo/Dockerfile b/examples/openui-artifact-demo/Dockerfile
deleted file mode 100644
index b3a36dfe1..000000000
--- a/examples/openui-artifact-demo/Dockerfile
+++ /dev/null
@@ -1,73 +0,0 @@
-# syntax=docker/dockerfile:1.7
-# --------------------------------------------------
-# Build stage
-# --------------------------------------------------
-FROM node:20-alpine AS builder
-
-WORKDIR /app
-
-RUN apk add --no-cache libc6-compat
-ARG PNPM_VERSION=9.12.0
-RUN corepack enable && corepack prepare pnpm@${PNPM_VERSION} --activate
-
-ENV NEXT_TELEMETRY_DISABLED=1
-
-COPY pnpm-workspace.yaml package.json pnpm-lock.yaml tsconfig.json ./
-
-COPY packages/openui-cli/package.json ./packages/openui-cli/
-COPY packages/react-ui/package.json ./packages/react-ui/
-COPY packages/react-headless/package.json ./packages/react-headless/
-COPY packages/react-lang/package.json ./packages/react-lang/
-COPY examples/openui-chat/package.json ./examples/openui-chat/
-
-RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
- pnpm install --frozen-lockfile --ignore-scripts
-
-COPY packages/openui-cli ./packages/openui-cli
-COPY packages/react-ui ./packages/react-ui
-COPY packages/react-headless ./packages/react-headless
-COPY packages/react-lang ./packages/react-lang
-COPY examples/openui-chat ./examples/openui-chat
-
-RUN pnpm --filter @openuidev/cli build
-RUN pnpm --filter @openuidev/react-ui build
-RUN pnpm --filter @openuidev/react-headless build
-RUN pnpm --filter @openuidev/react-lang build
-
-WORKDIR /app/examples/openui-chat
-RUN node /app/packages/openui-cli/dist/index.js generate src/library.ts --out src/generated/system-prompt.txt \
- && pnpm build
-
-
-
-# --------------------------------------------------
-# Runtime stage
-# --------------------------------------------------
-FROM node:20-alpine AS runner
-
-WORKDIR /app
-
-RUN apk add --no-cache libc6-compat
-
-ENV NODE_ENV=production
-ENV NEXT_TELEMETRY_DISABLED=1
-ENV PORT=3000 HOSTNAME=0.0.0.0
-
-RUN addgroup -S nodejs && adduser -S nextjs -G nodejs
-USER nextjs
-
-# Copy full standalone output to avoid brittle partial-copy assumptions
-COPY --from=builder --chown=nextjs:nodejs /app/examples/openui-chat/.next/standalone ./
-
-# Static assets expected by Next at runtime
-COPY --from=builder --chown=nextjs:nodejs /app/examples/openui-chat/.next/static ./examples/openui-chat/.next/static
-
-# If your app has a public directory, include this line
-# COPY --from=builder --chown=nextjs:nodejs /app/examples/openui-chat/public ./examples/openui-chat/public
-
-EXPOSE 3000
-
-HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
- CMD node -e "fetch('http://127.0.0.1:3000').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
-
-CMD ["node", "examples/openui-chat/server.js"]
\ No newline at end of file
diff --git a/examples/openui-artifact-demo/README.md b/examples/openui-artifact-demo/README.md
deleted file mode 100644
index e2f54d200..000000000
--- a/examples/openui-artifact-demo/README.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# OpenUI Artifact Demo
-
-A demo application showcasing the OpenUI artifact system for displaying generated code in a resizable side panel.
-
-## Features
-
-- **Artifact Code Blocks**: AI-generated code appears as compact previews in chat
-- **Side Panel**: Click "View Code" to open the full code in a resizable artifact panel
-- **Syntax Highlighting**: Full Prism-based syntax highlighting in the artifact panel
-- **Multiple Artifacts**: Multiple code blocks per conversation, one active at a time
-- **Copy to Clipboard**: One-click code copying from the artifact panel
-
-## Getting Started
-
-```bash
-# Install dependencies (from repo root)
-pnpm install
-
-# Generate the system prompt
-pnpm --filter openui-artifact-demo generate:prompt
-
-# Start the development server
-pnpm --filter openui-artifact-demo dev
-```
-
-Set your OpenAI API key:
-```bash
-export OPENAI_API_KEY=your-key-here
-```
-
-## How It Works
-
-This example extends the standard OpenUI chat library with a custom `ArtifactCodeBlock` component that integrates with the OpenUI artifact system:
-
-1. User asks for code (e.g., "Build me a React login form")
-2. AI generates a response using `ArtifactCodeBlock` components
-3. Each code block shows an inline preview in the chat
-4. Clicking "View Code" opens the full code in the artifact side panel
-5. The panel is resizable and supports syntax highlighting + copy
-
-## Architecture
-
-- `src/components/ArtifactCodeBlock/` — Custom genui component with inline preview and artifact panel view
-- `src/library.ts` — Extended component library with ArtifactCodeBlock
-- `src/app/page.tsx` — Main page using FullScreen layout
-- `src/app/api/chat/route.ts` — API route for OpenAI streaming
diff --git a/examples/openui-artifact-demo/next.config.ts b/examples/openui-artifact-demo/next.config.ts
deleted file mode 100644
index 7e1f0ae21..000000000
--- a/examples/openui-artifact-demo/next.config.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import type { NextConfig } from "next";
-
-const nextConfig: NextConfig = {
- output: "standalone",
- turbopack: {},
-};
-
-export default nextConfig;
diff --git a/examples/openui-artifact-demo/package.json b/examples/openui-artifact-demo/package.json
deleted file mode 100644
index 2f5f0184c..000000000
--- a/examples/openui-artifact-demo/package.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "name": "openui-artifact-demo",
- "version": "0.1.0",
- "private": true,
- "scripts": {
- "generate:prompt": "pnpm --filter @openuidev/cli build && pnpm exec openui generate src/library.ts --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",
- "react-syntax-highlighter": "^16.1.1",
- "zod": "^4.0.0"
- },
- "devDependencies": {
- "@openuidev/cli": "workspace:*",
- "@tailwindcss/postcss": "^4",
- "@types/node": "catalog:",
- "@types/react": "^19",
- "@types/react-dom": "^19",
- "@types/react-syntax-highlighter": "^15.5.13",
- "eslint": "^9",
- "eslint-config-next": "16.2.6",
- "tailwindcss": "^4",
- "typescript": "^5"
- }
-}
diff --git a/examples/openui-artifact-demo/src/app/api/chat/route.ts b/examples/openui-artifact-demo/src/app/api/chat/route.ts
deleted file mode 100644
index c0b88531c..000000000
--- a/examples/openui-artifact-demo/src/app/api/chat/route.ts
+++ /dev/null
@@ -1,274 +0,0 @@
-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");
-
-// ── Tool implementations ──
-
-function getWeather({ location }: { location: string }): Promise<string> {
- return new Promise((resolve) => {
- setTimeout(() => {
- const knownTemps: Record<string, number> = {
- tokyo: 22, "san francisco": 18, london: 14, "new york": 25,
- paris: 19, sydney: 27, mumbai: 33, berlin: 16,
- };
- const conditions = ["Sunny", "Partly Cloudy", "Cloudy", "Light Rain", "Clear Skies"];
- const temp = knownTemps[location.toLowerCase()] ?? Math.floor(Math.random() * 30 + 5);
- const condition = conditions[Math.floor(Math.random() * conditions.length)];
- resolve(JSON.stringify({
- location, temperature_celsius: temp,
- temperature_fahrenheit: Math.round(temp * 1.8 + 32),
- condition,
- humidity_percent: Math.floor(Math.random() * 40 + 40),
- wind_speed_kmh: Math.floor(Math.random() * 25 + 5),
- forecast: [
- { day: "Tomorrow", high: temp + 2, low: temp - 4, condition: "Partly Cloudy" },
- { day: "Day After", high: temp + 1, low: temp - 3, condition: "Sunny" },
- ],
- }));
- }, 800);
- });
-}
-
-function getStockPrice({ symbol }: { symbol: string }): Promise<string> {
- return new Promise((resolve) => {
- setTimeout(() => {
- const s = symbol.toUpperCase();
- const knownPrices: Record<string, number> = {
- AAPL: 189.84, GOOGL: 141.8, TSLA: 248.42, MSFT: 378.91,
- AMZN: 178.25, NVDA: 875.28, META: 485.58,
- };
- const price = knownPrices[s] ?? Math.floor(Math.random() * 500 + 20);
- const change = parseFloat((Math.random() * 8 - 4).toFixed(2));
- resolve(JSON.stringify({
- symbol: s,
- price: parseFloat((price + change).toFixed(2)),
- change, change_percent: parseFloat(((change / price) * 100).toFixed(2)),
- volume: `${(Math.random() * 50 + 10).toFixed(1)}M`,
- day_high: parseFloat((price + Math.abs(change) + 1.5).toFixed(2)),
- day_low: parseFloat((price - Math.abs(change) - 1.2).toFixed(2)),
- }));
- }, 600);
- });
-}
-
-function searchWeb({ query }: { query: string }): Promise<string> {
- return new Promise((resolve) => {
- setTimeout(() => {
- resolve(JSON.stringify({
- query,
- results: [
- { title: `Top result for "${query}"`, snippet: `Comprehensive overview of ${query} with the latest information.` },
- { title: `${query} - Latest News`, snippet: `Recent developments and updates related to ${query}.` },
- { title: `Understanding ${query}`, snippet: `An in-depth guide explaining everything about ${query}.` },
- ],
- }));
- }, 1000);
- });
-}
-
-// ── Tool definitions ──
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-const tools: any[] = [
- {
- type: "function",
- function: {
- name: "get_weather",
- description: "Get current weather for a location.",
- parameters: {
- type: "object",
- properties: { location: { type: "string", description: "City name" } },
- required: ["location"],
- },
- function: getWeather,
- parse: JSON.parse,
- },
- },
- {
- type: "function",
- function: {
- name: "get_stock_price",
- description: "Get stock price for a ticker symbol.",
- parameters: {
- type: "object",
- properties: { symbol: { type: "string", description: "Ticker symbol, e.g. AAPL" } },
- required: ["symbol"],
- },
- function: getStockPrice,
- parse: JSON.parse,
- },
- },
- {
- type: "function",
- function: {
- name: "search_web",
- description: "Search the web for information.",
- parameters: {
- type: "object",
- properties: { query: { type: "string", description: "Search query" } },
- required: ["query"],
- },
- function: searchWeb,
- parse: JSON.parse,
- },
- },
-];
-
-// ── SSE helpers ──
-
-function sseToolCallStart(
- encoder: TextEncoder,
- tc: { id: string; function: { name: string } },
- index: number,
-) {
- return encoder.encode(
- `data: ${JSON.stringify({
- id: `chatcmpl-tc-${tc.id}`,
- object: "chat.completion.chunk",
- choices: [{
- index: 0,
- delta: {
- tool_calls: [{ index, id: tc.id, type: "function", function: { name: tc.function.name, arguments: "" } }],
- },
- finish_reason: null,
- }],
- })}\n\n`,
- );
-}
-
-function sseToolCallArgs(
- encoder: TextEncoder,
- tc: { id: string; function: { arguments: string } },
- result: string,
- index: number,
-) {
- let enrichedArgs: string;
- try {
- enrichedArgs = JSON.stringify({ _request: JSON.parse(tc.function.arguments), _response: JSON.parse(result) });
- } catch {
- enrichedArgs = tc.function.arguments;
- }
- return encoder.encode(
- `data: ${JSON.stringify({
- id: `chatcmpl-tc-${tc.id}-args`,
- object: "chat.completion.chunk",
- choices: [{
- index: 0,
- delta: { tool_calls: [{ index, function: { arguments: enrichedArgs } }] },
- finish_reason: null,
- }],
- })}\n\n`,
- );
-}
-
-// ── Route handler ──
-
-export async function POST(req: NextRequest) {
- const { messages } = await req.json();
-
- const client = new OpenAI({
- apiKey: process.env.OPENAI_API_KEY,
- });
- const MODEL = process.env.OPENAI_MODEL || "gpt-5.5";
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const cleanMessages = (messages as any[])
- .filter((m) => m.role !== "tool")
- .map((m) => {
- if (m.role === "assistant" && m.tool_calls?.length) {
- // Strip tool_calls (runTools re-runs the agentic loop server-side)
- // but preserve content so prior replies remain in context.
- const { tool_calls: _tc, ...rest } = m; // eslint-disable-line @typescript-eslint/no-unused-vars
- return rest;
- }
- return m;
- });
-
- const chatMessages: ChatCompletionMessageParam[] = [
- { role: "system", content: systemPrompt },
- ...cleanMessages,
- ];
-
- const encoder = new TextEncoder();
- let controllerClosed = false;
-
- const readable = new ReadableStream({
- start(controller) {
- const enqueue = (data: Uint8Array) => {
- if (controllerClosed) return;
- try { controller.enqueue(data); } catch { /* already closed */ }
- };
- const close = () => {
- if (controllerClosed) return;
- controllerClosed = true;
- try { controller.close(); } catch { /* already closed */ }
- };
-
- const pendingCalls: Array<{ id: string; name: string; arguments: string }> = [];
- let callIdx = 0;
- let resultIdx = 0;
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const runner = (client.chat.completions as any).runTools({
- model: MODEL,
- messages: chatMessages,
- tools,
- stream: true
- });
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- runner.on("functionToolCall", (fc: any) => {
- const id = `tc-${callIdx}`;
- pendingCalls.push({ id, name: fc.name, arguments: fc.arguments });
- enqueue(sseToolCallStart(encoder, { id, function: { name: fc.name } }, callIdx));
- callIdx++;
- });
-
- runner.on("functionToolCallResult", (result: string) => {
- const tc = pendingCalls[resultIdx];
- if (tc) {
- enqueue(sseToolCallArgs(encoder, { id: tc.id, function: { arguments: tc.arguments } }, result, resultIdx));
- }
- resultIdx++;
- });
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- runner.on("chunk", (chunk: any) => {
- const choice = chunk.choices?.[0];
- const delta = choice?.delta;
- if (!delta) return;
- if (delta.content) {
- enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
- }
- if (choice?.finish_reason === "stop") {
- enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
- }
- });
-
- runner.on("end", () => {
- enqueue(encoder.encode("data: [DONE]\n\n"));
- close();
- });
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- runner.on("error", (err: any) => {
- const msg = err instanceof Error ? err.message : "Stream error";
- console.error("Chat route error:", msg);
- enqueue(encoder.encode(`data: ${JSON.stringify({ error: msg })}\n\n`));
- close();
- });
- },
- });
-
- return new Response(readable, {
- headers: {
- "Content-Type": "text/event-stream",
- "Cache-Control": "no-cache, no-transform",
- Connection: "keep-alive",
- },
- });
-}
diff --git a/examples/openui-artifact-demo/src/app/globals.css b/examples/openui-artifact-demo/src/app/globals.css
deleted file mode 100644
index d41e3795a..000000000
--- a/examples/openui-artifact-demo/src/app/globals.css
+++ /dev/null
@@ -1,3 +0,0 @@
-@import "tailwindcss";
-@import "@openuidev/react-ui/styles/index.css";
-
diff --git a/examples/openui-artifact-demo/src/app/page.tsx b/examples/openui-artifact-demo/src/app/page.tsx
deleted file mode 100644
index 648b5cdd9..000000000
--- a/examples/openui-artifact-demo/src/app/page.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-"use client";
-
-import { useTheme } from "@/hooks/use-system-theme";
-import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-import { artifactDemoLibrary } from "@/library";
-
-export default function Page() {
- const mode = useTheme();
-
- return (
- <div className="h-screen w-screen overflow-hidden relative">
- <FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIAdapter()}
- componentLibrary={artifactDemoLibrary}
- agentName="Artifact Demo"
- theme={{ mode }}
- conversationStarters={{
- variant: "short",
- options: [
- {
- displayText: "React login form",
- prompt:
- "Build me a React login form with email and password validation",
- },
- {
- displayText: "Python REST API",
- prompt:
- "Create a FastAPI REST API with CRUD endpoints for a todo app",
- },
- {
- displayText: "CSS animation",
- prompt:
- "Write a CSS animation for a bouncing loading indicator",
- },
- {
- displayText: "SQL schema",
- prompt:
- "Design a SQL schema for a blog with users, posts, and comments",
- },
- ],
- }}
- />
- </div>
- );
-}
diff --git a/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/ArtifactView.tsx b/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/ArtifactView.tsx
deleted file mode 100644
index bd5d85b2a..000000000
--- a/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/ArtifactView.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-"use client";
-
-import { useState, useCallback } from "react";
-import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
-import { vscDarkPlus } from "react-syntax-highlighter/dist/esm/styles/prism";
-import { Copy, CheckCheck } from "lucide-react";
-
-interface ArtifactViewProps {
- language: string;
- codeString: string;
- title: string;
-}
-
-export function ArtifactView({ language, codeString, title }: ArtifactViewProps) {
- const [copied, setCopied] = useState(false);
-
- const handleCopy = useCallback(async () => {
- try {
- await navigator.clipboard.writeText(codeString);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- } catch {
- // Fallback for environments where clipboard API is unavailable
- const textarea = document.createElement("textarea");
- textarea.value = codeString;
- textarea.style.position = "fixed";
- textarea.style.opacity = "0";
- document.body.appendChild(textarea);
- textarea.select();
- document.execCommand("copy");
- document.body.removeChild(textarea);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- }
- }, [codeString]);
-
- return (
- <div className="flex h-full flex-col overflow-hidden bg-[#1e1e1e]">
- {/* Toolbar */}
- <div className="flex shrink-0 items-center justify-between border-b border-zinc-700/50 px-4 py-2">
- <span className="text-sm font-medium text-zinc-300">{title}</span>
- <div className="flex items-center gap-3">
- <span className="rounded-md bg-zinc-800 px-2 py-0.5 text-xs font-medium text-zinc-400">
- {language}
- </span>
- <button
- type="button"
- onClick={handleCopy}
- className="flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs font-medium text-zinc-400 transition-colors hover:bg-zinc-700/50 hover:text-zinc-200"
- aria-label={copied ? "Copied" : "Copy code"}
- >
- {copied ? (
- <>
- <CheckCheck className="h-3.5 w-3.5 text-emerald-400" />
- <span className="text-emerald-400">Copied</span>
- </>
- ) : (
- <>
- <Copy className="h-3.5 w-3.5" />
- <span>Copy</span>
- </>
- )}
- </button>
- </div>
- </div>
-
- {/* Code */}
- <div className="min-h-0 flex-1 overflow-auto">
- <SyntaxHighlighter
- language={language}
- style={vscDarkPlus}
- showLineNumbers
- customStyle={{
- margin: 0,
- padding: "1rem",
- background: "transparent",
- fontSize: "13px",
- lineHeight: "1.6",
- minHeight: "100%",
- }}
- lineNumberStyle={{
- minWidth: "2.5em",
- paddingRight: "1em",
- color: "#555",
- userSelect: "none",
- }}
- >
- {codeString}
- </SyntaxHighlighter>
- </div>
- </div>
- );
-}
diff --git a/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/InlinePreview.tsx b/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/InlinePreview.tsx
deleted file mode 100644
index b75b860e5..000000000
--- a/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/InlinePreview.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-"use client";
-
-interface InlinePreviewProps {
- language: string;
- title: string;
- codeString: string;
- open: () => void;
- isActive: boolean;
-}
-
-export function InlinePreview({ language, title, codeString, open, isActive }: InlinePreviewProps) {
- const truncatedCode = codeString.split("\n").slice(0, 6).join("\n");
-
- return (
- <div className="my-2 overflow-hidden rounded-xl border border-zinc-700/60 bg-zinc-900 shadow-sm">
- {/* Header */}
- <div className="flex items-center justify-between border-b border-zinc-700/50 px-4 py-2.5">
- <div className="flex items-center gap-2.5">
- <svg
- className="h-4 w-4 shrink-0 text-zinc-400"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- >
- <polyline points="16 18 22 12 16 6" />
- <polyline points="8 6 2 12 8 18" />
- </svg>
- <span className="text-sm font-medium text-zinc-200">{title}</span>
- </div>
- <span className="rounded-md bg-zinc-800 px-2 py-0.5 text-xs font-medium text-zinc-400">
- {language}
- </span>
- </div>
-
- {/* Code preview */}
- <div className="relative">
- <pre className="overflow-hidden px-4 py-3 text-[13px] leading-relaxed">
- <code className="text-zinc-300">{truncatedCode}</code>
- </pre>
- {/* Gradient fade */}
- <div className="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-linear-to-t from-zinc-900 to-transparent" />
- </div>
-
- {/* Footer */}
- <div className="border-t border-zinc-700/50 px-4 py-2.5">
- <button
- type="button"
- onClick={() => !isActive && open()}
- className={`text-sm font-medium transition-colors ${
- isActive
- ? "cursor-default text-emerald-400"
- : "cursor-pointer text-blue-400 hover:text-blue-300"
- }`}
- >
- {isActive ? "✓ Viewing" : "View Code →"}
- </button>
- </div>
- </div>
- );
-}
diff --git a/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/index.tsx b/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/index.tsx
deleted file mode 100644
index ecf780567..000000000
--- a/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/index.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-"use client";
-
-import { defineComponent } from "@openuidev/react-lang";
-import { Artifact } from "@openuidev/react-ui";
-import { ArtifactView } from "./ArtifactView";
-import { InlinePreview } from "./InlinePreview";
-import { ArtifactCodeBlockSchema } from "./schema";
-
-export { ArtifactCodeBlockSchema } from "./schema";
-export type { ArtifactCodeBlockProps } from "./schema";
-
-export const ArtifactCodeBlock = defineComponent({
- name: "ArtifactCodeBlock",
- props: ArtifactCodeBlockSchema,
- description:
- "Code block that opens in the artifact side panel for full viewing with syntax highlighting",
- component: Artifact({
- title: (props) => props.title as string,
- preview: (props, { open, isActive }) => (
- <InlinePreview
- language={props.language as string}
- title={props.title as string}
- codeString={props.codeString as string}
- open={open}
- isActive={isActive}
- />
- ),
- panel: (props) => (
- <ArtifactView
- language={props.language as string}
- codeString={props.codeString as string}
- title={props.title as string}
- />
- ),
- }),
-});
diff --git a/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/schema.ts b/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/schema.ts
deleted file mode 100644
index 02ce83ac7..000000000
--- a/examples/openui-artifact-demo/src/components/ArtifactCodeBlock/schema.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { z } from "zod";
-
-export const ArtifactCodeBlockSchema = z.object({
- language: z.string(),
- title: z.string(),
- codeString: z.string(),
-});
-
-export type ArtifactCodeBlockProps = z.infer<typeof ArtifactCodeBlockSchema>;
diff --git a/examples/openui-artifact-demo/src/generated/system-prompt.txt b/examples/openui-artifact-demo/src/generated/system-prompt.txt
deleted file mode 100644
index f7263f410..000000000
--- a/examples/openui-artifact-demo/src/generated/system-prompt.txt
+++ /dev/null
@@ -1,239 +0,0 @@
-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 = Card(...)`
-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.
-Props typed `ActionExpression` accept an Action([@steps...]) expression. See the Action section for available steps (@ToAssistant, @OpenUrl).
-Props marked `$binding<type>` accept a `$variable` reference for two-way binding.
-
-### Content
-CardHeader(title?: string, subtitle?: string) — Header with optional title and subtitle
-TextContent(text: string, size?: "small" | "default" | "large" | "small-heavy" | "large-heavy") — Text block. Supports markdown. Optional size: "small" | "default" | "large" | "small-heavy" | "large-heavy".
-MarkDownRenderer(textMarkdown: string, variant?: "clear" | "card" | "sunk") — Renders markdown text with optional container variant
-Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string, visible?: $binding<boolean>) — Callout banner. Optional visible is a reactive $boolean — auto-dismisses after 3s by setting $visible to false.
-TextCallout(variant?: "neutral" | "info" | "warning" | "success" | "danger", title?: string, description?: string) — Text callout with variant, title, and description
-Image(alt: string, src?: string) — Image with alt text and optional URL
-ImageBlock(src: string, alt?: string) — Image block with loading state
-ImageGallery(images: {src: string, alt?: string, details?: string}[]) — Gallery grid of images with modal preview
-CodeBlock(language: string, codeString: string) — Syntax-highlighted code block
-Separator(orientation?: "horizontal" | "vertical", decorative?: boolean) — Visual divider between content sections
-ArtifactCodeBlock(language: string, title: string, codeString: string) — Code block that opens in the artifact side panel for full viewing with syntax highlighting
-
-### Tables
-Table(columns: Col[]) — Data table — column-oriented. Each Col holds its own data array.
-Col(label: string, data: any, type?: "string" | "number" | "action") — Column definition — holds label + data array
-
-### Charts (2D)
-BarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Vertical bars; use for comparing values across categories with one or more series
-LineChart(labels: string[], series: Series[], variant?: "linear" | "natural" | "step", xLabel?: string, yLabel?: string) — Lines over categories; use for trends and continuous data over time
-AreaChart(labels: string[], series: Series[], variant?: "linear" | "natural" | "step", xLabel?: string, yLabel?: string) — Filled area under lines; use for cumulative totals or volume trends over time
-RadarChart(labels: string[], series: Series[]) — Spider/web chart; use for comparing multiple variables across one or more entities
-HorizontalBarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Horizontal bars; prefer when category labels are long or for ranked lists
-Series(category: string, values: number[]) — One data series
-
-### Charts (1D)
-PieChart(labels: string[], values: number[], variant?: "pie" | "donut") — Circular slices; use plucked arrays: PieChart(data.categories, data.values)
-RadialChart(labels: string[], values: number[]) — Radial bars; use plucked arrays: RadialChart(data.categories, data.values)
-SingleStackedBarChart(labels: string[], values: number[]) — Single horizontal stacked bar; use plucked arrays: SingleStackedBarChart(data.categories, data.values)
-Slice(category: string, value: number) — One slice with label and numeric value
-
-### Charts (Scatter)
-ScatterChart(datasets: ScatterSeries[], xLabel?: string, yLabel?: string) — X/Y scatter plot; use for correlations, distributions, and clustering
-ScatterSeries(name: string, points: Point[]) — Named dataset
-Point(x: number, y: number, z?: number) — Data point with numeric coordinates
-
-### Forms
-Form(name: string, buttons: Buttons, fields?: FormControl[]) — Form container with fields and explicit action buttons
-FormControl(label: string, input: Input | TextArea | Select | DatePicker | Slider | CheckBoxGroup | RadioGroup, hint?: string) — Field with label, input component, and optional hint text
-Label(text: string) — Text label
-Input(name: string, placeholder?: string, type?: "text" | "email" | "password" | "number" | "url", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)
-TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)
-Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)
-SelectItem(value: string, label: string) — Option for Select
-DatePicker(name: string, mode?: "single" | "range", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<any>)
-Slider(name: string, variant: "continuous" | "discrete", min: number, max: number, step?: number, defaultValue?: number[], label?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<number[]>) — Numeric slider input; supports continuous and discrete (stepped) variants
-CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<Record<string, boolean>>)
-CheckBoxItem(label: string, description: string, name: string, defaultChecked?: boolean)
-RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)
-RadioItem(label: string, description: string, value: string)
-SwitchGroup(name: string, items: SwitchItem[], variant?: "clear" | "card" | "sunk", value?: $binding<Record<string, boolean>>) — Group of switch toggles
-SwitchItem(label?: string, description?: string, name: string, defaultChecked?: boolean) — Individual switch toggle
-- Define EACH FormControl as its own reference — do NOT inline all controls in one array.
-- NEVER nest Form inside Form.
-- Form requires explicit buttons. Always pass a Buttons(...) reference as the third Form argument.
-- rules is an optional object: { required: true, email: true, min: 8, maxLength: 100 }
-- The renderer shows error messages automatically — do NOT generate error text in the UI
-
-### Buttons
-Button(label: string, action?: ActionExpression, variant?: "primary" | "secondary" | "tertiary", type?: "normal" | "destructive", size?: "extra-small" | "small" | "medium" | "large") — Clickable button
-Buttons(buttons: Button[], direction?: "row" | "column") — Group of Button components. direction: "row" (default) | "column".
-
-### Lists & Follow-ups
-ListBlock(items: ListItem[], variant?: "number" | "image") — A list of items with number or image indicators. Each item can optionally have an action.
-ListItem(title: string, subtitle?: string, image?: {src: string, alt: string}, actionLabel?: string, action?: ActionExpression) — Item in a ListBlock — displays a title with an optional subtitle and image. When action is provided, the item becomes clickable.
-FollowUpBlock(items: FollowUpItem[]) — List of clickable follow-up suggestions placed at the end of a response
-FollowUpItem(text: string) — Clickable follow-up suggestion — when clicked, sends text as user message
-- Use ListBlock with ListItem references for numbered, clickable lists.
-- Use FollowUpBlock with FollowUpItem references at the end of a response to suggest next actions.
-- Clicking a ListItem or FollowUpItem sends its text to the LLM as a user message.
-- Example: list = ListBlock([item1, item2]) item1 = ListItem("Option A", "Details about A")
-
-### Sections
-SectionBlock(sections: SectionItem[], isFoldable?: boolean) — Collapsible accordion sections. Auto-opens sections as they stream in. Use SectionItem for each section.
-SectionItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | ListBlock | FollowUpBlock)[]) — Section with a label and collapsible content — used inside SectionBlock
-- SectionBlock renders collapsible accordion sections that auto-open as they stream.
-- Each section needs a unique `value` id, a `trigger` label, and a `content` array.
-- Example: sections = SectionBlock([s1, s2]) s1 = SectionItem("intro", "Introduction", [content1])
-- Set isFoldable=false to render sections as flat headers instead of accordion.
-
-### Layout
-Tabs(items: TabItem[]) — Tabbed container
-TabItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[]) — value is unique id, trigger is tab label, content is array of components
-Accordion(items: AccordionItem[]) — Collapsible sections
-AccordionItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[]) — value is unique id, trigger is section title
-Steps(items: StepsItem[]) — Step-by-step guide
-StepsItem(title: string, details: string) — title and details text for one step
-Carousel(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[][], variant?: "card" | "sunk") — Horizontal scrollable carousel
-- Use Tabs to present alternative views — each TabItem has a value id, trigger label, and content array.
-- Carousel takes an array of slides, where each slide is an array of content: carousel = Carousel([[t1, img1], [t2, img2]])
-- IMPORTANT: Every slide in a Carousel must have the same structure — same component types in the same order.
-- For image carousels use: [[title, image, description, tags], ...] — every slide must follow this exact pattern.
-- Use real, publicly accessible image URLs (e.g. https://picsum.photos/seed/KEYWORD/800/500). Never hallucinate image URLs.
-
-### Data Display
-TagBlock(tags: string[]) — tags is an array of strings
-Tag(text: string, icon?: string, size?: "sm" | "md" | "lg", variant?: "neutral" | "info" | "success" | "warning" | "danger") — Styled tag/badge with optional icon and variant
-
-### Other
-Card(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | ListBlock | FollowUpBlock | SectionBlock | Tabs | Carousel)[]) — Vertical container for all content in a chat response. Children stack top to bottom automatically.
-
-## Action — Button Behavior
-
-Action([@steps...]) wires button clicks to operations. Steps are @-prefixed built-in actions. Steps execute in order.
-Buttons without an explicit Action prop automatically send their label to the assistant (equivalent to Action([@ToAssistant(label)])).
-
-Available steps:
-- @ToAssistant("message") — Send a message to the assistant (for conversational buttons like "Tell me more", "Explain this")
-- @OpenUrl("https://...") — Navigate to a URL
-
-Example — simple nav:
-```
-viewBtn = Button("View", Action([@OpenUrl("https://example.com")]))
-```
-
-- Action can be assigned to a variable or inlined: Button("Go", onSubmit) and Button("Go", Action([...])) both work
-
-## 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 = Card(...)` — UI shell appears immediately
-2. Component definitions — fill in as they stream
-3. Data values — leaf content last
-
-Always write the root = Card(...) statement first so the UI shell appears immediately, even before child data has streamed in.
-
-## Examples
-
-Example 1 — Table with follow-ups:
-
-root = Card([title, tbl, followUps])
-title = TextContent("Top Languages", "large-heavy")
-tbl = Table([Col("Language", langs), Col("Users (M)", users), Col("Year", years)])
-langs = ["Python", "JavaScript", "Java"]
-users = [15.7, 14.2, 12.1]
-years = [1991, 1995, 1995]
-followUps = FollowUpBlock([fu1, fu2])
-fu1 = FollowUpItem("Tell me more about Python")
-fu2 = FollowUpItem("Show me a JavaScript comparison")
-
-Example 2 — Clickable list:
-
-root = Card([title, list])
-title = TextContent("Choose a topic", "large-heavy")
-list = ListBlock([item1, item2, item3])
-item1 = ListItem("Getting started", "New to the platform? Start here.")
-item2 = ListItem("Advanced features", "Deep dives into powerful capabilities.")
-item3 = ListItem("Troubleshooting", "Common issues and how to fix them.")
-
-Example 3 — Image carousel with consistent slides + follow-ups:
-
-root = Card([header, carousel, followups])
-header = CardHeader("Featured Destinations", "Discover highlights and best time to visit")
-carousel = Carousel([[t1, img1, d1, tags1], [t2, img2, d2, tags2], [t3, img3, d3, tags3]], "card")
-t1 = TextContent("Paris, France", "large-heavy")
-img1 = ImageBlock("https://picsum.photos/seed/paris/800/500", "Eiffel Tower at night")
-d1 = TextContent("City of light — best Apr–Jun and Sep–Oct.", "default")
-tags1 = TagBlock(["Landmark", "City Break", "Culture"])
-t2 = TextContent("Kyoto, Japan", "large-heavy")
-img2 = ImageBlock("https://picsum.photos/seed/kyoto/800/500", "Bamboo grove in Arashiyama")
-d2 = TextContent("Temples and bamboo groves — best Mar–Apr and Nov.", "default")
-tags2 = TagBlock(["Temples", "Autumn", "Culture"])
-t3 = TextContent("Machu Picchu, Peru", "large-heavy")
-img3 = ImageBlock("https://picsum.photos/seed/machupicchu/800/500", "Inca citadel in the clouds")
-d3 = TextContent("High-altitude Inca citadel — best May–Sep.", "default")
-tags3 = TagBlock(["Andes", "Hike", "UNESCO"])
-followups = FollowUpBlock([fu1, fu2])
-fu1 = FollowUpItem("Show me only beach destinations")
-fu2 = FollowUpItem("Turn this into a comparison table")
-
-Example 4 — Form with validation:
-
-root = Card([title, form])
-title = TextContent("Contact Us", "large-heavy")
-form = Form("contact", btns, [nameField, emailField, msgField])
-nameField = FormControl("Name", Input("name", "Your name", "text", { required: true, minLength: 2 }))
-emailField = FormControl("Email", Input("email", "[email protected]", "email", { required: true, email: true }))
-msgField = FormControl("Message", TextArea("message", "Tell us more...", 4, { required: true, minLength: 10 }))
-btns = Buttons([Button("Submit", Action([@ToAssistant("Submit")]), "primary")])
-
-Example — Code generation with artifacts:
-root = Card([intro, code1, explanation, code2, followUps])
-intro = TextContent("Here's a React login form with validation:", "default")
-code1 = ArtifactCodeBlock("typescript", "LoginForm.tsx", "import React, { useState } from 'react';\n\nexport function LoginForm() {\n const [email, setEmail] = useState('');\n const [password, setPassword] = useState('');\n\n return (\n <form>\n <input value={email} onChange={e => setEmail(e.target.value)} />\n <input type=\"password\" value={password} onChange={e => setPassword(e.target.value)} />\n <button type=\"submit\">Login</button>\n </form>\n );\n}")
-explanation = TextContent("And the validation helper:", "default")
-code2 = ArtifactCodeBlock("typescript", "validate.ts", "export function validateEmail(email: string): boolean {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);\n}")
-followUps = FollowUpBlock([fu1, fu2])
-fu1 = FollowUpItem("Add password strength indicator")
-fu2 = FollowUpItem("Add form styling with Tailwind")
-
-## 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 = Card(...) is the FIRST line (for optimal streaming).
-2. Every referenced name is defined. Every defined name (other than root) is reachable from root.
-
-- Every response is a single Card(children) — children stack vertically automatically. No layout params are needed on Card.
-- Card is the only layout container. Do NOT use Stack. Use Tabs to switch between sections, Carousel for horizontal scroll.
-- Use FollowUpBlock at the END of a Card to suggest what the user can do or ask next.
-- Use ListBlock when presenting a set of options or steps the user can click to select.
-- Use SectionBlock to group long responses into collapsible sections — good for reports, FAQs, and structured content.
-- Use SectionItem inside SectionBlock: each item needs a unique value id, a trigger (header label), and a content array.
-- Carousel takes an array of slides, where each slide is an array of content: carousel = Carousel([[t1, img1], [t2, img2]])
-- IMPORTANT: Every slide in a Carousel must use the same component structure in the same order — e.g. all slides: [title, image, description, tags].
-- For image carousels, always use real accessible URLs like https://picsum.photos/seed/KEYWORD/800/500. Never hallucinate or invent image URLs.
-- For forms, define one FormControl reference per field so controls can stream progressively.
-- For forms, always provide the second Form argument with Buttons(...) actions: Form(name, buttons, fields).
-- Never nest Form inside Form.
-- ALWAYS use ArtifactCodeBlock for ANY code output. NEVER use regular CodeBlock.
-- Set title to the filename (e.g. 'LoginForm.tsx', 'sort.py', 'schema.sql').
-- Set language to the correct syntax highlighting language (e.g. 'typescript', 'python', 'sql', 'css').
-- You can include multiple ArtifactCodeBlocks in one response — each with a unique title.
-- Surround code blocks with TextContent for explanations.
diff --git a/examples/openui-artifact-demo/src/library.ts b/examples/openui-artifact-demo/src/library.ts
deleted file mode 100644
index 0ab637d04..000000000
--- a/examples/openui-artifact-demo/src/library.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import type { ComponentGroup, PromptOptions } from "@openuidev/react-lang";
-import { createLibrary } from "@openuidev/react-lang";
-import {
- openuiChatComponentGroups,
- openuiChatLibrary,
- openuiChatPromptOptions,
-} from "@openuidev/react-ui/genui-lib";
-
-import { ArtifactCodeBlock } from "./components/ArtifactCodeBlock";
-
-// ── Component Groups — extend chat groups, add ArtifactCodeBlock to Content ──
-
-const artifactComponentGroups: ComponentGroup[] = openuiChatComponentGroups.map((group) => {
- if (group.name === "Content") {
- return {
- ...group,
- components: [...group.components, "ArtifactCodeBlock"],
- };
- }
- return group;
-});
-
-// ── Library — all chat components + ArtifactCodeBlock ──
-
-export const artifactDemoLibrary = createLibrary({
- root: "Card",
- componentGroups: artifactComponentGroups,
- components: [...Object.values(openuiChatLibrary.components), ArtifactCodeBlock],
-});
-
-// ── Prompt Options — extend chat rules with artifact-specific instructions ──
-
-export const artifactDemoPromptOptions: PromptOptions = {
- additionalRules: [
- ...(openuiChatPromptOptions.additionalRules ?? []),
- "ALWAYS use ArtifactCodeBlock for ANY code output. NEVER use regular CodeBlock.",
- "Set title to the filename (e.g. 'LoginForm.tsx', 'sort.py', 'schema.sql').",
- "Set language to the correct syntax highlighting language (e.g. 'typescript', 'python', 'sql', 'css').",
- "You can include multiple ArtifactCodeBlocks in one response — each with a unique title.",
- "Surround code blocks with TextContent for explanations.",
- ],
- examples: [
- ...(openuiChatPromptOptions.examples ?? []),
- `Example — Code generation with artifacts:
-root = Card([intro, code1, explanation, code2, followUps])
-intro = TextContent("Here's a React login form with validation:", "default")
-code1 = ArtifactCodeBlock("typescript", "LoginForm.tsx", "import React, { useState } from 'react';\\n\\nexport function LoginForm() {\\n const [email, setEmail] = useState('');\\n const [password, setPassword] = useState('');\\n\\n return (\\n <form>\\n <input value={email} onChange={e => setEmail(e.target.value)} />\\n <input type=\\"password\\" value={password} onChange={e => setPassword(e.target.value)} />\\n <button type=\\"submit\\">Login</button>\\n </form>\\n );\\n}")
-explanation = TextContent("And the validation helper:", "default")
-code2 = ArtifactCodeBlock("typescript", "validate.ts", "export function validateEmail(email: string): boolean {\\n return /^[^\\\\s@]+@[^\\\\s@]+\\\\.[^\\\\s@]+$/.test(email);\\n}")
-followUps = FollowUpBlock([fu1, fu2])
-fu1 = FollowUpItem("Add password strength indicator")
-fu2 = FollowUpItem("Add form styling with Tailwind")`,
- ],
-};
-
-// ── CLI exports — the generate:prompt script expects `library` and `promptOptions` ──
-
-export { artifactDemoLibrary as library, artifactDemoPromptOptions as promptOptions };
diff --git a/examples/openui-chat/src/app/page.tsx b/examples/openui-chat/src/app/page.tsx
index 2886da632..f3d7d3433 100644
--- a/examples/openui-chat/src/app/page.tsx
+++ b/examples/openui-chat/src/app/page.tsx
@@ -1,49 +1,59 @@
"use client";
import { useTheme } from "@/hooks/use-system-theme";
-import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
+import {
+ AgentInterface,
+ openAIAdapter,
+ openAIMessageFormat,
+ type ChatLLM,
+} from "@openuidev/react-ui";
import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
+import { useMemo } from "react";
export default function Page() {
const mode = useTheme();
+ // AgentInterface uses its built-in in-memory storage (wiped on reload). The
+ // backend call is unchanged — only the chat surface moved from FullScreen to
+ // AgentInterface.
+ 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">
- <FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIAdapter()}
+ <AgentInterface
+ llm={llm}
componentLibrary={openuiChatLibrary}
agentName="OpenUI Chat"
theme={{ mode }}
- conversationStarters={{
- variant: "short",
- options: [
- {
- displayText: "Weather in Tokyo",
- prompt: "What's the weather like in Tokyo right now?",
- },
- { displayText: "AAPL stock price", prompt: "What's the current Apple stock price?" },
- {
- displayText: "Contact form",
- prompt: "Build me a contact form with name, email, topic, and message fields.",
- },
- {
- displayText: "Data table",
- prompt:
- "Show me a table of the top 5 programming languages by popularity with year created.",
- },
- ],
- }}
+ starterVariant="short"
+ starters={[
+ {
+ displayText: "Weather in Tokyo",
+ prompt: "What's the weather like in Tokyo right now?",
+ },
+ { displayText: "AAPL stock price", prompt: "What's the current Apple stock price?" },
+ {
+ displayText: "Contact form",
+ prompt: "Build me a contact form with name, email, topic, and message fields.",
+ },
+ {
+ displayText: "Data table",
+ prompt:
+ "Show me a table of the top 5 programming languages by popularity with year created.",
+ },
+ ]}
/>
</div>
);
diff --git a/examples/openui-cloud/.env.example b/examples/openui-cloud/.env.example
new file mode 100644
index 000000000..1228d86e7
--- /dev/null
+++ b/examples/openui-cloud/.env.example
@@ -0,0 +1,15 @@
+# openui-cloud env template — copy to .env.local and fill in your own values.
+# .env.local is gitignored; this template is committed. Restart `pnpm dev` after edits.
+
+# ── REQUIRED ──────────────────────────────────────────────────────────────────
+# Your OpenUI Cloud ORG MASTER KEY. Server-side only — never reaches the browser
+# (the routes field-pick the response). The frontend-token route 500s if unset.
+THESYS_API_KEY=sk-th-your-org-master-key
+
+# ── Optional (have sensible defaults) ─────────────────────────────────────────
+# Bare provider/model id for /api/chat generation (default: openai/gpt-5).
+OPENUI_MODEL=openai/gpt-5
+
+# End-user identity the frontend-token route stamps server-side (default: demo-user).
+# A real app derives this from its own auth, not an env var.
+DEMO_USER_ID=demo-user
diff --git a/examples/openui-artifact-demo/.gitignore b/examples/openui-cloud/.gitignore
similarity index 69%
rename from examples/openui-artifact-demo/.gitignore
rename to examples/openui-cloud/.gitignore
index 5ef6a5207..4e5c4a9a3 100644
--- a/examples/openui-artifact-demo/.gitignore
+++ b/examples/openui-cloud/.gitignore
@@ -32,10 +32,18 @@ yarn-error.log*
# env files (can opt-in for committing if needed)
.env*
+!.env.example
# vercel
.vercel
+# local thread index (created at runtime)
+/.data/
+
# typescript
*.tsbuildinfo
next-env.d.ts
+
+# vendored @openuidev/thesys tarball — obtain separately; never commit (the
+# package is distributed via the registry, not this repo).
+/vendor/
diff --git a/examples/openui-cloud/README.md b/examples/openui-cloud/README.md
new file mode 100644
index 000000000..66d00e370
--- /dev/null
+++ b/examples/openui-cloud/README.md
@@ -0,0 +1,84 @@
+# openui-cloud — OpenUI Cloud integration example
+
+A Next.js app showing how an external app integrates with OpenUI Cloud using its
+**two-plane** model:
+
+- **Generation plane (master key, server-side):** `/api/chat` forwards
+ `{ threadId, input }` to `POST /v1/embed/responses` with the org master key
+ (`conversation: threadId`, `store:true`, `stream:true`, `tools:[artifactTool()]`,
+ `instructions: createResponsesInstructions()`) and pipes the SSE stream back
+ unchanged. `/api/frontend-token` proxies `POST /v1/frontend-tokens` so the
+ browser gets a short-lived `fct_` token **without ever seeing the master key**.
+- **Read/edit plane (fct_, browser-direct):** the client page wires
+ `<AgentInterface llm storage componentLibrary artifactRenderers artifactCategories />`
+ against a `ChatStorage` from the **`useOpenuiCloudStorage()`** hook (browser →
+ `/v1/conversations` + `/v1/artifacts` via the `x-thesys-frontend-token` header,
+ single-flight refresh + 401 retry) and the presentation/report artifact
+ renderers (`artifactRenderers` / `artifactCategories` from `@openuidev/thesys`).
+
+## Local dependency wiring (do this first)
+
+`@openuidev/thesys` is **not published** — this app consumes it from a sibling
+**genui-sdk** checkout via a vendored tarball, and `@openuidev/thesys-server` via a
+vendored build. **Both `vendor/` artifacts are gitignored**, so after cloning you
+must produce them yourself.
+
+Prereq: `genui-sdk` cloned as a **sibling of `openui`** (so `../../../genui-sdk`
+resolves from this dir), on branch **`ap-server`**.
+
+```bash
+# 1. Build the SDK packages in genui-sdk (on ap-server).
+cd /path/to/genui-sdk
+git checkout ap-server && git pull && pnpm install
+pnpm --filter @openuidev/thesys build
+pnpm --filter @openuidev/thesys-server build
+
+# 2. Vendor both into openui-cloud.
+VENDOR=/path/to/openui/examples/openui-cloud/vendor
+( cd packages/c1 && pnpm pack --pack-destination "$VENDOR" ) # → openuidev-thesys-0.1.0.tgz
+mkdir -p "$VENDOR/c1-server" && cp packages/c1-server/dist/index.* "$VENDOR/c1-server/"
+
+# 3. Install this app (force — the tgz filename is stable, so pnpm caches it).
+cd /path/to/openui/examples/openui-cloud
+pnpm install --force
+```
+
+Re-run these whenever you change `c1` / `c1-server` in genui-sdk. `next.config.ts`
+aliases `@openuidev/thesys-server` → `vendor/c1-server/index.mjs` (Turbopack won't
+follow the cross-repo symlink) and stubs `lucide-react/dynamic`.
+
+## Setup (env)
+
+```bash
+cp .env.example .env.local # fill THESYS_API_KEY and point the base URLs at your API
+```
+
+Required env (see `.env.example`): `THESYS_API_KEY`, `OPENUI_CLOUD_BASE_URL`,
+`OPENUI_MODEL` (bare `provider/model`, e.g. `openai/gpt-5`), `DEMO_USER_ID`,
+`NEXT_PUBLIC_OPENUI_CLOUD_BASE_URL`.
+
+## Run
+
+```bash
+pnpm dev # http://localhost:3300
+```
+
+Point `OPENUI_CLOUD_BASE_URL` / `NEXT_PUBLIC_OPENUI_CLOUD_BASE_URL` at your OpenUI
+Cloud API origin.
+
+## Typecheck
+
+```bash
+pnpm exec tsc --noEmit
+```
+
+## SDK packages
+
+- `@openuidev/thesys-server` — the server SDK (`artifactTool`,
+ `createResponsesInstructions`) used by the `/api/chat` route.
+- `@openuidev/thesys` — the React SDK: `useOpenuiCloudStorage` (browser storage
+ hook), `artifactRenderers` / `artifactCategories`, `chatLibrary`, and the
+ `Presentation` / `Report` viewers, used by the client page. **Not published** —
+ vendored from genui-sdk (see "Local dependency wiring").
+- `@openuidev/react-headless` / `@openuidev/react-ui` — the chat UI runtime
+ (`AgentInterface`, storage/stream contracts, `defineArtifactRenderer`).
diff --git a/examples/openui-artifact-demo/eslint.config.mjs b/examples/openui-cloud/eslint.config.mjs
similarity index 100%
rename from examples/openui-artifact-demo/eslint.config.mjs
rename to examples/openui-cloud/eslint.config.mjs
diff --git a/examples/openui-cloud/next.config.ts b/examples/openui-cloud/next.config.ts
new file mode 100644
index 000000000..1f9da2fb1
--- /dev/null
+++ b/examples/openui-cloud/next.config.ts
@@ -0,0 +1,26 @@
+import type { NextConfig } from "next";
+import path from "path";
+
+const nextConfig: NextConfig = {
+ output: "standalone",
+ turbopack: {
+ // Pin the Turbopack root to the openui monorepo root so it follows the
+ // symlinked workspace deps (@openuidev/react-ui, react-lang, lang-core,
+ // react-headless) that @openuidev/thesys imports — these live in
+ // openui/packages/* and are otherwise treated as outside the inferred root.
+ root: path.resolve(process.cwd(), "../.."),
+ resolveAlias: {
+ // @openuidev/thesys's icon wrapper imports lucide-react dynamic-icon
+ // subpaths that the installed lucide-react no longer ships; alias them to
+ // an empty stub so the bundle compiles (dynamic icons fall back to defaults).
+ "lucide-react/dynamic": "./stubs/lucide-dynamic.mjs",
+ "lucide-react/dynamicIconImports.mjs": "./stubs/lucide-dynamic.mjs",
+ // @openuidev/thesys-server is linked cross-repo and Turbopack won't follow
+ // a symlink to a target outside the workspace root, so its built entry is
+ // vendored in-repo (vendor/c1-server) and aliased here.
+ "@openuidev/thesys-server": "./vendor/c1-server/index.mjs",
+ },
+ },
+};
+
+export default nextConfig;
diff --git a/examples/openui-cloud/package.json b/examples/openui-cloud/package.json
new file mode 100644
index 000000000..c9c419042
--- /dev/null
+++ b/examples/openui-cloud/package.json
@@ -0,0 +1,56 @@
+{
+ "name": "openui-cloud",
+ "version": "0.1.0",
+ "private": true,
+ "scripts": {
+ "dev": "next dev -p 3300",
+ "build": "next build",
+ "start": "next start -p 3300",
+ "lint": "eslint",
+ "typecheck": "tsc --noEmit",
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "@floating-ui/react-dom": "2.1.3",
+ "@openuidev/lang-core": "workspace:*",
+ "@openuidev/react-headless": "workspace:*",
+ "@openuidev/react-lang": "workspace:*",
+ "@openuidev/react-ui": "workspace:*",
+ "@radix-ui/react-dialog": "1.1.15",
+ "@radix-ui/react-tooltip": "^1.2.0",
+ "@tanstack/react-table": "8.21.3",
+ "@tiptap/extension-placeholder": "2.27.2",
+ "@tiptap/react": "2.27.2",
+ "@tiptap/starter-kit": "2.27.2",
+ "clsx": "2.1.1",
+ "katex": "0.16.44",
+ "lodash": "4.17.21",
+ "lucide-react": "^0.575.0",
+ "mdast-util-find-and-replace": "3.0.2",
+ "mermaid": "11.15.0",
+ "next": "16.1.6",
+ "react": "19.2.3",
+ "react-dom": "19.2.3",
+ "recharts": "2.15.4",
+ "rehype-katex": "7.0.1",
+ "remark-breaks": "4.0.0",
+ "remark-gfm": "4.0.1",
+ "remark-math": "6.0.0",
+ "tiny-invariant": "1.3.3",
+ "unist-util-visit": "5.1.0",
+ "zod": "^4.0.0",
+ "zustand": "catalog:"
+ },
+ "devDependencies": {
+ "@tailwindcss/postcss": "^4",
+ "@types/node": "^20",
+ "@types/react": "^19",
+ "@types/react-dom": "^19",
+ "eslint": "^9",
+ "eslint-config-next": "16.1.6",
+ "openai": "^6.22.0",
+ "tailwindcss": "^4",
+ "typescript": "^5",
+ "vitest": "^4.1.0"
+ }
+}
diff --git a/examples/openui-artifact-demo/postcss.config.mjs b/examples/openui-cloud/postcss.config.mjs
similarity index 100%
rename from examples/openui-artifact-demo/postcss.config.mjs
rename to examples/openui-cloud/postcss.config.mjs
diff --git a/examples/openui-cloud/src/app/api/chat/route.ts b/examples/openui-cloud/src/app/api/chat/route.ts
new file mode 100644
index 000000000..48cf357f9
--- /dev/null
+++ b/examples/openui-cloud/src/app/api/chat/route.ts
@@ -0,0 +1,72 @@
+import { envOr, openuiCloudBaseUrl, requiredEnv } from "@/lib/env";
+import { artifactTool, createResponsesInstructions } from "@openuidev/thesys-server";
+import type { ResponseInputItem } from "openai/resources/responses/responses";
+
+/**
+ * Generation plane: browser → THIS route → OpenUI Cloud
+ * POST /v1/embed/responses with the org MASTER key (server env only).
+ * Reads/edits go browser → /v1/* with the fct_ token instead (see
+ * /api/frontend-token + the storage adapter). The artifact tool runs
+ * server-side, so this route is a pure pipe — no client-tool loop.
+ */
+export async function POST(req: Request) {
+ const { threadId, input } = (await req.json()) as {
+ threadId?: string;
+ input?: ResponseInputItem[];
+ };
+
+ // The conversation must already exist — the API replays history from it and
+ // stamps ownership on persist. The chat store creates the thread before the
+ // first send.
+ if (!threadId) {
+ return Response.json(
+ { error: { message: "threadId is required — create the conversation first" } },
+ { status: 400 },
+ );
+ }
+ if (!Array.isArray(input) || input.length === 0) {
+ return Response.json(
+ { error: { message: "input must be a non-empty ResponseInputItem[]" } },
+ { status: 400 },
+ );
+ }
+ console.log("artifactTool", artifactTool());
+ const upstream = await fetch(`${openuiCloudBaseUrl()}/v1/embed/responses`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${requiredEnv("THESYS_API_KEY")}`,
+ },
+ body: JSON.stringify({
+ // A bare provider/model id (versioned managed ids are mutually
+ // exclusive with the instructions config block). Configurable via
+ // OPENUI_MODEL (.env.local); defaults to openai/gpt-5.
+ model: envOr("OPENUI_MODEL", "openai/gpt-5"),
+ conversation: threadId,
+ input,
+ stream: true,
+ store: true,
+ tools: [artifactTool()],
+ instructions: createResponsesInstructions(),
+ }),
+ signal: req.signal, // propagate browser aborts (stop button / tab close)
+ });
+
+ if (!upstream.ok || !upstream.body) {
+ // Forward the upstream error body verbatim (OpenAI-shaped JSON).
+ const detail = await upstream.text().catch(() => "");
+ return new Response(detail || JSON.stringify({ error: { message: "upstream error" } }), {
+ status: upstream.status || 502,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+
+ // Pipe the SSE byte stream through untouched.
+ return new Response(upstream.body, {
+ headers: {
+ "Content-Type": "text/event-stream",
+ "Cache-Control": "no-cache, no-transform",
+ Connection: "keep-alive",
+ },
+ });
+}
diff --git a/examples/openui-cloud/src/app/api/frontend-token/route.ts b/examples/openui-cloud/src/app/api/frontend-token/route.ts
new file mode 100644
index 000000000..8f8e71918
--- /dev/null
+++ b/examples/openui-cloud/src/app/api/frontend-token/route.ts
@@ -0,0 +1,34 @@
+import { envOr, openuiCloudBaseUrl, requiredEnv } from "@/lib/env";
+
+/**
+ * Read-plane credential mint: proxies the OpenUI Cloud POST /v1/frontend-tokens
+ * (master-key plane) and returns ONLY { token, expires_at }.
+ *
+ * - The master key never reaches the browser (server env; the response is
+ * field-picked, never passed through).
+ * - user_id comes from server config — the browser must not choose its own
+ * identity.
+ */
+export async function POST() {
+ const upstream = await fetch(`${openuiCloudBaseUrl()}/v1/frontend-tokens`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${requiredEnv("THESYS_API_KEY")}`,
+ },
+ body: JSON.stringify({ user_id: envOr("DEMO_USER_ID", "demo-user") }),
+ });
+
+ if (!upstream.ok) {
+ // Never forward upstream auth-error bodies (they can embed key fragments).
+ console.error(
+ "[frontend-token] mint failed:",
+ upstream.status,
+ await upstream.text().catch(() => ""),
+ );
+ return Response.json({ error: { message: "token mint failed" } }, { status: 502 });
+ }
+
+ const { token, expires_at } = (await upstream.json()) as { token: string; expires_at: number };
+ return Response.json({ token, expires_at });
+}
diff --git a/examples/openui-cloud/src/app/globals.css b/examples/openui-cloud/src/app/globals.css
new file mode 100644
index 000000000..7070e07d3
--- /dev/null
+++ b/examples/openui-cloud/src/app/globals.css
@@ -0,0 +1,4 @@
+@import "tailwindcss";
+
+
+
\ No newline at end of file
diff --git a/examples/openui-artifact-demo/src/app/layout.tsx b/examples/openui-cloud/src/app/layout.tsx
similarity index 100%
rename from examples/openui-artifact-demo/src/app/layout.tsx
rename to examples/openui-cloud/src/app/layout.tsx
diff --git a/examples/openui-cloud/src/app/page.tsx b/examples/openui-cloud/src/app/page.tsx
new file mode 100644
index 000000000..dc818886a
--- /dev/null
+++ b/examples/openui-cloud/src/app/page.tsx
@@ -0,0 +1,88 @@
+"use client";
+import "@openuidev/react-ui/components.css";
+import "@openuidev/thesys/styles.css";
+
+import {
+ defineArtifactCategories,
+ openAIConversationMessageFormat,
+ openAIResponsesAdapter,
+ type ChatLLM,
+} from "@openuidev/react-headless";
+import { AgentInterface } from "@openuidev/react-ui";
+// chatLibrary, useOpenuiCloudStorage, and the artifact renderers all come from the
+// migrated SDK (@openuidev/thesys). Its artifact parser now reads the program from
+// the tool INPUT channel (args.artifact_content), so the rich preview renders live
+// during/after generation without a refresh.
+import { useTheme } from "@/hooks/use-system-theme";
+import {
+ chatLibrary,
+ presentationArtifactRenderer,
+ reportArtifactRenderer,
+ useOpenuiCloudStorage,
+} from "@openuidev/thesys";
+
+// Categories are consumer-owned (the SDK exports each renderer separately). One
+// category per genui artifact kind; `defineArtifactCategories` returns both the
+// deduped `artifactRenderers` and the `artifactCategories` (each `filter.type`
+// derived from the renderers' types). Presentation is listed first — it owns the
+// artifact tool names (the renderer registry is first-wins per toolName).
+const { artifactRenderers, artifactCategories } = defineArtifactCategories([
+ { name: "Presentations", renderers: [presentationArtifactRenderer] },
+ { name: "Reports", renderers: [reportArtifactRenderer] },
+]);
+
+const llm: ChatLLM = {
+ send: async ({ threadId, messages, signal }) => {
+ // The API replays full history via the conversation linkage — send only
+ // the latest message.
+ const latest = messages.slice(-1);
+ return fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ threadId, input: openAIConversationMessageFormat.toApi(latest) }),
+ signal,
+ });
+ },
+ streamProtocol: openAIResponsesAdapter(),
+};
+
+export default function Page() {
+ const mode = useTheme();
+ // useOpenuiCloudStorage: browser ChatStorage over /v1, fct_-authenticated. As a
+ // hook the storage + its fct_ token manager are created on mount (not at module
+ // load), so the token fetch follows this component's lifecycle.
+ const storage = useOpenuiCloudStorage({
+ // Backend mint proxy (POST → { token, expires_at }); the hook caches +
+ // refreshes it and injects x-thesys-frontend-token on every /v1 call.
+ token: "/api/frontend-token",
+ // Env-driven so a local stack can be targeted; defaults to prod when unset.
+ apiBaseUrl: process.env.NEXT_PUBLIC_OPENUI_CLOUD_BASE_URL,
+ features: { artifact: true },
+ });
+
+ return (
+ <div className="h-screen w-screen overflow-hidden relative">
+ <AgentInterface
+ storage={storage}
+ llm={llm}
+ componentLibrary={chatLibrary}
+ artifactRenderers={artifactRenderers}
+ artifactCategories={artifactCategories}
+ agentName="OpenUI Cloud"
+ scrollVariant="always"
+ scrollOnLoad={false}
+ theme={{ mode }}
+ starters={[
+ {
+ displayText: "Quarterly deck",
+ prompt: "Create a short presentation about our Q2 results with three slides.",
+ },
+ {
+ displayText: "Market report",
+ prompt: "Write a brief market-analysis report on the EV sector.",
+ },
+ ]}
+ />
+ </div>
+ );
+}
diff --git a/examples/openui-artifact-demo/src/hooks/use-system-theme.tsx b/examples/openui-cloud/src/hooks/use-system-theme.tsx
similarity index 100%
rename from examples/openui-artifact-demo/src/hooks/use-system-theme.tsx
rename to examples/openui-cloud/src/hooks/use-system-theme.tsx
diff --git a/examples/openui-cloud/src/lib/env.ts b/examples/openui-cloud/src/lib/env.ts
new file mode 100644
index 000000000..c1878281c
--- /dev/null
+++ b/examples/openui-cloud/src/lib/env.ts
@@ -0,0 +1,21 @@
+// Env reads happen at REQUEST time (inside handlers), never at module scope:
+// tests can vi.stubEnv per-case and `next build` doesn't bake values in.
+
+export function requiredEnv(name: string): string {
+ const value = process.env[name];
+ if (!value) throw new Error(`Missing required env var: ${name}`);
+ return value;
+}
+
+export function envOr(name: string, fallback: string): string {
+ return process.env[name] || fallback;
+}
+
+/**
+ * OpenUI Cloud API origin (master-key plane: /v1/embed/responses, /v1/frontend-tokens).
+ * Read at request time (per this file's convention) and env-driven so a local stack can be
+ * targeted via `OPENUI_CLOUD_BASE_URL`; defaults to production.
+ */
+export function openuiCloudBaseUrl(): string {
+ return envOr("OPENUI_CLOUD_BASE_URL", "https://api.thesys.dev");
+}
diff --git a/examples/openui-cloud/src/lib/thesys/artifactStorage.ts b/examples/openui-cloud/src/lib/thesys/artifactStorage.ts
new file mode 100644
index 000000000..81c1a1b5e
--- /dev/null
+++ b/examples/openui-cloud/src/lib/thesys/artifactStorage.ts
@@ -0,0 +1,70 @@
+import type {
+ Artifact,
+ ArtifactListParams,
+ ArtifactStorage,
+ ArtifactSummary,
+} from "@openuidev/react-headless";
+import { cloudRequest, nextCursorOf, type CloudArtifact, type CloudListEnvelope } from "./wire";
+
+export interface CloudArtifactStorageOptions {
+ /** OpenUI Cloud API origin, e.g. "http://localhost:3102". */
+ baseUrl: string;
+ /** The token-injecting fetch from createFctFetch. */
+ fetch: typeof fetch;
+ /** Default page size when the caller passes no limit. */
+ pageLimit?: number;
+}
+
+function toSummary(artifact: CloudArtifact): ArtifactSummary {
+ return {
+ id: artifact.id,
+ title: artifact.name ?? artifact.id,
+ type: artifact.kind,
+ threadId: artifact.conversation_id,
+ updatedAt: (artifact.updated_at ?? artifact.created_at) * 1000,
+ };
+}
+
+
+export function cloudArtifactStorage({
+ baseUrl,
+ fetch: fetchImpl,
+ pageLimit = 100,
+}: CloudArtifactStorageOptions): ArtifactStorage {
+ const request = cloudRequest(fetchImpl, baseUrl);
+
+ return {
+ /** GET /v1/artifacts?[name=][kind=…]&limit[&after=]. Omitting the
+ * conversation scope lists across conversations, token-scoped to the user. */
+ async list(params?: ArtifactListParams) {
+ const query = new URLSearchParams();
+ if (params?.name !== undefined && params.name !== "") query.set("name", params.name);
+ for (const type of params?.type ?? []) query.append("kind", type);
+ if (params?.cursor !== undefined) query.set("after", params.cursor);
+ query.set("limit", String(params?.limit ?? pageLimit));
+ const res = await request(`/v1/artifacts?${query.toString()}`);
+ const envelope = (await res.json()) as CloudListEnvelope<CloudArtifact>;
+ return { artifacts: envelope.data.map(toSummary), nextCursor: nextCursorOf(envelope) };
+ },
+
+ /** GET /v1/artifacts/:id → the stored openui-lang program (bare program;
+ * the renderer's parser sniffs the `root = …` root). */
+ async get(id: string): Promise<Artifact> {
+ const res = await request(`/v1/artifacts/${encodeURIComponent(id)}`);
+ const artifact = (await res.json()) as CloudArtifact;
+ return { ...toSummary(artifact), content: artifact.content };
+ },
+
+ /** POST /v1/artifacts/:id {content}. Send the edited inner program (a
+ * string); omit version to let the server bump it. */
+ async update(patch: { id: string; content: unknown }): Promise<ArtifactSummary> {
+ const content =
+ typeof patch.content === "string" ? patch.content : JSON.stringify(patch.content);
+ const res = await request(`/v1/artifacts/${encodeURIComponent(patch.id)}`, {
+ method: "POST",
+ body: JSON.stringify({ content }),
+ });
+ return toSummary((await res.json()) as CloudArtifact);
+ },
+ };
+}
diff --git a/examples/openui-cloud/src/lib/thesys/frontendTokenManager.ts b/examples/openui-cloud/src/lib/thesys/frontendTokenManager.ts
new file mode 100644
index 000000000..0f2055b54
--- /dev/null
+++ b/examples/openui-cloud/src/lib/thesys/frontendTokenManager.ts
@@ -0,0 +1,109 @@
+/**
+ * Frontend session-token (fct_) lifecycle for the browser plane.
+ *
+ * - The token rides ONLY the `x-thesys-frontend-token` header; `Authorization`
+ * on /v1/* always means the master key (server-side).
+ * - Minting happens on YOUR backend (here, the /api/frontend-token proxy),
+ * which calls the cloud mint endpoint with the master key and decides the
+ * end-user identity server-side. The browser sends no body and never names
+ * its own user.
+ * - Mint response: { token: 'fct_…', expires_at: <unix seconds> }, TTL ~15 min.
+ *
+ * A fetch override (not static headers) is used so the token can refresh
+ * mid-session — the chat provider captures the storage object once at mount.
+ */
+
+export const FRONTEND_TOKEN_HEADER = "x-thesys-frontend-token";
+
+export interface MintFrontendTokenResponse {
+ token: string;
+ expires_at: number; // unix seconds
+}
+
+export interface FrontendTokenManagerOptions {
+ /** Your backend mint endpoint, e.g. "/api/frontend-token". */
+ mintUrl: string;
+ /** Override for tests / SSR. Defaults to globalThis.fetch. */
+ fetch?: typeof fetch;
+ /** Refresh this many seconds before expiry. Default 60. */
+ refreshSkewSeconds?: number;
+}
+
+export interface FrontendTokenManager {
+ /** A token valid for at least refreshSkewSeconds (single-flight mint). */
+ getToken(): Promise<string>;
+ /** Drop the cached token. Pass the token that 401'd so a concurrent refresh
+ * is not discarded. */
+ invalidate(staleToken?: string): void;
+}
+
+export function createFrontendTokenManager({
+ mintUrl,
+ fetch: customFetch,
+ refreshSkewSeconds = 60,
+}: FrontendTokenManagerOptions): FrontendTokenManager {
+ const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);
+
+ let token: string | null = null;
+ let expiresAt = 0; // unix seconds
+ let inflight: Promise<string> | null = null;
+
+ const mint = async (): Promise<string> => {
+ const res = await fetchImpl(mintUrl, { method: "POST" });
+ if (!res.ok) {
+ throw new Error(`frontend-token mint failed: ${res.status} ${res.statusText}`);
+ }
+ const body = (await res.json()) as MintFrontendTokenResponse;
+ token = body.token;
+ expiresAt = body.expires_at;
+ return body.token;
+ };
+
+ return {
+ async getToken(): Promise<string> {
+ const nowSeconds = Date.now() / 1000;
+ if (token !== null && nowSeconds < expiresAt - refreshSkewSeconds) return token;
+ // Single-flight: callers during a refresh await the same mint.
+ if (inflight === null) {
+ inflight = mint().finally(() => {
+ inflight = null;
+ });
+ }
+ return inflight;
+ },
+
+ invalidate(staleToken?: string): void {
+ if (staleToken === undefined || staleToken === token) {
+ token = null;
+ expiresAt = 0;
+ }
+ },
+ };
+}
+
+/**
+ * Wrap a base fetch so every request carries a fresh token, with one reactive
+ * retry on 401. The request is re-sent with the same init — pass re-readable
+ * (string) bodies only.
+ */
+export function createFctFetch(tokens: FrontendTokenManager, baseFetch?: typeof fetch): typeof fetch {
+ const fetchImpl = baseFetch ?? globalThis.fetch.bind(globalThis);
+
+ return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
+ const token = await tokens.getToken();
+ const headers = new Headers(init?.headers);
+ headers.set(FRONTEND_TOKEN_HEADER, token);
+
+ let res = await fetchImpl(input, { ...init, headers });
+
+ if (res.status === 401) {
+ tokens.invalidate(token);
+ const freshToken = await tokens.getToken();
+ const retryHeaders = new Headers(init?.headers);
+ retryHeaders.set(FRONTEND_TOKEN_HEADER, freshToken);
+ res = await fetchImpl(input, { ...init, headers: retryHeaders });
+ }
+
+ return res;
+ };
+}
diff --git a/examples/openui-cloud/src/lib/thesys/index.ts b/examples/openui-cloud/src/lib/thesys/index.ts
new file mode 100644
index 000000000..f93d3e38e
--- /dev/null
+++ b/examples/openui-cloud/src/lib/thesys/index.ts
@@ -0,0 +1,101 @@
+import type { ChatStorage } from "@openuidev/react-headless";
+import { cloudArtifactStorage } from "./artifactStorage";
+import { cloudThreadStorage } from "./threadStorage";
+import {
+ createFctFetch,
+ createFrontendTokenManager,
+ type FrontendTokenManager,
+} from "./frontendTokenManager";
+
+export { cloudArtifactStorage, type CloudArtifactStorageOptions } from "./artifactStorage";
+export { cloudItemsToMessages } from "./items";
+export { cloudThreadStorage, deriveTitle, type CloudThreadStorageOptions } from "./threadStorage";
+export {
+ FRONTEND_TOKEN_HEADER,
+ createFctFetch,
+ createFrontendTokenManager,
+ type FrontendTokenManager,
+ type FrontendTokenManagerOptions,
+ type MintFrontendTokenResponse,
+} from "./frontendTokenManager";
+export * from "./wire";
+
+/** Which storage surfaces openuiCloud wires. */
+export interface OpenuiCloudFeatures {
+ /** Stored-artifact reads + edits. Default true. */
+ artifact?: boolean;
+}
+
+export interface OpenuiCloudOptions {
+ /**
+ * The OpenUI Cloud API origin. Defaults to "https://api.thesys.dev" (the
+ * storage layer appends `/v1/...`). Set this to e.g. "http://localhost:3102"
+ * to run against a local stack. The browser calls this directly with the
+ * fct_ token — there is no same-origin proxy in between.
+ */
+ apiBaseUrl?: string;
+ /**
+ * Where the short-lived fct_ session token comes from — either a URL of your
+ * backend mint endpoint (POST → { token, expires_at }, cached + refreshed
+ * here) or a function returning a fresh token (you own caching). The token
+ * rides the `x-thesys-frontend-token` header on every /v1 call. The master
+ * key is minted server-side and never reaches the browser.
+ */
+ token: string | (() => Promise<string>);
+ /** Which storage surfaces to wire. Omit to enable all. */
+ features?: OpenuiCloudFeatures;
+ /** fetch override (tests / SSR). Defaults to globalThis.fetch. */
+ fetch?: typeof fetch;
+ /** Refresh the cached token this many seconds before expiry (URL form). Default 60. */
+ refreshSkewSeconds?: number;
+}
+
+/**
+ * One-call browser wiring for OpenUI Cloud: a `ChatStorage` backed by the /v1
+ * API, authenticated per-request with an fct_ session token. Pass it straight
+ * to `<AgentInterface storage={…} />`.
+ *
+ * This is the READ/EDIT plane (browser → /v1/* with the fct_ token).
+ * Generation is the separate ChatLLM plane (browser → your backend →
+ * /v1/embed/responses with the master key).
+ */
+/** OpenUI Cloud API origin used when `apiBaseUrl` is omitted. The storage
+ * layer appends `/v1/...` to it. */
+const DEFAULT_API_BASE_URL = "https://api.thesys.dev";
+
+export function openuiCloud(options: OpenuiCloudOptions): ChatStorage {
+ const tokens = toTokenManager(options);
+ const fctFetch = createFctFetch(tokens, options.fetch);
+ const artifactOn = options.features?.artifact ?? true;
+ const baseUrl = options.apiBaseUrl ?? DEFAULT_API_BASE_URL;
+
+ const storage: ChatStorage = {
+ thread: cloudThreadStorage({ baseUrl, fetch: fctFetch }),
+ };
+ if (artifactOn) {
+ storage.artifact = cloudArtifactStorage({ baseUrl, fetch: fctFetch });
+ }
+ return storage;
+}
+
+/** Normalize the `token` option into a FrontendTokenManager. */
+function toTokenManager(options: OpenuiCloudOptions): FrontendTokenManager {
+ if (typeof options.token === "string") {
+ return createFrontendTokenManager({
+ mintUrl: options.token,
+ fetch: options.fetch,
+ refreshSkewSeconds: options.refreshSkewSeconds,
+ });
+ }
+ const provider = options.token;
+ let current: string | null = null;
+ return {
+ async getToken(): Promise<string> {
+ current = await provider();
+ return current;
+ },
+ invalidate(staleToken?: string): void {
+ if (staleToken === undefined || staleToken === current) current = null;
+ },
+ };
+}
diff --git a/examples/openui-cloud/src/lib/thesys/items.ts b/examples/openui-cloud/src/lib/thesys/items.ts
new file mode 100644
index 000000000..26c914d10
--- /dev/null
+++ b/examples/openui-cloud/src/lib/thesys/items.ts
@@ -0,0 +1,65 @@
+import { openAIConversationMessageFormat, type Message } from "@openuidev/react-headless";
+import type { CloudConversationItem } from "./wire";
+
+/**
+ * Convert /v1 conversation items to AG-UI Message[]. Each item is normalized
+ * into the OpenAI ConversationItem shape that openAIConversationMessageFormat
+ * .fromApi expects, then delegated — the grouping logic (function_call →
+ * assistant toolCalls, function_call_output → ToolMessage) stays in the SDK.
+ *
+ * Normalizations:
+ * - message content: assistant outputs arrive as part arrays; user inputs
+ * arrive as a plain string → wrap strings as a single text part.
+ * - function_call / function_call_output: a malformed row (missing the
+ * top-level call_id/name/output) is skipped so it can't crash fromApi.
+ * - other item types are skipped.
+ */
+function normalizeItem(item: CloudConversationItem): Record<string, unknown> | null {
+ switch (item.type) {
+ case "message": {
+ const content = item.content;
+ const parts = Array.isArray(content)
+ ? content
+ : [
+ {
+ type: item.role === "assistant" ? "output_text" : "input_text",
+ text: typeof content === "string" ? content : "",
+ },
+ ];
+ return {
+ id: item.id,
+ type: "message",
+ role: item.role ?? "user",
+ status: item.status ?? "completed",
+ content: parts,
+ };
+ }
+
+ case "function_call": {
+ if (typeof item.call_id !== "string" || typeof item.name !== "string") return null;
+ return {
+ id: item.id,
+ type: "function_call",
+ call_id: item.call_id,
+ name: item.name,
+ arguments:
+ typeof item.arguments === "string" ? item.arguments : JSON.stringify(item.arguments ?? {}),
+ };
+ }
+
+ case "function_call_output": {
+ if (typeof item.call_id !== "string" || item.output === undefined) return null;
+ return { id: item.id, type: "function_call_output", call_id: item.call_id, output: item.output };
+ }
+
+ default:
+ return null;
+ }
+}
+
+export function cloudItemsToMessages(items: CloudConversationItem[]): Message[] {
+ const normalized = items
+ .map(normalizeItem)
+ .filter((i): i is Record<string, unknown> => i !== null);
+ return openAIConversationMessageFormat.fromApi(normalized);
+}
diff --git a/examples/openui-cloud/src/lib/thesys/threadStorage.ts b/examples/openui-cloud/src/lib/thesys/threadStorage.ts
new file mode 100644
index 000000000..a89af1664
--- /dev/null
+++ b/examples/openui-cloud/src/lib/thesys/threadStorage.ts
@@ -0,0 +1,109 @@
+import type { Message, Thread, ThreadStorage, UserMessage } from "@openuidev/react-headless";
+import { cloudItemsToMessages } from "./items";
+import {
+ cloudRequest,
+ nextCursorOf,
+ type CloudConversation,
+ type CloudConversationItem,
+ type CloudListEnvelope,
+} from "./wire";
+
+export interface CloudThreadStorageOptions {
+ /** OpenUI Cloud API origin, e.g. "http://localhost:3102". */
+ baseUrl: string;
+ /** The token-injecting fetch from createFctFetch. */
+ fetch: typeof fetch;
+ /** Page size for list/items calls. */
+ pageLimit?: number;
+}
+
+/** Hard stop for the items pagination loop. */
+const MAX_ITEM_PAGES = 50;
+
+function toThread(conversation: CloudConversation): Thread {
+ return {
+ id: conversation.id,
+ title: conversation.title ?? "New conversation",
+ createdAt: conversation.created_at * 1000, // unix seconds → ms
+ };
+}
+
+/** Client-side title from the first user message (the API does not auto-title). */
+export function deriveTitle(firstMessage: UserMessage): string {
+ const content = firstMessage.content;
+ let text = "";
+ if (typeof content === "string") {
+ text = content;
+ } else if (Array.isArray(content)) {
+ for (const part of content) {
+ if (part.type === "text" && typeof part.text === "string" && part.text.trim() !== "") {
+ text = part.text;
+ break;
+ }
+ }
+ }
+ text = text.trim();
+ return (text === "" ? "New conversation" : text).slice(0, 60);
+}
+
+export function cloudThreadStorage({
+ baseUrl,
+ fetch: fetchImpl,
+ pageLimit = 100,
+}: CloudThreadStorageOptions): ThreadStorage {
+ const request = cloudRequest(fetchImpl, baseUrl);
+
+ return {
+ /** GET /v1/conversations?limit[&after]. Newest-first. */
+ async listThreads(cursor?: string) {
+ const query = new URLSearchParams({ limit: String(pageLimit) });
+ if (cursor !== undefined) query.set("after", cursor);
+ const res = await request(`/v1/conversations?${query.toString()}`);
+ const envelope = (await res.json()) as CloudListEnvelope<CloudConversation>;
+ return { threads: envelope.data.map(toThread), nextCursor: nextCursorOf(envelope) };
+ },
+
+ /** POST /v1/conversations {title}. No messages and no user_id — the user is
+ * bound from the token; the first message arrives later on the generation
+ * plane (conversation linkage). */
+ async createThread(firstMessage: UserMessage): Promise<Thread> {
+ const res = await request(`/v1/conversations`, {
+ method: "POST",
+ body: JSON.stringify({ title: deriveTitle(firstMessage) }),
+ });
+ return toThread((await res.json()) as CloudConversation);
+ },
+
+ /** GET /v1/conversations/:id/items?order=asc, paged, then mapped to Messages. */
+ async getMessages(threadId: string): Promise<Message[]> {
+ const items: CloudConversationItem[] = [];
+ let after: string | undefined;
+ for (let page = 0; page < MAX_ITEM_PAGES; page++) {
+ const query = new URLSearchParams({ order: "asc", limit: String(pageLimit) });
+ if (after !== undefined) query.set("after", after);
+ const res = await request(
+ `/v1/conversations/${encodeURIComponent(threadId)}/items?${query.toString()}`,
+ );
+ const envelope = (await res.json()) as CloudListEnvelope<CloudConversationItem>;
+ items.push(...envelope.data);
+ after = nextCursorOf(envelope);
+ if (after === undefined) break;
+ }
+ return cloudItemsToMessages(items);
+ },
+
+ /** POST /v1/conversations/:id {title}. */
+ async updateThread(thread: Thread): Promise<Thread> {
+ const res = await request(`/v1/conversations/${encodeURIComponent(thread.id)}`, {
+ method: "POST",
+ body: JSON.stringify({ title: thread.title }),
+ });
+ return toThread((await res.json()) as CloudConversation);
+ },
+
+ /** DELETE /v1/conversations/:id (soft delete). */
+ async deleteThread(id: string): Promise<void> {
+ await request(`/v1/conversations/${encodeURIComponent(id)}`, { method: "DELETE" });
+ },
+ };
+}
diff --git a/examples/openui-cloud/src/lib/thesys/wire.ts b/examples/openui-cloud/src/lib/thesys/wire.ts
new file mode 100644
index 000000000..c008bac6a
--- /dev/null
+++ b/examples/openui-cloud/src/lib/thesys/wire.ts
@@ -0,0 +1,82 @@
+/**
+ * Wire types for the OpenUI Cloud /v1 API, plus the shared list envelope,
+ * cursor rule, and request helper. Field-for-field mirrors of the API DTOs.
+ */
+
+/** A conversation. `created_at` is unix SECONDS. */
+export interface CloudConversation {
+ id: string;
+ object: "conversation";
+ created_at: number;
+ title?: string;
+ metadata?: Record<string, unknown>;
+ user_id?: string;
+ app_id?: string;
+}
+
+/** A conversation item (full Responses item shape). */
+export interface CloudConversationItem {
+ id: string;
+ object: "conversation.item";
+ type: string; // message | function_call | function_call_output | ...
+ role?: string;
+ status?: string;
+ content?: unknown;
+ metadata?: Record<string, unknown>;
+ created_at: number;
+ call_id?: string;
+ name?: string;
+ arguments?: string;
+ output?: unknown;
+}
+
+/** A stored artifact. `content` is the renderer-ready openui-lang program. */
+export interface CloudArtifact {
+ id: string;
+ object: "openui.artifact";
+ conversation_id: string;
+ kind: string; // 'slides' | 'report'
+ name?: string;
+ version?: string; // server bumps via String(Date.now()) when omitted
+ content: string;
+ created_at: number;
+ updated_at?: number;
+}
+
+/** List envelope shared by all paged endpoints. */
+export interface CloudListEnvelope<T> {
+ object: "list";
+ data: T[];
+ has_more: boolean;
+ first_id?: string;
+ last_id?: string;
+}
+
+/** Forward cursor: pass `last_id` back as `?after=` when there's another page. */
+export function nextCursorOf(envelope: CloudListEnvelope<unknown>): string | undefined {
+ return envelope.has_more && envelope.last_id ? envelope.last_id : undefined;
+}
+
+/**
+ * Request helper: prefix baseUrl, set JSON content-type only when sending a
+ * body, throw on non-2xx. `fetchImpl` is the token-injecting fetch — auth
+ * lives there, never here.
+ */
+export function cloudRequest(fetchImpl: typeof fetch, baseUrl: string) {
+ const base = baseUrl.replace(/\/+$/, "");
+ return async (path: string, init?: RequestInit): Promise<Response> => {
+ const res = await fetchImpl(`${base}${path}`, {
+ ...init,
+ headers: {
+ ...(init?.body ? { "Content-Type": "application/json" } : {}),
+ ...init?.headers,
+ },
+ });
+ if (!res.ok) {
+ throw new Error(
+ `OpenUI Cloud: ${init?.method ?? "GET"} ${path} failed: ${res.status} ${res.statusText}`,
+ );
+ }
+ return res;
+ };
+}
diff --git a/examples/openui-cloud/stubs/lucide-dynamic.mjs b/examples/openui-cloud/stubs/lucide-dynamic.mjs
new file mode 100644
index 000000000..b49cea677
--- /dev/null
+++ b/examples/openui-cloud/stubs/lucide-dynamic.mjs
@@ -0,0 +1,7 @@
+// Build shim for the example. The installed `lucide-react` version no longer
+// ships the dynamic-icon subpaths ('lucide-react/dynamic' and
+// 'lucide-react/dynamicIconImports.mjs') that @openuidev/thesys's icon wrapper
+// imports. next.config aliases those specifiers to this empty stub so the
+// bundle compiles; dynamic icons fall back to their defaults.
+export const dynamicIconImports = {};
+export default {};
diff --git a/examples/openui-artifact-demo/tsconfig.json b/examples/openui-cloud/tsconfig.json
similarity index 100%
rename from examples/openui-artifact-demo/tsconfig.json
rename to examples/openui-cloud/tsconfig.json
diff --git a/examples/react-email/package.json b/examples/react-email/package.json
index 9281e8e5d..b5d656cf9 100644
--- a/examples/react-email/package.json
+++ b/examples/react-email/package.json
@@ -11,9 +11,9 @@
},
"dependencies": {
"@openuidev/cli": "workspace:*",
- "@openuidev/react-email": "workspace:*",
- "@openuidev/react-headless": "workspace:*",
- "@openuidev/react-lang": "workspace:*",
+ "@openuidev/react-email": "0.2.4",
+ "@openuidev/react-headless": "0.8.2",
+ "@openuidev/react-lang": "0.2.6",
"@react-email/components": "^0.0.41",
"@react-email/render": "^1.0.6",
"lucide-react": "^0.562.0",
diff --git a/examples/react-email/src/components/composePage/starters.ts b/examples/react-email/src/components/composePage/starters.ts
index d94c94bf6..eb107d05e 100644
--- a/examples/react-email/src/components/composePage/starters.ts
+++ b/examples/react-email/src/components/composePage/starters.ts
@@ -23,7 +23,7 @@ Include these sections in order:
- (https://react.dev/favicon-32x32.png, "React", "React Components", "40+ production-ready components with defineComponent and Zod-powered type safety.")
- (https://openai.com/favicon.ico, "AI", "Any LLM Provider", "OpenAI, Anthropic, Gemini, Mistral — works with any OpenAI-compatible API.")
- (https://www.typescriptlang.org/favicon-32x32.png, "TypeScript", "OpenUI Lang", "A specialized format that LLMs generate natively — no JSON parsing, no prompt hacks.")
- - (https://vercel.com/favicon.ico, "Deploy", "Chat SDK Included", "Drop-in Copilot, FullScreen, and BottomTray layouts with streaming and persistence.")
+ - (https://vercel.com/favicon.ico, "Deploy", "Chat SDK Included", "Drop-in AgentInterface artifact UI with streaming and persistence.")
14. EmailDivider
15. EmailCodeBlock with this code:
"import { defineComponent } from '@openuidev/react-lang';\\nimport { z } from 'zod';\\n\\nexport const WeatherCard = defineComponent({\\n name: 'WeatherCard',\\n props: z.object({\\n city: z.string(),\\n temp: z.number(),\\n condition: z.string(),\\n }),\\n description: 'Shows current weather for a city',\\n component: ({ props }) => (\\n <div>\\n <h3>{props.city}</h3>\\n <p>{props.temp}° — {props.condition}</p>\\n </div>\\n ),\\n});"
diff --git a/examples/shadcn-chat/README.md b/examples/shadcn-chat/README.md
index a160db89d..4dc6d165a 100644
--- a/examples/shadcn-chat/README.md
+++ b/examples/shadcn-chat/README.md
@@ -30,7 +30,7 @@ Card([
])
```
-On the client, the `<FullScreen />` component from `@openuidev/react-ui` handles everything — conversation state, streaming, input, and rendering. It parses the incoming SSE stream with `openAIAdapter()` and renders each OpenUI Lang node using `shadcnChatLibrary` — the custom 45-component library defined in `src/lib/shadcn-genui/`.
+On the client, the `<AgentInterface />` component from `@openuidev/react-ui` handles everything — thread history, conversation state, streaming, input, and rendering. You give it an `llm` describing how to call your backend and parse its stream, and a `componentLibrary`. It parses the incoming SSE stream with `openAIAdapter()` and renders each OpenUI Lang node using `shadcnChatLibrary` — the custom 45-component library defined in `src/lib/shadcn-genui/`.
---
@@ -40,7 +40,7 @@ On the client, the `<FullScreen />` component from `@openuidev/react-ui` handles
┌────────────────────────────────────┐ ┌────────────────────────────────────┐
│ Browser │ HTTP │ Next.js API Route │
│ │ ──────►│ │
-│ • <FullScreen /> manages UI │ │ • Loads system-prompt.txt │
+│ • <AgentInterface /> manages UI │ │ • Loads system-prompt.txt │
│ • openAIAdapter() parses SSE │◄────── │ • Calls LLM with runTools │
│ • shadcnChatLibrary renders nodes │ SSE │ • Executes tools server-side │
│ • Conversation starters included │ │ • Streams response as SSE events │
@@ -49,11 +49,11 @@ On the client, the `<FullScreen />` component from `@openuidev/react-ui` handles
### Request / Response Flow
-1. User types a message. `<FullScreen />` calls `processMessage`, which sends `POST /api/chat` with the conversation history formatted via `openAIMessageFormat.toApi()`.
+1. User types a message. `<AgentInterface />` calls `llm.send`, which sends `POST /api/chat` with the conversation history formatted via `openAIMessageFormat.toApi()`.
2. The API route reads `system-prompt.txt`, instantiates an OpenAI client, and calls `runTools` — the OpenAI SDK's built-in multi-step tool execution loop.
3. If the LLM calls a tool, `runTools` executes it server-side and feeds the result back into the model automatically, emitting SSE events for the tool call and result.
4. The LLM generates a final OpenUI Lang response. Text deltas are streamed as SSE `chunk` events. The stream ends with `data: [DONE]`.
-5. On the client, `openAIAdapter()` parses the SSE events and hands the accumulated text to `<FullScreen />`'s internal renderer.
+5. On the client, `openAIAdapter()` parses the SSE events and hands the accumulated text to `<AgentInterface />`'s internal renderer.
6. The renderer passes the text to `<Renderer response={text} library={shadcnChatLibrary} />`, which parses the OpenUI Lang markup and renders each node as a shadcn/ui component in real time.
---
@@ -65,7 +65,7 @@ shadcn-chat/
├── src/
│ ├── app/
│ │ ├── api/chat/route.ts # Streaming chat endpoint (OpenAI SDK + SSE)
-│ │ ├── page.tsx # Single page — mounts <FullScreen />
+│ │ ├── page.tsx # Single page — mounts <AgentInterface />
│ │ └── layout.tsx # Root layout with ThemeProvider
│ ├── components/ui/ # Base shadcn/ui primitives (accordion, card, table, etc.)
│ ├── hooks/
@@ -146,17 +146,36 @@ Messages are cleaned before sending to the API: `tool` role messages are strippe
### `src/app/page.tsx` — Frontend
-The entire chat interface is the `<FullScreen />` component from `@openuidev/react-ui`. You configure it with three things:
+The entire chat interface is the `<AgentInterface />` component from `@openuidev/react-ui`. You configure it with two core props:
| Prop | Value | Purpose |
| ---- | ----- | ------- |
-| `processMessage` | `fetch("/api/chat", ...)` | How to call your backend |
-| `streamProtocol` | `openAIAdapter()` | How to parse the SSE stream |
+| `llm` | `{ send, streamProtocol }` | How to call your backend (`send`) and parse its stream (`streamProtocol`) |
| `componentLibrary` | `shadcnChatLibrary` | Which components to render OpenUI Lang nodes with |
-`openAIAdapter()` is imported from `@openuidev/react-headless`. It knows how to parse the OpenAI-style SSE format emitted by this route. `openAIMessageFormat.toApi()` converts the internal message objects into the format the OpenAI API expects.
+`storage` is optional — omit it for the built-in in-memory default (wiped on reload). Pass a `ChatStorage` adapter to persist the thread list.
+
+`llm.send` calls `fetch("/api/chat", ...)` with the conversation history formatted via `openAIMessageFormat.toApi()`, and `llm.streamProtocol` is set to `openAIAdapter()`:
+
+```tsx
+<AgentInterface
+ llm={{
+ send: ({ messages, signal }) =>
+ fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ messages: openAIMessageFormat.toApi(messages) }),
+ signal,
+ }),
+ streamProtocol: openAIAdapter(),
+ }}
+ componentLibrary={shadcnChatLibrary}
+/>
+```
+
+`openAIAdapter()` and `openAIMessageFormat` are imported from `@openuidev/react-ui`. `openAIAdapter()` knows how to parse the OpenAI-style SSE format emitted by this route, and `openAIMessageFormat.toApi()` converts the internal message objects into the format the OpenAI API expects.
-The page also includes 7 built-in conversation starters to showcase the component library:
+The page also passes 7 built-in `starters` (each a `{ displayText, prompt }` pair) to showcase the component library:
| Starter | What it demonstrates |
| ------- | -------------------- |
diff --git a/examples/shadcn-chat/src/app/page.tsx b/examples/shadcn-chat/src/app/page.tsx
index d068a639e..51561636b 100644
--- a/examples/shadcn-chat/src/app/page.tsx
+++ b/examples/shadcn-chat/src/app/page.tsx
@@ -2,69 +2,78 @@
import { useTheme } from "@/hooks/use-system-theme";
import { shadcnChatLibrary } from "@/lib/shadcn-genui";
-import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
+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">
- <FullScreen
- processMessage={async ({ messages, abortController }) => {
- return fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messages: openAIMessageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- }}
- streamProtocol={openAIAdapter()}
+ <AgentInterface
+ llm={llm}
componentLibrary={shadcnChatLibrary}
agentName="shadcn/ui Chat"
theme={{ mode }}
- conversationStarters={{
- variant: "short",
- options: [
- {
- displayText: "Startup dashboard",
- prompt:
- "Build a startup analytics dashboard with tags, Tabs (Revenue BarChart, Growth LineChart, Breakdown PieChart), a key metrics table, a progress bar toward the annual goal, and follow-ups.",
- },
- {
- displayText: "Travel planner",
- prompt:
- "Design a trip planner with a range CalendarBlock (2 months), an Accordion for 3 destinations (Tokyo, Paris, New York) each with description, tags, and a budget progress bar, then a preferences form with select, slider, and checkboxes. Add follow-ups.",
- },
- {
- displayText: "Market watch",
- prompt:
- "Fetch stock prices for AAPL, NVDA, GOOGL, and TSLA. Show a market overview with tags, a comparison table, an alert for the biggest mover, and a DrawerBlock with a BarChart comparing all four. Add follow-ups.",
- },
- {
- displayText: "Event RSVP",
- prompt:
- "Create an event RSVP form for a tech summit with an info alert, and a form containing inputs for name and email, a select for ticket tier, radio group for diet, date picker, slider for group size, checkboxes for sessions, and switches for notifications. Add follow-ups.",
- },
- {
- displayText: "Team standup",
- prompt:
- "Generate a team standup board with a sprint progress bar, a task table (5 members), a warning alert for blockers, an Accordion (Yesterday, Today, Blockers), and a DialogBlock that opens sprint metrics with a PieChart and summary table. Add follow-ups.",
- },
- {
- displayText: "Recipe card",
- prompt:
- "Build a recipe card for Spicy Thai Basil Chicken with tags, Tabs (Ingredients table, Instructions accordion with 5 steps, Nutrition donut PieChart + table), a blockquote chef's tip, and buttons with a DialogBlock for the full recipe. Add follow-ups.",
- },
- {
- displayText: "Chart showcase",
- prompt:
- "Build a 'Global Tech Industry Report 2025' with tags and Tabs containing six chart types: a grouped BarChart (quarterly revenue, 3 series), a LineChart (monthly trends, 2 series), an AreaChart (yearly adoption, 2 series), a donut PieChart (market share, 6 slices), a RadarChart (developer skills, 2 series), and a ScatterChart (funding vs revenue, 2 series with labeled points). Below add a summary table, a RadialChart for industry goals, and follow-ups.",
- },
- ],
- }}
+ starterVariant="short"
+ starters={[
+ {
+ displayText: "Startup dashboard",
+ prompt:
+ "Build a startup analytics dashboard with tags, Tabs (Revenue BarChart, Growth LineChart, Breakdown PieChart), a key metrics table, a progress bar toward the annual goal, and follow-ups.",
+ },
+ {
+ displayText: "Travel planner",
+ prompt:
+ "Design a trip planner with a range CalendarBlock (2 months), an Accordion for 3 destinations (Tokyo, Paris, New York) each with description, tags, and a budget progress bar, then a preferences form with select, slider, and checkboxes. Add follow-ups.",
+ },
+ {
+ displayText: "Market watch",
+ prompt:
+ "Fetch stock prices for AAPL, NVDA, GOOGL, and TSLA. Show a market overview with tags, a comparison table, an alert for the biggest mover, and a DrawerBlock with a BarChart comparing all four. Add follow-ups.",
+ },
+ {
+ displayText: "Event RSVP",
+ prompt:
+ "Create an event RSVP form for a tech summit with an info alert, and a form containing inputs for name and email, a select for ticket tier, radio group for diet, date picker, slider for group size, checkboxes for sessions, and switches for notifications. Add follow-ups.",
+ },
+ {
+ displayText: "Team standup",
+ prompt:
+ "Generate a team standup board with a sprint progress bar, a task table (5 members), a warning alert for blockers, an Accordion (Yesterday, Today, Blockers), and a DialogBlock that opens sprint metrics with a PieChart and summary table. Add follow-ups.",
+ },
+ {
+ displayText: "Recipe card",
+ prompt:
+ "Build a recipe card for Spicy Thai Basil Chicken with tags, Tabs (Ingredients table, Instructions accordion with 5 steps, Nutrition donut PieChart + table), a blockquote chef's tip, and buttons with a DialogBlock for the full recipe. Add follow-ups.",
+ },
+ {
+ displayText: "Chart showcase",
+ prompt:
+ "Build a 'Global Tech Industry Report 2025' with tags and Tabs containing six chart types: a grouped BarChart (quarterly revenue, 3 series), a LineChart (monthly trends, 2 series), an AreaChart (yearly adoption, 2 series), a donut PieChart (market share, 6 slices), a RadarChart (developer skills, 2 series), and a ScatterChart (funding vs revenue, 2 series with labeled points). Below add a summary table, a RadialChart for industry goals, and follow-ups.",
+ },
+ ]}
/>
</div>
);
diff --git a/examples/supabase-chat/src/app/page.tsx b/examples/supabase-chat/src/app/page.tsx
index fd8332329..d51769e64 100644
--- a/examples/supabase-chat/src/app/page.tsx
+++ b/examples/supabase-chat/src/app/page.tsx
@@ -1,11 +1,15 @@
"use client";
-
-import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";
-import { FullScreen } from "@openuidev/react-ui";
-import type { RealtimeChannel } from "@supabase/supabase-js";
-import { useEffect, useState } from "react";
import { createSupabaseBrowser } from "@/lib/supabase/browser";
+import {
+ AgentInterface,
+ openAIAdapter,
+ openAIMessageFormat,
+ restStorage,
+ type ChatLLM,
+} from "@openuidev/react-ui";
+import type { RealtimeChannel } from "@supabase/supabase-js";
+import { useEffect, useMemo, useState } from "react";
export default function Page() {
// Incrementing this key remounts ChatProvider, which re-runs fetchThreadList.
@@ -13,6 +17,31 @@ export default function Page() {
// another tab so the sidebar stays in sync without a full page reload.
const [threadListKey, setThreadListKey] = useState(0);
+ // Thread persistence stays server-backed (Supabase) via the same /api/threads
+ // REST contract the legacy `threadApiUrl` used — restStorage reproduces those
+ // conventions and keeps loadThread deserialization aligned with OpenAI format.
+ const storage = useMemo(
+ () => restStorage({ baseUrl: "/api/threads", messageFormat: openAIMessageFormat }),
+ [],
+ );
+ const llm = useMemo<ChatLLM>(
+ () => ({
+ send: ({ threadId, messages, signal }) =>
+ fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ // Convert from OpenUI's internal format to OpenAI chat format
+ messages: openAIMessageFormat.toApi(messages),
+ threadId,
+ }),
+ signal,
+ }),
+ streamProtocol: openAIAdapter(),
+ }),
+ [],
+ );
+
useEffect(() => {
const supabase = createSupabaseBrowser();
let channel: RealtimeChannel | undefined;
@@ -33,16 +62,12 @@ export default function Page() {
// including from another tab or device logged in with the same account.
channel = supabase
.channel("threads-realtime")
- .on(
- "postgres_changes",
- { event: "*", schema: "public", table: "threads" },
- () => {
- // Remount ChatProvider so the thread sidebar refreshes.
- // Note: remounting clears the current in-progress conversation.
- // For production, consider a more granular update strategy.
- setThreadListKey((k) => k + 1);
- },
- )
+ .on("postgres_changes", { event: "*", schema: "public", table: "threads" }, () => {
+ // Remount ChatProvider so the thread sidebar refreshes.
+ // Note: remounting clears the current in-progress conversation.
+ // For production, consider a more granular update strategy.
+ setThreadListKey((k) => k + 1);
+ })
.subscribe();
};
@@ -55,27 +80,7 @@ export default function Page() {
return (
<div className="h-screen w-screen overflow-hidden">
- <FullScreen
- key={threadListKey}
- processMessage={async ({ threadId, messages, abortController }) =>
- fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- // Convert from OpenUI's internal format to OpenAI chat format
- messages: openAIMessageFormat.toApi(messages),
- threadId,
- }),
- signal: abortController.signal,
- })
- }
- streamProtocol={openAIAdapter()}
- // Tell OpenUI that the thread API stores / returns messages in
- // OpenAI chat format so loadThread deserialization stays aligned.
- messageFormat={openAIMessageFormat}
- threadApiUrl="/api/threads"
- agentName="Supabase Chat"
- />
+ <AgentInterface key={threadListKey} storage={storage} llm={llm} agentName="Supabase Chat" />
</div>
);
}
diff --git a/examples/supabase-chat/tsconfig.json b/examples/supabase-chat/tsconfig.json
index 93e220ad6..1894d9ffc 100644
--- a/examples/supabase-chat/tsconfig.json
+++ b/examples/supabase-chat/tsconfig.json
@@ -1,7 +1,11 @@
{
"compilerOptions": {
"target": "ES2017",
- "lib": ["dom", "dom.iterable", "esnext"],
+ "lib": [
+ "dom",
+ "dom.iterable",
+ "esnext"
+ ],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
@@ -13,7 +17,26 @@
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
- "plugins": [{ "name": "next" }],
- "paths": { "@/*": ["./src/*"] }
- }
+ "plugins": [
+ {
+ "name": "next"
+ }
+ ],
+ "paths": {
+ "@/*": [
+ "./src/*"
+ ]
+ }
+ },
+ "include": [
+ "next-env.d.ts",
+ ".next/types/**/*.ts",
+ ".next/dev/types/**/*.ts",
+ "**/*.mts",
+ "**/*.ts",
+ "**/*.tsx"
+ ],
+ "exclude": [
+ "node_modules"
+ ]
}
diff --git a/packages/lang-core/package.json b/packages/lang-core/package.json
index 3e96ed168..c40b3f652 100644
--- a/packages/lang-core/package.json
+++ b/packages/lang-core/package.json
@@ -1,6 +1,6 @@
{
"name": "@openuidev/lang-core",
- "version": "0.2.6",
+ "version": "0.2.1",
"description": "Framework-agnostic core for OpenUI Lang: parser, prompt generation, validation, and type definitions",
"license": "MIT",
"type": "module",
diff --git a/packages/lang-core/src/parser/parser.ts b/packages/lang-core/src/parser/parser.ts
index 9be78733c..32b443aca 100644
--- a/packages/lang-core/src/parser/parser.ts
+++ b/packages/lang-core/src/parser/parser.ts
@@ -436,18 +436,23 @@ export interface StreamParser {
}
export function createStreamParser(cat: ParamMap, rootName?: string): StreamParser {
- let buf = "";
- let completedEnd = 0;
+ let buf = ""; // raw accumulated input (kept for set() diffing)
+ // Preprocessed view of `buf` (fences + comments stripped, same as parse()'s
+ // preprocess). The completed-statement scan runs over THIS, never the raw
+ // buffer — so leading markdown prose / ```fences``` (e.g. an apostrophe in
+ // "You're …" before the program) can't corrupt statement-boundary detection.
+ let cleaned = "";
+ let completedEnd = 0; // watermark: how far into `cleaned` is already completed
const completedStmtMap = new Map<string, Statement>();
let completedCount = 0;
let firstId = "";
function addStmt(text: string) {
- // Strip comments and skip fence markers
- const cleaned = stripComments(text).trim();
- if (!cleaned || /^```/.test(cleaned)) return;
- for (const s of split(tokenize(cleaned))) {
+ // `text` is sliced from `cleaned`, so it's already fence/comment-free.
+ const t = text.trim();
+ if (!t) return;
+ for (const s of split(tokenize(t))) {
const expr = parseExpression(s.tokens);
const stmt = classifyStatement(s, expr);
completedStmtMap.set(s.id, stmt);
@@ -456,6 +461,22 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
}
}
+ // Recompute `cleaned` from `buf`. If the already-completed prefix is no longer
+ // a prefix of the new cleaned text (e.g. an opening ```fence``` just appeared
+ // and shifted the stripped output), the watermark + cache are stale, so reset
+ // and re-scan. When the prefix is stable (the common streaming case) the cache
+ // is kept, so a partial trailing statement never blanks already-completed ones.
+ function refreshCleaned() {
+ const next = preprocess(buf);
+ if (!next.startsWith(cleaned.slice(0, completedEnd))) {
+ completedEnd = 0;
+ completedStmtMap.clear();
+ completedCount = 0;
+ firstId = "";
+ }
+ cleaned = next;
+ }
+
function scanNewCompleted(): number {
let depth = 0,
ternaryDepth = 0,
@@ -463,8 +484,8 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
esc = false;
let stmtStart = completedEnd;
- for (let i = completedEnd; i < buf.length; i++) {
- const c = buf[i];
+ for (let i = completedEnd; i < cleaned.length; i++) {
+ const c = cleaned[i];
if (esc) {
esc = false;
continue;
@@ -492,15 +513,21 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
// meaningful character is `?` or `:` — ternary continuation.
let peek = i + 1;
while (
- peek < buf.length &&
- (buf[peek] === " " || buf[peek] === "\t" || buf[peek] === "\r" || buf[peek] === "\n")
+ peek < cleaned.length &&
+ (cleaned[peek] === " " ||
+ cleaned[peek] === "\t" ||
+ cleaned[peek] === "\r" ||
+ cleaned[peek] === "\n")
)
peek++;
- if (peek < buf.length && (buf[peek] === "?" || (buf[peek] === ":" && ternaryDepth > 0))) {
+ if (
+ peek < cleaned.length &&
+ (cleaned[peek] === "?" || (cleaned[peek] === ":" && ternaryDepth > 0))
+ ) {
continue; // ternary continuation — don't split
}
// Depth-0 newline = end of a statement
- const t = buf.slice(stmtStart, i).trim();
+ const t = cleaned.slice(stmtStart, i).trim();
if (t) addStmt(t);
stmtStart = i + 1; // next statement begins after this newline
completedEnd = i + 1; // advance the "already processed" watermark
@@ -511,8 +538,9 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
}
function currentResult(): ParseResult {
+ refreshCleaned();
const pendingStart = scanNewCompleted();
- const pendingText = buf.slice(pendingStart).trim();
+ const pendingText = cleaned.slice(pendingStart).trim();
// No pending text — all statements are complete
if (!pendingText) {
@@ -528,22 +556,9 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
);
}
- // Apply same cleanup as parse() — strip fences, comments, whitespace
- const cleaned = stripComments(stripFences(pendingText)).trim();
- if (!cleaned) {
- if (completedCount === 0) return emptyResult();
- return buildResult(
- completedStmtMap,
- [...completedStmtMap.values()],
- firstId,
- false,
- completedCount,
- cat,
- rootName,
- );
- }
- // Autoclose the incomplete last statement so it's syntactically valid
- const { text: closed, wasIncomplete } = autoClose(cleaned);
+ // `cleaned` is already preprocessed (fences + comments stripped); just
+ // autoclose the incomplete trailing statement so it's syntactically valid.
+ const { text: closed, wasIncomplete } = autoClose(pendingText);
const stmts = split(tokenize(closed));
if (!stmts.length) {
@@ -587,6 +602,7 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
function reset() {
buf = "";
+ cleaned = "";
completedEnd = 0;
completedStmtMap.clear();
completedCount = 0;
diff --git a/packages/openui-cli/package.json b/packages/openui-cli/package.json
index eb35fd1a3..12be5876f 100644
--- a/packages/openui-cli/package.json
+++ b/packages/openui-cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@openuidev/cli",
- "version": "0.0.8",
+ "version": "0.0.9",
"description": "CLI for OpenUI — scaffold generative UI chat apps and generate LLM system prompts from component libraries",
"bin": {
"openui": "dist/index.js"
diff --git a/packages/openui-cli/src/templates/openui-chat/package.json b/packages/openui-cli/src/templates/openui-chat/package.json
index d043fd702..9cbc2a28c 100644
--- a/packages/openui-cli/src/templates/openui-chat/package.json
+++ b/packages/openui-cli/src/templates/openui-chat/package.json
@@ -1,6 +1,6 @@
{
"name": "openui-chat",
- "version": "0.1.0",
+ "version": "0.1.1",
"private": true,
"scripts": {
"dev": "next dev",
@@ -9,9 +9,9 @@
"lint": "eslint"
},
"dependencies": {
- "@openuidev/react-ui": "latest",
- "@openuidev/react-headless": "latest",
- "@openuidev/react-lang": "latest",
+ "@openuidev/react-ui": "0.11.9",
+ "@openuidev/react-headless": "0.8.2",
+ "@openuidev/react-lang": "0.2.6",
"next": "16.1.6",
"openai": "^6.22.0",
"react": "19.2.3",
diff --git a/packages/react-headless/package.json b/packages/react-headless/package.json
index bb5a39e9a..742f249a6 100644
--- a/packages/react-headless/package.json
+++ b/packages/react-headless/package.json
@@ -1,6 +1,6 @@
{
"name": "@openuidev/react-headless",
- "version": "0.8.2",
+ "version": "0.9.0",
"description": "Headless React primitives for AI chat — state management, streaming adapters for OpenAI and AG-UI, message format converters, and thread management for OpenUI generative UI apps",
"license": "MIT",
"type": "module",
@@ -77,6 +77,6 @@
"url": "https://github.com/thesysdev/openui/issues"
},
"dependencies": {
- "@ag-ui/core": "^0.0.45"
+ "@ag-ui/core": "^0.0.53"
}
}
diff --git a/packages/react-headless/src/adapters/__tests__/restStorage.test.ts b/packages/react-headless/src/adapters/__tests__/restStorage.test.ts
new file mode 100644
index 000000000..8ad6f081c
--- /dev/null
+++ b/packages/react-headless/src/adapters/__tests__/restStorage.test.ts
@@ -0,0 +1,105 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { Thread, UserMessage } from "../../store/types";
+import type { MessageFormat } from "../../types/messageFormat";
+import { restStorage } from "../restStorage";
+
+const json = (body: unknown, ok = true, status = 200) =>
+ new Response(JSON.stringify(body), { status, statusText: ok ? "OK" : "Error" });
+
+describe("restStorage", () => {
+ let fetchSpy: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ fetchSpy = vi.fn();
+ });
+
+ const make = (overrides?: { messageFormat?: MessageFormat; headers?: Record<string, string> }) =>
+ restStorage({
+ baseUrl: "/api/threads",
+ fetch: fetchSpy as unknown as typeof fetch,
+ ...overrides,
+ }).thread;
+
+ it("listThreads GETs {base}/get and returns the payload", async () => {
+ const payload = { threads: [{ id: "t1", title: "A", createdAt: 0 }], nextCursor: "c2" };
+ fetchSpy.mockResolvedValue(json(payload));
+
+ const result = await make().listThreads();
+
+ expect(fetchSpy).toHaveBeenCalledWith("/api/threads/get", expect.objectContaining({}));
+ expect(result).toEqual(payload);
+ });
+
+ it("listThreads passes cursor as query param", async () => {
+ fetchSpy.mockResolvedValue(json({ threads: [] }));
+ await make().listThreads("abc");
+ expect(fetchSpy.mock.calls[0][0]).toBe("/api/threads/get?cursor=abc");
+ });
+
+ it("createThread POSTs {base}/create with messageFormat.toApi applied", async () => {
+ const thread: Thread = { id: "t-new", title: "New", createdAt: 0 };
+ fetchSpy.mockResolvedValue(json(thread));
+ const toApi = vi.fn((msgs) => msgs.map((m: any) => ({ custom: m.id })));
+ const messageFormat: MessageFormat = { toApi, fromApi: (d) => d as any };
+
+ const result = await make({ messageFormat }).createThread({
+ id: "m1",
+ role: "user",
+ content: "hi",
+ } as UserMessage);
+
+ const [url, opts] = fetchSpy.mock.calls[0];
+ expect(url).toBe("/api/threads/create");
+ expect(opts.method).toBe("POST");
+ expect(opts.headers["Content-Type"]).toBe("application/json");
+ expect(toApi).toHaveBeenCalled();
+ expect(JSON.parse(opts.body)).toEqual({ messages: [{ custom: "m1" }] });
+ expect(result).toEqual(thread);
+ });
+
+ it("getMessages GETs {base}/get/:id and applies messageFormat.fromApi", async () => {
+ const raw = [{ r: "user", c: "hi" }];
+ const parsed = [{ id: "m1", role: "user", content: "hi" }];
+ fetchSpy.mockResolvedValue(json(raw));
+ const fromApi = vi.fn().mockReturnValue(parsed);
+
+ const result = await make({ messageFormat: { toApi: (m) => m, fromApi } }).getMessages("t1");
+
+ expect(fetchSpy.mock.calls[0][0]).toBe("/api/threads/get/t1");
+ expect(fromApi).toHaveBeenCalledWith(raw);
+ expect(result).toEqual(parsed);
+ });
+
+ it("updateThread PATCHes {base}/update/:id with the thread body", async () => {
+ const updated: Thread = { id: "t1", title: "Renamed", createdAt: 0 };
+ fetchSpy.mockResolvedValue(json(updated));
+
+ const result = await make().updateThread(updated);
+
+ const [url, opts] = fetchSpy.mock.calls[0];
+ expect(url).toBe("/api/threads/update/t1");
+ expect(opts.method).toBe("PATCH");
+ expect(JSON.parse(opts.body)).toEqual(updated);
+ expect(result).toEqual(updated);
+ });
+
+ it("deleteThread DELETEs {base}/delete/:id", async () => {
+ fetchSpy.mockResolvedValue(json({}, true));
+ await make().deleteThread("t1");
+ expect(fetchSpy).toHaveBeenCalledWith(
+ "/api/threads/delete/t1",
+ expect.objectContaining({ method: "DELETE" }),
+ );
+ });
+
+ it("merges custom headers into requests", async () => {
+ fetchSpy.mockResolvedValue(json({ threads: [] }));
+ await make({ headers: { Authorization: "Bearer x" } }).listThreads();
+ expect(fetchSpy.mock.calls[0][1].headers).toMatchObject({ Authorization: "Bearer x" });
+ });
+
+ it("throws a descriptive error when res.ok is false", async () => {
+ fetchSpy.mockResolvedValue(json({ error: "nope" }, false, 500));
+ await expect(make().listThreads()).rejects.toThrow(/GET \/api\/threads\/get failed: 500/);
+ });
+});
diff --git a/packages/react-headless/src/adapters/_defaultStorage.ts b/packages/react-headless/src/adapters/_defaultStorage.ts
new file mode 100644
index 000000000..85fec9617
--- /dev/null
+++ b/packages/react-headless/src/adapters/_defaultStorage.ts
@@ -0,0 +1,48 @@
+import type { Thread } from "../store/types";
+import type { Message, UserMessage } from "../types/message";
+import type { ChatStorage } from "./types";
+
+/**
+ * Internal default storage — in-memory, no persistence across reload.
+ * Used by `<ChatProvider>` when no `storage` prop is provided. Not exported
+ * from the package; callers who want explicit in-memory behavior should
+ * construct their own adapter object.
+ */
+export function createDefaultInMemoryStorage(): ChatStorage {
+ let threads: Thread[] = [];
+ const messagesByThread = new Map<string, Message[]>();
+
+ return {
+ thread: {
+ async listThreads() {
+ return { threads };
+ },
+ async createThread(firstMessage: UserMessage) {
+ const thread: Thread = {
+ id: crypto.randomUUID(),
+ title:
+ typeof firstMessage.content === "string"
+ ? firstMessage.content.slice(0, 40) || "New thread"
+ : "New thread",
+ createdAt: new Date().toISOString(),
+ };
+ threads = [thread, ...threads];
+ messagesByThread.set(thread.id, [
+ { ...firstMessage, id: firstMessage.id ?? crypto.randomUUID() },
+ ]);
+ return thread;
+ },
+ async getMessages(threadId: string) {
+ return messagesByThread.get(threadId) ?? [];
+ },
+ async updateThread(thread: Thread) {
+ threads = threads.map((t) => (t.id === thread.id ? thread : t));
+ return thread;
+ },
+ async deleteThread(id: string) {
+ threads = threads.filter((t) => t.id !== id);
+ messagesByThread.delete(id);
+ },
+ },
+ };
+}
diff --git a/packages/react-headless/src/adapters/fetchLLM.ts b/packages/react-headless/src/adapters/fetchLLM.ts
new file mode 100644
index 000000000..29929f172
--- /dev/null
+++ b/packages/react-headless/src/adapters/fetchLLM.ts
@@ -0,0 +1,56 @@
+import { identityMessageFormat, type MessageFormat } from "../types/messageFormat";
+import type { StreamProtocolAdapter } from "../types/stream";
+import type { ChatLLM } from "./types";
+
+export interface FetchLLMOptions {
+ /** Endpoint that accepts POST'd messages and returns a streaming Response. */
+ url: string;
+ /** Stream protocol adapter for parsing the response body (e.g., agUIAdapter, openAIAdapter). */
+ streamAdapter: StreamProtocolAdapter;
+ /** Wire-format conversion for outgoing messages. Defaults to identity (canonical Message). */
+ messageFormat?: MessageFormat;
+ /** Extra headers merged into the request. */
+ headers?: Record<string, string>;
+ /** Override fetch implementation (for tests, custom auth wrappers, etc.). */
+ fetch?: typeof fetch;
+}
+
+/**
+ * Generic HTTP-based LLM adapter. POSTs an AG-UI `RunAgentInput`-shaped body
+ * (`{ threadId, runId, messages, tools, context }`, messages in the chosen wire
+ * format) to `url` and returns the streaming `Response` for downstream processing.
+ *
+ * The fields the {@link ChatLLM} `send` contract doesn't carry are defaulted
+ * here so the body satisfies a spec-compliant AG-UI agent: a fresh `runId` is
+ * generated per send, and `tools`/`context` default to `[]` (override via options).
+ */
+export function fetchLLM({
+ url,
+ streamAdapter,
+ messageFormat = identityMessageFormat,
+ headers,
+ fetch: customFetch,
+}: FetchLLMOptions): ChatLLM {
+ const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);
+ return {
+ send: ({ threadId, messages, signal }) => {
+ const wire = messageFormat.toApi(messages);
+ return fetchImpl(url, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...headers,
+ },
+ body: JSON.stringify({
+ threadId,
+ runId: crypto.randomUUID(),
+ messages: wire,
+ tools: [],
+ context: [],
+ }),
+ signal,
+ });
+ },
+ streamProtocol: streamAdapter,
+ };
+}
diff --git a/packages/react-headless/src/adapters/index.ts b/packages/react-headless/src/adapters/index.ts
new file mode 100644
index 000000000..3e45d59be
--- /dev/null
+++ b/packages/react-headless/src/adapters/index.ts
@@ -0,0 +1,18 @@
+export type {
+ Artifact,
+ ArtifactCategory,
+ ArtifactListParams,
+ ArtifactStorage,
+ ArtifactSummary,
+ ChatLLM,
+ ChatStorage,
+ ThreadStorage,
+} from "./types";
+
+export { fetchLLM } from "./fetchLLM";
+export type { FetchLLMOptions } from "./fetchLLM";
+
+export { restStorage } from "./restStorage";
+export type { RestStorageOptions } from "./restStorage";
+
+// _defaultStorage is intentionally NOT exported — it's internal to ChatProvider.
diff --git a/packages/react-headless/src/adapters/restStorage.ts b/packages/react-headless/src/adapters/restStorage.ts
new file mode 100644
index 000000000..d4a2af9b7
--- /dev/null
+++ b/packages/react-headless/src/adapters/restStorage.ts
@@ -0,0 +1,89 @@
+import type { Thread, UserMessage } from "../store/types";
+import type { Message } from "../types/message";
+import { identityMessageFormat, type MessageFormat } from "../types/messageFormat";
+import type { ChatStorage } from "./types";
+
+export interface RestStorageOptions {
+ /**
+ * Base URL for thread endpoints (the old `threadApiUrl`). The factory hits
+ * the same conventions the legacy default used:
+ * - list: GET {baseUrl}/get (· ?cursor={cursor})
+ * - create: POST {baseUrl}/create
+ * - get: GET {baseUrl}/get/{threadId}
+ * - update: PATCH {baseUrl}/update/{threadId}
+ * - delete: DELETE {baseUrl}/delete/{threadId}
+ */
+ baseUrl: string;
+ /** Wire-format conversion. Defaults to identity (canonical Message). */
+ messageFormat?: MessageFormat;
+ /** Extra headers merged into every request. */
+ headers?: Record<string, string>;
+ /** Override fetch implementation (for tests, custom auth wrappers, etc.). */
+ fetch?: typeof fetch;
+}
+
+/**
+ * Generic REST-based thread storage. Reproduces the conventions the removed
+ * `threadApiUrl` prop used, so an existing backend keeps working by swapping
+ * `threadApiUrl="/x"` for `storage={restStorage({ baseUrl: "/x" })}`.
+ *
+ * Only the `thread` channel is implemented. Pair with an `llm` adapter
+ * (e.g. `fetchLLM`).
+ */
+export function restStorage({
+ baseUrl,
+ messageFormat = identityMessageFormat,
+ headers,
+ fetch: customFetch,
+}: RestStorageOptions): ChatStorage {
+ const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);
+
+ const request = async (url: string, init?: RequestInit): Promise<Response> => {
+ const res = await fetchImpl(url, {
+ ...init,
+ headers: {
+ ...(init?.body ? { "Content-Type": "application/json" } : {}),
+ ...headers,
+ ...init?.headers,
+ },
+ });
+ if (!res.ok) {
+ throw new Error(
+ `restStorage: ${init?.method ?? "GET"} ${url} failed: ${res.status} ${res.statusText}`,
+ );
+ }
+ return res;
+ };
+
+ return {
+ thread: {
+ async listThreads(cursor?: string) {
+ const url = cursor ? `${baseUrl}/get?cursor=${cursor}` : `${baseUrl}/get`;
+ const res = await request(url);
+ return res.json();
+ },
+ async createThread(firstMessage: UserMessage): Promise<Thread> {
+ const res = await request(`${baseUrl}/create`, {
+ method: "POST",
+ body: JSON.stringify({ messages: messageFormat.toApi([firstMessage]) }),
+ });
+ return res.json();
+ },
+ async getMessages(threadId: string): Promise<Message[]> {
+ const res = await request(`${baseUrl}/get/${threadId}`);
+ const raw: unknown = await res.json();
+ return messageFormat.fromApi(raw);
+ },
+ async updateThread(thread: Thread): Promise<Thread> {
+ const res = await request(`${baseUrl}/update/${thread.id}`, {
+ method: "PATCH",
+ body: JSON.stringify(thread),
+ });
+ return res.json();
+ },
+ async deleteThread(id: string): Promise<void> {
+ await request(`${baseUrl}/delete/${id}`, { method: "DELETE" });
+ },
+ },
+ };
+}
diff --git a/packages/react-headless/src/adapters/types.ts b/packages/react-headless/src/adapters/types.ts
new file mode 100644
index 000000000..6c8af8828
--- /dev/null
+++ b/packages/react-headless/src/adapters/types.ts
@@ -0,0 +1,86 @@
+import type { ReactNode } from "react";
+import type { Thread } from "../store/types";
+import type { Message, UserMessage } from "../types/message";
+import type { StreamProtocolAdapter } from "../types/stream";
+
+// ── Storage adapter interfaces ──
+
+export interface ThreadStorage {
+ listThreads(cursor?: string): Promise<{ threads: Thread[]; nextCursor?: string }>;
+ createThread(firstMessage: UserMessage): Promise<Thread>;
+ getMessages(threadId: string): Promise<Message[]>;
+ updateThread(thread: Thread): Promise<Thread>;
+ deleteThread(id: string): Promise<void>;
+}
+
+// ── Artifact storage (global, cross-thread) ──
+
+/** Listing-level artifact record. `content` is fetched separately via `get`. */
+export interface ArtifactSummary {
+ id: string;
+ title: string;
+ /** Artifact type, e.g. `'th_dashboard'`, `'th_presentation'`. Matched against renderer `type` and category filters. */
+ type: string;
+ /** Thread the artifact was created in. Drives the "go to original thread" action. */
+ threadId: string;
+ updatedAt?: string | number;
+}
+
+/** Full artifact. `content` must have the same shape as the tool-call `response` the renderer's parser expects. */
+export interface Artifact extends ArtifactSummary {
+ content: unknown;
+}
+
+export interface ArtifactListParams {
+ /** Partial-match search on `title`. Server-side. */
+ name?: string;
+ /** Filter by artifact types. Server-side. */
+ type?: string[];
+ cursor?: string;
+ limit?: number;
+}
+
+export interface ArtifactStorage {
+ list(params?: ArtifactListParams): Promise<{ artifacts: ArtifactSummary[]; nextCursor?: string }>;
+ get(id: string): Promise<Artifact>;
+ /** Persist edited artifact content. Called by renderer implementations (via `useArtifactStorage`), not by the framework. */
+ update(patch: { id: string; content: unknown }): Promise<ArtifactSummary>;
+}
+
+/**
+ * Global artifact category. Categories split the sidebar "Artifacts" nav and
+ * the per-thread Workspace sections, and pre-apply filters in the artifact browser.
+ */
+export interface ArtifactCategory {
+ /** Display label + key, e.g. `'Apps'`. */
+ name: string;
+ filter: {
+ /** Artifact types belonging to this category. */
+ type: string[];
+ };
+ /**
+ * Icon for this category's sidebar nav item. A platform-neutral node (a web
+ * element or a React Native element). When omitted, the nav falls back to the
+ * `<ArtifactNav icon>` prop, then a generic default.
+ */
+ icon?: ReactNode;
+}
+
+export interface ChatStorage {
+ thread: ThreadStorage;
+ /** Optional global artifact storage. Absent → the Artifacts nav and browser are unavailable. */
+ artifact?: ArtifactStorage;
+ // search, ... — added as features land
+}
+
+// ── LLM adapter interface ──
+
+export interface ChatLLM {
+ send(params: { threadId: string; messages: Message[]; signal: AbortSignal }): Promise<Response>;
+ streamProtocol: StreamProtocolAdapter;
+}
+
+// Re-exports kept here so adapter consumers can import everything in one shot.
+export type { Thread } from "../store/types";
+export type { Message, UserMessage } from "../types/message";
+export type { StreamProtocolAdapter } from "../types/stream";
diff --git a/packages/react-headless/src/hooks/useActiveArtifact.ts b/packages/react-headless/src/hooks/useActiveArtifact.ts
deleted file mode 100644
index b5d48b082..000000000
--- a/packages/react-headless/src/hooks/useActiveArtifact.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { useCallback } from "react";
-import { useStore } from "zustand";
-import { useArtifactStore } from "../store/ArtifactContext";
-
-/**
- * Return type for {@link useActiveArtifact}.
- *
- * @category Hooks
- */
-type UseActiveArtifactReturn = {
- /** Whether any artifact is currently active (panel is open). */
- isArtifactActive: boolean;
- /** The ID of the currently active artifact, or `null` if none. */
- activeArtifactId: string | null;
- /** Closes whichever artifact is currently active. No-op if none is active. */
- closeArtifact: () => void;
-};
-
-/**
- * Returns global artifact activation state — whether *any* artifact is open,
- * and a close action that dismisses it.
- *
- * Use this in layout components that react to artifact presence (resizing panels,
- * showing overlays) without needing to know *which* artifact is active.
- * For per-artifact state and actions, use {@link useArtifact} instead.
- *
- * Must be called within a `<ChatProvider>`.
- *
- * @category Hooks
- * @returns {@link UseActiveArtifactReturn}
- */
-export function useActiveArtifact(): UseActiveArtifactReturn {
- const store = useArtifactStore();
-
- const activeArtifactId = useStore(store, (s) => s.activeArtifactId);
- const isArtifactActive = activeArtifactId !== null;
-
- const closeArtifact = useCallback(() => {
- const state = store.getState();
- if (state.activeArtifactId) {
- state.closeArtifact(state.activeArtifactId);
- }
- }, [store]);
-
- return { isArtifactActive, activeArtifactId, closeArtifact };
-}
diff --git a/packages/react-headless/src/hooks/useActiveDetailedView.ts b/packages/react-headless/src/hooks/useActiveDetailedView.ts
new file mode 100644
index 000000000..34bc705b6
--- /dev/null
+++ b/packages/react-headless/src/hooks/useActiveDetailedView.ts
@@ -0,0 +1,45 @@
+import { useCallback } from "react";
+import { useStore } from "zustand";
+import { useDetailedViewStore } from "../store/DetailedViewContext";
+
+/**
+ * Return type for {@link useActiveDetailedView}.
+ *
+ * @category Hooks
+ */
+type UseActiveDetailedViewReturn = {
+ /** Whether any detailed view is currently active (panel is open). */
+ isDetailedViewActive: boolean;
+ /** The id of the currently active detailed view, or `null` if none. */
+ activeDetailedViewId: string | null;
+ /** Closes whichever detailed view is currently active. No-op if none is active. */
+ closeDetailedView: () => void;
+};
+
+/**
+ * Returns global detailed-view activation state — whether *any* view is open,
+ * and a close action that dismisses it.
+ *
+ * Use this in layout components that react to detailed-view presence (resizing
+ * panels, showing overlays) without needing to know *which* view is active.
+ * For per-view state and actions, use {@link useDetailedView} instead.
+ *
+ * Must be called within a `<ChatProvider>`.
+ *
+ * @category Hooks
+ * @returns {@link UseActiveDetailedViewReturn}
+ */
+export function useActiveDetailedView(): UseActiveDetailedViewReturn {
+ const store = useDetailedViewStore();
+
+ const activeDetailedViewId = useStore(store, (s) => s.activeDetailedViewId);
+ const isDetailedViewActive = activeDetailedViewId !== null;
+
+ const closeDetailedView = useCallback(() => {
+ if (store.getState().activeDetailedViewId !== null) {
+ store.getState().setActiveDetailedView(null);
+ }
+ }, [store]);
+
+ return { isDetailedViewActive, activeDetailedViewId, closeDetailedView };
+}
diff --git a/packages/react-headless/src/hooks/useArtifact.ts b/packages/react-headless/src/hooks/useArtifact.ts
deleted file mode 100644
index ff1775958..000000000
--- a/packages/react-headless/src/hooks/useArtifact.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { useCallback } from "react";
-import { useStore } from "zustand";
-import { useArtifactStore } from "../store/ArtifactContext";
-
-/**
- * Return type for {@link useArtifact}.
- *
- * @category Hooks
- */
-type UseArtifactReturn = {
- /** Whether this artifact is the currently active (visible) one. */
- isActive: boolean;
- /** Activates this artifact. */
- open: () => void;
- /** Deactivates this artifact. */
- close: () => void;
- /** Toggles this artifact: opens if closed, closes if open. */
- toggle: () => void;
-};
-
-/**
- * Binds a component to a specific artifact by ID, providing activation state
- * and actions (open, close, toggle).
- *
- * Multiple `useArtifact` hooks with different IDs can coexist —
- * only one artifact is active at a time.
- *
- * Must be called within a `<ChatProvider>`.
- *
- * @category Hooks
- * @param artifactId - Unique identifier for the artifact
- * @returns {@link UseArtifactReturn}
- *
- * @example
- * ```tsx
- * function PreviewButton({ id }: { id: string }) {
- * const { isActive, toggle } = useArtifact(id);
- * return (
- * <button onClick={() => toggle()}>
- * {isActive ? "Hide" : "Show"} Preview
- * </button>
- * );
- * }
- * ```
- */
-export function useArtifact(artifactId: string): UseArtifactReturn {
- const store = useArtifactStore();
-
- const isActive = useStore(store, (s) => s.activeArtifactId === artifactId);
-
- const open = useCallback(() => {
- store.getState().openArtifact(artifactId);
- }, [store, artifactId]);
-
- const close = useCallback(() => {
- store.getState().closeArtifact(artifactId);
- }, [store, artifactId]);
-
- const toggle = useCallback(() => {
- const state = store.getState();
- if (state.activeArtifactId === artifactId) {
- state.closeArtifact(artifactId);
- } else {
- state.openArtifact(artifactId);
- }
- }, [store, artifactId]);
-
- return { isActive, open, close, toggle };
-}
diff --git a/packages/react-headless/src/hooks/useArtifactList.ts b/packages/react-headless/src/hooks/useArtifactList.ts
new file mode 100644
index 000000000..9fd728ade
--- /dev/null
+++ b/packages/react-headless/src/hooks/useArtifactList.ts
@@ -0,0 +1,55 @@
+import { useMemo } from "react";
+import { useStore } from "zustand";
+import { useThreadContextStore } from "../store/ThreadContextContext";
+import type { ArtifactEntry } from "../store/threadContextTypes";
+
+export interface ArtifactListFilter {
+ /** Only entries whose `type` is in this list. Omit for all entries. */
+ type?: string[];
+}
+
+/**
+ * Returns artifacts registered in the active thread, grouped by `id` and
+ * sorted ascending by `version`. The latest version of each artifact is the
+ * last element.
+ *
+ * Pass a filter to restrict by artifact `type` — e.g. the types from an
+ * `ArtifactCategory` to build category-grouped workspace sections.
+ *
+ * Must be called within a `<ChatProvider>`.
+ *
+ * @category Hooks
+ * @returns Map of artifact id → ordered version list
+ *
+ * @example
+ * ```tsx
+ * function WorkspaceSection({ category }: { category: ArtifactCategory }) {
+ * const artifacts = useArtifactList({ type: category.filter.type });
+ * const latest = Object.values(artifacts).map((v) => v[v.length - 1]);
+ * return (
+ * <ul>
+ * {latest.map((a) => (
+ * <li key={a.id}>{a.heading}</li>
+ * ))}
+ * </ul>
+ * );
+ * }
+ * ```
+ */
+export function useArtifactList(filter?: ArtifactListFilter): Record<string, ArtifactEntry[]> {
+ const store = useThreadContextStore();
+ const artifacts = useStore(store, (s) => s.artifacts);
+ const typeKey = filter?.type?.join(" ");
+
+ return useMemo(() => {
+ if (typeKey === undefined) return artifacts;
+ const allowed = new Set(typeKey.split(" "));
+ const result: Record<string, ArtifactEntry[]> = {};
+ for (const [id, versions] of Object.entries(artifacts)) {
+ // All versions of an id share a type in practice; filter on the latest.
+ const latest = versions[versions.length - 1];
+ if (latest && allowed.has(latest.type)) result[id] = versions;
+ }
+ return result;
+ }, [artifacts, typeKey]);
+}
diff --git a/packages/react-headless/src/hooks/useArtifactRenderer.ts b/packages/react-headless/src/hooks/useArtifactRenderer.ts
new file mode 100644
index 000000000..f8cae4326
--- /dev/null
+++ b/packages/react-headless/src/hooks/useArtifactRenderer.ts
@@ -0,0 +1,23 @@
+import {
+ lookupArtifactRenderer,
+ useArtifactRendererRegistry,
+} from "../store/ArtifactRenderersContext";
+import type { ArtifactRendererConfig } from "../store/artifactRendererTypes";
+
+/**
+ * Resolves the artifact-renderer config matching a given `toolName`, or `null`
+ * if none match.
+ *
+ * Thin React wrapper over {@link lookupArtifactRenderer}: reads the registry
+ * from `<ChatProvider>` context and runs the lookup.
+ *
+ * Returns `null` if no `artifactRenderers` were supplied to the provider —
+ * callers should fall back to default rendering in that case.
+ *
+ * @category Hooks
+ */
+export function useArtifactRenderer(toolName: string): ArtifactRendererConfig<unknown> | null {
+ const registry = useArtifactRendererRegistry();
+ if (!registry) return null;
+ return lookupArtifactRenderer(registry, toolName);
+}
diff --git a/packages/react-headless/src/hooks/useDetailedView.ts b/packages/react-headless/src/hooks/useDetailedView.ts
new file mode 100644
index 000000000..20efd09ec
--- /dev/null
+++ b/packages/react-headless/src/hooks/useDetailedView.ts
@@ -0,0 +1,73 @@
+import { useCallback } from "react";
+import { useStore } from "zustand";
+import { useDetailedViewStore } from "../store/DetailedViewContext";
+
+/**
+ * Return type for {@link useDetailedView}.
+ *
+ * @category Hooks
+ */
+type UseDetailedViewReturn = {
+ /** Whether this view is the currently active (visible) one. */
+ isActive: boolean;
+ /** Activates this view as the side panel. */
+ open: () => void;
+ /** Closes this view if it is currently active. */
+ close: () => void;
+ /** Toggles this view: opens if closed, closes if open. */
+ toggle: () => void;
+};
+
+/**
+ * Binds a component to a specific detailed view by id, providing activation
+ * state and actions (open, close, toggle).
+ *
+ * Only one detailed view is active at a time across all kinds (apps, artifacts,
+ * and custom consumers). The `viewId` format is renderer-defined. The built-in
+ * App and Artifact renderers use `"${id}:${version}"`; custom consumers may
+ * pick any unique string.
+ *
+ * Must be called within a `<ChatProvider>`.
+ *
+ * @category Hooks
+ * @param viewId - Unique identifier for the detailed view
+ * @returns {@link UseDetailedViewReturn}
+ *
+ * @example
+ * ```tsx
+ * function PreviewButton({ viewId }: { viewId: string }) {
+ * const { isActive, toggle } = useDetailedView(viewId);
+ * return (
+ * <button onClick={toggle}>
+ * {isActive ? "Hide" : "Show"} Preview
+ * </button>
+ * );
+ * }
+ * ```
+ */
+export function useDetailedView(viewId: string): UseDetailedViewReturn {
+ const store = useDetailedViewStore();
+
+ const isActive = useStore(store, (s) => s.activeDetailedViewId === viewId);
+
+ const open = useCallback(() => {
+ store.getState().setActiveDetailedView(viewId);
+ }, [store, viewId]);
+
+ const close = useCallback(() => {
+ if (store.getState().activeDetailedViewId === viewId) {
+ store.getState().setActiveDetailedView(null);
+ }
+ }, [store, viewId]);
+
+ const toggle = useCallback(() => {
+ const state = store.getState();
+ if (state.activeDetailedViewId === viewId) {
+ state.setActiveDetailedView(null);
+ } else {
+ state.setActiveDetailedView(viewId);
+ }
+ }, [store, viewId]);
+
+ return { isActive, open, close, toggle };
+}
diff --git a/packages/react-headless/src/hooks/useArtifactPortalTarget.ts b/packages/react-headless/src/hooks/useDetailedViewPortalTarget.ts
similarity index 56%
rename from packages/react-headless/src/hooks/useArtifactPortalTarget.ts
rename to packages/react-headless/src/hooks/useDetailedViewPortalTarget.ts
index f7abfec65..be055cc6b 100644
--- a/packages/react-headless/src/hooks/useArtifactPortalTarget.ts
+++ b/packages/react-headless/src/hooks/useDetailedViewPortalTarget.ts
@@ -1,13 +1,13 @@
import { useCallback } from "react";
import { useStore } from "zustand";
-import { useArtifactStore } from "../store/ArtifactContext";
+import { useDetailedViewStore } from "../store/DetailedViewContext";
/**
- * Provides access to the artifact portal target DOM node.
+ * Provides access to the detailed-view portal target DOM node.
*
* This hook serves two roles:
* - **Registering a portal target:** Call `setNode` from a ref callback to
- * designate a DOM element as the render target for artifact content.
+ * designate a DOM element as the render target for detailed-view content.
* Only one target should be registered at a time.
* - **Reading the portal target:** Read `node` to get the current target
* element for use with `createPortal()`.
@@ -21,26 +21,26 @@ import { useArtifactStore } from "../store/ArtifactContext";
* ```tsx
* // Registering a portal target
* function MyPortalTarget() {
- * const { setNode } = useArtifactPortalTarget();
+ * const { setNode } = useDetailedViewPortalTarget();
* return <div ref={setNode} />;
* }
*
- * // Building a custom artifact panel
- * function MyArtifactPanel({ artifactId, children }) {
- * const { isActive } = useArtifact(artifactId);
- * const { node } = useArtifactPortalTarget();
+ * // Building a custom detailed-view panel
+ * function MyDetailedViewPanel({ viewId, children }) {
+ * const { isActive } = useDetailedView(viewId);
+ * const { node } = useDetailedViewPortalTarget();
* if (!isActive || !node) return null;
* return createPortal(<div>{children}</div>, node);
* }
* ```
*/
-export function useArtifactPortalTarget() {
- const store = useArtifactStore();
- const node = useStore(store, (s) => s._artifactPanelNode);
+export function useDetailedViewPortalTarget() {
+ const store = useDetailedViewStore();
+ const node = useStore(store, (s) => s._detailedViewPanelNode);
const setNode = useCallback(
(node: HTMLElement | null) => {
- store.getState()._setArtifactPanelNode(node);
+ store.getState()._setDetailedViewPanelNode(node);
},
[store],
);
diff --git a/packages/react-headless/src/hooks/useThread.ts b/packages/react-headless/src/hooks/useThread.ts
index 68dfc6b59..55c601250 100644
--- a/packages/react-headless/src/hooks/useThread.ts
+++ b/packages/react-headless/src/hooks/useThread.ts
@@ -17,6 +17,7 @@ const threadSelector = (s: ChatStore): ThreadSlice => ({
isRunning: s.isRunning,
isLoadingMessages: s.isLoadingMessages,
threadError: s.threadError,
+ executingToolCallIds: s.executingToolCallIds,
processMessage: s.processMessage,
appendMessages: s.appendMessages,
updateMessage: s.updateMessage,
diff --git a/packages/react-headless/src/hooks/useToolActivities.ts b/packages/react-headless/src/hooks/useToolActivities.ts
new file mode 100644
index 000000000..5260ba385
--- /dev/null
+++ b/packages/react-headless/src/hooks/useToolActivities.ts
@@ -0,0 +1,38 @@
+import { useMemo } from "react";
+import { pairToolActivity, type ToolActivity } from "../store/toolActivity";
+import type { AssistantMessage, Message, ToolMessage } from "../types";
+import { useThread } from "./useThread";
+
+/**
+ * Memoized view of an assistant message's tool calls paired with their results,
+ * as a typed {@link ToolActivity} array.
+ *
+ * Wraps {@link pairToolActivity}, re-pairing only when something that affects
+ * the result actually changes: an argument string grows, a tool result lands or
+ * changes length/error, or the store's executing set changes. Keying on both
+ * args length **and** result length matters — a result can arrive after args
+ * are already closed, and vice versa.
+ *
+ * @category Hooks
+ */
+export function useToolActivities(
+ message: AssistantMessage,
+ allMessages: Message[],
+): ToolActivity[] {
+ const executingIds = useThread((s) => s.executingToolCallIds);
+
+ const argsKey = (message.toolCalls ?? [])
+ .map((t) => `${t.id}:${t.function.arguments.length}`)
+ .join("|");
+
+ const resultKey = allMessages
+ .filter((m): m is ToolMessage => m.role === "tool")
+ .map((m) => `${m.toolCallId}:${m.content?.length ?? 0}:${m.error ? 1 : 0}`)
+ .join("|");
+
+ return useMemo(
+ () => pairToolActivity(message, allMessages, executingIds),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [message.id, argsKey, resultKey, executingIds],
+ );
+}
diff --git a/packages/react-headless/src/index.ts b/packages/react-headless/src/index.ts
index 868af6412..6bd05b30a 100644
--- a/packages/react-headless/src/index.ts
+++ b/packages/react-headless/src/index.ts
@@ -1,11 +1,28 @@
-export { useActiveArtifact } from "./hooks/useActiveArtifact";
-export { useArtifact } from "./hooks/useArtifact";
-export { useArtifactPortalTarget } from "./hooks/useArtifactPortalTarget";
+export { useActiveDetailedView } from "./hooks/useActiveDetailedView";
+export { useArtifactList } from "./hooks/useArtifactList";
+export type { ArtifactListFilter } from "./hooks/useArtifactList";
+export { useArtifactRenderer } from "./hooks/useArtifactRenderer";
+export { useDetailedView } from "./hooks/useDetailedView";
+export { useDetailedViewPortalTarget } from "./hooks/useDetailedViewPortalTarget";
export { MessageContext, MessageProvider, useMessage } from "./hooks/useMessage";
export { useThread, useThreadList } from "./hooks/useThread";
+export { useToolActivities } from "./hooks/useToolActivities";
-export { ArtifactContext, useArtifactStore } from "./store/ArtifactContext";
+export { defineArtifactCategories } from "./store/artifactCategories";
+export type { ArtifactCategoryGroup } from "./store/artifactCategories";
+export { useArtifactCategories } from "./store/ArtifactCategoriesContext";
+export {
+ ArtifactRenderersContext,
+ lookupArtifactRenderer,
+ lookupArtifactRendererByType,
+ useArtifactRendererRegistry,
+} from "./store/ArtifactRenderersContext";
+export { defineArtifactRenderer } from "./store/artifactRendererTypes";
+export { useArtifactStorage } from "./store/ArtifactStorageContext";
export { ChatProvider } from "./store/ChatProvider";
+export { DetailedViewContext, useDetailedViewStore } from "./store/DetailedViewContext";
+export { ThreadContextContext, useThreadContextStore } from "./store/ThreadContextContext";
+export { pairToolActivity, partialJSONParse } from "./store/toolActivity";
export {
agUIAdapter,
langGraphAdapter,
@@ -20,7 +37,37 @@ export {
} from "./stream/formats";
export { processStreamedMessage } from "./stream/processStreamedMessage";
-export type { ArtifactActions, ArtifactState } from "./store/artifactTypes";
+// ── Adapter interfaces + factories ──
+export { fetchLLM, restStorage } from "./adapters";
+export type {
+ Artifact,
+ ArtifactCategory,
+ ArtifactListParams,
+ ArtifactStorage,
+ ArtifactSummary,
+ ChatLLM,
+ ChatStorage,
+ FetchLLMOptions,
+ RestStorageOptions,
+ ThreadStorage,
+} from "./adapters";
+
+export type {
+ ArtifactRendererConfig,
+ ArtifactRendererControls,
+ ParsedArtifact,
+} from "./store/artifactRendererTypes";
+
+export type { ToolActivity, ToolCallStatus } from "./store/toolActivity";
+
+export type { DetailedViewActions, DetailedViewState } from "./store/detailedViewTypes";
+
+export type {
+ ArtifactEntry,
+ ThreadContextActions,
+ ThreadContextState,
+ ThreadContextStore,
+} from "./store/threadContextTypes";
export type {
ChatProviderProps,
diff --git a/packages/react-headless/src/store/ArtifactCategoriesContext.ts b/packages/react-headless/src/store/ArtifactCategoriesContext.ts
new file mode 100644
index 000000000..e820c5f1c
--- /dev/null
+++ b/packages/react-headless/src/store/ArtifactCategoriesContext.ts
@@ -0,0 +1,17 @@
+import { createContext, useContext } from "react";
+import type { ArtifactCategory } from "../adapters/types";
+
+/** @internal Provided by `ChatProvider` from the `artifactCategories` prop. */
+export const ArtifactCategoriesContext = createContext<ArtifactCategory[]>([]);
+
+/**
+ * Returns the global artifact categories configured on `<ChatProvider>`.
+ * Empty array when none were provided.
+ *
+ * Categories drive the sidebar Artifacts split, the artifact browser's
+ * pre-applied filters, and category-grouped workspace sections.
+ *
+ * @category Hooks
+ */
+export const useArtifactCategories = (): ArtifactCategory[] =>
+ useContext(ArtifactCategoriesContext);
diff --git a/packages/react-headless/src/store/ArtifactContext.ts b/packages/react-headless/src/store/ArtifactContext.ts
deleted file mode 100644
index 153a39334..000000000
--- a/packages/react-headless/src/store/ArtifactContext.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { createContext, useContext } from "react";
-import type { StoreApi } from "zustand";
-import type { ArtifactStore } from "./artifactTypes";
-
-/** @internal React context holding the artifact Zustand store. Provided by `ChatProvider`. */
-export const ArtifactContext = createContext<StoreApi<ArtifactStore> | null>(null);
-
-/**
- * Returns the raw artifact Zustand store for advanced use cases.
- *
- * Prefer {@link useArtifact} or {@link useActiveArtifact} for most cases —
- * this hook is an escape hatch when you need direct store access.
- *
- * @category Hooks
- * @returns The Zustand `StoreApi<ArtifactStore>` instance
- * @throws Error if called outside a `<ChatProvider>`
- */
-export const useArtifactStore = (): StoreApi<ArtifactStore> => {
- const store = useContext(ArtifactContext);
- if (!store) {
- throw new Error("useArtifactStore must be used within a <ChatProvider>");
- }
- return store;
-};
diff --git a/packages/react-headless/src/store/ArtifactRenderersContext.ts b/packages/react-headless/src/store/ArtifactRenderersContext.ts
new file mode 100644
index 000000000..44c93777d
--- /dev/null
+++ b/packages/react-headless/src/store/ArtifactRenderersContext.ts
@@ -0,0 +1,99 @@
+import { createContext, useContext } from "react";
+import type { ArtifactRendererConfig } from "./artifactRendererTypes";
+
+/**
+ * Pre-built lookup structure for artifact-renderer matching.
+ *
+ * Built once at `ChatProvider` mount from the user-supplied `artifactRenderers`
+ * array. Subsequent prop changes are ignored (with a dev-mode warning) so
+ * renderer registration stays stable for the lifetime of the provider.
+ *
+ * @internal
+ */
+export type ArtifactRendererRegistry = {
+ /** toolName → renderer. A renderer with several toolNames appears once per name. */
+ byToolName: Map<string, ArtifactRendererConfig<unknown>>;
+ /** artifact type → renderer. Used by the artifact browser to render stored artifacts. */
+ byType: Map<string, ArtifactRendererConfig<unknown>>;
+};
+
+const isDev = () => typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production";
+
+/**
+ * Builds an {@link ArtifactRendererRegistry} from a list of configs.
+ *
+ * First-wins on duplicate `toolName` or `type`: subsequent registrations are
+ * ignored with a dev-mode warning so the user can reorder their array
+ * (custom renderers should come *before* SDK defaults).
+ *
+ * @internal
+ */
+export function buildArtifactRendererRegistry(
+ configs: ReadonlyArray<ArtifactRendererConfig<any>>,
+): ArtifactRendererRegistry {
+ const byToolName = new Map<string, ArtifactRendererConfig<unknown>>();
+ const byType = new Map<string, ArtifactRendererConfig<unknown>>();
+
+ for (const config of configs) {
+ const toolNames = Array.isArray(config.toolName) ? config.toolName : [config.toolName];
+ for (const name of toolNames) {
+ if (byToolName.has(name)) {
+ if (isDev()) {
+ console.warn(
+ `[OpenUI] Artifact renderer for toolName "${name}" was ignored ` +
+ `(already registered earlier in the array).`,
+ );
+ }
+ continue;
+ }
+ byToolName.set(name, config);
+ }
+
+ if (byType.has(config.type)) {
+ if (isDev()) {
+ console.warn(
+ `[OpenUI] Artifact renderer for type "${config.type}" was ignored for type-based ` +
+ `lookup (already registered earlier in the array).`,
+ );
+ }
+ continue;
+ }
+ byType.set(config.type, config);
+ }
+
+ return { byToolName, byType };
+}
+
+/** Resolves the renderer matching a tool name, or `null`. @internal */
+export function lookupArtifactRenderer(
+ registry: ArtifactRendererRegistry,
+ toolName: string,
+): ArtifactRendererConfig<unknown> | null {
+ return registry.byToolName.get(toolName) ?? null;
+}
+
+/** Resolves the renderer matching an artifact type, or `null`. @internal */
+export function lookupArtifactRendererByType(
+ registry: ArtifactRendererRegistry,
+ type: string,
+): ArtifactRendererConfig<unknown> | null {
+ return registry.byType.get(type) ?? null;
+}
+
+/** @internal React context holding the renderer registry. Provided by `ChatProvider`. */
+export const ArtifactRenderersContext = createContext<ArtifactRendererRegistry | null>(null);
+
+/**
+ * Returns the raw artifact-renderer registry for advanced use cases.
+ *
+ * Prefer {@link useArtifactRenderer} for resolving a specific tool name —
+ * this hook is an escape hatch for custom dispatching.
+ *
+ * Returns `null` if no `artifactRenderers` were provided to the `<ChatProvider>` —
+ * this is not an error since renderers are optional.
+ *
+ * @category Hooks
+ */
+export const useArtifactRendererRegistry = (): ArtifactRendererRegistry | null => {
+ return useContext(ArtifactRenderersContext);
+};
diff --git a/packages/react-headless/src/store/ArtifactStorageContext.ts b/packages/react-headless/src/store/ArtifactStorageContext.ts
new file mode 100644
index 000000000..77c58e3ce
--- /dev/null
+++ b/packages/react-headless/src/store/ArtifactStorageContext.ts
@@ -0,0 +1,16 @@
+import { createContext, useContext } from "react";
+import type { ArtifactStorage } from "../adapters/types";
+
+/** @internal Provided by `ChatProvider` from `storage.artifact`. */
+export const ArtifactStorageContext = createContext<ArtifactStorage | null>(null);
+
+/**
+ * Returns the configured global {@link ArtifactStorage} channel, or `null`
+ * when the storage adapter doesn't provide one.
+ *
+ * Renderer implementations use this to lazily fetch (`get`) or persist
+ * (`update`) artifact content; the artifact browser uses it for `list`.
+ *
+ * @category Hooks
+ */
+export const useArtifactStorage = (): ArtifactStorage | null => useContext(ArtifactStorageContext);
diff --git a/packages/react-headless/src/store/ChatProvider.tsx b/packages/react-headless/src/store/ChatProvider.tsx
index 3ec368d64..76f708a26 100644
--- a/packages/react-headless/src/store/ChatProvider.tsx
+++ b/packages/react-headless/src/store/ChatProvider.tsx
@@ -1,27 +1,82 @@
-import { useEffect, useState, type FC } from "react";
-import { ArtifactContext } from "./ArtifactContext";
+import { useEffect, useRef, useState, type FC } from "react";
+import { createDefaultInMemoryStorage } from "../adapters/_defaultStorage";
+import { ArtifactCategoriesContext } from "./ArtifactCategoriesContext";
+import {
+ ArtifactRenderersContext,
+ buildArtifactRendererRegistry,
+} from "./ArtifactRenderersContext";
+import { ArtifactStorageContext } from "./ArtifactStorageContext";
import { ChatContext } from "./ChatContext";
-import { createArtifactStore } from "./createArtifactStore";
import { createChatStore } from "./createChatStore";
+import { createDetailedViewStore } from "./createDetailedViewStore";
+import { createThreadContextStore } from "./createThreadContextStore";
+import { DetailedViewContext } from "./DetailedViewContext";
+import { ThreadContextContext } from "./ThreadContextContext";
import type { ChatProviderProps } from "./types";
-export const ChatProvider: FC<ChatProviderProps> = ({ children, ...config }) => {
- const [chatStore] = useState(() => createChatStore(config));
- const [artifactStore] = useState(() => createArtifactStore());
+const EMPTY_CATEGORIES: never[] = [];
- // Cross-store subscription: reset artifacts when the active thread changes.
+export const ChatProvider: FC<ChatProviderProps> = ({
+ children,
+ storage,
+ llm,
+ artifactRenderers,
+ artifactCategories,
+}) => {
+ const [resolvedStorage] = useState(() => storage ?? createDefaultInMemoryStorage());
+ const [chatStore] = useState(() => createChatStore({ storage: resolvedStorage, llm }));
+ const [detailedViewStore] = useState(() => createDetailedViewStore());
+ const [threadContextStore] = useState(() => createThreadContextStore());
+ const [artifactRendererRegistry] = useState(() =>
+ buildArtifactRendererRegistry(artifactRenderers ?? []),
+ );
+
+ // Dev-mode warning if artifactRenderers reference changes after mount —
+ // captured registry is mount-only, so changes are silently ignored otherwise.
+ const initialRenderersRef = useRef(artifactRenderers);
+ const hasWarnedRef = useRef(false);
+ useEffect(() => {
+ if (
+ typeof process !== "undefined" &&
+ process.env?.["NODE_ENV"] !== "production" &&
+ !hasWarnedRef.current &&
+ initialRenderersRef.current !== artifactRenderers
+ ) {
+ console.warn(
+ "[OpenUI] `artifactRenderers` prop changed after ChatProvider mount. " +
+ "The original array is kept; new renderers will not be registered. " +
+ "Memoize the array (useMemo) to avoid this warning.",
+ );
+ hasWarnedRef.current = true;
+ }
+ }, [artifactRenderers]);
+
+ // Cross-store subscription: reset detailed-view + thread-context state when the active thread changes.
// useEffect (not inline) so the cleanup function unsubscribes on unmount.
useEffect(() => {
const unsubscribe = chatStore.subscribe(
(state) => state.selectedThreadId,
- () => artifactStore.getState().resetArtifacts(),
+ () => {
+ detailedViewStore.getState().reset();
+ threadContextStore.getState().reset();
+ },
);
return unsubscribe;
- }, [chatStore, artifactStore]);
+ }, [chatStore, detailedViewStore, threadContextStore]);
return (
<ChatContext.Provider value={chatStore}>
- <ArtifactContext.Provider value={artifactStore}>{children}</ArtifactContext.Provider>
+ <DetailedViewContext.Provider value={detailedViewStore}>
+ <ThreadContextContext.Provider value={threadContextStore}>
+ <ArtifactRenderersContext.Provider value={artifactRendererRegistry}>
+ <ArtifactStorageContext.Provider value={resolvedStorage.artifact ?? null}>
+ <ArtifactCategoriesContext.Provider value={artifactCategories ?? EMPTY_CATEGORIES}>
+ {children}
+ </ArtifactCategoriesContext.Provider>
+ </ArtifactStorageContext.Provider>
+ </ArtifactRenderersContext.Provider>
+ </ThreadContextContext.Provider>
+ </DetailedViewContext.Provider>
</ChatContext.Provider>
);
};
diff --git a/packages/react-headless/src/store/DetailedViewContext.ts b/packages/react-headless/src/store/DetailedViewContext.ts
new file mode 100644
index 000000000..553e53863
--- /dev/null
+++ b/packages/react-headless/src/store/DetailedViewContext.ts
@@ -0,0 +1,24 @@
+import { createContext, useContext } from "react";
+import type { StoreApi } from "zustand";
+import type { DetailedViewStore } from "./detailedViewTypes";
+
+/** @internal React context holding the detailed-view Zustand store. Provided by `ChatProvider`. */
+export const DetailedViewContext = createContext<StoreApi<DetailedViewStore> | null>(null);
+
+/**
+ * Returns the raw detailed-view Zustand store for advanced use cases.
+ *
+ * Prefer {@link useDetailedView} or {@link useActiveDetailedView} for most cases —
+ * this hook is an escape hatch when you need direct store access.
+ *
+ * @category Hooks
+ * @returns The Zustand `StoreApi<DetailedViewStore>` instance
+ * @throws Error if called outside a `<ChatProvider>`
+ */
+export const useDetailedViewStore = (): StoreApi<DetailedViewStore> => {
+ const store = useContext(DetailedViewContext);
+ if (!store) {
+ throw new Error("useDetailedViewStore must be used within a <ChatProvider>");
+ }
+ return store;
+};
diff --git a/packages/react-headless/src/store/ThreadContextContext.ts b/packages/react-headless/src/store/ThreadContextContext.ts
new file mode 100644
index 000000000..cd0718c18
--- /dev/null
+++ b/packages/react-headless/src/store/ThreadContextContext.ts
@@ -0,0 +1,25 @@
+import { createContext, useContext } from "react";
+import type { StoreApi } from "zustand";
+import type { ThreadContextStore } from "./threadContextTypes";
+
+/** @internal React context holding the ThreadContext Zustand store. Provided by `ChatProvider`. */
+export const ThreadContextContext = createContext<StoreApi<ThreadContextStore> | null>(null);
+
+/**
+ * Returns the raw ThreadContext Zustand store for advanced use cases.
+ *
+ * Prefer {@link useDetailedView}, {@link useActiveDetailedView}, {@link useAppList},
+ * or {@link useArtifactList} for most cases — this hook is an escape hatch when you
+ * need direct store access.
+ *
+ * @category Hooks
+ * @returns The Zustand `StoreApi<ThreadContextStore>` instance
+ * @throws Error if called outside a `<ChatProvider>`
+ */
+export const useThreadContextStore = (): StoreApi<ThreadContextStore> => {
+ const store = useContext(ThreadContextContext);
+ if (!store) {
+ throw new Error("useThreadContextStore must be used within a <ChatProvider>");
+ }
+ return store;
+};
diff --git a/packages/react-headless/src/store/__tests__/__helpers/makeStore.ts b/packages/react-headless/src/store/__tests__/__helpers/makeStore.ts
new file mode 100644
index 000000000..4f08e1e86
--- /dev/null
+++ b/packages/react-headless/src/store/__tests__/__helpers/makeStore.ts
@@ -0,0 +1,39 @@
+import { vi } from "vitest";
+import type { ChatLLM, ChatStorage, ThreadStorage } from "../../../adapters/types";
+import { createChatStore } from "../../createChatStore";
+
+export interface MakeStoreOverrides extends Partial<ThreadStorage> {
+ send?: ChatLLM["send"];
+ streamProtocol?: ChatLLM["streamProtocol"];
+}
+
+/**
+ * Build a chat store with mocked storage + LLM adapters. Per-field overrides
+ * for any storage method or `llm.send`/`llm.streamProtocol`. Anything not
+ * overridden gets a vi.fn() mock with a sensible default return.
+ */
+export function makeStore(overrides: MakeStoreOverrides = {}) {
+ const { send, streamProtocol, ...threadOverrides } = overrides;
+
+ const storage: ChatStorage = {
+ thread: {
+ listThreads: vi.fn().mockResolvedValue({ threads: [] }),
+ createThread: vi.fn().mockResolvedValue({
+ id: "new",
+ title: "New",
+ createdAt: new Date().toISOString(),
+ }),
+ getMessages: vi.fn().mockResolvedValue([]),
+ updateThread: vi.fn(async (t) => t),
+ deleteThread: vi.fn().mockResolvedValue(undefined),
+ ...threadOverrides,
+ },
+ };
+
+ const llm: ChatLLM = {
+ send: send ?? vi.fn().mockResolvedValue(new Response("", { status: 200 })),
+ streamProtocol: streamProtocol ?? { parse: async function* () {} },
+ };
+
+ return createChatStore({ storage, llm });
+}
diff --git a/packages/react-headless/src/store/__tests__/artifactRendererRegistry.test.ts b/packages/react-headless/src/store/__tests__/artifactRendererRegistry.test.ts
new file mode 100644
index 000000000..1b9c1a541
--- /dev/null
+++ b/packages/react-headless/src/store/__tests__/artifactRendererRegistry.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ buildArtifactRendererRegistry,
+ lookupArtifactRenderer,
+ lookupArtifactRendererByType,
+} from "../ArtifactRenderersContext";
+import { defineArtifactRenderer } from "../artifactRendererTypes";
+
+const makeRenderer = (type: string, toolName: string | string[]) =>
+ defineArtifactRenderer({
+ type,
+ toolName,
+ parser: () => ({ props: {}, meta: null }),
+ preview: () => null,
+ actual: () => null,
+ });
+
+describe("buildArtifactRendererRegistry", () => {
+ it("indexes a single toolName", () => {
+ const r = makeRenderer("th_presentation", "presentation:create");
+ const registry = buildArtifactRendererRegistry([r]);
+ expect(registry.byToolName.get("presentation:create")).toBe(r);
+ });
+
+ it("indexes every name of a toolName array under the same renderer", () => {
+ const r = makeRenderer("th_presentation", ["presentation:create", "presentation:edit"]);
+ const registry = buildArtifactRendererRegistry([r]);
+ expect(registry.byToolName.get("presentation:create")).toBe(r);
+ expect(registry.byToolName.get("presentation:edit")).toBe(r);
+ });
+
+ it("indexes by type", () => {
+ const r = makeRenderer("th_dashboard", "dashboard:create");
+ const registry = buildArtifactRendererRegistry([r]);
+ expect(registry.byType.get("th_dashboard")).toBe(r);
+ });
+
+ it("first-wins on duplicate toolName with dev warning", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const first = makeRenderer("a", "tool:x");
+ const second = makeRenderer("b", "tool:x");
+ const registry = buildArtifactRendererRegistry([first, second]);
+ expect(registry.byToolName.get("tool:x")).toBe(first);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('toolName "tool:x"'));
+ warn.mockRestore();
+ });
+
+ it("first-wins on duplicate type with dev warning", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const first = makeRenderer("th_report", "report:create");
+ const second = makeRenderer("th_report", "report:edit");
+ const registry = buildArtifactRendererRegistry([first, second]);
+ expect(registry.byType.get("th_report")).toBe(first);
+ // second's toolName still registers (different name), only type lookup is deduped
+ expect(registry.byToolName.get("report:edit")).toBe(second);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('type "th_report"'));
+ warn.mockRestore();
+ });
+});
+
+describe("lookupArtifactRenderer", () => {
+ it("resolves by toolName and returns null on miss", () => {
+ const r = makeRenderer("th_presentation", ["p:create", "p:edit"]);
+ const registry = buildArtifactRendererRegistry([r]);
+ expect(lookupArtifactRenderer(registry, "p:edit")).toBe(r);
+ expect(lookupArtifactRenderer(registry, "unknown")).toBeNull();
+ });
+});
+
+describe("lookupArtifactRendererByType", () => {
+ it("resolves by type and returns null on miss", () => {
+ const r = makeRenderer("th_dashboard", "d:create");
+ const registry = buildArtifactRendererRegistry([r]);
+ expect(lookupArtifactRendererByType(registry, "th_dashboard")).toBe(r);
+ expect(lookupArtifactRendererByType(registry, "th_other")).toBeNull();
+ });
+});
diff --git a/packages/react-headless/src/store/__tests__/artifactThreadSwitch.test.ts b/packages/react-headless/src/store/__tests__/artifactThreadSwitch.test.ts
deleted file mode 100644
index 56ebf2487..000000000
--- a/packages/react-headless/src/store/__tests__/artifactThreadSwitch.test.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-import { createArtifactStore } from "../createArtifactStore";
-import { createChatStore } from "../createChatStore";
-
-const flushPromises = () => new Promise((r) => setTimeout(r, 0));
-
-describe("artifact thread-switch cleanup", () => {
- const setupStores = () => {
- const chatStore = createChatStore({ processMessage: vi.fn() });
- const artifactStore = createArtifactStore();
-
- const unsubscribe = chatStore.subscribe(
- (state) => state.selectedThreadId,
- () => artifactStore.getState().resetArtifacts(),
- );
-
- return { chatStore, artifactStore, unsubscribe };
- };
-
- it("clears active artifact when selectThread is called", async () => {
- const { chatStore, artifactStore, unsubscribe } = setupStores();
-
- artifactStore.getState().openArtifact("art-1");
- expect(artifactStore.getState().activeArtifactId).toBe("art-1");
-
- chatStore.getState().selectThread("thread-2");
- await flushPromises();
-
- expect(artifactStore.getState().activeArtifactId).toBeNull();
-
- unsubscribe();
- });
-
- it("clears active artifact when switchToNewThread is called", async () => {
- const { chatStore, artifactStore, unsubscribe } = setupStores();
-
- chatStore.setState({ selectedThreadId: "thread-1" });
- artifactStore.getState().openArtifact("art-1");
-
- chatStore.getState().switchToNewThread();
- await flushPromises();
-
- expect(artifactStore.getState().activeArtifactId).toBeNull();
-
- unsubscribe();
- });
-
- it("clears active artifact when active thread is deleted", async () => {
- const deleteThread = vi.fn().mockResolvedValue(undefined);
- const chatStore = createChatStore({ deleteThread, processMessage: vi.fn() });
- const artifactStore = createArtifactStore();
-
- const unsubscribe = chatStore.subscribe(
- (state) => state.selectedThreadId,
- () => artifactStore.getState().resetArtifacts(),
- );
-
- chatStore.setState({
- selectedThreadId: "thread-1",
- threads: [
- {
- id: "thread-1",
- title: "Test",
- createdAt: new Date().toISOString(),
- },
- ],
- });
-
- artifactStore.getState().openArtifact("art-1");
-
- chatStore.getState().deleteThread("thread-1");
- await flushPromises();
-
- expect(artifactStore.getState().activeArtifactId).toBeNull();
-
- unsubscribe();
- });
-
- it("does not clear active artifact when re-selecting the same thread", async () => {
- const { chatStore, artifactStore, unsubscribe } = setupStores();
-
- chatStore.setState({ selectedThreadId: "thread-1" });
- await flushPromises();
-
- artifactStore.getState().openArtifact("art-1");
- expect(artifactStore.getState().activeArtifactId).toBe("art-1");
-
- chatStore.getState().selectThread("thread-1");
- await flushPromises();
-
- expect(artifactStore.getState().activeArtifactId).toBe("art-1");
-
- unsubscribe();
- });
-
- it("handles rapid thread switches cleanly", async () => {
- const loadThread = vi.fn().mockResolvedValue([]);
- const chatStore = createChatStore({ loadThread, processMessage: vi.fn() });
- const artifactStore = createArtifactStore();
-
- const unsubscribe = chatStore.subscribe(
- (state) => state.selectedThreadId,
- () => artifactStore.getState().resetArtifacts(),
- );
-
- artifactStore.getState().openArtifact("art-1");
-
- chatStore.getState().selectThread("thread-1");
- chatStore.getState().selectThread("thread-2");
- chatStore.getState().selectThread("thread-3");
- await flushPromises();
-
- expect(artifactStore.getState().activeArtifactId).toBeNull();
- expect(chatStore.getState().selectedThreadId).toBe("thread-3");
-
- unsubscribe();
- });
-});
diff --git a/packages/react-headless/src/store/__tests__/createArtifactStore.test.ts b/packages/react-headless/src/store/__tests__/createArtifactStore.test.ts
deleted file mode 100644
index 40bf14379..000000000
--- a/packages/react-headless/src/store/__tests__/createArtifactStore.test.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { createArtifactStore } from "../createArtifactStore";
-
-describe("createArtifactStore", () => {
- it("has correct initial state", () => {
- const store = createArtifactStore();
- const state = store.getState();
-
- expect(state.activeArtifactId).toBeNull();
- expect(state._artifactPanelNode).toBeNull();
- });
-
- describe("openArtifact", () => {
- it("sets activeArtifactId", () => {
- const store = createArtifactStore();
-
- store.getState().openArtifact("art-1");
-
- expect(store.getState().activeArtifactId).toBe("art-1");
- });
-
- it("replaces active artifact when opening a different one", () => {
- const store = createArtifactStore();
-
- store.getState().openArtifact("art-1");
- store.getState().openArtifact("art-2");
-
- expect(store.getState().activeArtifactId).toBe("art-2");
- });
-
- it("is idempotent when opening the same artifact", () => {
- const store = createArtifactStore();
-
- store.getState().openArtifact("art-1");
- store.getState().openArtifact("art-1");
-
- expect(store.getState().activeArtifactId).toBe("art-1");
- });
- });
-
- describe("closeArtifact", () => {
- it("clears activeArtifactId when closing the active artifact", () => {
- const store = createArtifactStore();
-
- store.getState().openArtifact("art-1");
- expect(store.getState().activeArtifactId).toBe("art-1");
-
- store.getState().closeArtifact("art-1");
- expect(store.getState().activeArtifactId).toBeNull();
- });
-
- it("no-ops when closing a non-active artifact", () => {
- const store = createArtifactStore();
-
- store.getState().openArtifact("art-1");
- store.getState().closeArtifact("art-2");
-
- expect(store.getState().activeArtifactId).toBe("art-1");
- });
-
- it("no-ops when nothing is active", () => {
- const store = createArtifactStore();
-
- store.getState().closeArtifact("art-1");
-
- expect(store.getState().activeArtifactId).toBeNull();
- });
- });
-
- describe("resetArtifacts", () => {
- it("resets activeArtifactId to null", () => {
- const store = createArtifactStore();
-
- store.getState().openArtifact("art-1");
- expect(store.getState().activeArtifactId).toBe("art-1");
-
- store.getState().resetArtifacts();
- expect(store.getState().activeArtifactId).toBeNull();
- });
- });
-
- describe("_setArtifactPanelNode", () => {
- it("sets and clears DOM reference", () => {
- const store = createArtifactStore();
-
- const node = {} as HTMLElement;
- store.getState()._setArtifactPanelNode(node);
- expect(store.getState()._artifactPanelNode).toBe(node);
-
- store.getState()._setArtifactPanelNode(null);
- expect(store.getState()._artifactPanelNode).toBeNull();
- });
- });
-});
diff --git a/packages/react-headless/src/store/__tests__/createChatStore.test.ts b/packages/react-headless/src/store/__tests__/createChatStore.test.ts
index c50d0dd1c..1d28dfbab 100644
--- a/packages/react-headless/src/store/__tests__/createChatStore.test.ts
+++ b/packages/react-headless/src/store/__tests__/createChatStore.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { createChatStore } from "../createChatStore";
import type { Message, Thread, UserMessage } from "../types";
+import { makeStore } from "./__helpers/makeStore";
// ── Helpers ──
@@ -25,9 +25,9 @@ describe("createChatStore", () => {
describe("loadThreads", () => {
it("fetches threads and sets state", async () => {
const threads = [makeThread("t1"), makeThread("t2", 1)];
- const fetchThreadList = vi.fn().mockResolvedValue({ threads });
+ const listThreads = vi.fn().mockResolvedValue({ threads });
- const store = createChatStore({ fetchThreadList, processMessage: vi.fn() });
+ const store = makeStore({ listThreads });
expect(store.getState().isLoadingThreads).toBe(false);
store.getState().loadThreads();
@@ -38,14 +38,14 @@ describe("createChatStore", () => {
expect(store.getState().isLoadingThreads).toBe(false);
expect(store.getState().threads).toHaveLength(2);
expect(store.getState().hasMoreThreads).toBe(false);
- expect(fetchThreadList).toHaveBeenCalledWith(undefined);
+ expect(listThreads).toHaveBeenCalledWith(undefined);
});
it("sets threadListError on failure", async () => {
const error = new Error("network");
- const fetchThreadList = vi.fn().mockRejectedValue(error);
+ const listThreads = vi.fn().mockRejectedValue(error);
- const store = createChatStore({ fetchThreadList, processMessage: vi.fn() });
+ const store = makeStore({ listThreads });
store.getState().loadThreads();
await flushPromises();
@@ -54,17 +54,17 @@ describe("createChatStore", () => {
});
it("handles pagination cursor", async () => {
- const fetchThreadList = vi.fn().mockResolvedValue({
+ const listThreads = vi.fn().mockResolvedValue({
threads: [makeThread("t1")],
nextCursor: "page2",
});
- const store = createChatStore({ fetchThreadList, processMessage: vi.fn() });
+ const store = makeStore({ listThreads });
store.getState().loadThreads();
await flushPromises();
expect(store.getState().hasMoreThreads).toBe(true);
- expect(fetchThreadList).toHaveBeenCalledWith(undefined);
+ expect(listThreads).toHaveBeenCalledWith(undefined);
});
});
@@ -72,12 +72,12 @@ describe("createChatStore", () => {
it("appends threads using cursor", async () => {
const page1 = [makeThread("t1")];
const page2 = [makeThread("t2", 1)];
- const fetchThreadList = vi
+ const listThreads = vi
.fn()
.mockResolvedValueOnce({ threads: page1, nextCursor: "c2" })
.mockResolvedValueOnce({ threads: page2 });
- const store = createChatStore({ fetchThreadList, processMessage: vi.fn() });
+ const store = makeStore({ listThreads });
store.getState().loadThreads();
await flushPromises();
@@ -88,29 +88,29 @@ describe("createChatStore", () => {
expect(store.getState().threads).toHaveLength(2);
expect(store.getState().hasMoreThreads).toBe(false);
- expect(fetchThreadList).toHaveBeenCalledWith("c2");
+ expect(listThreads).toHaveBeenCalledWith("c2");
});
it("no-ops when no more pages", async () => {
- const fetchThreadList = vi.fn().mockResolvedValue({ threads: [makeThread("t1")] });
+ const listThreads = vi.fn().mockResolvedValue({ threads: [makeThread("t1")] });
- const store = createChatStore({ fetchThreadList, processMessage: vi.fn() });
+ const store = makeStore({ listThreads });
store.getState().loadThreads();
await flushPromises();
store.getState().loadMoreThreads();
await flushPromises();
- expect(fetchThreadList).toHaveBeenCalledTimes(1);
+ expect(listThreads).toHaveBeenCalledTimes(1);
});
});
describe("selectThread", () => {
it("sets selectedThreadId, loads messages, clears previous", async () => {
const messages: Message[] = [makeMessage("m1"), makeMessage("m2", "assistant")];
- const loadThread = vi.fn().mockResolvedValue(messages);
+ const getMessages = vi.fn().mockResolvedValue(messages);
- const store = createChatStore({ loadThread, processMessage: vi.fn() });
+ const store = makeStore({ getMessages });
store.setState({ messages: [makeMessage("old")] });
@@ -124,14 +124,14 @@ describe("createChatStore", () => {
expect(store.getState().messages).toEqual(messages);
expect(store.getState().isLoadingMessages).toBe(false);
- expect(loadThread).toHaveBeenCalledWith("t1");
+ expect(getMessages).toHaveBeenCalledWith("t1");
});
it("sets threadError on load failure", async () => {
const error = new Error("load failed");
- const loadThread = vi.fn().mockRejectedValue(error);
+ const getMessages = vi.fn().mockRejectedValue(error);
- const store = createChatStore({ loadThread, processMessage: vi.fn() });
+ const store = makeStore({ getMessages });
store.getState().selectThread("t1");
await flushPromises();
@@ -142,7 +142,7 @@ describe("createChatStore", () => {
describe("switchToNewThread", () => {
it("clears selection, messages, and errors", () => {
- const store = createChatStore({ processMessage: vi.fn() });
+ const store = makeStore();
store.setState({
selectedThreadId: "t1",
@@ -163,7 +163,7 @@ describe("createChatStore", () => {
const newThread = makeThread("t-new");
const createThread = vi.fn().mockResolvedValue(newThread);
- const store = createChatStore({ createThread, processMessage: vi.fn() });
+ const store = makeStore({ createThread });
store.setState({ threads: [makeThread("t-existing")] });
const result = await store.getState().createThread({
@@ -181,7 +181,7 @@ describe("createChatStore", () => {
describe("deleteThread", () => {
it("removes thread from list", async () => {
const deleteThread = vi.fn().mockResolvedValue(undefined);
- const store = createChatStore({ deleteThread, processMessage: vi.fn() });
+ const store = makeStore({ deleteThread });
store.setState({ threads: [makeThread("t1"), makeThread("t2", 1)] });
@@ -194,7 +194,7 @@ describe("createChatStore", () => {
it("switches to new thread if deleted thread was selected", async () => {
const deleteThread = vi.fn().mockResolvedValue(undefined);
- const store = createChatStore({ deleteThread, processMessage: vi.fn() });
+ const store = makeStore({ deleteThread });
store.setState({
threads: [makeThread("t1")],
@@ -218,7 +218,7 @@ describe("createChatStore", () => {
}),
);
- const store = createChatStore({ deleteThread, processMessage: vi.fn() });
+ const store = makeStore({ deleteThread });
store.setState({ threads: [makeThread("t1")] });
store.getState().deleteThread("t1");
@@ -237,7 +237,7 @@ describe("createChatStore", () => {
const updated = { ...makeThread("t1"), title: "Renamed" };
const updateThread = vi.fn().mockResolvedValue(updated);
- const store = createChatStore({ updateThread, processMessage: vi.fn() });
+ const store = makeStore({ updateThread });
store.setState({ threads: [makeThread("t1")] });
store.getState().updateThread(updated);
@@ -252,10 +252,10 @@ describe("createChatStore", () => {
// ────────────────────────────────────────────
describe("message CRUD", () => {
- let store: ReturnType<typeof createChatStore>;
+ let store: ReturnType<typeof makeStore>;
beforeEach(() => {
- store = createChatStore({ processMessage: vi.fn() });
+ store = makeStore();
store.setState({ messages: [makeMessage("m1"), makeMessage("m2", "assistant")] });
});
@@ -285,15 +285,15 @@ describe("createChatStore", () => {
});
// ────────────────────────────────────────────
- // processMessage
+ // processMessage (calls llm.send)
// ────────────────────────────────────────────
describe("processMessage", () => {
- it("appends optimistic user message and calls processMessage", async () => {
- const processMessage = vi.fn().mockResolvedValue(new Response("", { status: 200 }));
+ it("appends optimistic user message and calls llm.send", async () => {
+ const send = vi.fn().mockResolvedValue(new Response("", { status: 200 }));
- const store = createChatStore({
- processMessage,
+ const store = makeStore({
+ send,
streamProtocol: { parse: async function* () {} },
});
@@ -304,17 +304,17 @@ describe("createChatStore", () => {
expect(store.getState().messages).toHaveLength(1);
expect(store.getState().messages[0].role).toBe("user");
expect(store.getState().isRunning).toBe(false);
- expect(processMessage).toHaveBeenCalledOnce();
+ expect(send).toHaveBeenCalledOnce();
});
it("creates thread when none selected", async () => {
const newThread = makeThread("t-auto");
const createThread = vi.fn().mockResolvedValue(newThread);
- const processMessage = vi.fn().mockResolvedValue(new Response("", { status: 200 }));
+ const send = vi.fn().mockResolvedValue(new Response("", { status: 200 }));
- const store = createChatStore({
+ const store = makeStore({
createThread,
- processMessage,
+ send,
streamProtocol: { parse: async function* () {} },
});
@@ -325,24 +325,24 @@ describe("createChatStore", () => {
});
it("no-ops when already running", async () => {
- const processMessage = vi.fn().mockResolvedValue(new Response("", { status: 200 }));
+ const send = vi.fn().mockResolvedValue(new Response("", { status: 200 }));
- const store = createChatStore({
- processMessage,
+ const store = makeStore({
+ send,
streamProtocol: { parse: async function* () {} },
});
store.setState({ isRunning: true, selectedThreadId: "t1" });
await store.getState().processMessage({ role: "user", content: "hello" });
- expect(processMessage).not.toHaveBeenCalled();
+ expect(send).not.toHaveBeenCalled();
});
it("sets threadError on failure", async () => {
- const processMessage = vi.fn().mockRejectedValue(new Error("api down"));
+ const send = vi.fn().mockRejectedValue(new Error("api down"));
- const store = createChatStore({
- processMessage,
+ const store = makeStore({
+ send,
streamProtocol: { parse: async function* () {} },
});
store.setState({ selectedThreadId: "t1" });
@@ -361,14 +361,14 @@ describe("createChatStore", () => {
describe("cancelMessage", () => {
it("aborts in-flight request", async () => {
- let capturedAbort: AbortController;
- const processMessage = vi.fn().mockImplementation(({ abortController }) => {
- capturedAbort = abortController;
+ let capturedSignal: AbortSignal;
+ const send = vi.fn().mockImplementation(({ signal }) => {
+ capturedSignal = signal;
return new Promise(() => {}); // never resolves
});
- const store = createChatStore({
- processMessage,
+ const store = makeStore({
+ send,
streamProtocol: { parse: async function* () {} },
});
store.setState({ selectedThreadId: "t1" });
@@ -382,415 +382,7 @@ describe("createChatStore", () => {
await flushPromises();
expect(store.getState().isRunning).toBe(false);
- expect(capturedAbort!.signal.aborted).toBe(true);
- });
- });
-
- // ────────────────────────────────────────────
- // apiUrl (default fetch-based processMessage)
- // ────────────────────────────────────────────
-
- describe("apiUrl", () => {
- let fetchSpy: ReturnType<typeof vi.fn>;
-
- beforeEach(() => {
- fetchSpy = vi.fn();
- vi.stubGlobal("fetch", fetchSpy);
- });
-
- it("sends POST to apiUrl with threadId and messages", async () => {
- const sseBody = `data: ${JSON.stringify({ type: "TEXT_MESSAGE_CONTENT", delta: "hi" })}\n\ndata: [DONE]\n\n`;
- const stream = new ReadableStream({
- start(c) {
- c.enqueue(new TextEncoder().encode(sseBody));
- c.close();
- },
- });
- fetchSpy.mockResolvedValue(new Response(stream));
-
- const store = createChatStore({ apiUrl: "/api/chat" });
- store.setState({ selectedThreadId: "t1" });
-
- await store.getState().processMessage({ role: "user", content: "hello" });
-
- expect(fetchSpy).toHaveBeenCalledOnce();
- const [url, opts] = fetchSpy.mock.calls[0];
- expect(url).toBe("/api/chat");
- expect(opts.method).toBe("POST");
-
- const body = JSON.parse(opts.body);
- expect(body.threadId).toBe("t1");
- expect(body.messages).toHaveLength(1);
- expect(body.messages[0].role).toBe("user");
- });
-
- it("passes abortController.signal to fetch", async () => {
- fetchSpy.mockImplementation(() => new Promise(() => {}));
-
- const store = createChatStore({ apiUrl: "/api/chat" });
- store.setState({ selectedThreadId: "t1" });
-
- store.getState().processMessage({ role: "user", content: "hi" });
- await flushPromises();
-
- const [, opts] = fetchSpy.mock.calls[0];
- expect(opts.signal).toBeInstanceOf(AbortSignal);
- });
-
- it("streams response via processStreamedMessage", async () => {
- const sseBody = `data: ${JSON.stringify({ type: "TEXT_MESSAGE_CONTENT", delta: "response text" })}\n\ndata: [DONE]\n\n`;
- const stream = new ReadableStream({
- start(c) {
- c.enqueue(new TextEncoder().encode(sseBody));
- c.close();
- },
- });
- fetchSpy.mockResolvedValue(new Response(stream));
-
- const store = createChatStore({ apiUrl: "/api/chat" });
- store.setState({ selectedThreadId: "t1" });
-
- await store.getState().processMessage({ role: "user", content: "hello" });
-
- expect(store.getState().messages).toHaveLength(2);
- expect(store.getState().messages[0].role).toBe("user");
- expect(store.getState().messages[1].role).toBe("assistant");
- expect((store.getState().messages[1] as any).content).toBe("response text");
- });
-
- it("throws when neither apiUrl nor processMessage provided", async () => {
- const store = createChatStore({});
- store.setState({ selectedThreadId: "t1" });
-
- await store.getState().processMessage({ role: "user", content: "hello" });
-
- expect(store.getState().threadError).toBeInstanceOf(Error);
- expect(store.getState().threadError?.message).toContain("apiUrl or processMessage required");
- });
-
- it("applies messageFormat.toApi to outbound messages", async () => {
- const sseBody = `data: [DONE]\n\n`;
- const stream = new ReadableStream({
- start(c) {
- c.enqueue(new TextEncoder().encode(sseBody));
- c.close();
- },
- });
- fetchSpy.mockResolvedValue(new Response(stream));
-
- const toApi = vi.fn((msgs: Message[]) => msgs.map((m) => ({ custom: m.id })));
-
- const store = createChatStore({
- apiUrl: "/api/chat",
- messageFormat: { toApi, fromApi: (d) => d as Message[] },
- });
- store.setState({ selectedThreadId: "t1" });
-
- await store.getState().processMessage({ role: "user", content: "hi" });
-
- const body = JSON.parse(fetchSpy.mock.calls[0][1].body);
- expect(body.messages[0]).toHaveProperty("custom");
- expect(toApi).toHaveBeenCalled();
- });
-
- it("uses ephemeral threadId when no thread selected and no createThread", async () => {
- const sseBody = `data: [DONE]\n\n`;
- const stream = new ReadableStream({
- start(c) {
- c.enqueue(new TextEncoder().encode(sseBody));
- c.close();
- },
- });
- fetchSpy.mockResolvedValue(new Response(stream));
-
- const store = createChatStore({ apiUrl: "/api/chat" });
-
- await store.getState().processMessage({ role: "user", content: "hello" });
-
- const body = JSON.parse(fetchSpy.mock.calls[0][1].body);
- expect(body.threadId).toBe("ephemeral");
- });
- });
-
- // ────────────────────────────────────────────
- // threadApiUrl (default fetch-based thread ops)
- // ────────────────────────────────────────────
-
- describe("threadApiUrl", () => {
- let fetchSpy: ReturnType<typeof vi.fn>;
-
- beforeEach(() => {
- fetchSpy = vi.fn();
- vi.stubGlobal("fetch", fetchSpy);
- });
-
- it("loadThreads fetches from threadApiUrl/get", async () => {
- const threads = [makeThread("t1"), makeThread("t2", 1)];
- fetchSpy.mockResolvedValue(new Response(JSON.stringify({ threads })));
-
- const store = createChatStore({ threadApiUrl: "/api/threads", apiUrl: "/api/chat" });
- store.getState().loadThreads();
- await flushPromises();
-
- expect(fetchSpy).toHaveBeenCalledWith("/api/threads/get");
- expect(store.getState().threads).toHaveLength(2);
- });
-
- it("loadMoreThreads passes cursor as query param", async () => {
- fetchSpy
- .mockResolvedValueOnce(
- new Response(JSON.stringify({ threads: [makeThread("t1")], nextCursor: "abc" })),
- )
- .mockResolvedValueOnce(new Response(JSON.stringify({ threads: [makeThread("t2", 1)] })));
-
- const store = createChatStore({ threadApiUrl: "/api/threads", apiUrl: "/api/chat" });
- store.getState().loadThreads();
- await flushPromises();
-
- store.getState().loadMoreThreads();
- await flushPromises();
-
- expect(fetchSpy).toHaveBeenCalledWith("/api/threads/get?cursor=abc");
- expect(store.getState().threads).toHaveLength(2);
- });
-
- it("createThread POSTs to threadApiUrl/create", async () => {
- const thread = makeThread("t-new");
- fetchSpy.mockResolvedValue(new Response(JSON.stringify(thread)));
-
- const store = createChatStore({ threadApiUrl: "/api/threads", apiUrl: "/api/chat" });
-
- const result = await store.getState().createThread({
- id: "m1",
- role: "user",
- content: "hello",
- } as UserMessage);
-
- const [url, opts] = fetchSpy.mock.calls[0];
- expect(url).toBe("/api/threads/create");
- expect(opts.method).toBe("POST");
- expect(JSON.parse(opts.body)).toHaveProperty("messages");
- expect(result.id).toBe("t-new");
- });
-
- it("deleteThread DELETEs threadApiUrl/delete/:id", async () => {
- fetchSpy.mockResolvedValue(new Response(""));
-
- const store = createChatStore({ threadApiUrl: "/api/threads", apiUrl: "/api/chat" });
- store.setState({ threads: [makeThread("t1")] });
-
- store.getState().deleteThread("t1");
- await flushPromises();
-
- expect(fetchSpy).toHaveBeenCalledWith("/api/threads/delete/t1", { method: "DELETE" });
- expect(store.getState().threads).toHaveLength(0);
- });
-
- it("updateThread PATCHes threadApiUrl/update/:id", async () => {
- const updated = { ...makeThread("t1"), title: "Renamed" };
- fetchSpy.mockResolvedValue(new Response(JSON.stringify(updated)));
-
- const store = createChatStore({ threadApiUrl: "/api/threads", apiUrl: "/api/chat" });
- store.setState({ threads: [makeThread("t1")] });
-
- store.getState().updateThread(updated);
- await flushPromises();
-
- const [url, opts] = fetchSpy.mock.calls[0];
- expect(url).toBe("/api/threads/update/t1");
- expect(opts.method).toBe("PATCH");
- expect(store.getState().threads[0]!.title).toBe("Renamed");
- });
-
- it("selectThread GETs threadApiUrl/get/:id and applies messageFormat.fromApi", async () => {
- const rawMessages = [{ custom: "data" }];
- const parsed: Message[] = [makeMessage("m1")];
- const fromApi = vi.fn().mockReturnValue(parsed);
-
- fetchSpy.mockResolvedValue(new Response(JSON.stringify(rawMessages)));
-
- const store = createChatStore({
- threadApiUrl: "/api/threads",
- apiUrl: "/api/chat",
- messageFormat: { toApi: (m) => m, fromApi },
- });
-
- store.getState().selectThread("t1");
- await flushPromises();
-
- expect(fetchSpy).toHaveBeenCalledWith("/api/threads/get/t1");
- expect(fromApi).toHaveBeenCalledWith(rawMessages);
- expect(store.getState().messages).toEqual(parsed);
- });
-
- it("processMessage auto-creates thread via threadApiUrl when none selected", async () => {
- const thread = makeThread("t-auto");
- fetchSpy.mockResolvedValueOnce(new Response(JSON.stringify(thread))).mockResolvedValueOnce(
- new Response(
- new ReadableStream({
- start(c) {
- c.enqueue(new TextEncoder().encode("data: [DONE]\n\n"));
- c.close();
- },
- }),
- ),
- );
-
- const store = createChatStore({ threadApiUrl: "/api/threads", apiUrl: "/api/chat" });
-
- await store.getState().processMessage({ role: "user", content: "hello" });
-
- expect(fetchSpy.mock.calls[0][0]).toBe("/api/threads/create");
- expect(store.getState().selectedThreadId).toBe("t-auto");
- });
- });
-
- // ────────────────────────────────────────────
- // messageFormat round-tripping
- // ────────────────────────────────────────────
-
- describe("messageFormat", () => {
- let fetchSpy: ReturnType<typeof vi.fn>;
-
- beforeEach(() => {
- fetchSpy = vi.fn();
- vi.stubGlobal("fetch", fetchSpy);
- });
-
- const doneStream = () =>
- new ReadableStream({
- start(c) {
- c.enqueue(new TextEncoder().encode("data: [DONE]\n\n"));
- c.close();
- },
- });
-
- const customFormat = {
- toApi: (msgs: Message[]) => msgs.map((m) => ({ r: m.role, c: (m as any).content })),
- fromApi: (data: unknown) =>
- (data as Array<{ r: string; c: string }>).map((d, i) => ({
- id: `parsed-${i}`,
- role: d.r,
- content: d.c,
- })) as Message[],
- };
-
- it("toApi is applied when sending messages via apiUrl", async () => {
- fetchSpy.mockResolvedValue(new Response(doneStream()));
-
- const toApi = vi.fn((msgs: Message[]) =>
- msgs.map((m) => ({ custom_role: m.role, custom_content: (m as any).content })),
- );
-
- const store = createChatStore({
- apiUrl: "/api/chat",
- messageFormat: { toApi, fromApi: (d) => d as Message[] },
- });
- store.setState({ selectedThreadId: "t1" });
-
- await store.getState().processMessage({ role: "user", content: "hello" });
-
- expect(toApi).toHaveBeenCalled();
- const body = JSON.parse(fetchSpy.mock.calls[0][1].body);
- expect(body.messages[0]).toEqual({ custom_role: "user", custom_content: "hello" });
- expect(body.messages[0]).not.toHaveProperty("id");
- });
-
- it("fromApi is applied when loading thread via threadApiUrl", async () => {
- const serverPayload = [
- { r: "user", c: "hi" },
- { r: "assistant", c: "hello" },
- ];
- fetchSpy.mockResolvedValue(new Response(JSON.stringify(serverPayload)));
-
- const fromApi = vi.fn(customFormat.fromApi);
-
- const store = createChatStore({
- apiUrl: "/api/chat",
- threadApiUrl: "/api/threads",
- messageFormat: { toApi: (m) => m, fromApi },
- });
-
- store.getState().selectThread("t1");
- await flushPromises();
-
- expect(fromApi).toHaveBeenCalledWith(serverPayload);
- expect(store.getState().messages).toHaveLength(2);
- expect(store.getState().messages[0].role).toBe("user");
- expect((store.getState().messages[0] as any).content).toBe("hi");
- expect(store.getState().messages[1].role).toBe("assistant");
- expect((store.getState().messages[1] as any).content).toBe("hello");
- });
-
- it("toApi is applied when creating thread via threadApiUrl", async () => {
- const thread = makeThread("t-new");
- fetchSpy.mockResolvedValue(new Response(JSON.stringify(thread)));
-
- const toApi = vi.fn((msgs: Message[]) =>
- msgs.map((m) => ({ r: m.role, c: (m as any).content })),
- );
-
- const store = createChatStore({
- apiUrl: "/api/chat",
- threadApiUrl: "/api/threads",
- messageFormat: { toApi, fromApi: (d) => d as Message[] },
- });
-
- await store.getState().createThread({
- id: "m1",
- role: "user",
- content: "hello",
- } as UserMessage);
-
- expect(toApi).toHaveBeenCalled();
- const [url, opts] = fetchSpy.mock.calls[0];
- expect(url).toBe("/api/threads/create");
- const body = JSON.parse(opts.body);
- expect(body.messages).toEqual([{ r: "user", c: "hello" }]);
- });
-
- it("round-trip: toApi then fromApi preserves data", async () => {
- const thread = makeThread("t-rt");
-
- fetchSpy
- .mockResolvedValueOnce(new Response(JSON.stringify(thread)))
- .mockResolvedValueOnce(new Response(doneStream()))
- .mockResolvedValueOnce(new Response(JSON.stringify([{ r: "user", c: "round-trip" }])));
-
- const store = createChatStore({
- apiUrl: "/api/chat",
- threadApiUrl: "/api/threads",
- messageFormat: customFormat,
- });
-
- await store.getState().processMessage({ role: "user", content: "round-trip" });
-
- const createBody = JSON.parse(fetchSpy.mock.calls[0][1].body);
- expect(createBody.messages[0]).toEqual({ r: "user", c: "round-trip" });
-
- const sendBody = JSON.parse(fetchSpy.mock.calls[1][1].body);
- expect(sendBody.messages[0]).toEqual({ r: "user", c: "round-trip" });
-
- store.getState().selectThread("t-rt");
- await flushPromises();
-
- expect(store.getState().messages).toHaveLength(1);
- expect(store.getState().messages[0].role).toBe("user");
- expect((store.getState().messages[0] as any).content).toBe("round-trip");
- });
-
- it("default identityMessageFormat passes through unchanged", async () => {
- fetchSpy.mockResolvedValue(new Response(doneStream()));
-
- const store = createChatStore({ apiUrl: "/api/chat" });
- store.setState({ selectedThreadId: "t1" });
-
- await store.getState().processMessage({ role: "user", content: "raw" });
-
- const body = JSON.parse(fetchSpy.mock.calls[0][1].body);
- expect(body.messages[0]).toHaveProperty("id");
- expect(body.messages[0].role).toBe("user");
- expect(body.messages[0].content).toBe("raw");
+ expect(capturedSignal!.aborted).toBe(true);
});
});
@@ -800,17 +392,17 @@ describe("createChatStore", () => {
describe("selectThread while streaming", () => {
it("cancels current stream and loads new thread", async () => {
- let capturedAbort: AbortController;
- const processMessage = vi.fn().mockImplementation(({ abortController }) => {
- capturedAbort = abortController;
+ let capturedSignal: AbortSignal;
+ const send = vi.fn().mockImplementation(({ signal }) => {
+ capturedSignal = signal;
return new Promise(() => {}); // never resolves
});
const newMessages = [makeMessage("new-m1")];
- const loadThread = vi.fn().mockResolvedValue(newMessages);
+ const getMessages = vi.fn().mockResolvedValue(newMessages);
- const store = createChatStore({
- processMessage,
- loadThread,
+ const store = makeStore({
+ send,
+ getMessages,
streamProtocol: { parse: async function* () {} },
});
store.setState({ selectedThreadId: "t1" });
@@ -823,7 +415,7 @@ describe("createChatStore", () => {
// Switch thread mid-stream
store.getState().selectThread("t2");
- expect(capturedAbort!.signal.aborted).toBe(true);
+ expect(capturedSignal!.aborted).toBe(true);
expect(store.getState().selectedThreadId).toBe("t2");
expect(store.getState().isLoadingMessages).toBe(true);
diff --git a/packages/react-headless/src/store/__tests__/createDetailedViewStore.test.ts b/packages/react-headless/src/store/__tests__/createDetailedViewStore.test.ts
new file mode 100644
index 000000000..c07d355a3
--- /dev/null
+++ b/packages/react-headless/src/store/__tests__/createDetailedViewStore.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+import { createDetailedViewStore } from "../createDetailedViewStore";
+
+describe("createDetailedViewStore", () => {
+ it("has correct initial state", () => {
+ const store = createDetailedViewStore();
+ const state = store.getState();
+
+ expect(state.activeDetailedViewId).toBeNull();
+ expect(state._detailedViewPanelNode).toBeNull();
+ });
+
+ describe("setActiveDetailedView", () => {
+ it("sets activeDetailedViewId", () => {
+ const store = createDetailedViewStore();
+
+ store.getState().setActiveDetailedView("view-1");
+
+ expect(store.getState().activeDetailedViewId).toBe("view-1");
+ });
+
+ it("replaces active view when called with a different id", () => {
+ const store = createDetailedViewStore();
+
+ store.getState().setActiveDetailedView("view-1");
+ store.getState().setActiveDetailedView("view-2");
+
+ expect(store.getState().activeDetailedViewId).toBe("view-2");
+ });
+
+ it("clears with null", () => {
+ const store = createDetailedViewStore();
+
+ store.getState().setActiveDetailedView("view-1");
+ store.getState().setActiveDetailedView(null);
+
+ expect(store.getState().activeDetailedViewId).toBeNull();
+ });
+ });
+
+ describe("reset", () => {
+ it("resets activeDetailedViewId to null", () => {
+ const store = createDetailedViewStore();
+
+ store.getState().setActiveDetailedView("view-1");
+ expect(store.getState().activeDetailedViewId).toBe("view-1");
+
+ store.getState().reset();
+ expect(store.getState().activeDetailedViewId).toBeNull();
+ });
+ });
+
+ describe("_setDetailedViewPanelNode", () => {
+ it("sets and clears DOM reference", () => {
+ const store = createDetailedViewStore();
+
+ const node = {} as HTMLElement;
+ store.getState()._setDetailedViewPanelNode(node);
+ expect(store.getState()._detailedViewPanelNode).toBe(node);
+
+ store.getState()._setDetailedViewPanelNode(null);
+ expect(store.getState()._detailedViewPanelNode).toBeNull();
+ });
+ });
+});
diff --git a/packages/react-headless/src/store/__tests__/createThreadContextStore.test.ts b/packages/react-headless/src/store/__tests__/createThreadContextStore.test.ts
new file mode 100644
index 000000000..3e07bd0f2
--- /dev/null
+++ b/packages/react-headless/src/store/__tests__/createThreadContextStore.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from "vitest";
+import { createThreadContextStore } from "../createThreadContextStore";
+
+const entry = (id: string, version: number, heading = `H${version}`, type = "th_dashboard") => ({
+ id,
+ version,
+ heading,
+ type,
+});
+
+describe("createThreadContextStore", () => {
+ it("has correct initial state", () => {
+ const store = createThreadContextStore();
+ expect(store.getState().artifacts).toEqual({});
+ });
+
+ describe("registerArtifact", () => {
+ it("adds a new entry", () => {
+ const store = createThreadContextStore();
+ store.getState().registerArtifact(entry("a", 1));
+ expect(store.getState().artifacts["a"]).toEqual([entry("a", 1)]);
+ });
+
+ it("adds multiple versions sorted ascending by version", () => {
+ const store = createThreadContextStore();
+ store.getState().registerArtifact(entry("a", 2));
+ store.getState().registerArtifact(entry("a", 1));
+ store.getState().registerArtifact(entry("a", 3));
+ expect(store.getState().artifacts["a"]!.map((e) => e.version)).toEqual([1, 2, 3]);
+ });
+
+ it("groups separate ids in their own buckets", () => {
+ const store = createThreadContextStore();
+ store.getState().registerArtifact(entry("a", 1));
+ store.getState().registerArtifact(entry("b", 1));
+ expect(Object.keys(store.getState().artifacts)).toEqual(["a", "b"]);
+ });
+
+ it("updates heading when same (id, version) re-registers with different heading", () => {
+ const store = createThreadContextStore();
+ store.getState().registerArtifact(entry("a", 1, "Old"));
+ store.getState().registerArtifact(entry("a", 1, "New"));
+ expect(store.getState().artifacts["a"]).toEqual([entry("a", 1, "New")]);
+ });
+
+ it("updates type when same (id, version) re-registers with different type", () => {
+ const store = createThreadContextStore();
+ store.getState().registerArtifact(entry("a", 1, "H1", "th_dashboard"));
+ store.getState().registerArtifact(entry("a", 1, "H1", "th_presentation"));
+ expect(store.getState().artifacts["a"]![0]!.type).toBe("th_presentation");
+ });
+
+ it("is referentially stable when same (id, version, heading, type) re-registers", () => {
+ const store = createThreadContextStore();
+ store.getState().registerArtifact(entry("a", 1));
+ const before = store.getState().artifacts;
+ store.getState().registerArtifact(entry("a", 1));
+ expect(store.getState().artifacts).toBe(before);
+ });
+ });
+
+ describe("unregisterArtifact", () => {
+ it("removes the matching version", () => {
+ const store = createThreadContextStore();
+ store.getState().registerArtifact(entry("a", 1));
+ store.getState().registerArtifact(entry("a", 2));
+ store.getState().unregisterArtifact("a", 1);
+ expect(store.getState().artifacts["a"]!.map((e) => e.version)).toEqual([2]);
+ });
+
+ it("removes the bucket when last version is removed", () => {
+ const store = createThreadContextStore();
+ store.getState().registerArtifact(entry("a", 1));
+ store.getState().unregisterArtifact("a", 1);
+ expect(store.getState().artifacts).toEqual({});
+ });
+
+ it("is referentially stable when version does not exist", () => {
+ const store = createThreadContextStore();
+ store.getState().registerArtifact(entry("a", 1));
+ const before = store.getState().artifacts;
+ store.getState().unregisterArtifact("a", 99);
+ expect(store.getState().artifacts).toBe(before);
+ });
+
+ it("is referentially stable when id does not exist", () => {
+ const store = createThreadContextStore();
+ const before = store.getState().artifacts;
+ store.getState().unregisterArtifact("missing", 1);
+ expect(store.getState().artifacts).toBe(before);
+ });
+ });
+
+ describe("reset", () => {
+ it("clears the registry", () => {
+ const store = createThreadContextStore();
+ store.getState().registerArtifact(entry("a", 1));
+ store.getState().reset();
+ expect(store.getState().artifacts).toEqual({});
+ });
+ });
+});
diff --git a/packages/react-headless/src/store/__tests__/detailedViewThreadSwitch.test.ts b/packages/react-headless/src/store/__tests__/detailedViewThreadSwitch.test.ts
new file mode 100644
index 000000000..e261af996
--- /dev/null
+++ b/packages/react-headless/src/store/__tests__/detailedViewThreadSwitch.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it, vi } from "vitest";
+import { createDetailedViewStore } from "../createDetailedViewStore";
+import { makeStore } from "./__helpers/makeStore";
+
+const flushPromises = () => new Promise((r) => setTimeout(r, 0));
+
+describe("detailed-view thread-switch cleanup", () => {
+ const setupStores = () => {
+ const chatStore = makeStore();
+ const detailedViewStore = createDetailedViewStore();
+
+ const unsubscribe = chatStore.subscribe(
+ (state) => state.selectedThreadId,
+ () => detailedViewStore.getState().reset(),
+ );
+
+ return { chatStore, detailedViewStore, unsubscribe };
+ };
+
+ it("clears active view when selectThread is called", async () => {
+ const { chatStore, detailedViewStore, unsubscribe } = setupStores();
+
+ detailedViewStore.getState().setActiveDetailedView("view-1");
+ expect(detailedViewStore.getState().activeDetailedViewId).toBe("view-1");
+
+ chatStore.getState().selectThread("thread-2");
+ await flushPromises();
+
+ expect(detailedViewStore.getState().activeDetailedViewId).toBeNull();
+
+ unsubscribe();
+ });
+
+ it("clears active view when switchToNewThread is called", async () => {
+ const { chatStore, detailedViewStore, unsubscribe } = setupStores();
+
+ chatStore.setState({ selectedThreadId: "thread-1" });
+ detailedViewStore.getState().setActiveDetailedView("view-1");
+
+ chatStore.getState().switchToNewThread();
+ await flushPromises();
+
+ expect(detailedViewStore.getState().activeDetailedViewId).toBeNull();
+
+ unsubscribe();
+ });
+
+ it("clears active view when active thread is deleted", async () => {
+ const deleteThread = vi.fn().mockResolvedValue(undefined);
+ const chatStore = makeStore({ deleteThread });
+ const detailedViewStore = createDetailedViewStore();
+
+ const unsubscribe = chatStore.subscribe(
+ (state) => state.selectedThreadId,
+ () => detailedViewStore.getState().reset(),
+ );
+
+ chatStore.setState({
+ selectedThreadId: "thread-1",
+ threads: [
+ {
+ id: "thread-1",
+ title: "Test",
+ createdAt: new Date().toISOString(),
+ },
+ ],
+ });
+
+ detailedViewStore.getState().setActiveDetailedView("view-1");
+
+ chatStore.getState().deleteThread("thread-1");
+ await flushPromises();
+
+ expect(detailedViewStore.getState().activeDetailedViewId).toBeNull();
+
+ unsubscribe();
+ });
+
+ it("does not clear active view when re-selecting the same thread", async () => {
+ const { chatStore, detailedViewStore, unsubscribe } = setupStores();
+
+ chatStore.setState({ selectedThreadId: "thread-1" });
+ await flushPromises();
+
+ detailedViewStore.getState().setActiveDetailedView("view-1");
+ expect(detailedViewStore.getState().activeDetailedViewId).toBe("view-1");
+
+ chatStore.getState().selectThread("thread-1");
+ await flushPromises();
+
+ expect(detailedViewStore.getState().activeDetailedViewId).toBe("view-1");
+
+ unsubscribe();
+ });
+
+ it("handles rapid thread switches cleanly", async () => {
+ const getMessages = vi.fn().mockResolvedValue([]);
+ const chatStore = makeStore({ getMessages });
+ const detailedViewStore = createDetailedViewStore();
+
+ const unsubscribe = chatStore.subscribe(
+ (state) => state.selectedThreadId,
+ () => detailedViewStore.getState().reset(),
+ );
+
+ detailedViewStore.getState().setActiveDetailedView("view-1");
+
+ chatStore.getState().selectThread("thread-1");
+ chatStore.getState().selectThread("thread-2");
+ chatStore.getState().selectThread("thread-3");
+ await flushPromises();
+
+ expect(detailedViewStore.getState().activeDetailedViewId).toBeNull();
+ expect(chatStore.getState().selectedThreadId).toBe("thread-3");
+
+ unsubscribe();
+ });
+});
diff --git a/packages/react-headless/src/store/__tests__/threadContextSwitch.test.ts b/packages/react-headless/src/store/__tests__/threadContextSwitch.test.ts
new file mode 100644
index 000000000..c4cf1e674
--- /dev/null
+++ b/packages/react-headless/src/store/__tests__/threadContextSwitch.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, it, vi } from "vitest";
+import { createThreadContextStore } from "../createThreadContextStore";
+import { makeStore } from "./__helpers/makeStore";
+
+const flushPromises = () => new Promise((r) => setTimeout(r, 0));
+
+describe("thread-context thread-switch cleanup", () => {
+ const setupStores = () => {
+ const chatStore = makeStore();
+ const threadContextStore = createThreadContextStore();
+
+ const unsubscribe = chatStore.subscribe(
+ (state) => state.selectedThreadId,
+ () => threadContextStore.getState().reset(),
+ );
+
+ return { chatStore, threadContextStore, unsubscribe };
+ };
+
+ const populate = (store: ReturnType<typeof createThreadContextStore>) => {
+ store
+ .getState()
+ .registerArtifact({ id: "app-1", version: 1, heading: "App", type: "th_dashboard" });
+ store
+ .getState()
+ .registerArtifact({ id: "art-1", version: 1, heading: "Artifact", type: "th_presentation" });
+ };
+
+ const expectEmpty = (store: ReturnType<typeof createThreadContextStore>) => {
+ expect(store.getState().artifacts).toEqual({});
+ };
+
+ it("clears thread context when selectThread is called", async () => {
+ const { chatStore, threadContextStore, unsubscribe } = setupStores();
+
+ populate(threadContextStore);
+
+ chatStore.getState().selectThread("thread-2");
+ await flushPromises();
+
+ expectEmpty(threadContextStore);
+
+ unsubscribe();
+ });
+
+ it("clears thread context when switchToNewThread is called", async () => {
+ const { chatStore, threadContextStore, unsubscribe } = setupStores();
+
+ chatStore.setState({ selectedThreadId: "thread-1" });
+ populate(threadContextStore);
+
+ chatStore.getState().switchToNewThread();
+ await flushPromises();
+
+ expectEmpty(threadContextStore);
+
+ unsubscribe();
+ });
+
+ it("clears thread context when active thread is deleted", async () => {
+ const deleteThread = vi.fn().mockResolvedValue(undefined);
+ const chatStore = makeStore({ deleteThread });
+ const threadContextStore = createThreadContextStore();
+
+ const unsubscribe = chatStore.subscribe(
+ (state) => state.selectedThreadId,
+ () => threadContextStore.getState().reset(),
+ );
+
+ chatStore.setState({
+ selectedThreadId: "thread-1",
+ threads: [
+ {
+ id: "thread-1",
+ title: "Test",
+ createdAt: new Date().toISOString(),
+ },
+ ],
+ });
+
+ populate(threadContextStore);
+
+ chatStore.getState().deleteThread("thread-1");
+ await flushPromises();
+
+ expectEmpty(threadContextStore);
+
+ unsubscribe();
+ });
+
+ it("does not clear thread context when re-selecting the same thread", async () => {
+ const { chatStore, threadContextStore, unsubscribe } = setupStores();
+
+ chatStore.setState({ selectedThreadId: "thread-1" });
+ await flushPromises();
+
+ populate(threadContextStore);
+
+ chatStore.getState().selectThread("thread-1");
+ await flushPromises();
+
+ expect(threadContextStore.getState().artifacts["app-1"]?.length).toBe(1);
+ expect(threadContextStore.getState().artifacts["art-1"]?.length).toBe(1);
+
+ unsubscribe();
+ });
+
+ it("handles rapid thread switches cleanly", async () => {
+ const getMessages = vi.fn().mockResolvedValue([]);
+ const chatStore = makeStore({ getMessages });
+ const threadContextStore = createThreadContextStore();
+
+ const unsubscribe = chatStore.subscribe(
+ (state) => state.selectedThreadId,
+ () => threadContextStore.getState().reset(),
+ );
+
+ populate(threadContextStore);
+
+ chatStore.getState().selectThread("thread-1");
+ chatStore.getState().selectThread("thread-2");
+ chatStore.getState().selectThread("thread-3");
+ await flushPromises();
+
+ expectEmpty(threadContextStore);
+ expect(chatStore.getState().selectedThreadId).toBe("thread-3");
+
+ unsubscribe();
+ });
+});
diff --git a/packages/react-headless/src/store/__tests__/toolActivity.test.ts b/packages/react-headless/src/store/__tests__/toolActivity.test.ts
new file mode 100644
index 000000000..5bb4d81b3
--- /dev/null
+++ b/packages/react-headless/src/store/__tests__/toolActivity.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from "vitest";
+import type { AssistantMessage, ToolCall, ToolMessage } from "../../types";
+import { pairToolActivity, partialJSONParse } from "../toolActivity";
+
+const tc = (id: string, name: string, args: string): ToolCall => ({
+ id,
+ type: "function",
+ function: { name, arguments: args },
+});
+
+const assistant = (toolCalls: ToolCall[]): AssistantMessage => ({
+ id: "a1",
+ role: "assistant",
+ content: "",
+ toolCalls,
+});
+
+const toolMsg = (toolCallId: string, content: string, error?: string): ToolMessage => ({
+ id: `t_${toolCallId}`,
+ role: "tool",
+ toolCallId,
+ content,
+ ...(error ? { error } : {}),
+});
+
+describe("partialJSONParse", () => {
+ it("returns {} for empty input", () => {
+ expect(partialJSONParse("")).toEqual({});
+ });
+
+ it("parses complete JSON", () => {
+ expect(partialJSONParse('{"a":1,"b":"x"}')).toEqual({ a: 1, b: "x" });
+ });
+
+ it("balances a truncated object (open brace)", () => {
+ expect(partialJSONParse('{"a":1,"b":2')).toEqual({ a: 1, b: 2 });
+ });
+
+ it("closes a mid-stream string", () => {
+ expect(partialJSONParse('{"a":"hel')).toEqual({ a: "hel" });
+ });
+
+ it("drops a dangling key awaiting a value (trailing colon)", () => {
+ expect(partialJSONParse('{"a":1,"b":')).toEqual({ a: 1 });
+ });
+
+ it("keeps complete array elements when truncated", () => {
+ expect(partialJSONParse('["a","b"')).toEqual(["a", "b"]);
+ });
+
+ it("never throws on garbage", () => {
+ expect(partialJSONParse("not json")).toEqual({});
+ });
+});
+
+describe("pairToolActivity", () => {
+ it("reports `streaming` while args arrive with no result and not executing", () => {
+ const [a] = pairToolActivity(assistant([tc("1", "search", '{"q":"par')]), []);
+ expect(a?.status).toBe("streaming");
+ expect(a?.input).toEqual({ q: "par" });
+ expect(a?.result).toBeUndefined();
+ expect(a?.isError).toBe(false);
+ });
+
+ it("reports `executing` when args have closed (in the executing set) with no result", () => {
+ const [a] = pairToolActivity(
+ assistant([tc("1", "search", '{"q":"paris"}')]),
+ [],
+ new Set(["1"]),
+ );
+ expect(a?.status).toBe("executing");
+ expect(a?.input).toEqual({ q: "paris" });
+ });
+
+ it("reports `complete` when a result message lands without error", () => {
+ const [a] = pairToolActivity(assistant([tc("1", "search", '{"q":"paris"}')]), [
+ toolMsg("1", '{"ok":true}'),
+ ]);
+ expect(a?.status).toBe("complete");
+ expect(a?.result).toBe('{"ok":true}');
+ expect(a?.isError).toBe(false);
+ });
+
+ it("reports `error` when the result message carries an error", () => {
+ const [a] = pairToolActivity(assistant([tc("1", "search", "{}")]), [
+ toolMsg("1", "boom", "tool exploded"),
+ ]);
+ expect(a?.status).toBe("error");
+ expect(a?.isError).toBe(true);
+ if (a?.status === "error") expect(a.errorText).toBe("tool exploded");
+ });
+
+ it("pairs by toolCallId regardless of message position (no positional break)", () => {
+ // Tool result for call "2" appears before the result for call "1".
+ const activities = pairToolActivity(assistant([tc("1", "a", "{}"), tc("2", "b", "{}")]), [
+ toolMsg("2", "r2"),
+ toolMsg("1", "r1"),
+ ]);
+ expect(activities).toHaveLength(2);
+ expect(activities[0]?.id).toBe("1");
+ expect(activities[0]?.result).toBe("r1");
+ expect(activities[1]?.id).toBe("2");
+ expect(activities[1]?.result).toBe("r2");
+ });
+
+ it("reads the deprecated `_title` arg key into statusMessage", () => {
+ const [a] = pairToolActivity(assistant([tc("1", "x", '{"_title":"Searching"}')]), []);
+ expect(a?.statusMessage).toBe("Searching");
+ });
+
+ it("renders an orphan tool result (a trailing tool message with no matching call)", () => {
+ const a = assistant([]); // no tool calls
+ const tm = toolMsg("orphan-1", "the result");
+ const activities = pairToolActivity(a, [a, tm]);
+ expect(activities).toHaveLength(1);
+ expect(activities[0]?.toolCall.id).toBe("orphan-1");
+ expect(activities[0]?.status).toBe("complete");
+ expect(activities[0]?.result).toBe("the result");
+ });
+
+ it("gives two orphan results sharing a toolCallId distinct activity ids (no key collision)", () => {
+ const a = assistant([]);
+ const tm1: ToolMessage = { id: "tm-a", role: "tool", toolCallId: "dup", content: "r1" };
+ const tm2: ToolMessage = { id: "tm-b", role: "tool", toolCallId: "dup", content: "r2" };
+ const activities = pairToolActivity(a, [a, tm1, tm2]);
+ expect(activities).toHaveLength(2);
+ expect(new Set(activities.map((x) => x.id)).size).toBe(2);
+ });
+
+ it("does not double-render a result owned by another assistant message's call", () => {
+ const a1 = assistant([tc("1", "x", "{}")]); // owns call "1"
+ const a2: AssistantMessage = { id: "a2", role: "assistant", content: "", toolCalls: [] };
+ const tm = toolMsg("1", "r1");
+ // Order a1, a2, tm: tm positionally trails a2 but its call belongs to a1.
+ expect(pairToolActivity(a2, [a1, a2, tm])).toHaveLength(0); // not an orphan under a2
+ const owned = pairToolActivity(a1, [a1, a2, tm]);
+ expect(owned).toHaveLength(1); // paired by id under a1
+ expect(owned[0]?.result).toBe("r1");
+ });
+});
diff --git a/packages/react-headless/src/store/artifactCategories.ts b/packages/react-headless/src/store/artifactCategories.ts
new file mode 100644
index 000000000..2216fb221
--- /dev/null
+++ b/packages/react-headless/src/store/artifactCategories.ts
@@ -0,0 +1,72 @@
+import type { ReactNode } from "react";
+
+import type { ArtifactCategory } from "../adapters/types";
+import type { ArtifactRendererConfig } from "./artifactRendererTypes";
+
+/**
+ * One named artifact category and the renderers that belong to it. Passed to
+ * {@link defineArtifactCategories}.
+ *
+ * @category Types
+ */
+export interface ArtifactCategoryGroup {
+ /** Display label and key for the category, e.g. `"Reports"`. */
+ name: string;
+ /**
+ * Renderers in this category. Each renderer's `type` populates the category's
+ * filter, and the renderers themselves are collected into `artifactRenderers`.
+ */
+ renderers: ArtifactRendererConfig<any>[];
+ /** Sidebar nav icon for the category. Omit to fall back to the default. */
+ icon?: ReactNode;
+}
+
+/**
+ * Wraps the manual `artifactRenderers` + `artifactCategories` wiring: declare
+ * each category once with its renderers, and get both props back, ready to
+ * spread onto `<AgentInterface>`.
+ *
+ * - `artifactRenderers` is every group's renderers, in order, de-duplicated by
+ * identity (a renderer listed in two groups registers once).
+ * - `artifactCategories` is one {@link ArtifactCategory} per group, its
+ * `filter.type` collected from the group's renderer `type`s (de-duplicated).
+ *
+ * @category Functions
+ *
+ * @example
+ * ```tsx
+ * const artifacts = defineArtifactCategories([
+ * { name: "Reports", renderers: [reportRenderer], icon: <ReportIcon /> },
+ * { name: "Dashboards", renderers: [dashboardRenderer], icon: <AppIcon /> },
+ * ]);
+ *
+ * <AgentInterface llm={llm} {...artifacts} />;
+ * ```
+ */
+export function defineArtifactCategories(groups: ArtifactCategoryGroup[]): {
+ artifactRenderers: ArtifactRendererConfig<any>[];
+ artifactCategories: ArtifactCategory[];
+} {
+ const artifactRenderers: ArtifactRendererConfig<any>[] = [];
+ const seenRenderers = new Set<ArtifactRendererConfig<any>>();
+
+ const artifactCategories = groups.map((group): ArtifactCategory => {
+ const type: string[] = [];
+ const seenTypes = new Set<string>();
+
+ for (const renderer of group.renderers) {
+ if (!seenRenderers.has(renderer)) {
+ seenRenderers.add(renderer);
+ artifactRenderers.push(renderer);
+ }
+ if (!seenTypes.has(renderer.type)) {
+ seenTypes.add(renderer.type);
+ type.push(renderer.type);
+ }
+ }
+
+ return { name: group.name, filter: { type }, icon: group.icon };
+ });
+
+ return { artifactRenderers, artifactCategories };
+}
diff --git a/packages/react-headless/src/store/artifactRendererTypes.ts b/packages/react-headless/src/store/artifactRendererTypes.ts
new file mode 100644
index 000000000..117e011de
--- /dev/null
+++ b/packages/react-headless/src/store/artifactRendererTypes.ts
@@ -0,0 +1,147 @@
+import type { ReactNode } from "react";
+
+/**
+ * Controls passed to a renderer's `preview` and `actual` render functions.
+ *
+ * @category Types
+ */
+export interface ArtifactRendererControls {
+ /** Whether this renderer's detailed view is the currently active one. */
+ isActive: boolean;
+ /**
+ * `true` while the tool call is still streaming — i.e. its arguments are
+ * arriving incrementally and no tool result has been paired in yet. Becomes
+ * `false` once the tool result message lands and the renderer is invoked
+ * with the full `response`. Always `false` for storage-opened artifacts.
+ *
+ * The same component instance is reused across the streaming → completed
+ * transition, so renderers can rely on this flag to swap UI states (e.g.
+ * show a skeleton or "streaming…" badge during partial args, then the final
+ * view) without remounting.
+ */
+ isStreaming: boolean;
+ /** Activates this renderer's detailed view. */
+ open: () => void;
+ /** Closes this renderer's detailed view if currently active. */
+ close: () => void;
+ /** Toggles this renderer's detailed view. */
+ toggle: () => void;
+}
+
+/**
+ * Result of a renderer's `parser`.
+ *
+ * - Returning `null` from `parser` skips rendering this tool call entirely.
+ * - `meta: null` renders preview/actual but skips ThreadContext registration —
+ * a common pattern while `ctx.isStreaming` is `true` so the entry only
+ * appears in the registry once the tool result has arrived.
+ *
+ * @category Types
+ */
+export interface ParsedArtifact<Props> {
+ props: Props;
+ // `type`, when a parser provides it, is the artifact's REAL kind. It lets the
+ // ThreadContext registration label/resolve the artifact by its own kind even
+ // when a single tool-owning renderer matched the tool name (e.g. one renderer
+ // owns the generate/edit tools but emits both presentations and reports).
+ // Optional: parsers that don't set it fall back to the matched renderer's type.
+ meta: { id: string; version: number; heading: string; type?: string } | null;
+}
+
+/**
+ * Configuration for a single artifact renderer, returned by {@link defineArtifactRenderer}.
+ *
+ * Renderers are matched against tool calls by `toolName` (one or many literal
+ * strings) and against stored artifacts by `type`. When a match fires, `parser`
+ * converts the raw envelope into typed `Props` + an optional ThreadContext
+ * `meta` entry, and `preview` / `actual` render the inline chat preview and
+ * the full view respectively.
+ *
+ * @category Types
+ */
+export interface ArtifactRendererConfig<Props = unknown> {
+ /**
+ * Artifact type this renderer handles, e.g. `"th_presentation"`.
+ * Links the renderer to {@link ArtifactCategory} filters and to stored
+ * artifacts (`ArtifactSummary.type`) for thread-independent rendering.
+ */
+ type: string;
+ /**
+ * Tool name(s) to match. Literal strings only; first registration wins on
+ * duplicates. An array registers the same renderer for several tools.
+ */
+ toolName: string | string[];
+ /**
+ * Converts the raw envelope into `{ props, meta }`.
+ *
+ * Tool-call path: receives `{ args, response }` exactly as the backend
+ * emitted them — the SDK does not pre-parse JSON. Called on every update,
+ * including during streaming, so implementations must tolerate:
+ * - `args` as a *partial* JSON string (the LLM is still emitting it), and
+ * - `response` as `null` (the tool result hasn't arrived yet — see
+ * {@link ArtifactRendererControls.isStreaming}).
+ *
+ * Storage path (artifact browser): receives `{ args: undefined, response: artifact.content }` —
+ * stored `content` must therefore have the same shape as the tool-call response.
+ *
+ * Return `null` to skip rendering. Return `meta: null` to render without
+ * registering in the ThreadContext (entry hidden from workspace lists).
+ * `meta.id` should be stable across re-runs of the same logical entry —
+ * when `(id, version)` changes, the registry entry is re-registered.
+ */
+ parser: (
+ raw: { args: unknown; response: unknown },
+ ctx: { isStreaming: boolean },
+ ) => ParsedArtifact<Props> | null;
+ /** Renders the inline preview shown in the chat message. */
+ preview: (props: Props, controls: ArtifactRendererControls) => ReactNode;
+ /** Renders the full artifact view (side panel in-thread, full page in the artifact browser). */
+ actual: (props: Props, controls: ArtifactRendererControls) => ReactNode;
+ /**
+ * Icon for this artifact type, used by the artifact nav for the category this
+ * type belongs to. A platform-neutral node (a web element or a React Native
+ * element). When a category groups several types, the nav uses the first
+ * member type's icon; if none is set the UI falls back to a generic default.
+ */
+ icon?: ReactNode;
+ /**
+ * Human-readable display label for this artifact type, shown as the type
+ * metadata on artifact browser cards and workspace items (e.g. `"Report"`).
+ * When omitted, the UI prettifies the `type` id (never shows the raw id).
+ * Mirrors `icon` — declared via `defineArtifactRenderer({ label })`.
+ */
+ label?: string;
+}
+
+/**
+ * Identity helper that returns its argument while preserving `Props` inference.
+ *
+ * Without this, users would have to write `const r: ArtifactRendererConfig<MyProps> = {...}`
+ * to get type checking. With it, `defineArtifactRenderer({...})` infers `Props`
+ * from `parser`'s return type.
+ *
+ * @category Functions
+ *
+ * @example
+ * ```ts
+ * const presentationRenderer = defineArtifactRenderer({
+ * type: "th_presentation",
+ * toolName: ["presentation:create", "presentation:edit"],
+ * parser: ({ response }) => {
+ * const slides = response as { id: string; slides: Slide[] } | null;
+ * if (!slides) return null;
+ * return {
+ * props: slides,
+ * meta: { id: slides.id, version: 1, heading: `Presentation ${slides.id}` },
+ * };
+ * },
+ * preview: (props, controls) => <PresentationCard onOpen={controls.open} />,
+ * actual: (props) => <SlideDeck slides={props.slides} />,
+ * });
+ * ```
+ */
+export function defineArtifactRenderer<Props>(
+ config: ArtifactRendererConfig<Props>,
+): ArtifactRendererConfig<Props> {
+ return config;
+}
diff --git a/packages/react-headless/src/store/artifactTypes.ts b/packages/react-headless/src/store/artifactTypes.ts
deleted file mode 100644
index 014dd5ad7..000000000
--- a/packages/react-headless/src/store/artifactTypes.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * Read-only state slice for the artifact system.
- *
- * @category Types
- */
-export type ArtifactState = {
- /** The currently displayed artifact, or `null` if the panel is collapsed. */
- activeArtifactId: string | null;
-};
-
-/**
- * Actions for managing artifacts in the store.
- *
- * @category Types
- */
-export type ArtifactActions = {
- /** Activates an artifact by ID. */
- openArtifact: (id: string) => void;
- /**
- * Deactivates the artifact if it is the currently active one.
- * No-op if `id` does not match `activeArtifactId`.
- */
- closeArtifact: (id: string) => void;
- /**
- * Resets `activeArtifactId` to `null`.
- * Called automatically on thread switch.
- */
- resetArtifacts: () => void;
-};
-
-/**
- * Internal implementation details — not part of the public API.
- *
- * @internal
- */
-export type ArtifactInternals = {
- /** @internal */
- _artifactPanelNode: HTMLElement | null;
- /** @internal */
- _setArtifactPanelNode: (node: HTMLElement | null) => void;
-};
-
-/** Combined artifact store type (state + actions + internals). */
-export type ArtifactStore = ArtifactState & ArtifactActions & ArtifactInternals;
diff --git a/packages/react-headless/src/store/createArtifactStore.ts b/packages/react-headless/src/store/createArtifactStore.ts
deleted file mode 100644
index 070c7571a..000000000
--- a/packages/react-headless/src/store/createArtifactStore.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { createStore } from "zustand";
-import { subscribeWithSelector } from "zustand/middleware";
-import type { ArtifactStore } from "./artifactTypes";
-
-/**
- * Creates a Zustand store managing artifact state.
- * Instantiated once by `ChatProvider` — consumers should not call this directly.
- *
- * @internal
- */
-export const createArtifactStore = () => {
- return createStore<ArtifactStore>()(
- subscribeWithSelector((set, get) => ({
- activeArtifactId: null,
-
- openArtifact: (id) => {
- set({ activeArtifactId: id });
- },
-
- closeArtifact: (id) => {
- if (get().activeArtifactId === id) {
- set({ activeArtifactId: null });
- }
- },
-
- resetArtifacts: () => {
- set({ activeArtifactId: null });
- },
-
- _artifactPanelNode: null,
- _setArtifactPanelNode: (node) => {
- if (
- process.env["NODE_ENV"] !== "production" &&
- node &&
- get()._artifactPanelNode &&
- get()._artifactPanelNode !== node
- ) {
- console.warn(
- "[OpenUI] Multiple ArtifactPortalTarget instances detected. " +
- "Only one should be mounted at a time.",
- );
- }
- set({ _artifactPanelNode: node });
- },
- })),
- );
-};
diff --git a/packages/react-headless/src/store/createChatStore.ts b/packages/react-headless/src/store/createChatStore.ts
index 95e7d7fb8..ef26cfa0c 100644
--- a/packages/react-headless/src/store/createChatStore.ts
+++ b/packages/react-headless/src/store/createChatStore.ts
@@ -1,105 +1,22 @@
import { createStore } from "zustand";
import { subscribeWithSelector } from "zustand/middleware";
+import type { ChatLLM, ChatStorage } from "../adapters/types";
import { processStreamedMessage } from "../stream/processStreamedMessage";
-import { identityMessageFormat } from "../types/messageFormat";
-import type { ChatProviderProps, ChatStore, Message, Thread, UserMessage } from "./types";
+import type { ChatStore, Message, Thread, UserMessage } from "./types";
-type StoreConfig = Omit<ChatProviderProps, "children">;
+export interface CreateChatStoreConfig {
+ storage: ChatStorage;
+ llm: ChatLLM;
+}
const mergeThreadList = (existing: Thread[], incoming: Thread[]): Thread[] =>
Array.from(new Map([...existing, ...incoming].map((t) => [t.id, t])).values()).sort(
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
);
-export const createChatStore = (config: StoreConfig) => {
- const {
- apiUrl,
- threadApiUrl,
- processMessage: userProcessMessage,
- fetchThreadList: userFetchThreadList,
- createThread: userCreateThread,
- deleteThread: userDeleteThread,
- updateThread: userUpdateThread,
- loadThread: userLoadThread,
- streamProtocol,
- messageFormat = identityMessageFormat,
- } = config;
-
- // ── Default implementations (when threadApiUrl is provided) ──
-
- const fetchThreadList =
- userFetchThreadList ??
- (async (cursor?: any) => {
- if (!threadApiUrl) return { threads: [] };
- const url = cursor ? `${threadApiUrl}/get?cursor=${cursor}` : `${threadApiUrl}/get`;
- const res = await fetch(url);
- return res.json();
- });
-
- const createThread =
- userCreateThread ??
- (async (firstMessage: UserMessage) => {
- if (!threadApiUrl) throw new Error("threadApiUrl or createThread required");
- const res = await fetch(`${threadApiUrl}/create`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ messages: messageFormat.toApi([firstMessage]) }),
- });
- return res.json();
- });
-
- const deleteThreadFn =
- userDeleteThread ??
- (async (id: string) => {
- if (!threadApiUrl) return;
- await fetch(`${threadApiUrl}/delete/${id}`, { method: "DELETE" });
- });
-
- const updateThreadFn =
- userUpdateThread ??
- (async (updated: Thread) => {
- if (!threadApiUrl) return updated;
- const res = await fetch(`${threadApiUrl}/update/${updated.id}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(updated),
- });
- return res.json();
- });
-
- const loadThread =
- userLoadThread ??
- (async (threadId: string): Promise<Message[]> => {
- if (!threadApiUrl) return [];
- const res = await fetch(`${threadApiUrl}/get/${threadId}`);
- const raw: unknown = await res.json();
- return messageFormat.fromApi(raw);
- });
-
- const sendMessage =
- userProcessMessage ??
- (async ({
- threadId,
- messages,
- abortController,
- }: {
- threadId: string;
- messages: Message[];
- abortController: AbortController;
- }) => {
- if (!apiUrl) throw new Error("apiUrl or processMessage required");
- return fetch(apiUrl, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- threadId,
- messages: messageFormat.toApi(messages),
- }),
- signal: abortController.signal,
- });
- });
-
- // ── Store ──
+export const createChatStore = (config: CreateChatStoreConfig) => {
+ const { storage, llm } = config;
+ const { thread: threadStorage } = storage;
const store = createStore<ChatStore>()(
subscribeWithSelector((set, get) => ({
@@ -116,13 +33,15 @@ export const createChatStore = (config: StoreConfig) => {
isRunning: false,
isLoadingMessages: false,
threadError: null,
+ executingToolCallIds: new Set<string>(),
_abortController: null,
// ── Thread List Actions ──
loadThreads: () => {
set({ isLoadingThreads: true, threadListError: null });
- fetchThreadList(undefined)
+ threadStorage
+ .listThreads(undefined)
.then(({ threads = [], nextCursor }) => {
set({
threads,
@@ -139,7 +58,8 @@ export const createChatStore = (config: StoreConfig) => {
loadMoreThreads: () => {
const cursor = get()._nextCursor;
if (cursor === undefined) return;
- fetchThreadList(cursor)
+ threadStorage
+ .listThreads(cursor)
.then(({ threads = [], nextCursor }) => {
set((s) => ({
threads: mergeThreadList(s.threads, threads),
@@ -154,11 +74,16 @@ export const createChatStore = (config: StoreConfig) => {
switchToNewThread: () => {
get().cancelMessage();
- set({ selectedThreadId: null, messages: [], threadError: null });
+ set({
+ selectedThreadId: null,
+ messages: [],
+ threadError: null,
+ executingToolCallIds: new Set<string>(),
+ });
},
createThread: async (firstMessage: UserMessage) => {
- const thread = await createThread(firstMessage);
+ const thread = await threadStorage.createThread(firstMessage);
set((s) => ({ threads: mergeThreadList(s.threads, [thread]) }));
return thread;
},
@@ -170,8 +95,10 @@ export const createChatStore = (config: StoreConfig) => {
messages: [],
isLoadingMessages: true,
threadError: null,
+ executingToolCallIds: new Set<string>(),
});
- loadThread(threadId)
+ threadStorage
+ .getMessages(threadId)
.then((messages) => set({ messages, isLoadingMessages: false }))
.catch((e) => set({ threadError: e, isLoadingMessages: false }));
},
@@ -180,7 +107,8 @@ export const createChatStore = (config: StoreConfig) => {
const setPending = (id: string, isPending: boolean) =>
set((s) => ({ threads: s.threads.map((t) => (t.id === id ? { ...t, isPending } : t)) }));
setPending(thread.id, true);
- updateThreadFn(thread)
+ threadStorage
+ .updateThread(thread)
.then((updated) => {
set((s) => ({
threads: s.threads.map((t) => (t.id === updated.id ? updated : t)),
@@ -193,7 +121,8 @@ export const createChatStore = (config: StoreConfig) => {
const setPending = (id: string, isPending: boolean) =>
set((s) => ({ threads: s.threads.map((t) => (t.id === id ? { ...t, isPending } : t)) }));
setPending(threadId, true);
- deleteThreadFn(threadId)
+ threadStorage
+ .deleteThread(threadId)
.then(() => {
const state = get();
set({ threads: state.threads.filter((t) => t.id !== threadId) });
@@ -217,7 +146,12 @@ export const createChatStore = (config: StoreConfig) => {
role: "user",
};
- set({ _abortController: abortController, isRunning: true, threadError: null });
+ set({
+ _abortController: abortController,
+ isRunning: true,
+ threadError: null,
+ executingToolCallIds: new Set<string>(),
+ });
set((s) => ({ messages: [...s.messages, optimisticMessage] }));
abortController.signal.addEventListener("abort", () => {
@@ -228,19 +162,15 @@ export const createChatStore = (config: StoreConfig) => {
let threadId = get().selectedThreadId;
if (!threadId) {
- if (userCreateThread || threadApiUrl) {
- const created = await get().createThread(optimisticMessage);
- threadId = created.id;
- set({ selectedThreadId: threadId });
- } else {
- threadId = "ephemeral";
- }
+ const created = await get().createThread(optimisticMessage);
+ threadId = created.id;
+ set({ selectedThreadId: threadId });
}
- const response = await sendMessage({
+ const response = await llm.send({
threadId,
messages: get().messages,
- abortController,
+ signal: abortController.signal,
});
if (response instanceof Response && !response.ok) {
@@ -254,16 +184,37 @@ export const createChatStore = (config: StoreConfig) => {
set((s) => ({
messages: s.messages.map((m) => (m.id === msg.id ? msg : m)),
})),
- deleteMessage: (id) =>
- set((s) => ({ messages: s.messages.filter((m) => m.id !== id) })),
- adapter: streamProtocol,
+ // A tool's args have closed (TOOL_CALL_END) → it is now executing.
+ markToolExecuting: (id) =>
+ set((s) =>
+ s.executingToolCallIds.has(id)
+ ? s
+ : { executingToolCallIds: new Set(s.executingToolCallIds).add(id) },
+ ),
+ // Its result landed (or it errored) → no longer executing.
+ clearToolExecuting: (id) =>
+ set((s) => {
+ if (!s.executingToolCallIds.has(id)) return s;
+ const next = new Set(s.executingToolCallIds);
+ next.delete(id);
+ return { executingToolCallIds: next };
+ }),
+ adapter: llm.streamProtocol,
});
} catch (e) {
if (!abortController.signal.aborted) {
set({ threadError: e instanceof Error ? e : new Error(String(e)) });
}
} finally {
- set({ _abortController: null, isRunning: false });
+ // Clear any tool calls still flagged "executing" — adapters that emit
+ // TOOL_CALL_END without a matching TOOL_CALL_RESULT (e.g. client-side
+ // tool calls in the OpenAI adapters) would otherwise leave them stuck
+ // in the executing set after the run ends.
+ set({
+ _abortController: null,
+ isRunning: false,
+ executingToolCallIds: new Set<string>(),
+ });
}
},
diff --git a/packages/react-headless/src/store/createDetailedViewStore.ts b/packages/react-headless/src/store/createDetailedViewStore.ts
new file mode 100644
index 000000000..e9f71c3a6
--- /dev/null
+++ b/packages/react-headless/src/store/createDetailedViewStore.ts
@@ -0,0 +1,42 @@
+import { createStore } from "zustand";
+import { subscribeWithSelector } from "zustand/middleware";
+import type { DetailedViewStore } from "./detailedViewTypes";
+
+/**
+ * Creates a Zustand store managing detailed-view state.
+ * Instantiated once by `ChatProvider` — consumers should not call this directly.
+ *
+ * @internal
+ */
+export const createDetailedViewStore = () => {
+ return createStore<DetailedViewStore>()(
+ subscribeWithSelector((set, get) => ({
+ activeDetailedViewId: null,
+
+ setActiveDetailedView: (id) => {
+ set({ activeDetailedViewId: id });
+ },
+
+ reset: () => {
+ set({ activeDetailedViewId: null });
+ },
+
+ _detailedViewPanelNode: null,
+ _setDetailedViewPanelNode: (node) => {
+ if (
+ typeof process !== "undefined" &&
+ process.env?.["NODE_ENV"] !== "production" &&
+ node &&
+ get()._detailedViewPanelNode &&
+ get()._detailedViewPanelNode !== node
+ ) {
+ console.warn(
+ "[OpenUI] Multiple DetailedViewPortalTarget instances detected. " +
+ "Only one should be mounted at a time.",
+ );
+ }
+ set({ _detailedViewPanelNode: node });
+ },
+ })),
+ );
+};
diff --git a/packages/react-headless/src/store/createThreadContextStore.ts b/packages/react-headless/src/store/createThreadContextStore.ts
new file mode 100644
index 000000000..669aa18d4
--- /dev/null
+++ b/packages/react-headless/src/store/createThreadContextStore.ts
@@ -0,0 +1,81 @@
+import { createStore } from "zustand";
+import { subscribeWithSelector } from "zustand/middleware";
+import type { ArtifactEntry, ThreadContextStore } from "./threadContextTypes";
+
+const entriesEqual = (a: ArtifactEntry, b: ArtifactEntry) =>
+ a.heading === b.heading && a.type === b.type;
+
+const upsertVersion = (
+ registry: Record<string, ArtifactEntry[]>,
+ entry: ArtifactEntry,
+): Record<string, ArtifactEntry[]> => {
+ const existing = registry[entry.id] ?? [];
+ const sameVersionIdx = existing.findIndex((e) => e.version === entry.version);
+
+ if (sameVersionIdx !== -1) {
+ const current = existing[sameVersionIdx]!;
+ if (entriesEqual(current, entry)) return registry;
+ const next = existing.slice();
+ next[sameVersionIdx] = entry;
+ return { ...registry, [entry.id]: next };
+ }
+
+ // Insert sorted ascending by version.
+ const insertIdx = existing.findIndex((e) => e.version > entry.version);
+ const next =
+ insertIdx === -1
+ ? [...existing, entry]
+ : [...existing.slice(0, insertIdx), entry, ...existing.slice(insertIdx)];
+ return { ...registry, [entry.id]: next };
+};
+
+const removeVersion = (
+ registry: Record<string, ArtifactEntry[]>,
+ id: string,
+ version: number,
+): Record<string, ArtifactEntry[]> => {
+ const existing = registry[id];
+ if (!existing) return registry;
+ const idx = existing.findIndex((e) => e.version === version);
+ if (idx === -1) return registry;
+
+ if (existing.length === 1) {
+ const { [id]: _removed, ...rest } = registry;
+ return rest;
+ }
+
+ const next = existing.slice();
+ next.splice(idx, 1);
+ return { ...registry, [id]: next };
+};
+
+/**
+ * Creates a Zustand store managing the per-thread artifact registry.
+ *
+ * Active detailed-view state lives in a separate store
+ * (see {@link useDetailedView} / {@link useActiveDetailedView}) — TC tracks
+ * what's *attached* to the thread; detailed-view state tracks what's *visible*.
+ *
+ * Instantiated once by `ChatProvider` — consumers should not call this directly.
+ *
+ * @internal
+ */
+export const createThreadContextStore = () => {
+ return createStore<ThreadContextStore>()(
+ subscribeWithSelector((set) => ({
+ artifacts: {},
+
+ registerArtifact: (entry) => {
+ set((s) => ({ artifacts: upsertVersion(s.artifacts, entry) }));
+ },
+
+ unregisterArtifact: (id, version) => {
+ set((s) => ({ artifacts: removeVersion(s.artifacts, id, version) }));
+ },
+
+ reset: () => {
+ set({ artifacts: {} });
+ },
+ })),
+ );
+};
diff --git a/packages/react-headless/src/store/detailedViewTypes.ts b/packages/react-headless/src/store/detailedViewTypes.ts
new file mode 100644
index 000000000..a8b0f52f8
--- /dev/null
+++ b/packages/react-headless/src/store/detailedViewTypes.ts
@@ -0,0 +1,41 @@
+/**
+ * Read-only state slice for the detailed-view system.
+ *
+ * @category Types
+ */
+export type DetailedViewState = {
+ /** The currently displayed detailed view, or `null` if the panel is collapsed. */
+ activeDetailedViewId: string | null;
+};
+
+/**
+ * Actions for managing the active detailed view.
+ *
+ * @category Types
+ */
+export type DetailedViewActions = {
+ /**
+ * Sets which detailed view is currently active, or `null` to close the panel.
+ * Only one view is active at a time across all kinds (apps, artifacts, custom).
+ */
+ setActiveDetailedView: (id: string | null) => void;
+ /**
+ * Resets `activeDetailedViewId` to `null`. Called automatically on thread switch.
+ */
+ reset: () => void;
+};
+
+/**
+ * Internal implementation details — not part of the public API.
+ *
+ * @internal
+ */
+export type DetailedViewInternals = {
+ /** @internal */
+ _detailedViewPanelNode: HTMLElement | null;
+ /** @internal */
+ _setDetailedViewPanelNode: (node: HTMLElement | null) => void;
+};
+
+/** Combined detailed-view store type (state + actions + internals). */
+export type DetailedViewStore = DetailedViewState & DetailedViewActions & DetailedViewInternals;
diff --git a/packages/react-headless/src/store/threadContextTypes.ts b/packages/react-headless/src/store/threadContextTypes.ts
new file mode 100644
index 000000000..36a8b0081
--- /dev/null
+++ b/packages/react-headless/src/store/threadContextTypes.ts
@@ -0,0 +1,57 @@
+/**
+ * A registered artifact entry in the per-thread context.
+ *
+ * Artifacts are durable structured outputs (dashboards, presentations,
+ * reports, …) produced by tool calls. Versions for the same `id` are kept in
+ * an ordered list so the workspace can show history; the latest version
+ * (highest `version` number) is the default open target.
+ *
+ * `type` comes from the matched renderer's config and drives category
+ * grouping (see `ArtifactCategory`).
+ *
+ * @category Types
+ */
+export type ArtifactEntry = {
+ id: string;
+ version: number;
+ heading: string;
+ /** Artifact type from the renderer config, e.g. `'th_dashboard'`. */
+ type: string;
+ /** Timestamp when this artifact was registered/updated in the thread context. */
+ updatedAt?: string | number;
+};
+
+/**
+ * Read-only state slice for the ThreadContext.
+ *
+ * @category Types
+ */
+export type ThreadContextState = {
+ /** Artifacts registered in the active thread, grouped by `id`, sorted ascending by `version`. */
+ artifacts: Record<string, ArtifactEntry[]>;
+};
+
+/**
+ * Actions for managing the ThreadContext.
+ *
+ * @category Types
+ */
+export type ThreadContextActions = {
+ /**
+ * Upserts an artifact entry by `(id, version)`.
+ *
+ * - If no entry with the same `id` exists, creates a new bucket.
+ * - If a different `version` exists, inserts and keeps versions sorted ascending.
+ * - If the same `(id, version)` exists, updates `heading`/`type` (no-op when unchanged).
+ */
+ registerArtifact: (entry: ArtifactEntry) => void;
+ /** Removes an artifact version. No-op if `(id, version)` is not registered. */
+ unregisterArtifact: (id: string, version: number) => void;
+ /**
+ * Clears the registry. Called automatically on thread switch.
+ */
+ reset: () => void;
+};
+
+/** Combined ThreadContext store type (state + actions). */
+export type ThreadContextStore = ThreadContextState & ThreadContextActions;
diff --git a/packages/react-headless/src/store/toolActivity.ts b/packages/react-headless/src/store/toolActivity.ts
new file mode 100644
index 000000000..e72cd38ce
--- /dev/null
+++ b/packages/react-headless/src/store/toolActivity.ts
@@ -0,0 +1,297 @@
+import type { AssistantMessage, Message, ToolCall, ToolMessage } from "../types";
+
+/**
+ * Real per-call lifecycle of a tool invocation.
+ *
+ * Derived from AG-UI stream events (never faked from `!!content`):
+ * - `streaming` — arguments are still arriving (`TOOL_CALL_ARGS` deltas).
+ * - `executing` — arguments closed (`TOOL_CALL_END` seen), awaiting a result.
+ * - `complete` — a `TOOL_CALL_RESULT` landed without an error.
+ * - `error` — a `TOOL_CALL_RESULT`/`RUN_ERROR` carried a failure.
+ *
+ * @category Types
+ */
+export type ToolCallStatus = "streaming" | "executing" | "complete" | "error";
+
+/**
+ * Single source of truth for one tool call + its (optional) result, used by the
+ * UI layer instead of reading raw `ToolCall`/`ToolMessage` separately.
+ *
+ * Discriminated by `status` so impossible states are unrepresentable: the view
+ * literally cannot read `result`/`errorText` in a state where they don't exist,
+ * nor render an error as a success.
+ *
+ * - `streaming` → args still arriving; `input` is `Partial<T>`, no result.
+ * - `executing` → args closed; `input` is `T`, awaiting result.
+ * - `complete` → result landed OK; `input` is `T`, `result` is a string.
+ * - `error` → result landed with a failure; `errorText` present.
+ *
+ * `input` is {@link partialJSONParse}'d **once** by the selector — never a raw
+ * string for the consumer to parse.
+ *
+ * @category Types
+ */
+export type ToolActivity<T = unknown> =
+ | {
+ status: "streaming";
+ id: string;
+ toolName: string;
+ toolCall: ToolCall;
+ toolMessage: null;
+ input: Partial<T>;
+ result?: undefined;
+ isError: false;
+ errorText?: undefined;
+ statusMessage?: string;
+ }
+ | {
+ status: "executing";
+ id: string;
+ toolName: string;
+ toolCall: ToolCall;
+ toolMessage: null;
+ input: T;
+ result?: undefined;
+ isError: false;
+ errorText?: undefined;
+ statusMessage?: string;
+ }
+ | {
+ status: "complete";
+ id: string;
+ toolName: string;
+ toolCall: ToolCall;
+ toolMessage: ToolMessage;
+ input: T;
+ result: string;
+ isError: false;
+ errorText?: undefined;
+ statusMessage?: string;
+ }
+ | {
+ status: "error";
+ id: string;
+ toolName: string;
+ toolCall: ToolCall;
+ toolMessage: ToolMessage;
+ input: T;
+ result: string;
+ isError: true;
+ errorText?: string;
+ statusMessage?: string;
+ };
+
+const isDev = () => typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production";
+
+/**
+ * Closes dangling brackets/quotes for a partial (mid-stream) JSON string so it
+ * can be parsed for a best-effort snapshot. Conservative: only trims a trailing
+ * object key that is provably awaiting a value (signalled by a trailing colon),
+ * leaving complete array/values intact.
+ */
+function balanceOpenJSON(raw: string): string {
+ const closers: string[] = [];
+ let inString = false;
+ let escaped = false;
+
+ for (let i = 0; i < raw.length; i++) {
+ const ch = raw[i];
+ if (inString) {
+ if (escaped) escaped = false;
+ else if (ch === "\\") escaped = true;
+ else if (ch === '"') inString = false;
+ continue;
+ }
+ if (ch === '"') inString = true;
+ else if (ch === "{") closers.push("}");
+ else if (ch === "[") closers.push("]");
+ else if (ch === "}" || ch === "]") closers.pop();
+ }
+
+ let out = raw;
+ if (inString) {
+ // Mid-string: drop a dangling escape, then close the string literal.
+ if (escaped) out = out.slice(0, -1);
+ out += '"';
+ }
+
+ // Drop a dangling object key with no value yet (`… "key":`). The colon is the
+ // reliable "awaiting value" signal — a trailing string WITHOUT a colon may be
+ // a complete array element/value, so leave it. Then drop any exposed comma.
+ out = out.replace(/(?:,\s*)?"(?:[^"\\]|\\.)*"\s*:\s*$/, "");
+ out = out.replace(/,\s*$/, "");
+
+ for (let i = closers.length - 1; i >= 0; i--) out += closers[i];
+ return out;
+}
+
+/**
+ * Tolerant single-pass JSON parse for streamed tool arguments. Tries a straight
+ * parse, then a bracket-balanced parse for partial input. **Never throws** —
+ * returns `{}` when nothing parseable can be recovered.
+ *
+ * @category Utilities
+ */
+export function partialJSONParse(raw: string): unknown {
+ if (!raw) return {};
+ try {
+ return JSON.parse(raw);
+ } catch {
+ /* fall through to the balanced attempt */
+ }
+ try {
+ return JSON.parse(balanceOpenJSON(raw));
+ } catch {
+ return {};
+ }
+}
+
+let warnedTitle = false;
+
+/**
+ * Maps the deprecated `_title` tool-arg key onto a typed `statusMessage` for one
+ * minor release (with a one-time dev warning). Prefer a renderer-owned typed
+ * field going forward.
+ */
+function readStatusMessage(input: unknown): string | undefined {
+ if (input && typeof input === "object" && "_title" in input) {
+ const value = (input as Record<string, unknown>)["_title"];
+ if (typeof value === "string") {
+ if (isDev() && !warnedTitle) {
+ warnedTitle = true;
+ console.warn(
+ "[OpenUI] The `_title` tool-arg key is deprecated and will be removed; " +
+ "the renderer now exposes a typed `statusMessage` on ToolActivity instead.",
+ );
+ }
+ return value;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Pairs every tool call on an assistant message with its result message **by
+ * `toolCallId`** (id-keyed, no positional `break`), producing a typed
+ * {@link ToolActivity} per call. Turn-safe even when tool messages trail or
+ * interleave with other messages.
+ *
+ * @param message The assistant message owning the tool calls.
+ * @param allMessages The full thread message list (scanned for tool results).
+ * @param executingIds Tool-call ids whose args have closed but whose result
+ * hasn't landed (the store's `executingToolCallIds`).
+ *
+ * @category Utilities
+ */
+export function pairToolActivity(
+ message: AssistantMessage,
+ allMessages: ReadonlyArray<Message>,
+ executingIds: ReadonlySet<string> = new Set(),
+): ToolActivity[] {
+ const byCallId = new Map<string, ToolMessage>();
+ // Every tool-call id owned by ANY assistant message — used to detect orphan
+ // tool results (a `role:"tool"` message whose call exists nowhere).
+ const ownedCallIds = new Set<string>();
+ for (const m of allMessages) {
+ if (m.role === "tool") {
+ const tm = m as ToolMessage;
+ if (tm.toolCallId) byCallId.set(tm.toolCallId, tm);
+ } else if (m.role === "assistant") {
+ for (const tc of (m as AssistantMessage).toolCalls ?? []) ownedCallIds.add(tc.id);
+ }
+ }
+
+ const activities = (message.toolCalls ?? []).map((toolCall): ToolActivity => {
+ const toolMessage = byCallId.get(toolCall.id) ?? null;
+ const input = partialJSONParse(toolCall.function.arguments) as Record<string, unknown>;
+ const statusMessage = readStatusMessage(input);
+ const base = {
+ id: toolCall.id,
+ toolName: toolCall.function.name,
+ toolCall,
+ statusMessage,
+ };
+
+ if (toolMessage) {
+ return toolMessage.error
+ ? {
+ ...base,
+ status: "error",
+ toolMessage,
+ input: input as never,
+ result: toolMessage.content,
+ isError: true,
+ errorText: toolMessage.error,
+ }
+ : {
+ ...base,
+ status: "complete",
+ toolMessage,
+ input: input as never,
+ result: toolMessage.content,
+ isError: false,
+ };
+ }
+
+ return executingIds.has(toolCall.id)
+ ? {
+ ...base,
+ status: "executing",
+ toolMessage: null,
+ input: input as never,
+ isError: false,
+ }
+ : {
+ ...base,
+ status: "streaming",
+ toolMessage: null,
+ input: input as Partial<unknown>,
+ isError: false,
+ };
+ });
+
+ // Orphan tool results: tool messages that trail THIS assistant message but
+ // belong to no tool call anywhere. Previously these still rendered (as a
+ // generic result chip); pairing by id alone would drop them. Attribute each
+ // to the assistant message it positionally trails so it renders exactly once.
+ const msgIndex = allMessages.findIndex((m) => m.id === message.id);
+ if (msgIndex !== -1) {
+ for (let i = msgIndex + 1; i < allMessages.length; i++) {
+ const m = allMessages[i];
+ if (!m || m.role !== "tool") break;
+ const tm = m as ToolMessage;
+ if (!tm.toolCallId || ownedCallIds.has(tm.toolCallId)) continue;
+ const orphanCall: ToolCall = {
+ id: tm.toolCallId,
+ type: "function",
+ function: { name: "", arguments: "" },
+ };
+ // Key by the (unique) tool-message id, not the toolCallId — two orphan
+ // results can share a toolCallId in persisted history and would otherwise
+ // collide on the React key.
+ const base = { id: tm.id, toolName: "", toolCall: orphanCall };
+ activities.push(
+ tm.error
+ ? {
+ ...base,
+ status: "error",
+ toolMessage: tm,
+ input: {} as never,
+ result: tm.content,
+ isError: true,
+ errorText: tm.error,
+ }
+ : {
+ ...base,
+ status: "complete",
+ toolMessage: tm,
+ input: {} as never,
+ result: tm.content,
+ isError: false,
+ },
+ );
+ }
+ }
+
+ return activities;
+}
diff --git a/packages/react-headless/src/store/types.ts b/packages/react-headless/src/store/types.ts
index 8989da8b1..4ddc3c870 100644
--- a/packages/react-headless/src/store/types.ts
+++ b/packages/react-headless/src/store/types.ts
@@ -1,6 +1,6 @@
+import type { ArtifactCategory, ChatLLM, ChatStorage } from "../adapters/types";
import type { Message, UserMessage } from "../types/message";
-import type { MessageFormat } from "../types/messageFormat";
-import type { StreamProtocolAdapter } from "../types/stream";
+import type { ArtifactRendererConfig } from "./artifactRendererTypes";
export type { Message, UserMessage } from "../types/message";
export type CreateMessage = Omit<UserMessage, "id">;
@@ -39,6 +39,15 @@ export type ThreadState = {
isRunning: boolean;
isLoadingMessages: boolean;
threadError: Error | null;
+ /**
+ * Tool calls whose arguments have closed (`TOOL_CALL_END` seen) but whose
+ * result message has not yet arrived — i.e. the tool is currently executing.
+ * Drives the `"executing"` status in {@link ToolActivity}; reset to an empty
+ * set when a new message run starts or the thread switches. The reference is
+ * stable across unrelated store updates (a new `Set` is created only when the
+ * membership changes), so selector consumers don't re-render needlessly.
+ */
+ executingToolCallIds: Set<string>;
};
export type ThreadActions = {
@@ -57,48 +66,30 @@ export type ChatStore = ThreadListState &
ThreadState &
ThreadActions & {
/** @internal */
- _nextCursor?: any;
+ _nextCursor?: string | undefined;
/** @internal */
_abortController: AbortController | null;
};
// ── Provider props ──
-type ThreadApiConfig =
- | {
- threadApiUrl: string;
- fetchThreadList?: never;
- createThread?: never;
- deleteThread?: never;
- updateThread?: never;
- loadThread?: never;
- }
- | {
- threadApiUrl?: never;
- fetchThreadList?: (cursor?: any) => Promise<{ threads: Thread[]; nextCursor?: any }>;
- createThread?: (firstMessage: UserMessage) => Promise<Thread>;
- deleteThread?: (id: string) => Promise<void>;
- updateThread?: (updated: Thread) => Promise<Thread>;
- loadThread?: (threadId: string) => Promise<Message[]>;
- };
+export interface ChatProviderProps {
+ /** Optional — defaults to an internal in-memory storage (no persistence). */
+ storage?: ChatStorage;
+ /** Required — drives message sending and stream parsing. */
+ llm: ChatLLM;
+ /**
+ * Artifact renderers matched against tool calls (by `toolName`) and stored
+ * artifacts (by `type`). Captured at mount; subsequent prop changes are
+ * ignored (dev warning). Order is priority: first registration wins on
+ * duplicate `toolName`/`type`.
+ */
-type ChatApiConfig =
- | {
- apiUrl: string;
- processMessage?: never;
- }
- | {
- apiUrl?: never;
- processMessage: (params: {
- threadId: string;
- messages: Message[];
- abortController: AbortController;
- }) => Promise<Response>;
- };
-
-export type ChatProviderProps = ThreadApiConfig &
- ChatApiConfig & {
- streamProtocol?: StreamProtocolAdapter;
- messageFormat?: MessageFormat;
- children: React.ReactNode;
- };
+ artifactRenderers?: ReadonlyArray<ArtifactRendererConfig<any>>;
+ /**
+ * Global artifact categories. Drive the sidebar Artifacts split, the
+ * artifact browser's pre-applied filters, and workspace section grouping.
+ */
+ artifactCategories?: ArtifactCategory[];
+ children: React.ReactNode;
+}
diff --git a/packages/react-headless/src/stream/__tests__/processStreamedMessage.test.ts b/packages/react-headless/src/stream/__tests__/processStreamedMessage.test.ts
new file mode 100644
index 000000000..f3c98b9aa
--- /dev/null
+++ b/packages/react-headless/src/stream/__tests__/processStreamedMessage.test.ts
@@ -0,0 +1,107 @@
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import { EventType, type AGUIEvent, type Message, type StreamProtocolAdapter } from "../../types";
+import { processStreamedMessage } from "../processStreamedMessage";
+
+// jsdom is not enabled for this package; stub the rAF API used by the debouncer.
+beforeAll(() => {
+ const g = globalThis as unknown as {
+ requestAnimationFrame?: (cb: FrameRequestCallback) => number;
+ cancelAnimationFrame?: (id: number) => void;
+ };
+ if (typeof g.requestAnimationFrame !== "function") {
+ g.requestAnimationFrame = (cb: FrameRequestCallback) =>
+ setTimeout(() => cb(performance.now()), 0) as unknown as number;
+ g.cancelAnimationFrame = (id: number) => clearTimeout(id);
+ }
+});
+
+const adapterFromEvents = (events: AGUIEvent[]): StreamProtocolAdapter => ({
+ async *parse() {
+ for (const event of events) {
+ yield event;
+ }
+ },
+});
+
+const flush = () => new Promise<void>((r) => setTimeout(r, 10));
+
+describe("processStreamedMessage — TOOL_CALL_RESULT handling", () => {
+ it("creates a ToolMessage when a TOOL_CALL_RESULT event is emitted", async () => {
+ const adapter = adapterFromEvents([
+ { type: EventType.TEXT_MESSAGE_START, messageId: "msg-1", role: "assistant" },
+ {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "tc-1",
+ toolCallName: "code_block:create",
+ },
+ { type: EventType.TOOL_CALL_ARGS, toolCallId: "tc-1", delta: '{"language":"ts"}' },
+ { type: EventType.TOOL_CALL_END, toolCallId: "tc-1" },
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tc-1",
+ content: '{"ok":true}',
+ messageId: "msg-tool-1",
+ role: "tool",
+ },
+ ]);
+
+ const created: Message[] = [];
+ const updated: Message[] = [];
+
+ await processStreamedMessage({
+ response: new Response(""),
+ createMessage: (m) => created.push(m),
+ updateMessage: (m) => updated.push(m),
+ adapter,
+ });
+
+ await flush();
+
+ // Expect: one assistant message created, then one tool message created
+ expect(created).toHaveLength(2);
+ expect(created[0]?.role).toBe("assistant");
+ expect(created[1]).toMatchObject({
+ role: "tool",
+ toolCallId: "tc-1",
+ content: '{"ok":true}',
+ });
+ });
+
+ it("creates one ToolMessage per TOOL_CALL_RESULT event", async () => {
+ const adapter = adapterFromEvents([
+ { type: EventType.TEXT_MESSAGE_START, messageId: "msg-1", role: "assistant" },
+ { type: EventType.TOOL_CALL_START, toolCallId: "tc-1", toolCallName: "a" },
+ { type: EventType.TOOL_CALL_START, toolCallId: "tc-2", toolCallName: "b" },
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tc-1",
+ content: "res-1",
+ messageId: "msg-tool-1",
+ role: "tool",
+ },
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tc-2",
+ content: "res-2",
+ messageId: "msg-tool-2",
+ role: "tool",
+ },
+ ]);
+
+ const created: Message[] = [];
+
+ await processStreamedMessage({
+ response: new Response(""),
+ createMessage: (m) => created.push(m),
+ updateMessage: vi.fn(),
+ adapter,
+ });
+
+ await flush();
+
+ const toolMessages = created.filter((m) => m.role === "tool");
+ expect(toolMessages).toHaveLength(2);
+ expect(toolMessages[0]).toMatchObject({ toolCallId: "tc-1", content: "res-1" });
+ expect(toolMessages[1]).toMatchObject({ toolCallId: "tc-2", content: "res-2" });
+ });
+});
diff --git a/packages/react-headless/src/stream/__tests__/processStreamedMessageToolStatus.test.ts b/packages/react-headless/src/stream/__tests__/processStreamedMessageToolStatus.test.ts
new file mode 100644
index 000000000..2fde83492
--- /dev/null
+++ b/packages/react-headless/src/stream/__tests__/processStreamedMessageToolStatus.test.ts
@@ -0,0 +1,191 @@
+import { beforeAll, describe, expect, it } from "vitest";
+import {
+ EventType,
+ type AGUIEvent,
+ type AssistantMessage,
+ type Message,
+ type StreamProtocolAdapter,
+} from "../../types";
+import { processStreamedMessage } from "../processStreamedMessage";
+
+beforeAll(() => {
+ const g = globalThis as unknown as {
+ requestAnimationFrame?: (cb: FrameRequestCallback) => number;
+ cancelAnimationFrame?: (id: number) => void;
+ };
+ if (typeof g.requestAnimationFrame !== "function") {
+ g.requestAnimationFrame = (cb: FrameRequestCallback) =>
+ setTimeout(() => cb(performance.now()), 0) as unknown as number;
+ g.cancelAnimationFrame = (id: number) => clearTimeout(id);
+ }
+});
+
+const adapterFromEvents = (events: AGUIEvent[]): StreamProtocolAdapter => ({
+ async *parse() {
+ for (const event of events) yield event;
+ },
+});
+
+const flush = () => new Promise<void>((r) => setTimeout(r, 10));
+
+describe("processStreamedMessage — tool status + errors", () => {
+ it("marks a tool executing on TOOL_CALL_END and clears it on TOOL_CALL_RESULT", async () => {
+ const marked: string[] = [];
+ const cleared: string[] = [];
+ const created: Message[] = [];
+
+ await processStreamedMessage({
+ response: new Response(""),
+ createMessage: (m) => created.push(m),
+ updateMessage: () => {},
+ markToolExecuting: (id) => marked.push(id),
+ clearToolExecuting: (id) => cleared.push(id),
+ adapter: adapterFromEvents([
+ { type: EventType.TEXT_MESSAGE_START, messageId: "m1", role: "assistant" },
+ { type: EventType.TOOL_CALL_START, toolCallId: "tc-1", toolCallName: "search" },
+ { type: EventType.TOOL_CALL_ARGS, toolCallId: "tc-1", delta: "{}" },
+ { type: EventType.TOOL_CALL_END, toolCallId: "tc-1" },
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tc-1",
+ content: "ok",
+ messageId: "tm-1",
+ role: "tool",
+ },
+ ]),
+ });
+ await flush();
+
+ expect(marked).toEqual(["tc-1"]);
+ expect(cleared).toEqual(["tc-1"]);
+ });
+
+ it("surfaces isError/error from TOOL_CALL_RESULT onto ToolMessage.error", async () => {
+ const created: Message[] = [];
+
+ await processStreamedMessage({
+ response: new Response(""),
+ createMessage: (m) => created.push(m),
+ updateMessage: () => {},
+ adapter: adapterFromEvents([
+ { type: EventType.TOOL_CALL_START, toolCallId: "tc-1", toolCallName: "search" },
+ // passthrough fields on the result event signal a failure
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tc-1",
+ content: "boom",
+ messageId: "tm-1",
+ role: "tool",
+ isError: true,
+ error: "tool exploded",
+ } as unknown as AGUIEvent,
+ ]),
+ });
+ await flush();
+
+ const toolMessage = created.find((m) => m.role === "tool");
+ expect(toolMessage).toBeDefined();
+ expect((toolMessage as { error?: string }).error).toBe("tool exploded");
+ });
+
+ it("rejects on RUN_ERROR without synthesizing an empty tool message for a result-less in-flight call", async () => {
+ const created: Message[] = [];
+
+ await expect(
+ processStreamedMessage({
+ response: new Response(""),
+ createMessage: (m) => created.push(m),
+ updateMessage: () => {},
+ adapter: adapterFromEvents([
+ { type: EventType.TOOL_CALL_START, toolCallId: "tc-1", toolCallName: "search" },
+ { type: EventType.RUN_ERROR, message: "stream blew up" } as AGUIEvent,
+ ]),
+ }),
+ ).rejects.toThrow("stream blew up");
+
+ // The in-flight call never streamed a result, so NO empty-content tool
+ // message is created (that would blank an in-flight renderer). The error
+ // surfaces as the thrown thread-level error instead.
+ expect(created.find((m) => m.role === "tool")).toBeUndefined();
+ });
+
+ it("keeps an already-delivered tool result intact when RUN_ERROR fires afterwards", async () => {
+ const created: Message[] = [];
+
+ await expect(
+ processStreamedMessage({
+ response: new Response(""),
+ createMessage: (m) => created.push(m),
+ updateMessage: () => {},
+ adapter: adapterFromEvents([
+ { type: EventType.TOOL_CALL_START, toolCallId: "tc-1", toolCallName: "search" },
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tc-1",
+ content: "the result",
+ messageId: "tm-1",
+ role: "tool",
+ },
+ { type: EventType.RUN_ERROR, message: "stream blew up" } as AGUIEvent,
+ ]),
+ }),
+ ).rejects.toThrow("stream blew up");
+
+ await flush();
+
+ // A delivered result is NOT retroactively errored by a later RUN_ERROR.
+ const toolMessage = created.find((m) => m.role === "tool");
+ expect(toolMessage).toBeDefined();
+ expect((toolMessage as { content?: string }).content).toBe("the result");
+ expect((toolMessage as { error?: string }).error).toBeUndefined();
+ });
+
+ it("handles TOOL_CALL_CHUNK: lazily starts the call and accumulates streamed args", async () => {
+ const created: Message[] = [];
+ const updated: Message[] = [];
+
+ const result = await processStreamedMessage({
+ response: new Response(""),
+ createMessage: (m) => created.push(m),
+ updateMessage: (m) => updated.push(m),
+ adapter: adapterFromEvents([
+ // First chunk carries the id + name (acts as START) plus an args fragment.
+ {
+ type: EventType.TOOL_CALL_CHUNK,
+ toolCallId: "tc-1",
+ toolCallName: "search",
+ delta: '{"q":',
+ },
+ // Subsequent chunks carry only the delta (act as ARGS).
+ { type: EventType.TOOL_CALL_CHUNK, toolCallId: "tc-1", delta: '"hi"}' },
+ ] as unknown as AGUIEvent[]),
+ });
+ await flush();
+
+ const assistant = result as AssistantMessage;
+ expect(assistant?.toolCalls).toHaveLength(1);
+ const tc = assistant.toolCalls![0]!;
+ expect(tc.id).toBe("tc-1");
+ expect(tc.function.name).toBe("search");
+ expect(tc.function.arguments).toBe('{"q":"hi"}');
+ });
+
+ it("fills a TOOL_CALL_CHUNK tool name that arrives on a later chunk than the id", async () => {
+ const result = await processStreamedMessage({
+ response: new Response(""),
+ createMessage: () => {},
+ updateMessage: () => {},
+ adapter: adapterFromEvents([
+ { type: EventType.TOOL_CALL_CHUNK, toolCallId: "tc-2", delta: "" },
+ { type: EventType.TOOL_CALL_CHUNK, toolCallId: "tc-2", toolCallName: "lookup" },
+ { type: EventType.TOOL_CALL_CHUNK, toolCallId: "tc-2", delta: "{}" },
+ ] as unknown as AGUIEvent[]),
+ });
+ await flush();
+
+ const tc = (result as AssistantMessage).toolCalls?.[0];
+ expect(tc?.id).toBe("tc-2");
+ expect(tc?.function.name).toBe("lookup");
+ expect(tc?.function.arguments).toBe("{}");
+ });
+});
diff --git a/packages/react-headless/src/stream/adapters/__tests__/sseLines.test.ts b/packages/react-headless/src/stream/adapters/__tests__/sseLines.test.ts
new file mode 100644
index 000000000..f85c8f283
--- /dev/null
+++ b/packages/react-headless/src/stream/adapters/__tests__/sseLines.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+import { sseLineIterator } from "../_shared/sseLines";
+
+function responseFromChunks(chunks: string[]): Response {
+ const encoder = new TextEncoder();
+ const stream = new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const c of chunks) controller.enqueue(encoder.encode(c));
+ controller.close();
+ },
+ });
+ return new Response(stream);
+}
+
+async function collect(res: Response): Promise<string[]> {
+ const out: string[] = [];
+ for await (const line of sseLineIterator(res)) out.push(line);
+ return out;
+}
+
+describe("sseLineIterator", () => {
+ it("reassembles a line split across network chunks", async () => {
+ // "data: line1" is split mid-token between two chunks.
+ const res = responseFromChunks(["da", "ta: line1\nda", "ta: line2\n"]);
+ expect(await collect(res)).toEqual(["data: line1", "data: line2"]);
+ });
+
+ it("flushes a trailing line with no final newline", async () => {
+ const res = responseFromChunks(["data: a\n", "data: b"]);
+ expect(await collect(res)).toEqual(["data: a", "data: b"]);
+ });
+
+ it("skips blank lines", async () => {
+ const res = responseFromChunks(["data: a\n\n\n", "data: b\n"]);
+ expect(await collect(res)).toEqual(["data: a", "data: b"]);
+ });
+
+ it("handles a JSON event split exactly at a brace across chunks", async () => {
+ const res = responseFromChunks(['data: {"hello":', '"world"}\n']);
+ expect(await collect(res)).toEqual(['data: {"hello":"world"}']);
+ });
+});
diff --git a/packages/react-headless/src/stream/adapters/_shared/sseLines.ts b/packages/react-headless/src/stream/adapters/_shared/sseLines.ts
new file mode 100644
index 000000000..496e1ea9e
--- /dev/null
+++ b/packages/react-headless/src/stream/adapters/_shared/sseLines.ts
@@ -0,0 +1,40 @@
+/**
+ * Shared line iterator for streamed HTTP responses.
+ *
+ * Buffers the leftover partial line between network chunks so an SSE event (or
+ * NDJSON record) split across two `reader.read()` results is reassembled rather
+ * than silently dropped. The reference implementation lived in
+ * `openai-readable-stream.ts`; this extracts it so `ag-ui.ts` and
+ * `openai-completions.ts` share the same correct buffering.
+ *
+ * Yields each complete line verbatim (caller strips any `data: ` SSE prefix);
+ * blank lines are skipped. The trailing buffered line is flushed on stream end.
+ *
+ * @internal
+ */
+export async function* sseLineIterator(response: Response): AsyncGenerator<string> {
+ const reader = response.body?.getReader();
+ if (!reader) throw new Error("No response body");
+
+ const decoder = new TextDecoder();
+ let buffer = "";
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split("\n");
+ // Keep the straddling partial line (everything after the last "\n") for the
+ // next chunk; it may be completed by the bytes that follow.
+ buffer = lines.pop() ?? "";
+
+ for (const line of lines) {
+ if (line.trim()) yield line;
+ }
+ }
+
+ // Flush the tail — a stream that ends without a trailing newline still has a
+ // complete final line sitting in the buffer.
+ if (buffer.trim()) yield buffer;
+}
diff --git a/packages/react-headless/src/stream/adapters/ag-ui.ts b/packages/react-headless/src/stream/adapters/ag-ui.ts
index e934b0726..35691cbc8 100644
--- a/packages/react-headless/src/stream/adapters/ag-ui.ts
+++ b/packages/react-headless/src/stream/adapters/ag-ui.ts
@@ -1,30 +1,18 @@
import { AGUIEvent, StreamProtocolAdapter } from "../../types";
+import { sseLineIterator } from "./_shared/sseLines";
export const agUIAdapter = (): StreamProtocolAdapter => ({
async *parse(response: Response): AsyncIterable<AGUIEvent> {
- const reader = response.body?.getReader();
- if (!reader) throw new Error("No response body");
+ for await (const line of sseLineIterator(response)) {
+ if (!line.startsWith("data: ")) continue;
+ const data = line.slice(6).trim();
+ if (!data || data === "[DONE]") continue;
- const decoder = new TextDecoder();
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
-
- const chunk = decoder.decode(value, { stream: true });
- const lines = chunk.split("\n");
-
- for (const line of lines) {
- if (!line.startsWith("data: ")) continue;
- const data = line.slice(6).trim();
- if (!data || data === "[DONE]") continue;
-
- try {
- const event = JSON.parse(data);
- yield event as AGUIEvent;
- } catch (e) {
- console.error("Failed to parse SSE event", e);
- }
+ try {
+ const event = JSON.parse(data);
+ yield event as AGUIEvent;
+ } catch (e) {
+ console.error("Failed to parse SSE event", e);
}
}
},
diff --git a/packages/react-headless/src/stream/adapters/langgraph.ts b/packages/react-headless/src/stream/adapters/langgraph.ts
index 8cc58fd17..60749204a 100644
--- a/packages/react-headless/src/stream/adapters/langgraph.ts
+++ b/packages/react-headless/src/stream/adapters/langgraph.ts
@@ -73,15 +73,17 @@ export const langGraphAdapter = (options?: LangGraphAdapterOptions): StreamProto
while (true) {
const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
+ // Accumulate across reads: an SSE event block (e.g. a multi-KB artifact
+ // function_call_arguments payload) can span several network reads. Hold the
+ // trailing partial block until the next read; on done, flush what remains
+ // (the old early `if (done) break` dropped the final un-terminated block).
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
- // SSE events are separated by double newlines.
- // Split on \n\n to get complete event blocks, keeping the last
- // (possibly incomplete) block in the buffer.
+ // SSE events are separated by double newlines; keep the last (possibly
+ // incomplete) block in the buffer until more arrives.
const blocks = buffer.split("\n\n");
- buffer = blocks.pop() ?? "";
+ buffer = done ? "" : (blocks.pop() ?? "");
for (const block of blocks) {
const trimmed = block.trim();
@@ -249,6 +251,8 @@ export const langGraphAdapter = (options?: LangGraphAdapterOptions): StreamProto
break;
}
}
+
+ if (done) break;
}
// If stream ended without an explicit "end" event, close out.
diff --git a/packages/react-headless/src/stream/adapters/openai-completions.ts b/packages/react-headless/src/stream/adapters/openai-completions.ts
index d45ca9be8..5cc4445c2 100644
--- a/packages/react-headless/src/stream/adapters/openai-completions.ts
+++ b/packages/react-headless/src/stream/adapters/openai-completions.ts
@@ -1,96 +1,85 @@
import type { ChatCompletionChunk } from "openai/resources/chat/completions";
import { AGUIEvent, EventType, StreamProtocolAdapter } from "../../types";
+import { sseLineIterator } from "./_shared/sseLines";
export const openAIAdapter = (): StreamProtocolAdapter => ({
async *parse(response: Response): AsyncIterable<AGUIEvent> {
- const reader = response.body?.getReader();
- if (!reader) throw new Error("No response body");
-
- const decoder = new TextDecoder();
const messageId = crypto.randomUUID();
const toolCallIds: Record<number, string> = {};
let messageStarted = false;
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
-
- const chunk = decoder.decode(value, { stream: true });
- const lines = chunk.split("\n");
+ for await (const line of sseLineIterator(response)) {
+ if (!line.startsWith("data: ")) continue;
+ const data = line.slice(6).trim();
+ if (!data || data === "[DONE]") continue;
- for (const line of lines) {
- if (!line.startsWith("data: ")) continue;
- const data = line.slice(6).trim();
- if (!data || data === "[DONE]") continue;
+ try {
+ const json = JSON.parse(data) as ChatCompletionChunk;
+ const choice = json.choices?.[0];
+ const delta = choice?.delta;
- try {
- const json = JSON.parse(data) as ChatCompletionChunk;
- const choice = json.choices?.[0];
- const delta = choice?.delta;
+ if (!delta) continue;
- if (!delta) continue;
+ // Emit TEXT_MESSAGE_START on first meaningful delta
+ if (!messageStarted && (delta.content || delta.role)) {
+ yield {
+ type: EventType.TEXT_MESSAGE_START,
+ messageId,
+ role: "assistant",
+ };
+ messageStarted = true;
+ }
- // Emit TEXT_MESSAGE_START on first meaningful delta
- if (!messageStarted && (delta.content || delta.role)) {
- yield {
- type: EventType.TEXT_MESSAGE_START,
- messageId,
- role: "assistant",
- };
- messageStarted = true;
- }
+ if (delta.content) {
+ yield {
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ messageId,
+ delta: delta.content,
+ };
+ }
- if (delta.content) {
- yield {
- type: EventType.TEXT_MESSAGE_CONTENT,
- messageId,
- delta: delta.content,
- };
- }
+ if (delta.tool_calls) {
+ for (const toolCall of delta.tool_calls) {
+ const index = toolCall.index;
- if (delta.tool_calls) {
- for (const toolCall of delta.tool_calls) {
- const index = toolCall.index;
+ if (toolCall.id) {
+ toolCallIds[index] = toolCall.id;
+ yield {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: toolCall.id,
+ toolCallName: toolCall.function?.name || "",
+ };
+ }
- if (toolCall.id) {
- toolCallIds[index] = toolCall.id;
+ if (toolCall.function?.arguments) {
+ const toolCallId = toolCallIds[index];
+ if (toolCallId) {
yield {
- type: EventType.TOOL_CALL_START,
- toolCallId: toolCall.id,
- toolCallName: toolCall.function?.name || "",
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId,
+ delta: toolCall.function.arguments,
};
}
-
- if (toolCall.function?.arguments) {
- const toolCallId = toolCallIds[index];
- if (toolCallId) {
- yield {
- type: EventType.TOOL_CALL_ARGS,
- toolCallId,
- delta: toolCall.function.arguments,
- };
- }
- }
}
}
+ }
- // Emit end events based on finish_reason
- if (choice?.finish_reason === "stop") {
+ // Emit end events based on finish_reason
+ if (choice?.finish_reason === "stop") {
+ yield {
+ type: EventType.TEXT_MESSAGE_END,
+ messageId,
+ };
+ } else if (choice?.finish_reason === "tool_calls") {
+ for (const toolCallId of Object.values(toolCallIds)) {
yield {
- type: EventType.TEXT_MESSAGE_END,
- messageId,
+ type: EventType.TOOL_CALL_END,
+ toolCallId,
};
- } else if (choice?.finish_reason === "tool_calls") {
- for (const toolCallId of Object.values(toolCallIds)) {
- yield {
- type: EventType.TOOL_CALL_END,
- toolCallId,
- };
- }
}
- } catch (e) {
- console.error("Failed to parse OpenAI SSE event", e);
}
+ } catch (e) {
+ console.error("Failed to parse OpenAI SSE event", e);
}
}
},
diff --git a/packages/react-headless/src/stream/adapters/openai-readable-stream.ts b/packages/react-headless/src/stream/adapters/openai-readable-stream.ts
index 9497a4ad1..f13773d24 100644
--- a/packages/react-headless/src/stream/adapters/openai-readable-stream.ts
+++ b/packages/react-headless/src/stream/adapters/openai-readable-stream.ts
@@ -1,5 +1,6 @@
import type { ChatCompletionChunk } from "openai/resources/chat/completions";
import { AGUIEvent, EventType, StreamProtocolAdapter } from "../../types";
+import { sseLineIterator } from "./_shared/sseLines";
/**
* Adapter for streams produced by the OpenAI SDK's `Stream.toReadableStream()`.
@@ -8,93 +9,79 @@ import { AGUIEvent, EventType, StreamProtocolAdapter } from "../../types";
*/
export const openAIReadableStreamAdapter = (): StreamProtocolAdapter => ({
async *parse(response: Response): AsyncIterable<AGUIEvent> {
- const reader = response.body?.getReader();
- if (!reader) throw new Error("No response body");
-
- const decoder = new TextDecoder();
const messageId = crypto.randomUUID();
const toolCallIds: Record<number, string> = {};
let messageStarted = false;
- let buffer = "";
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split("\n");
- buffer = lines.pop() ?? "";
+ for await (const line of sseLineIterator(response)) {
+ const data = line.trim();
+ if (!data) continue;
- for (const line of lines) {
- const data = line.trim();
- if (!data) continue;
+ try {
+ const json = JSON.parse(data) as ChatCompletionChunk;
+ const choice = json.choices?.[0];
+ const delta = choice?.delta;
- try {
- const json = JSON.parse(data) as ChatCompletionChunk;
- const choice = json.choices?.[0];
- const delta = choice?.delta;
+ if (!delta) continue;
- if (!delta) continue;
+ if (!messageStarted && (delta.content || delta.role)) {
+ yield {
+ type: EventType.TEXT_MESSAGE_START,
+ messageId,
+ role: "assistant",
+ };
+ messageStarted = true;
+ }
- if (!messageStarted && (delta.content || delta.role)) {
- yield {
- type: EventType.TEXT_MESSAGE_START,
- messageId,
- role: "assistant",
- };
- messageStarted = true;
- }
+ if (delta.content) {
+ yield {
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ messageId,
+ delta: delta.content,
+ };
+ }
- if (delta.content) {
- yield {
- type: EventType.TEXT_MESSAGE_CONTENT,
- messageId,
- delta: delta.content,
- };
- }
+ if (delta.tool_calls) {
+ for (const toolCall of delta.tool_calls) {
+ const index = toolCall.index;
- if (delta.tool_calls) {
- for (const toolCall of delta.tool_calls) {
- const index = toolCall.index;
+ if (toolCall.id) {
+ toolCallIds[index] = toolCall.id;
+ yield {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: toolCall.id,
+ toolCallName: toolCall.function?.name || "",
+ };
+ }
- if (toolCall.id) {
- toolCallIds[index] = toolCall.id;
+ if (toolCall.function?.arguments) {
+ const toolCallId = toolCallIds[index];
+ if (toolCallId) {
yield {
- type: EventType.TOOL_CALL_START,
- toolCallId: toolCall.id,
- toolCallName: toolCall.function?.name || "",
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId,
+ delta: toolCall.function.arguments,
};
}
-
- if (toolCall.function?.arguments) {
- const toolCallId = toolCallIds[index];
- if (toolCallId) {
- yield {
- type: EventType.TOOL_CALL_ARGS,
- toolCallId,
- delta: toolCall.function.arguments,
- };
- }
- }
}
}
+ }
- if (choice?.finish_reason === "stop") {
+ if (choice?.finish_reason === "stop") {
+ yield {
+ type: EventType.TEXT_MESSAGE_END,
+ messageId,
+ };
+ } else if (choice?.finish_reason === "tool_calls") {
+ for (const toolCallId of Object.values(toolCallIds)) {
yield {
- type: EventType.TEXT_MESSAGE_END,
- messageId,
+ type: EventType.TOOL_CALL_END,
+ toolCallId,
};
- } else if (choice?.finish_reason === "tool_calls") {
- for (const toolCallId of Object.values(toolCallIds)) {
- yield {
- type: EventType.TOOL_CALL_END,
- toolCallId,
- };
- }
}
- } catch (e) {
- console.error("Failed to parse OpenAI NDJSON chunk", e);
}
+ } catch (e) {
+ console.error("Failed to parse OpenAI NDJSON chunk", e);
}
}
},
diff --git a/packages/react-headless/src/stream/adapters/openai-responses.ts b/packages/react-headless/src/stream/adapters/openai-responses.ts
index 17c0ea94b..3b912f11b 100644
--- a/packages/react-headless/src/stream/adapters/openai-responses.ts
+++ b/packages/react-headless/src/stream/adapters/openai-responses.ts
@@ -1,4 +1,7 @@
-import type { ResponseStreamEvent } from "openai/resources/responses/responses";
+import type {
+ ResponseFunctionToolCallOutputItem,
+ ResponseStreamEvent,
+} from "openai/resources/responses/responses";
import { AGUIEvent, EventType, StreamProtocolAdapter } from "../../types";
export const openAIResponsesAdapter = (): StreamProtocolAdapter => ({
@@ -10,12 +13,17 @@ export const openAIResponsesAdapter = (): StreamProtocolAdapter => ({
// Map item_id → call_id so TOOL_CALL_ARGS can reference the correct toolCallId
const itemIdToCallId: Record<string, string> = {};
+ let buffer = "";
while (true) {
const { done, value } = await reader.read();
- if (done) break;
-
- const chunk = decoder.decode(value, { stream: true });
- const lines = chunk.split("\n");
+ // Accumulate across reads: a single SSE `data:` line (e.g. a multi-KB
+ // artifact function_call_output payload) can span several network
+ // chunks. Splitting each chunk independently tears that line in two and
+ // drops it on JSON.parse. Hold the trailing partial line until the next
+ // read; on done, flush whatever remains.
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
+ const lines = buffer.split("\n");
+ buffer = done ? "" : (lines.pop() ?? "");
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
@@ -27,7 +35,10 @@ export const openAIResponsesAdapter = (): StreamProtocolAdapter => ({
switch (event.type) {
case "response.output_item.added": {
- const item = event.item;
+ // OpenAI's Conversations API surfaces function_call_output as an
+ // output item even though the SDK's ResponseOutputItem union does
+ // not declare it. Widen the type so we can branch on it below.
+ const item = event.item as typeof event.item | ResponseFunctionToolCallOutputItem;
if (item.type === "message" && item.role === "assistant") {
yield {
type: EventType.TEXT_MESSAGE_START,
@@ -42,6 +53,17 @@ export const openAIResponsesAdapter = (): StreamProtocolAdapter => ({
toolCallId: item.call_id,
toolCallName: item.name,
};
+ } else if (item.type === "function_call_output") {
+ // Fired when a function_call_output we submitted as input is
+ // integrated into a conversation-linked response — surfaces
+ // server-side tool execution to the SDK store.
+ yield {
+ type: EventType.TOOL_CALL_RESULT,
+ messageId: item.id,
+ toolCallId: item.call_id,
+ content:
+ typeof item.output === "string" ? item.output : JSON.stringify(item.output),
+ };
}
break;
}
@@ -107,6 +129,7 @@ export const openAIResponsesAdapter = (): StreamProtocolAdapter => ({
console.error("Failed to parse OpenAI Responses SSE event", e);
}
}
+ if (done) break;
}
},
});
diff --git a/packages/react-headless/src/stream/formats/openai-conversation-message-format.ts b/packages/react-headless/src/stream/formats/openai-conversation-message-format.ts
index 04d376f00..fc74a83cd 100644
--- a/packages/react-headless/src/stream/formats/openai-conversation-message-format.ts
+++ b/packages/react-headless/src/stream/formats/openai-conversation-message-format.ts
@@ -118,15 +118,34 @@ function toInputMessage(message: UserMessage): EasyInputMessage {
function fromItems(items: ConversationItem[]): Message[] {
const messages: Message[] = [];
let currentAssistant: AssistantMessage | null = null;
+ // Tool outputs for the in-progress assistant turn. BUFFERED rather than
+ // pushed immediately so that an assistant turn with MULTIPLE tool calls
+ // (e.g. thesys_get_artifact_description THEN thesys_generate_artifact)
+ // reconstructs as ONE assistant message + its tool messages — matching the
+ // live stream shape — instead of one assistant message PER tool call. The
+ // latter renders a duplicate "Behind the scenes" group for every call on
+ // reload, because each function_call_output used to flush the assistant.
+ let pendingToolMsgs: ToolMessage[] = [];
+
+ // Emit the in-progress assistant turn: the assistant message first, then its
+ // buffered tool results (the renderer pairs tool messages that immediately
+ // follow their assistant message).
+ const flushAssistant = () => {
+ if (currentAssistant) {
+ messages.push(currentAssistant);
+ currentAssistant = null;
+ }
+ if (pendingToolMsgs.length > 0) {
+ messages.push(...pendingToolMsgs);
+ pendingToolMsgs = [];
+ }
+ };
for (const item of items) {
switch (item.type) {
case "message": {
- // Flush any pending assistant message
- if (currentAssistant) {
- messages.push(currentAssistant);
- currentAssistant = null;
- }
+ // A non-tool message ends the current assistant turn.
+ flushAssistant();
const msg = item as ConversationMessage;
@@ -180,13 +199,10 @@ function fromItems(items: ConversationItem[]): Message[] {
}
case "function_call_output": {
- if (currentAssistant) {
- messages.push(currentAssistant);
- currentAssistant = null;
- }
-
+ // Buffer alongside the current assistant — do NOT flush here, so
+ // sibling tool calls in the same turn stay on one assistant message.
const output = item as ResponseFunctionToolCallOutputItem;
- messages.push({
+ pendingToolMsgs.push({
id: output.id,
role: "tool",
content:
@@ -202,9 +218,7 @@ function fromItems(items: ConversationItem[]): Message[] {
}
}
- if (currentAssistant) {
- messages.push(currentAssistant);
- }
+ flushAssistant();
return messages;
}
diff --git a/packages/react-headless/src/stream/processStreamedMessage.ts b/packages/react-headless/src/stream/processStreamedMessage.ts
index 507f28c2a..0be567fa0 100644
--- a/packages/react-headless/src/stream/processStreamedMessage.ts
+++ b/packages/react-headless/src/stream/processStreamedMessage.ts
@@ -1,4 +1,4 @@
-import { AssistantMessage, EventType, StreamProtocolAdapter } from "../types";
+import { AssistantMessage, EventType, Message, StreamProtocolAdapter, ToolMessage } from "../types";
import { agUIAdapter } from "./adapters";
/**
@@ -6,12 +6,18 @@ import { agUIAdapter } from "./adapters";
*/
interface Parameters {
response: Response;
- /** A function that creates a new assistant message in the thread */
- createMessage: (message: AssistantMessage) => void;
- /** A function that updates an existing assistant message in the thread */
- updateMessage: (message: AssistantMessage) => void;
- /** A function that deletes an assistant message from the thread */
- deleteMessage: (messageId: string) => void;
+ /** A function that creates a new message in the thread (assistant or tool). */
+ createMessage: (message: Message) => void;
+ /** A function that updates an existing message in the thread (matched by id). */
+ updateMessage: (message: Message) => void;
+ /**
+ * Marks a tool call as executing (args closed, awaiting result). Wired to the
+ * store's `executingToolCallIds` set so `pairToolActivity` can report the
+ * `"executing"` status. Optional — defaults to a no-op for standalone use.
+ */
+ markToolExecuting?: (toolCallId: string) => void;
+ /** Clears a tool call from the executing set (result landed or errored). */
+ clearToolExecuting?: (toolCallId: string) => void;
/** The adapter to use for parsing the stream */
adapter?: StreamProtocolAdapter;
}
@@ -23,7 +29,8 @@ export const processStreamedMessage = async ({
response,
createMessage,
updateMessage,
- deleteMessage,
+ markToolExecuting = () => {},
+ clearToolExecuting = () => {},
adapter = agUIAdapter(),
}: Parameters): Promise<AssistantMessage | void> => {
let currentMessage: AssistantMessage = {
@@ -35,6 +42,14 @@ export const processStreamedMessage = async ({
let isFirst = true;
+ // Tool messages by toolCallId, so repeated TOOL_CALL_RESULTs for the same
+ // call UPDATE one message in place instead of duplicating it.
+ const toolMessagesByCallId = new Map<string, ToolMessage>();
+
+ // Tool calls that have started but not yet received a result. On RUN_ERROR
+ // these are surfaced as errored tool messages instead of being left hanging.
+ const inFlightToolCallIds = new Set<string>();
+
let rafId: number | null = null;
const debouncedUpdate = (msg: AssistantMessage) => {
if (rafId !== null) cancelAnimationFrame(rafId);
@@ -58,6 +73,7 @@ export const processStreamedMessage = async ({
break;
case EventType.TOOL_CALL_START:
+ inFlightToolCallIds.add(event.toolCallId);
currentMessage = {
...currentMessage,
toolCalls: [
@@ -74,6 +90,13 @@ export const processStreamedMessage = async ({
};
break;
+ case EventType.TOOL_CALL_END:
+ // Args have finished arriving → the call is now executing (awaiting its
+ // result), not "streaming". Previously this event was dropped and
+ // completion was faked from "did assistant text start".
+ markToolExecuting(event.toolCallId);
+ break;
+
case EventType.TOOL_CALL_ARGS:
if (currentMessage.toolCalls) {
const toolCalls = [...currentMessage.toolCalls];
@@ -95,18 +118,109 @@ export const processStreamedMessage = async ({
}
break;
- case EventType.TEXT_MESSAGE_START:
- // Use the ID from the event if it differs from our optimistic ID
- if (event.messageId !== currentMessage.id) {
- deleteMessage(currentMessage.id);
- currentMessage = { ...currentMessage, id: event.messageId };
- isFirst = true; // Will trigger createMessage with new ID
+ case EventType.TOOL_CALL_CHUNK: {
+ // Combined convenience form of START + ARGS (AG-UI). Some servers emit
+ // only chunks instead of the explicit START/ARGS/END triad; without
+ // this case their tool calls would be silently dropped. Lazily START on
+ // the first chunk carrying an id, fill the name if it arrives on a later
+ // chunk, and append any `delta` as ARGS. (No END is implied — a
+ // chunk-only call stays "streaming" until its result lands.)
+ const id = event.toolCallId;
+ if (!id) break;
+ const toolCalls = [...(currentMessage.toolCalls || [])];
+ let index = toolCalls.findIndex((tc) => tc.id === id);
+ if (index === -1) {
+ inFlightToolCallIds.add(id);
+ toolCalls.push({
+ id,
+ type: "function",
+ function: { name: event.toolCallName ?? "", arguments: "" },
+ });
+ index = toolCalls.length - 1;
+ }
+ const existing = toolCalls[index];
+ if (existing) {
+ toolCalls[index] = {
+ id: existing.id,
+ type: "function",
+ function: {
+ name: existing.function.name || event.toolCallName || "",
+ arguments: existing.function.arguments + (event.delta ?? ""),
+ },
+ };
+ currentMessage = { ...currentMessage, toolCalls };
}
break;
+ }
+
+ case EventType.TEXT_MESSAGE_START:
+ // The optimistic id is kept regardless of `event.messageId` — swapping
+ // ids mid-stream by deleting + re-creating the assistant message
+ // breaks ordering when tool messages have already been appended
+ // between the original create and this event (e.g. from
+ // TOOL_CALL_RESULT). Persistence layers should map ids on save.
+ break;
+
+ case EventType.TOOL_CALL_RESULT: {
+ // Result landed → no longer executing / in flight.
+ clearToolExecuting(event.toolCallId);
+ inFlightToolCallIds.delete(event.toolCallId);
+
+ // Surface a failure onto the @ag-ui/core ToolMessage.error field. The
+ // TOOL_CALL_RESULT schema is `passthrough`, so adapters may carry an
+ // `isError` flag and/or `error` string; map either onto `error` so the
+ // selector can emit `status:"error"` (the previously-dead error branch
+ // in ToolResult lights up). Absent any failure signal it stays a
+ // success — no regression vs. today.
+ const failed = event as unknown as { isError?: boolean; error?: string };
+ const errorText =
+ failed.isError === true || (typeof failed.error === "string" && failed.error.length > 0)
+ ? (failed.error ?? event.content)
+ : undefined;
+
+ // Upsert the tool message for this toolCallId. First result → create;
+ // any subsequent result for the same call → update the same message in
+ // place (no duplicates).
+ const existing = toolMessagesByCallId.get(event.toolCallId);
+ if (existing) {
+ const updated: ToolMessage = {
+ ...existing,
+ content: event.content,
+ ...(errorText ? { error: errorText } : {}),
+ };
+ toolMessagesByCallId.set(event.toolCallId, updated);
+ updateMessage(updated);
+ } else {
+ const toolMessage: ToolMessage = {
+ id: crypto.randomUUID(),
+ role: "tool",
+ toolCallId: event.toolCallId,
+ content: event.content,
+ ...(errorText ? { error: errorText } : {}),
+ };
+ toolMessagesByCallId.set(event.toolCallId, toolMessage);
+ createMessage(toolMessage);
+ }
+ continue; // skip the trailing isFirst/update logic — this event doesn't touch currentMessage
+ }
case EventType.RUN_ERROR: {
- const msg = (event as any).message || (event as any).error || "Stream error";
- throw new Error(typeof msg === "string" ? msg : JSON.stringify(msg));
+ const raw = (event as any).message || (event as any).error || "Stream error";
+ const errorText = typeof raw === "string" ? raw : JSON.stringify(raw);
+
+ // RUN_ERROR carries no toolCallId. Clear the executing flag for any
+ // tool call still in flight (started, no result yet) so it doesn't spin
+ // forever, but do NOT synthesize an empty-content tool message for it —
+ // an empty result would blank an in-flight renderer (e.g. an artifact
+ // skeleton). A call that already streamed a result was removed from the
+ // in-flight set on TOOL_CALL_RESULT, so it keeps its delivered content.
+ // The failure surfaces as the thread-level error thrown below.
+ for (const toolCallId of inFlightToolCallIds) {
+ clearToolExecuting(toolCallId);
+ }
+ inFlightToolCallIds.clear();
+
+ throw new Error(errorText);
}
}
diff --git a/packages/react-ui/.storybook/main.ts b/packages/react-ui/.storybook/main.ts
index c829b3241..650af766e 100644
--- a/packages/react-ui/.storybook/main.ts
+++ b/packages/react-ui/.storybook/main.ts
@@ -41,10 +41,12 @@ const config: StorybookConfig = {
resolve: {
alias: {
"@openuidev/react-headless": path.resolve(__dirname, "../../react-headless/src/index.ts"),
+ "@openuidev/react-lang": path.resolve(__dirname, "../../react-lang/src/index.ts"),
+ "@openuidev/lang-core": path.resolve(__dirname, "../../lang-core/src/index.ts"),
},
},
optimizeDeps: {
- exclude: ["@openuidev/react-headless"],
+ exclude: ["@openuidev/react-headless", "@openuidev/react-lang", "@openuidev/lang-core"],
include: ["react", "react-dom"],
},
build: {
diff --git a/packages/react-ui/README.md b/packages/react-ui/README.md
index 7658ad503..544875ec7 100644
--- a/packages/react-ui/README.md
+++ b/packages/react-ui/README.md
@@ -1,6 +1,6 @@
# @openuidev/react-ui
-React components and chat layouts for OpenUI. Use the ready-made chat surfaces, the built-in model-renderable component library, or the individual UI primitives in your own layout.
+React components and a ready-made chat surface for OpenUI. Use the `AgentInterface` chat surface, the built-in model-renderable component library, or the individual UI primitives in your own layout.
[![npm version](https://img.shields.io/npm/v/@openuidev/react-ui)](https://www.npmjs.com/package/@openuidev/react-ui)
[![monthly downloads](https://img.shields.io/npm/dm/@openuidev/react-ui)](https://www.npmjs.com/package/@openuidev/react-ui)
@@ -28,47 +28,61 @@ import "@openuidev/react-ui/styles/index.css";
This package provides three layers:
-1. **Chat layouts** for full-screen chat, copilots, and bottom-tray experiences.
+1. **A ready-made chat surface** — `AgentInterface`, a complete chat experience with thread history, streaming, and a model-renderable message area.
2. **Model-renderable components** for charts, tables, forms, cards, and other OpenUI Lang output.
-3. **Standalone UI primitives** such as `Button`, `Card`, `Table`, `Charts`, and the chat shell pieces.
+3. **Standalone UI primitives** such as `Button`, `Card`, `Table`, and `Charts`.
## Quick Start
-The fastest way to get a working chat app:
+The fastest way to get a working chat app is `AgentInterface`. Give it an `llm` transport that talks to your backend. Storage is optional — without it, threads live in memory and are wiped on reload:
```tsx
-import { FullScreen } from "@openuidev/react-ui";
+import {
+ AgentInterface,
+ openAIAdapter,
+ openAIMessageFormat,
+ type ChatLLM,
+} from "@openuidev/react-ui";
+import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
import "@openuidev/react-ui/styles/index.css";
+const llm: ChatLLM = {
+ send: ({ messages, signal }) =>
+ fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ messages: openAIMessageFormat.toApi(messages) }),
+ signal,
+ }),
+ streamProtocol: openAIAdapter(),
+};
+
function App() {
- return <FullScreen apiUrl="/api/chat" threadApiUrl="/api/threads" />;
+ return (
+ <AgentInterface
+ llm={llm}
+ componentLibrary={openuiChatLibrary}
+ agentName="My Assistant"
+ theme={{ mode: "light" }}
+ />
+ );
}
```
-### Chat Layouts
+### The chat surface
-| Component | Description |
-| :----------- | :----------------------------------- |
-| `FullScreen` | Full-page chat with a thread sidebar |
-| `Copilot` | Side-panel copilot overlay |
-| `BottomTray` | Collapsible bottom tray chat |
+`AgentInterface` is the single chat surface. It adapts its layout responsively and accepts:
-All chat layouts accept `apiUrl`, `threadApiUrl`, and theming props. See the [chat docs](https://openui.com/docs/chat) for full configuration.
-
-### Copilot example
-
-```tsx
-import { Copilot } from "@openuidev/react-ui";
+| Prop | Description |
+| :----------------- | :------------------------------------------------------------------------------------------- |
+| `storage` | Optional persistence adapter for thread history; defaults to in-memory (wiped on reload). Use `restStorage` from `@openuidev/react-ui` to back it with your own REST API |
+| `llm` | Chat transport: `{ send({ messages, signal }), streamProtocol }` |
+| `componentLibrary` | OpenUI Lang library used to render assistant messages (e.g. `openuiChatLibrary`) |
+| `theme` | Theme configuration, e.g. `{ mode: "light" }` |
+| `agentName` | Name displayed in the header |
+| `starters` | Conversation-starter prompts shown on the welcome screen |
-function App() {
- return (
- <div>
- <main>Your app content</main>
- <Copilot apiUrl="/api/chat" threadApiUrl="/api/threads" />
- </div>
- );
-}
-```
+See the [chat docs](https://openui.com/docs/chat) for full configuration.
## Built-in Component Libraries
@@ -184,7 +198,7 @@ All components are available as individual imports:
| **Actions** | `Button`, `Buttons`, `IconButton`, `FollowUpBlock`, `FollowUpItem` |
| **Feedback** | `Callout`, `TextCallout`, `MessageLoading` |
| **Content** | `TextContent`, `MarkDownRenderer` |
-| **Chat** | `FullScreen`, `Copilot`, `BottomTray`, `Shell.*`, `CopilotShell.*`, `ToolCall`, `ToolResult` |
+| **Chat** | `AgentInterface`, `ToolCall`, `ToolResult` |
### Per-component imports
diff --git a/packages/react-ui/package.json b/packages/react-ui/package.json
index ac75767e8..de1f549b8 100644
--- a/packages/react-ui/package.json
+++ b/packages/react-ui/package.json
@@ -2,7 +2,7 @@
"type": "module",
"name": "@openuidev/react-ui",
"license": "MIT",
- "version": "0.11.9",
+ "version": "0.12.0",
"description": "Component library for Generative UI SDK",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
diff --git a/packages/react-ui/src/__test-helpers/mockChat.ts b/packages/react-ui/src/__test-helpers/mockChat.ts
new file mode 100644
index 000000000..79c403ddf
--- /dev/null
+++ b/packages/react-ui/src/__test-helpers/mockChat.ts
@@ -0,0 +1,56 @@
+import type { ChatLLM, ChatStorage, ThreadStorage } from "@openuidev/react-headless";
+import { agUIAdapter } from "@openuidev/react-headless";
+
+/**
+ * Test helpers for stories — construct ChatStorage / ChatLLM objects
+ * with sensible defaults and per-story overrides.
+ */
+
+export type MockStorageOverrides = Partial<ThreadStorage>;
+
+export function makeMockStorage(overrides: MockStorageOverrides = {}): ChatStorage {
+ return {
+ thread: {
+ listThreads: async () => ({ threads: [] }),
+ createThread: async () => ({
+ id: crypto.randomUUID(),
+ title: "New Chat",
+ createdAt: Date.now(),
+ }),
+ getMessages: async () => [],
+ updateThread: async (t) => t,
+ deleteThread: async () => {},
+ ...overrides,
+ },
+ };
+}
+
+export interface MockLLMOverrides {
+ send?: ChatLLM["send"];
+}
+
+export function makeMockLLM(overrides: MockLLMOverrides = {}): ChatLLM {
+ return {
+ send: overrides.send ?? (async () => new Response("data: [DONE]\n\n")),
+ streamProtocol: agUIAdapter(),
+ };
+}
+
+/**
+ * Build a streaming mock Response that emits a single TEXT_MESSAGE_CONTENT
+ * delta followed by [DONE]. Useful for stories simulating the LLM reply.
+ */
+export function mockSSEResponse(text: string, delayMs = 500): Promise<Response> {
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ const events = `data: ${JSON.stringify({ type: "TEXT_MESSAGE_CONTENT", delta: text })}\n\ndata: [DONE]\n\n`;
+ const stream = new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode(events));
+ controller.close();
+ },
+ });
+ resolve(new Response(stream));
+ }, delayMs);
+ });
+}
diff --git a/packages/react-ui/src/artifact/Artifact.tsx b/packages/react-ui/src/artifact/Artifact.tsx
deleted file mode 100644
index 1ef54edd2..000000000
--- a/packages/react-ui/src/artifact/Artifact.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-"use client";
-
-import { useArtifact } from "@openuidev/react-headless";
-import type { ComponentRenderer } from "@openuidev/react-lang";
-import { useId, type ReactNode } from "react";
-import { ArtifactPanel, type ArtifactPanelProps } from "../components/_shared/artifact";
-
-/**
- * Controls injected into `preview` and `panel` render functions.
- */
-export interface ArtifactControls {
- /** Whether this artifact is the currently active (visible) one. */
- isActive: boolean;
- /** Activates this artifact. */
- open: () => void;
- /** Deactivates this artifact. */
- close: () => void;
- /** Toggles this artifact: opens if closed, closes if open. */
- toggle: () => void;
-}
-
-/**
- * Configuration for {@link Artifact}.
- */
-export interface ArtifactConfig<P = Record<string, unknown>> {
- /** Panel title — static string or derived from props. */
- title: string | ((props: P) => string);
- /** Renders the inline preview shown in the chat message. */
- preview: (props: P, controls: ArtifactControls) => ReactNode;
- /** Renders the content inside the artifact side panel. */
- panel: (props: P, controls: ArtifactControls) => ReactNode;
- /** Optional props forwarded to the underlying `<ArtifactPanel>`. */
- panelProps?: Pick<ArtifactPanelProps, "className" | "errorFallback" | "header">;
-}
-
-/**
- * Factory that returns a `ComponentRenderer<P>` wiring up `useId`, `useArtifact`,
- * and `<ArtifactPanel>` internally. Pass the result as `defineComponent`'s `component`.
- *
- * @example
- * ```tsx
- * export const ArtifactCodeBlock = defineComponent({
- * name: "ArtifactCodeBlock",
- * props: ArtifactCodeBlockSchema,
- * description: "Code block that opens in the artifact side panel",
- * component: Artifact({
- * title: (props) => props.title,
- * preview: (props, { open, isActive }) => (
- * <InlinePreview title={props.title} onOpen={open} isActive={isActive} />
- * ),
- * panel: (props) => (
- * <ArtifactView language={props.language} codeString={props.codeString} />
- * ),
- * }),
- * });
- * ```
- */
-export function Artifact<P = Record<string, unknown>>(
- config: ArtifactConfig<P>,
-): ComponentRenderer<P> {
- const { title, preview, panel, panelProps } = config;
-
- const ArtifactComponent: ComponentRenderer<P> = ({ props }) => {
- const artifactId = useId();
- const { isActive, open, close, toggle } = useArtifact(artifactId);
-
- const controls: ArtifactControls = { isActive, open, close, toggle };
- const resolvedTitle = typeof title === "function" ? title(props) : title;
-
- return (
- <>
- {preview(props, controls)}
- <ArtifactPanel artifactId={artifactId} title={resolvedTitle} {...panelProps}>
- {panel(props, controls)}
- </ArtifactPanel>
- </>
- );
- };
-
- ArtifactComponent.displayName = `Artifact(${typeof title === "string" ? title : "dynamic"})`;
-
- return ArtifactComponent;
-}
diff --git a/packages/react-ui/src/artifact/index.ts b/packages/react-ui/src/artifact/index.ts
deleted file mode 100644
index 199e769a9..000000000
--- a/packages/react-ui/src/artifact/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { Artifact } from "./Artifact";
-export type { ArtifactConfig, ArtifactControls } from "./Artifact";
diff --git a/packages/react-ui/src/components/AgentInterface/AgentInterface.tsx b/packages/react-ui/src/components/AgentInterface/AgentInterface.tsx
new file mode 100644
index 000000000..4e1c66f82
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/AgentInterface.tsx
@@ -0,0 +1,470 @@
+import {
+ ChatProvider,
+ useActiveDetailedView,
+ useArtifactList,
+ useArtifactStorage,
+ useThreadList,
+ type Artifact,
+ type AssistantMessage,
+ type ChatProviderProps,
+ type UserMessage,
+} from "@openuidev/react-headless";
+import type { Library } from "@openuidev/react-lang";
+import { ArrowLeft, MessageSquare } from "lucide-react";
+import {
+ Children,
+ isValidElement,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type FC,
+ type ReactElement,
+ type ReactNode,
+} from "react";
+import type { ScrollVariant } from "../../hooks/useScrollToBottom";
+import type { ConversationStarterProps } from "../../types/ConversationStarter";
+import { IconButton } from "../IconButton";
+import { GenUIAssistantMessage } from "../OpenUIChat/GenUIAssistantMessage";
+import { GenUIUserMessage } from "../OpenUIChat/GenUIUserMessage";
+import { ThemeProvider, type ThemeProps } from "../ThemeProvider";
+import { AgentInterfaceTooltip } from "./_shared/AgentInterfaceTooltip";
+import { artifactListPath, parseArtifactPath } from "./_shared/artifactPaths";
+import { GalleryHorizontalEndIcon } from "./_shared/GalleryHorizontalEndIcon";
+import {
+ LabelsProvider,
+ useAgentInterfaceLabels,
+ type AgentInterfaceLabels,
+} from "./_shared/labelsContext";
+import { NavProvider, useNav } from "./_shared/navContext";
+import { StartersProvider } from "./_shared/startersContext";
+import { useAgentInterfaceStore } from "./_shared/store";
+import type { AssistantMessageComponent, UserMessageComponent } from "./_shared/types";
+import { ArtifactBrowserPage } from "./ArtifactBrowserPage";
+import { ArtifactNav } from "./ArtifactNav";
+import { ArtifactViewPage } from "./ArtifactViewPage";
+import { Composer } from "./Composer";
+import { Container } from "./Container";
+import { type ConversationStarterVariant } from "./ConversationStarter";
+import { MobileHeader } from "./MobileHeader";
+import { NewChatButton } from "./NewChatButton";
+import { Route } from "./Route";
+import { SidebarContainer, SidebarContent, SidebarHeader, SidebarSeparator } from "./Sidebar";
+import { SidebarItem } from "./SidebarItem";
+import { SidebarSlot } from "./SidebarSlot";
+import { MessageLoading, Messages, ScrollArea, ThreadContainer, ThreadHeader } from "./Thread";
+import { ThreadList } from "./ThreadList";
+import { WelcomeScreen } from "./WelcomeScreen";
+import { Workspace } from "./Workspace";
+
+export interface AgentInterfaceComponents {
+ AssistantMessage?: AssistantMessageComponent;
+ UserMessage?: UserMessageComponent;
+}
+
+export interface AgentInterfaceProps extends Omit<ChatProviderProps, "children"> {
+ /** Component library for auto-GenUI rendering when `components.AssistantMessage` is not provided. */
+ componentLibrary?: Library;
+ /** Explicit component overrides. Takes precedence over GenUI auto-derivation. */
+ components?: AgentInterfaceComponents;
+ /** Theme props passed to <ThemeProvider>. */
+ theme?: ThemeProps;
+ /** When true, skips wrapping in <ThemeProvider>. */
+ disableThemeProvider?: boolean;
+ /** Brand logo shown in default SidebarHeader + MobileHeader. */
+ logoUrl?: string;
+ /** Agent display name. */
+ agentName?: string;
+ /** Consumer-overridable display strings for the artifact browser + workspace. */
+ labels?: AgentInterfaceLabels;
+ /** Global starters inherited by Welcome (when active) or Composer. */
+ starters?: ConversationStarterProps[];
+ /** Layout variant for inherited starters. */
+ starterVariant?: ConversationStarterVariant;
+ /** Controlled current path. Pair with `onNavigate`. `undefined` = thread view. */
+ path?: string;
+ /** Initial path for uncontrolled mode. Ignored when `onNavigate` is provided. */
+ defaultPath?: string;
+ /** Called when navigation occurs. Presence selects controlled mode. */
+ onNavigate?: (next: string | undefined) => void;
+ /**
+ * How the thread scrolls as messages stream in.
+ * `"always"` follows the streaming response to the bottom (until the user scrolls up);
+ * `"user-message-anchor"` (default) pins the latest user message to the top.
+ */
+ scrollVariant?: ScrollVariant;
+ /** When false, the thread does not auto-scroll on load / conversation switch (auto-scroll only while generating). Default true. */
+ scrollOnLoad?: boolean;
+ children?: ReactNode;
+}
+
+interface ExtractedSlots {
+ sidebar?: ReactElement;
+ sidebarHeader?: ReactElement;
+ mobileHeader?: ReactElement;
+ threadHeader?: ReactElement;
+ welcome?: ReactElement;
+ composer?: ReactElement;
+ workspace?: ReactElement;
+ routes: ReactElement[];
+ rest: ReactNode[];
+}
+
+type SingleSlotKey = Exclude<keyof ExtractedSlots, "rest" | "routes">;
+
+const SLOT_KEY_BY_TYPE = new Map<unknown, SingleSlotKey>([
+ [SidebarSlot, "sidebar"],
+ [SidebarHeader, "sidebarHeader"],
+ [MobileHeader, "mobileHeader"],
+ [ThreadHeader, "threadHeader"],
+ [WelcomeScreen, "welcome"],
+ [Composer, "composer"],
+ [Workspace, "workspace"],
+]);
+
+const isDev = () => typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production";
+
+function extractSlots(children: ReactNode): ExtractedSlots {
+ const result: ExtractedSlots = { routes: [], rest: [] };
+ Children.forEach(children, (child) => {
+ if (!isValidElement(child)) {
+ result.rest.push(child);
+ return;
+ }
+ if (child.type === Route) {
+ result.routes.push(child);
+ return;
+ }
+ const key = SLOT_KEY_BY_TYPE.get(child.type);
+ if (!key) {
+ result.rest.push(child);
+ return;
+ }
+ if (result[key]) {
+ if (isDev()) {
+ console.warn(
+ `[AgentInterface] Multiple <AgentInterface.${key}> slot children — using the first; ignoring the rest.`,
+ );
+ }
+ return;
+ }
+ result[key] = child;
+ });
+ return result;
+}
+
+const DummyThemeProvider = ({ children }: { children: ReactNode }) => <>{children}</>;
+
+interface AgentInterfaceComponent extends FC<AgentInterfaceProps> {
+ Sidebar: typeof SidebarSlot;
+ SidebarHeader: typeof SidebarHeader;
+ SidebarContent: typeof SidebarContent;
+ SidebarSeparator: typeof SidebarSeparator;
+ SidebarItem: typeof SidebarItem;
+ ArtifactNav: typeof ArtifactNav;
+ Workspace: typeof Workspace;
+ Route: typeof Route;
+ MobileHeader: typeof MobileHeader;
+ ThreadHeader: typeof ThreadHeader;
+ Welcome: typeof WelcomeScreen;
+ Composer: typeof Composer;
+ NewChatButton: typeof NewChatButton;
+ ThreadList: typeof ThreadList;
+ Messages: typeof Messages;
+ MessageLoading: typeof MessageLoading;
+ ScrollArea: typeof ScrollArea;
+}
+
+export const AgentInterface: AgentInterfaceComponent = ((props: AgentInterfaceProps) => {
+ const {
+ storage,
+ llm,
+ artifactRenderers,
+ artifactCategories,
+ componentLibrary,
+ components,
+ theme,
+ disableThemeProvider,
+ logoUrl,
+ agentName,
+ labels,
+ starters,
+ starterVariant,
+ path,
+ defaultPath,
+ onNavigate,
+ scrollVariant,
+ scrollOnLoad,
+ children,
+ } = props;
+
+ const slots = useMemo(() => extractSlots(children), [children]);
+
+ if (slots.sidebar && slots.sidebarHeader) {
+ if (isDev()) {
+ console.warn(
+ "[AgentInterface] <AgentInterface.SidebarHeader> at top level is ignored because <AgentInterface.Sidebar> is provided. Put SidebarHeader inside Sidebar instead.",
+ );
+ }
+ slots.sidebarHeader = undefined;
+ }
+
+ const resolvedAssistantMessage = useMemo<AssistantMessageComponent | undefined>(() => {
+ if (components?.AssistantMessage) return components.AssistantMessage;
+ if (componentLibrary) {
+ const Cmp = ({ message }: { message: AssistantMessage }) => (
+ <GenUIAssistantMessage message={message} library={componentLibrary} />
+ );
+ return Cmp;
+ }
+ return undefined;
+ }, [components?.AssistantMessage, componentLibrary]);
+
+ const resolvedUserMessage = useMemo<UserMessageComponent | undefined>(() => {
+ if (components?.UserMessage) return components.UserMessage;
+ if (componentLibrary) {
+ const Cmp = ({ message }: { message: UserMessage }) => <GenUIUserMessage message={message} />;
+ return Cmp;
+ }
+ return undefined;
+ }, [components?.UserMessage, componentLibrary]);
+
+ const ThemeProviderComponent = disableThemeProvider ? DummyThemeProvider : ThemeProvider;
+
+ return (
+ <ThemeProviderComponent {...theme}>
+ <ChatProvider
+ storage={storage}
+ llm={llm}
+ artifactRenderers={artifactRenderers}
+ artifactCategories={artifactCategories}
+ >
+ <NavProvider path={path} defaultPath={defaultPath} onNavigate={onNavigate}>
+ <StartersProvider starters={starters} starterVariant={starterVariant}>
+ <LabelsProvider labels={labels}>
+ <AgentInterfaceBody
+ slots={slots}
+ logoUrl={logoUrl ?? ""}
+ agentName={agentName ?? ""}
+ resolvedAssistantMessage={resolvedAssistantMessage}
+ resolvedUserMessage={resolvedUserMessage}
+ scrollVariant={scrollVariant}
+ scrollOnLoad={scrollOnLoad}
+ />
+ </LabelsProvider>
+ </StartersProvider>
+ </NavProvider>
+ </ChatProvider>
+ </ThemeProviderComponent>
+ );
+}) as AgentInterfaceComponent;
+
+interface AgentInterfaceBodyProps {
+ slots: ExtractedSlots;
+ logoUrl: string;
+ agentName: string;
+ resolvedAssistantMessage: AssistantMessageComponent | undefined;
+ resolvedUserMessage: UserMessageComponent | undefined;
+ scrollVariant?: ScrollVariant;
+ scrollOnLoad?: boolean;
+}
+
+const ArtifactViewMobileHeader = ({
+ artifactId,
+ categoryName,
+}: {
+ artifactId: string;
+ categoryName?: string;
+}) => {
+ const storage = useArtifactStorage();
+ const selectThread = useThreadList(
+ (s: { selectThread: (threadId: string) => void }) => s.selectThread,
+ );
+ const { navigate } = useNav();
+ const [artifact, setArtifact] = useState<Artifact | null>(null);
+ const requestIdRef = useRef(0);
+
+ useEffect(() => {
+ if (!storage) {
+ setArtifact(null);
+ return;
+ }
+
+ const requestId = ++requestIdRef.current;
+ setArtifact(null);
+ storage
+ .get(artifactId)
+ .then((a: Artifact) => {
+ if (requestId !== requestIdRef.current) return;
+ setArtifact(a);
+ })
+ .catch(() => {
+ if (requestId !== requestIdRef.current) return;
+ setArtifact(null);
+ });
+ }, [storage, artifactId]);
+
+ const backToList = () => navigate(artifactListPath(categoryName));
+ const goToThread = () => {
+ if (!artifact) return;
+ selectThread(artifact.threadId);
+ navigate(undefined);
+ };
+
+ return (
+ <MobileHeader
+ menuButton={
+ <IconButton
+ size="medium"
+ icon={<ArrowLeft size="1em" />}
+ onClick={backToList}
+ variant="secondary"
+ aria-label="Back to artifacts"
+ />
+ }
+ agentName={
+ <span className="openui-agent-mobile-header-agent-name">{artifact?.title ?? ""}</span>
+ }
+ newChatButton={
+ <IconButton
+ size="medium"
+ icon={<MessageSquare size="1em" />}
+ onClick={goToThread}
+ variant="secondary"
+ aria-label="Go to thread"
+ disabled={!artifact}
+ />
+ }
+ />
+ );
+};
+
+const MobileWorkspaceToggleButton = () => {
+ const artifacts = useArtifactList();
+ const { isDetailedViewActive } = useActiveDetailedView();
+ const { workspaceToggle } = useAgentInterfaceLabels();
+ const { isWorkspaceOpen, setIsWorkspaceOpen } = useAgentInterfaceStore((state) => ({
+ isWorkspaceOpen: state.isWorkspaceOpen,
+ setIsWorkspaceOpen: state.setIsWorkspaceOpen,
+ }));
+ const hasArtifacts = Object.keys(artifacts).length > 0;
+
+ if (!hasArtifacts || isDetailedViewActive) return null;
+
+ return (
+ <AgentInterfaceTooltip content={workspaceToggle} side="left">
+ <IconButton
+ size="medium"
+ icon={<GalleryHorizontalEndIcon size="1em" />}
+ onClick={() => setIsWorkspaceOpen(!isWorkspaceOpen)}
+ variant="secondary"
+ aria-label={isWorkspaceOpen ? "Collapse workspace" : "Expand workspace"}
+ />
+ </AgentInterfaceTooltip>
+ );
+};
+
+const AgentInterfaceBody = ({
+ slots,
+ logoUrl,
+ agentName,
+ resolvedAssistantMessage,
+ resolvedUserMessage,
+ scrollVariant,
+ scrollOnLoad,
+}: AgentInterfaceBodyProps) => {
+ const { path } = useNav();
+
+ // Reserved `artifacts/` prefix is matched BEFORE user-defined Routes.
+ const artifactPath = useMemo(() => (path === undefined ? null : parseArtifactPath(path)), [path]);
+
+ const activeRoute = useMemo(() => {
+ if (path === undefined || artifactPath) return undefined;
+ return slots.routes.find((route) => (route.props as { path: string }).path === path);
+ }, [path, artifactPath, slots.routes]);
+
+ return (
+ <Container logoUrl={logoUrl} agentName={agentName}>
+ <SidebarContainer>
+ {slots.sidebar ? (
+ (slots.sidebar.props as { children?: ReactNode }).children
+ ) : (
+ <>
+ <div className="openui-agent-sidebar-actions">
+ {slots.sidebarHeader ?? <SidebarHeader />}
+ <div className="openui-agent-sidebar-primary-actions">
+ <NewChatButton />
+ <ArtifactNav className="openui-agent-sidebar-artifact-nav" />
+ </div>
+ </div>
+ <SidebarContent>
+ <ThreadList />
+ </SidebarContent>
+ </>
+ )}
+ </SidebarContainer>
+ {artifactPath ? (
+ <ThreadContainer>
+ {slots.mobileHeader ??
+ (artifactPath.kind === "view" ? (
+ <ArtifactViewMobileHeader
+ artifactId={artifactPath.artifactId}
+ categoryName={artifactPath.categoryName}
+ />
+ ) : (
+ <MobileHeader />
+ ))}
+ {artifactPath.kind === "list" ? (
+ <ArtifactBrowserPage categoryName={artifactPath.categoryName} />
+ ) : (
+ <ArtifactViewPage
+ artifactId={artifactPath.artifactId}
+ categoryName={artifactPath.categoryName}
+ />
+ )}
+ </ThreadContainer>
+ ) : activeRoute ? (
+ <ThreadContainer>
+ {(activeRoute.props as { children?: ReactNode }).children}
+ </ThreadContainer>
+ ) : (
+ <>
+ <ThreadContainer>
+ {slots.mobileHeader ?? <MobileHeader actions={<MobileWorkspaceToggleButton />} />}
+ {slots.threadHeader ?? <ThreadHeader />}
+ {slots.welcome}
+ <ScrollArea scrollVariant={scrollVariant} scrollOnLoad={scrollOnLoad}>
+ <Messages
+ loader={<MessageLoading />}
+ assistantMessage={resolvedAssistantMessage}
+ userMessage={resolvedUserMessage}
+ />
+ </ScrollArea>
+ {slots.composer ?? <Composer />}
+ </ThreadContainer>
+ {/* Per-thread workspace rail — thread view only (hidden on Route/artifact pages). */}
+ {slots.workspace ?? <Workspace />}
+ </>
+ )}
+ {slots.rest}
+ </Container>
+ );
+};
+
+AgentInterface.Sidebar = SidebarSlot;
+AgentInterface.SidebarHeader = SidebarHeader;
+AgentInterface.SidebarContent = SidebarContent;
+AgentInterface.SidebarSeparator = SidebarSeparator;
+AgentInterface.SidebarItem = SidebarItem;
+AgentInterface.ArtifactNav = ArtifactNav;
+AgentInterface.Workspace = Workspace;
+AgentInterface.Route = Route;
+AgentInterface.MobileHeader = MobileHeader;
+AgentInterface.ThreadHeader = ThreadHeader;
+AgentInterface.Welcome = WelcomeScreen;
+AgentInterface.Composer = Composer;
+AgentInterface.NewChatButton = NewChatButton;
+AgentInterface.ThreadList = ThreadList;
+AgentInterface.Messages = Messages;
+AgentInterface.MessageLoading = MessageLoading;
+AgentInterface.ScrollArea = ScrollArea;
diff --git a/packages/react-ui/src/components/AgentInterface/ArtifactBrowserPage.tsx b/packages/react-ui/src/components/AgentInterface/ArtifactBrowserPage.tsx
new file mode 100644
index 000000000..521b64862
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/ArtifactBrowserPage.tsx
@@ -0,0 +1,266 @@
+import {
+ lookupArtifactRendererByType,
+ useArtifactCategories,
+ useArtifactRendererRegistry,
+ useArtifactStorage,
+ type ArtifactSummary,
+} from "@openuidev/react-headless";
+import { Boxes, Search, X } from "lucide-react";
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import { Button } from "../Button";
+import { IconButton } from "../IconButton";
+import { artifactListPath, artifactViewPath } from "./_shared/artifactPaths";
+import { useAgentInterfaceLabels } from "./_shared/labelsContext";
+import { useNav } from "./_shared/navContext";
+
+const SEARCH_DEBOUNCE_MS = 300;
+
+/** Last-resort label: `"chart_v2"` → `"Chart V2"` (never the raw machine id). */
+const prettifyType = (type: string): string =>
+ type
+ .replace(/[_-]+/g, " ")
+ .trim()
+ .replace(/\b\w/g, (c) => c.toUpperCase()) || type;
+
+export const formatArtifactUpdatedAt = (updatedAt: ArtifactSummary["updatedAt"]) => {
+ if (updatedAt === undefined) return undefined;
+ const date = new Date(updatedAt);
+ if (Number.isNaN(date.getTime())) return undefined;
+ return new Intl.DateTimeFormat(undefined, {
+ dateStyle: "medium",
+ }).format(date);
+};
+
+/**
+ * Resolves the visual for an artifact type: the icon declared on its renderer
+ * (`defineArtifactRenderer({ icon })`) — any ReactNode the consumer chose — or a
+ * generic default. The framework is agnostic about what that node is.
+ */
+export const useArtifactIcon = (type: string): ReactNode => {
+ const registry = useArtifactRendererRegistry();
+ const rendererIcon = registry ? lookupArtifactRendererByType(registry, type)?.icon : undefined;
+ return rendererIcon ?? <Boxes size="1em" />;
+};
+
+/**
+ * Resolves the display label for an artifact type: the label declared on its
+ * renderer (`defineArtifactRenderer({ label })`), else a prettified `type`.
+ * Mirrors {@link useArtifactIcon} — never shows the raw machine id.
+ */
+export const useArtifactTypeLabel = (type: string): string => {
+ const registry = useArtifactRendererRegistry();
+ const label = registry ? lookupArtifactRendererByType(registry, type)?.label : undefined;
+ return label ?? prettifyType(type);
+};
+
+const ArtifactBrowserCard = ({
+ artifact,
+ updatedAt,
+ onClick,
+}: {
+ artifact: ArtifactSummary;
+ updatedAt?: string;
+ onClick: () => void;
+}) => {
+ const icon = useArtifactIcon(artifact.type);
+ const typeLabel = useArtifactTypeLabel(artifact.type);
+ const metadata = [typeLabel, updatedAt].filter(Boolean).join(" · ");
+
+ return (
+ <button type="button" className="openui-agent-artifact-browser__item" onClick={onClick}>
+ <span className="openui-agent-artifact-browser__item-icon">{icon}</span>
+ <div className="openui-agent-artifact-browser__item-meta">
+ <span className="openui-agent-artifact-browser__item-title">{artifact.title}</span>
+ {metadata && (
+ <span className="openui-agent-artifact-browser__item-updated-at">{metadata}</span>
+ )}
+ </div>
+ </button>
+ );
+};
+
+/**
+ * Full-page searchable artifact list for one category (reserved path
+ * `artifacts/{category}`). Title search + category type filter are applied
+ * server-side via `ArtifactStorage.list`; pagination via cursor.
+ *
+ * Internal — rendered by AgentInterface when the current path matches the
+ * reserved `artifacts/` prefix.
+ *
+ * @internal
+ */
+export const ArtifactBrowserPage = ({ categoryName }: { categoryName?: string }) => {
+ const storage = useArtifactStorage();
+ const categories = useArtifactCategories();
+ const { navigate } = useNav();
+ const { defaultCategory } = useAgentInterfaceLabels();
+
+ const category = categoryName ? categories.find((c) => c.name === categoryName) : undefined;
+ // A named category that matches no configured category (stale/renamed path,
+ // hand-edited or bookmarked URL). Distinct from `all` (categoryName undefined),
+ // which intentionally lists everything. `categories` is static config, so this
+ // is decided synchronously with no loading race.
+ const notFound = categoryName !== undefined && category === undefined;
+ const typeFilter = category?.filter.type;
+
+ const [search, setSearch] = useState("");
+ const [debouncedSearch, setDebouncedSearch] = useState("");
+ const [artifacts, setArtifacts] = useState<ArtifactSummary[]>([]);
+ const [nextCursor, setNextCursor] = useState<string | undefined>(undefined);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<Error | null>(null);
+ const requestIdRef = useRef(0);
+
+ useEffect(() => {
+ const t = setTimeout(() => setDebouncedSearch(search), SEARCH_DEBOUNCE_MS);
+ return () => clearTimeout(t);
+ }, [search]);
+
+ const typeKey = typeFilter?.join(" ");
+ // Noun derived from the category name (not a hardcoded "Apps" match).
+ const emptyItemLabel = categoryName ? categoryName.toLowerCase() : "artifacts";
+ const emptyMessage = debouncedSearch
+ ? `No ${emptyItemLabel} match your search`
+ : `No ${emptyItemLabel} yet`;
+
+ // Initial page + reload on search/category change.
+ useEffect(() => {
+ if (!storage || notFound) return;
+ const requestId = ++requestIdRef.current;
+ setIsLoading(true);
+ setError(null);
+ storage
+ .list({
+ name: debouncedSearch || undefined,
+ type: typeKey === undefined ? undefined : typeKey.split(" "),
+ })
+ .then(({ artifacts: page, nextCursor: cursor }) => {
+ if (requestId !== requestIdRef.current) return;
+ setArtifacts(page);
+ setNextCursor(cursor);
+ setIsLoading(false);
+ })
+ .catch((e) => {
+ if (requestId !== requestIdRef.current) return;
+ setError(e instanceof Error ? e : new Error(String(e)));
+ setIsLoading(false);
+ });
+ }, [storage, debouncedSearch, typeKey, notFound]);
+
+ const loadMore = () => {
+ if (!storage || nextCursor === undefined || isLoading) return;
+ const requestId = ++requestIdRef.current;
+ setIsLoading(true);
+ storage
+ .list({
+ name: debouncedSearch || undefined,
+ type: typeKey === undefined ? undefined : typeKey.split(" "),
+ cursor: nextCursor,
+ })
+ .then(({ artifacts: page, nextCursor: cursor }) => {
+ if (requestId !== requestIdRef.current) return;
+ setArtifacts((prev) => [...prev, ...page]);
+ setNextCursor(cursor);
+ setIsLoading(false);
+ })
+ .catch((e) => {
+ if (requestId !== requestIdRef.current) return;
+ setError(e instanceof Error ? e : new Error(String(e)));
+ setIsLoading(false);
+ });
+ };
+
+ if (!storage) return null;
+
+ if (notFound) {
+ return (
+ <div className="openui-agent-artifact-browser">
+ <div className="openui-agent-artifact-browser__content">
+ <div className="openui-agent-artifact-browser__header">
+ <h2 className="openui-agent-artifact-browser__title">{defaultCategory}</h2>
+ </div>
+ <div className="openui-agent-artifact-browser__list">
+ <div className="openui-agent-artifact-browser__empty">
+ <span className="openui-agent-artifact-browser__empty-illustration">
+ <Boxes size="1em" />
+ </span>
+ <span className="openui-agent-artifact-browser__empty-text">
+ No category named “{categoryName}”
+ </span>
+ <Button variant="secondary" size="small" onClick={() => navigate(artifactListPath())}>
+ View all artifacts
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="openui-agent-artifact-browser">
+ <div className="openui-agent-artifact-browser__content">
+ <div className="openui-agent-artifact-browser__header">
+ <h2 className="openui-agent-artifact-browser__title">
+ {categoryName ?? defaultCategory}
+ </h2>
+ <div className="openui-agent-artifact-browser__search">
+ <Search size={14} className="openui-agent-artifact-browser__search-icon" />
+ <input
+ type="text"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search by title"
+ className="openui-agent-artifact-browser__search-input"
+ aria-label="Search artifacts by title"
+ />
+ {search && (
+ <IconButton
+ size="2-extra-small"
+ variant="tertiary"
+ icon={<X size="1em" />}
+ aria-label="Clear search"
+ onClick={() => setSearch("")}
+ />
+ )}
+ </div>
+ </div>
+
+ <div className="openui-agent-artifact-browser__list">
+ {error && (
+ <div className="openui-agent-artifact-browser__error">
+ Failed to load artifacts: {error.message}
+ </div>
+ )}
+ {!error && artifacts.length === 0 && !isLoading && (
+ <div className="openui-agent-artifact-browser__empty">
+ <span className="openui-agent-artifact-browser__empty-illustration">
+ <Boxes size="1em" />
+ </span>
+ <span className="openui-agent-artifact-browser__empty-text">{emptyMessage}</span>
+ </div>
+ )}
+ {artifacts.map((artifact) => {
+ const updatedAt = formatArtifactUpdatedAt(artifact.updatedAt);
+ return (
+ <ArtifactBrowserCard
+ key={artifact.id}
+ artifact={artifact}
+ updatedAt={updatedAt}
+ onClick={() => navigate(artifactViewPath(categoryName, artifact.id))}
+ />
+ );
+ })}
+ {isLoading && <div className="openui-agent-artifact-browser__loading">Loading…</div>}
+ {!isLoading && nextCursor !== undefined && (
+ <div className="openui-agent-artifact-browser__load-more">
+ <Button variant="secondary" size="small" onClick={loadMore}>
+ Load more
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/react-ui/src/components/AgentInterface/ArtifactNav.tsx b/packages/react-ui/src/components/AgentInterface/ArtifactNav.tsx
new file mode 100644
index 000000000..9ef69ae25
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/ArtifactNav.tsx
@@ -0,0 +1,79 @@
+import { useArtifactCategories, useArtifactStorage } from "@openuidev/react-headless";
+import { Boxes } from "lucide-react";
+import type { ReactNode } from "react";
+import { artifactListPath } from "./_shared/artifactPaths";
+import { useAgentInterfaceLabels } from "./_shared/labelsContext";
+import { useOptionalNav } from "./_shared/navContext";
+import { SidebarItem } from "./SidebarItem";
+
+export interface ArtifactNavProps {
+ className?: string;
+ /**
+ * Fallback icon for category items that don't set their own `icon`.
+ * Defaults to a boxes icon.
+ */
+ icon?: ReactNode;
+}
+
+/**
+ * Sidebar navigation for the global artifact browser.
+ *
+ * Renders one {@link SidebarItem} per configured `artifactCategories` entry
+ * (or a single "Artifacts" item when no categories are configured). Clicking
+ * navigates to the reserved `artifacts/{category}` path, which AgentInterface
+ * renders as the searchable artifact browser in the thread region.
+ *
+ * Each item's icon is the category's own `icon` (`artifactCategories: [{ icon }]`),
+ * else the `icon` prop, else a generic default — the library hardcodes no
+ * per-category icons.
+ *
+ * Renders nothing when `storage.artifact` is not configured.
+ *
+ * Included automatically in the default sidebar; compose it manually inside
+ * a custom `<AgentInterface.Sidebar>`.
+ *
+ * @category Components
+ */
+export const ArtifactNav = ({ className, icon }: ArtifactNavProps) => {
+ const storage = useArtifactStorage();
+ const categories = useArtifactCategories();
+ const nav = useOptionalNav();
+ const { defaultCategory } = useAgentInterfaceLabels();
+
+ if (!storage) return null;
+
+ const items =
+ categories.length > 0
+ ? categories.map((c) => ({
+ label: c.name,
+ path: artifactListPath(c.name),
+ categoryIcon: c.icon,
+ }))
+ : [
+ {
+ label: defaultCategory,
+ path: artifactListPath(),
+ categoryIcon: undefined as ReactNode,
+ },
+ ];
+
+ // Category nav icon: the category's own icon → the `icon` prop → a generic default.
+ const getItemIcon = (categoryIcon: ReactNode): ReactNode =>
+ categoryIcon ?? icon ?? <Boxes size="1em" />;
+
+ return (
+ <div className={className}>
+ {items.map((item) => (
+ <SidebarItem
+ key={item.path}
+ path={item.path}
+ icon={getItemIcon(item.categoryIcon)}
+ // Highlight on the list page AND while viewing an artifact within it.
+ selected={nav?.path === item.path || nav?.path?.startsWith(`${item.path}/`) === true}
+ >
+ {item.label}
+ </SidebarItem>
+ ))}
+ </div>
+ );
+};
diff --git a/packages/react-ui/src/components/AgentInterface/ArtifactViewPage.tsx b/packages/react-ui/src/components/AgentInterface/ArtifactViewPage.tsx
new file mode 100644
index 000000000..cd08cc3a0
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/ArtifactViewPage.tsx
@@ -0,0 +1,144 @@
+import {
+ lookupArtifactRendererByType,
+ useArtifactRendererRegistry,
+ useArtifactStorage,
+ useThreadList,
+ type Artifact,
+ type ArtifactRendererControls,
+} from "@openuidev/react-headless";
+import { ArrowLeft, MessageSquare } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { Button } from "../Button";
+import { IconButton } from "../IconButton";
+import { artifactListPath } from "./_shared/artifactPaths";
+import { useNav } from "./_shared/navContext";
+
+/**
+ * Full-page artifact view (reserved path `artifacts/{category}/{id}`),
+ * rendered independent of any thread.
+ *
+ * Fetches the artifact via `ArtifactStorage.get`, resolves the renderer by
+ * `artifact.type`, runs the renderer's `parser` with
+ * `{ args: undefined, response: artifact.content }` (stored content must have
+ * the same shape as the tool-call response), and renders `actual` filling the
+ * page. No DetailedView involvement.
+ *
+ * `controls.close` navigates back to the category list; `open`/`toggle` are
+ * no-ops (the page IS the open state). `isStreaming` is always `false`.
+ *
+ * Internal — rendered by AgentInterface for the reserved `artifacts/` prefix.
+ *
+ * @internal
+ */
+export const ArtifactViewPage = ({
+ artifactId,
+ categoryName,
+}: {
+ artifactId: string;
+ categoryName?: string;
+}) => {
+ const storage = useArtifactStorage();
+ const registry = useArtifactRendererRegistry();
+ const { navigate } = useNav();
+ const selectThread = useThreadList((s) => s.selectThread);
+
+ const [artifact, setArtifact] = useState<Artifact | null>(null);
+ const [error, setError] = useState<Error | null>(null);
+ const requestIdRef = useRef(0);
+
+ useEffect(() => {
+ if (!storage) return;
+ const requestId = ++requestIdRef.current;
+ setArtifact(null);
+ setError(null);
+ storage
+ .get(artifactId)
+ .then((a) => {
+ if (requestId !== requestIdRef.current) return;
+ setArtifact(a);
+ })
+ .catch((e) => {
+ if (requestId !== requestIdRef.current) return;
+ setError(e instanceof Error ? e : new Error(String(e)));
+ });
+ }, [storage, artifactId]);
+
+ const backToList = () => navigate(artifactListPath(categoryName));
+
+ const goToThread = () => {
+ if (!artifact) return;
+ selectThread(artifact.threadId);
+ navigate(undefined);
+ };
+
+ const renderer = useMemo(() => {
+ if (!artifact || !registry) return null;
+ return lookupArtifactRendererByType(registry, artifact.type);
+ }, [artifact, registry]);
+
+ const parsed = useMemo(() => {
+ if (!artifact || !renderer) return null;
+ return renderer.parser({ args: undefined, response: artifact.content }, { isStreaming: false });
+ }, [artifact, renderer]);
+
+ const controls: ArtifactRendererControls = {
+ isActive: true,
+ isStreaming: false,
+ open: () => {},
+ close: backToList,
+ toggle: backToList,
+ };
+
+ let body: React.ReactNode;
+ if (!storage) {
+ body = null;
+ } else if (error) {
+ body = (
+ <div className="openui-agent-artifact-view__error">
+ Failed to load artifact: {error.message}
+ </div>
+ );
+ } else if (!artifact) {
+ body = <div className="openui-agent-artifact-view__loading">Loading…</div>;
+ } else if (!renderer) {
+ body = (
+ <div className="openui-agent-artifact-view__error">
+ No renderer registered for artifact type "{artifact.type}".
+ </div>
+ );
+ } else if (!parsed) {
+ body = (
+ <div className="openui-agent-artifact-view__error">
+ The renderer could not parse this artifact's content.
+ </div>
+ );
+ } else {
+ body = renderer.actual(parsed.props, controls);
+ }
+
+ return (
+ <div className="openui-agent-artifact-view">
+ <div className="openui-agent-artifact-view__header">
+ <IconButton
+ variant="tertiary"
+ size="small"
+ icon={<ArrowLeft size="1em" />}
+ aria-label="Back"
+ onClick={backToList}
+ />
+ <span className="openui-agent-artifact-view__title">{artifact?.title ?? ""}</span>
+ {artifact && (
+ <Button
+ variant="tertiary"
+ size="small"
+ iconLeft={<MessageSquare size={14} />}
+ onClick={goToThread}
+ >
+ Go to thread
+ </Button>
+ )}
+ </div>
+ <div className="openui-agent-artifact-view__content">{body}</div>
+ </div>
+ );
+};
diff --git a/packages/react-ui/src/components/AgentInterface/Composer.tsx b/packages/react-ui/src/components/AgentInterface/Composer.tsx
new file mode 100644
index 000000000..fa7a6bdcd
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/Composer.tsx
@@ -0,0 +1,51 @@
+import { useThread } from "@openuidev/react-headless";
+import clsx from "clsx";
+import type { ReactNode } from "react";
+import type { ConversationStarterProps } from "../../types/ConversationStarter";
+import { useStartersFromContext } from "./_shared/startersContext";
+import { isChatEmpty } from "./_shared/utils";
+import { Composer as ComposerInput } from "./components/Composer";
+import { ConversationStarter, type ConversationStarterVariant } from "./ConversationStarter";
+
+export interface ComposerProps {
+ className?: string;
+ placeholder?: string;
+ /** Starters chips shown above the input when chat is empty. Inherits from <AgentInterface starters>. */
+ starters?: ConversationStarterProps[];
+ /** Layout variant for starters. Inherits from <AgentInterface starterVariant>. */
+ starterVariant?: ConversationStarterVariant;
+ /** Mode C — fully replaces the composer area. When provided, auto-starters rendering is disabled. */
+ children?: ReactNode;
+}
+
+export const Composer = ({
+ className,
+ placeholder,
+ starters: ownStarters,
+ starterVariant: ownVariant,
+ children,
+}: ComposerProps) => {
+ const fromCtx = useStartersFromContext();
+ const messages = useThread((s) => s.messages);
+ const isLoadingMessages = useThread((s) => s.isLoadingMessages);
+
+ if (children != null) {
+ return <div className={clsx("openui-agent-composer-slot", className)}>{children}</div>;
+ }
+
+ const effectiveStarters = ownStarters ?? fromCtx.starters;
+ const effectiveVariant = ownVariant ?? fromCtx.starterVariant ?? "short";
+ const showStarters =
+ isChatEmpty({ isLoadingMessages, messages }) &&
+ effectiveStarters !== undefined &&
+ effectiveStarters.length > 0;
+
+ return (
+ <div className={clsx("openui-agent-composer-slot", className)}>
+ {showStarters && (
+ <ConversationStarter starters={effectiveStarters!} variant={effectiveVariant} />
+ )}
+ <ComposerInput placeholder={placeholder} />
+ </div>
+ );
+};
diff --git a/packages/react-ui/src/components/AgentInterface/Container.tsx b/packages/react-ui/src/components/AgentInterface/Container.tsx
new file mode 100644
index 000000000..e236c5e77
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/Container.tsx
@@ -0,0 +1,52 @@
+import * as Tooltip from "@radix-ui/react-tooltip";
+import clsx from "clsx";
+import { useRef } from "react";
+import { LayoutContextProvider } from "../../context/LayoutContext";
+import { useElementSize } from "../../hooks/useElementSize";
+import { ShellStoreProvider } from "../_shared/store";
+import { AgentInterfaceStoreProvider } from "./_shared/store";
+
+interface ContainerProps {
+ children?: React.ReactNode;
+ logoUrl: string;
+ agentName: string;
+ className?: string;
+}
+
+export const Container = ({ children, logoUrl, agentName, className }: ContainerProps) => {
+ const ref = useRef<HTMLDivElement>(null);
+ const { width } = useElementSize({ ref }) || {};
+ // TODO: revisit this logic
+ const isMobile = width > 0 && width < 768;
+ const isFullScreen = width > 768;
+ const layout = isMobile ? "mobile" : isFullScreen ? "fullscreen" : "tray";
+
+ return (
+ <AgentInterfaceStoreProvider logoUrl={logoUrl} agentName={agentName}>
+ {/* Provide the shell store too: assistant-message components read
+ agentName/logoUrl/showAssistantLogo from it, so a real provider must
+ exist here (instead of falling back to defaults). */}
+ <ShellStoreProvider logoUrl={logoUrl} agentName={agentName}>
+ <LayoutContextProvider layout={layout}>
+ {/* Single shared Tooltip.Provider for the whole interface so hover-open
+ delay and skip-delay behavior are shared across all tooltips
+ (instead of each tooltip mounting its own provider). */}
+ <Tooltip.Provider delayDuration={250}>
+ <div
+ className={clsx(
+ "openui-agent-container",
+ {
+ "openui-agent-container--mobile": isMobile,
+ },
+ className,
+ )}
+ ref={ref}
+ >
+ {children}
+ </div>
+ </Tooltip.Provider>
+ </LayoutContextProvider>
+ </ShellStoreProvider>
+ </AgentInterfaceStoreProvider>
+ );
+};
diff --git a/packages/react-ui/src/components/Shell/ConversationStarter.tsx b/packages/react-ui/src/components/AgentInterface/ConversationStarter.tsx
similarity index 82%
rename from packages/react-ui/src/components/Shell/ConversationStarter.tsx
rename to packages/react-ui/src/components/AgentInterface/ConversationStarter.tsx
index dc9d20869..12e03a272 100644
--- a/packages/react-ui/src/components/Shell/ConversationStarter.tsx
+++ b/packages/react-ui/src/components/AgentInterface/ConversationStarter.tsx
@@ -4,7 +4,7 @@ import { ArrowUp, Lightbulb } from "lucide-react";
import { Fragment, ReactNode, isValidElement } from "react";
import { ConversationStarterIcon, ConversationStarterProps } from "../../types/ConversationStarter";
import { Carousel, CarouselContent } from "../Carousel";
-import { isChatEmpty } from "../_shared/utils";
+import { isChatEmpty } from "./_shared/utils";
export type ConversationStarterVariant = "short" | "long";
@@ -51,13 +51,13 @@ const ConversationStarterItem = ({
return (
<button
type="button"
- className="openui-shell-conversation-starter-item-short"
+ className="openui-agent-conversation-starter-item-short"
onClick={() => onClick(prompt)}
>
{shouldRenderIcon && (
- <span className="openui-shell-conversation-starter-item-short__icon">{renderedIcon}</span>
+ <span className="openui-agent-conversation-starter-item-short__icon">{renderedIcon}</span>
)}
- <span className="openui-shell-conversation-starter-item-short__text">{displayText}</span>
+ <span className="openui-agent-conversation-starter-item-short__text">{displayText}</span>
</button>
);
}
@@ -66,16 +66,16 @@ const ConversationStarterItem = ({
return (
<button
type="button"
- className="openui-shell-conversation-starter-item-long"
+ className="openui-agent-conversation-starter-item-long"
onClick={() => onClick(prompt)}
>
- <div className="openui-shell-conversation-starter-item-long__content">
+ <div className="openui-agent-conversation-starter-item-long__content">
{shouldRenderIcon && (
- <span className="openui-shell-conversation-starter-item-long__icon">{renderedIcon}</span>
+ <span className="openui-agent-conversation-starter-item-long__icon">{renderedIcon}</span>
)}
- <span className="openui-shell-conversation-starter-item-long__text">{displayText}</span>
+ <span className="openui-agent-conversation-starter-item-long__text">{displayText}</span>
</div>
- <span className="openui-shell-conversation-starter-item-long__arrow">
+ <span className="openui-agent-conversation-starter-item-long__arrow">
<ArrowUp size={16} />
</span>
</button>
@@ -87,7 +87,7 @@ export interface ConversationStarterContainerProps {
className?: string;
/**
* Variant of the conversation starter
- * - "short": Pill-style buttons that wrap (default)
+ * - "short": Pill-style horizontal buttons (default)
* - "long": Vertical list items with icons and hover arrow
*/
variant?: ConversationStarterVariant;
@@ -125,12 +125,12 @@ export const ConversationStarter = ({
<Carousel
showButtons={false}
className={clsx(
- "openui-shell-conversation-starter",
- "openui-shell-conversation-starter--short",
+ "openui-agent-conversation-starter",
+ "openui-agent-conversation-starter--short",
className,
)}
>
- <CarouselContent className="openui-shell-conversation-starter__carousel-content">
+ <CarouselContent className="openui-agent-conversation-starter__carousel-content">
{starters.map((item, index) => (
<ConversationStarterItem
key={`${item.displayText}-${index}`}
@@ -149,8 +149,8 @@ export const ConversationStarter = ({
return (
<div
className={clsx(
- "openui-shell-conversation-starter",
- `openui-shell-conversation-starter--${variant}`,
+ "openui-agent-conversation-starter",
+ `openui-agent-conversation-starter--${variant}`,
className,
)}
>
diff --git a/packages/react-ui/src/components/AgentInterface/MobileHeader.tsx b/packages/react-ui/src/components/AgentInterface/MobileHeader.tsx
new file mode 100644
index 000000000..c47b05b6f
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/MobileHeader.tsx
@@ -0,0 +1,87 @@
+import { useThreadList } from "@openuidev/react-headless";
+import clsx from "clsx";
+import { Menu, SquarePen } from "lucide-react";
+import type { ReactNode } from "react";
+import { IconButton } from "../IconButton";
+import { useAgentInterfaceStore } from "./_shared/store";
+
+export interface MobileHeaderProps {
+ className?: string;
+ logo?: ReactNode;
+ agentName?: ReactNode;
+ menuButton?: ReactNode | false;
+ newChatButton?: ReactNode | false;
+ actions?: ReactNode;
+ children?: ReactNode;
+}
+
+export const MobileHeader = ({
+ className,
+ logo,
+ agentName: agentNameProp,
+ menuButton,
+ newChatButton,
+ actions,
+ children,
+}: MobileHeaderProps) => {
+ const switchToNewThread = useThreadList((s) => s.switchToNewThread);
+ const { agentName: ctxAgentName, setIsSidebarOpen } = useAgentInterfaceStore((state) => ({
+ agentName: state.agentName,
+ setIsSidebarOpen: state.setIsSidebarOpen,
+ }));
+
+ if (children != null) {
+ if (
+ typeof process !== "undefined" &&
+ process.env?.["NODE_ENV"] !== "production" &&
+ (logo !== undefined ||
+ agentNameProp !== undefined ||
+ menuButton !== undefined ||
+ newChatButton !== undefined ||
+ actions !== undefined)
+ ) {
+ console.warn(
+ "[AgentInterface] <AgentInterface.MobileHeader> received both children and override props; children win.",
+ );
+ }
+ return <div className={clsx("openui-agent-mobile-header", className)}>{children}</div>;
+ }
+
+ const defaultMenuButton = (
+ <IconButton
+ size="medium"
+ icon={<Menu size="1em" />}
+ onClick={() => setIsSidebarOpen(true)}
+ variant="secondary"
+ aria-label="Open sidebar"
+ />
+ );
+
+ const defaultAgentName = (
+ <span className="openui-agent-mobile-header-agent-name">{ctxAgentName}</span>
+ );
+
+ const defaultNewChatButton = (
+ <IconButton
+ size="medium"
+ icon={<SquarePen size="1em" />}
+ onClick={switchToNewThread}
+ variant="secondary"
+ aria-label="New chat"
+ />
+ );
+
+ return (
+ <div className={clsx("openui-agent-mobile-header", className)}>
+ {menuButton === false ? null : (menuButton ?? defaultMenuButton)}
+ <div className="openui-agent-mobile-header-logo-container">
+ {logo}
+ {agentNameProp ?? defaultAgentName}
+ </div>
+ <div className="openui-agent-mobile-header-actions">
+ {newChatButton === false ? null : (newChatButton ?? defaultNewChatButton)}
+ {actions}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/react-ui/src/components/AgentInterface/NewChatButton.tsx b/packages/react-ui/src/components/AgentInterface/NewChatButton.tsx
new file mode 100644
index 000000000..26ae5db95
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/NewChatButton.tsx
@@ -0,0 +1,67 @@
+import { useThreadList } from "@openuidev/react-headless";
+import clsx from "clsx";
+import { SquarePen } from "lucide-react";
+import type { MouseEvent } from "react";
+import { useLayoutContext } from "../../context/LayoutContext";
+import { Button } from "../Button";
+import { useOptionalSidebarVisualState } from "./Sidebar";
+import { SidebarTooltip } from "./SidebarTooltip";
+import { useOptionalNav } from "./_shared/navContext";
+import { useAgentInterfaceStore } from "./_shared/store";
+
+export const NewChatButton = ({ className }: { className?: string }) => {
+ const switchToNewThread = useThreadList((s) => s.switchToNewThread);
+ const { isSidebarOpen } = useAgentInterfaceStore((state) => ({
+ isSidebarOpen: state.isSidebarOpen,
+ }));
+ const sidebarVisualState = useOptionalSidebarVisualState();
+ const showExpandedButton = sidebarVisualState
+ ? !sidebarVisualState.isCollapsedLayout
+ : isSidebarOpen;
+ const nav = useOptionalNav();
+ const { layout } = useLayoutContext();
+ const isMobile = layout === "mobile";
+
+ const handleNewChat = (e: MouseEvent<HTMLButtonElement>) => {
+ e.stopPropagation();
+ switchToNewThread();
+ if (nav && nav.path !== undefined) {
+ nav.navigate(undefined);
+ }
+ };
+
+ if (isMobile) {
+ return (
+ <Button
+ variant="primary"
+ size="large"
+ iconLeft={<SquarePen size="1em" />}
+ className={clsx("openui-agent-new-chat-floating-button", className)}
+ onClick={handleNewChat}
+ aria-label="New chat"
+ >
+ New Chat
+ </Button>
+ );
+ }
+
+ return (
+ <SidebarTooltip content="New Chat" disabled={showExpandedButton}>
+ <button
+ type="button"
+ className={clsx(
+ "openui-agent-new-chat-button",
+ { "openui-agent-new-chat-button--collapsed": !showExpandedButton },
+ className,
+ )}
+ onClick={handleNewChat}
+ aria-label="New chat"
+ >
+ <div className="openui-agent-new-chat-button__icon" aria-hidden="true">
+ <SquarePen size="1em" />
+ </div>
+ <div className="openui-agent-new-chat-button__label">New Chat</div>
+ </button>
+ </SidebarTooltip>
+ );
+};
diff --git a/packages/react-ui/src/components/AgentInterface/README.md b/packages/react-ui/src/components/AgentInterface/README.md
new file mode 100644
index 000000000..2bad376c9
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/README.md
@@ -0,0 +1,641 @@
+# AgentInterface
+
+A full, drop-in **agent-chat UI** shipped as a single compound React component. It renders the
+whole shell — sidebar with thread history, a streaming conversation thread (assistant / user / tool
+messages), a composer with conversation starters, an empty-state welcome screen, a global artifact
+browser, and a per-thread **Workspace** rail with a resizable **detailed-view** side panel.
+
+This document is for **contributors** working inside `AgentInterface/`. It explains the mental
+model, the public API, how data and state flow, the rendering pipeline, the styling system, and the
+sharp edges you will hit. If you only want to _use_ the component, the Storybook stories
+(`stories/AgentInterface.stories.tsx`) are the fastest reference.
+
+---
+
+## Table of contents
+
+1. [Mental model](#mental-model)
+2. [Quick start](#quick-start)
+3. [The slot / compound-component model](#the-slot--compound-component-model)
+4. [Public API reference](#public-api-reference)
+5. [Render tree & provider stack](#render-tree--provider-stack)
+6. [Composition modes (A / B / C)](#composition-modes-a--b--c)
+7. [State & data model](#state--data-model)
+8. [Navigation & routing](#navigation--routing)
+9. [Message rendering pipeline](#message-rendering-pipeline)
+10. [Artifacts, the Workspace rail & DetailedView](#artifacts-the-workspace-rail--detailedview)
+11. [Layout & responsiveness](#layout--responsiveness)
+12. [Styling & theming](#styling--theming)
+13. [Directory guide](#directory-guide)
+14. [Extending the component](#extending-the-component)
+15. [Gotchas & known rough edges](#gotchas--known-rough-edges)
+16. [Local development](#local-development)
+
+---
+
+## Mental model
+
+AgentInterface is a **pure view layer**. It owns _zero_ chat business logic. Everything stateful
+comes from three external sources, all from sibling packages:
+
+| Concern | Source package | How AgentInterface gets it |
+| ------------------------------------------ | --------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
+| Threads, messages, streaming, artifacts | `@openuidev/react-headless` | Mounts `<ChatProvider>`; reads via `useThread`, `useThreadList`, `useArtifactList`, `useDetailedView`, … |
+| GenUI auto-rendering of assistant messages | `@openuidev/react-lang` | Optional `componentLibrary` prop → `GenUIAssistantMessage` |
+| Wire message shapes | `@ag-ui/core` (re-exported by react-headless) | `Message`, `AssistantMessage`, `UserMessage`, `ToolMessage`, `InputContent`, … |
+
+What AgentInterface itself adds on top:
+
+- A **slot-based composition API** (`<AgentInterface.Sidebar>`, `.Composer`, `.Route`, …).
+- **Layout & chrome**: sidebar collapse/expand, mobile vs. desktop, the workspace rail, the
+ resizable detailed-view split.
+- **Navigation** (`NavContext`) including a reserved `artifacts/…` URL space.
+- A handful of small **UI-only stores/contexts** (sidebar/workspace open state, starters,
+ layout breakpoint).
+
+> **Rule of thumb:** if it's _data_, it lives in react-headless. If it's _layout/chrome/UI state_,
+> it lives here.
+
+---
+
+## Quick start
+
+The bare form renders everything from internal defaults:
+
+```tsx
+import { AgentInterface } from "@openuidev/react-ui"; // or the local component path
+
+<AgentInterface
+ storage={storage} // ChatStorage from react-headless
+ llm={llm} // LLM transport from react-headless
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+/>;
+```
+
+With GenUI auto-rendering of assistant messages:
+
+```tsx
+<AgentInterface storage={storage} llm={llm} componentLibrary={myLibrary} />
+```
+
+See `stories/AgentInterface.stories.tsx` (`Default`, `WithWelcome`, `Routing`, `ArtifactBrowser`,
+`WithWorkspace`, …) for runnable examples of every feature.
+
+---
+
+## The slot / compound-component model
+
+`AgentInterface` is a function component with ~17 **static members** attached
+(`AgentInterface.Sidebar`, `AgentInterface.Composer`, …). At render time it walks
+`props.children` once (`extractSlots`, in `AgentInterface.tsx`) and routes each child by the
+**identity of its element type**:
+
+```ts
+const SLOT_KEY_BY_TYPE = new Map<unknown, SingleSlotKey>([
+ [SidebarSlot, "sidebar"],
+ [SidebarHeader, "sidebarHeader"],
+ [MobileHeader, "mobileHeader"],
+ [ThreadHeader, "threadHeader"],
+ [WelcomeScreen, "welcome"],
+ [Composer, "composer"],
+ [Workspace, "workspace"],
+]);
+// <AgentInterface.Route> is collected separately into `routes[]`.
+// Anything else falls through to `rest[]` and is rendered as-is at the end.
+```
+
+### ⚠️ Slots are matched by reference, not by name
+
+A child is recognized **only** if `child.type === <the exact component reference>`. That means:
+
+- Wrapping a slot in `React.memo`, an HOC, a styled wrapper, or re-exporting it through a _second_
+ module instance **silently breaks slot detection** — the element lands in `rest[]` and the
+ default is rendered instead.
+- You must use the canonical `AgentInterface.*` members (e.g. `<AgentInterface.Composer>`), not a
+ hand-rolled clone.
+
+### Single-slot rules (dev warnings)
+
+- Passing the **same slot twice** keeps the first and `console.warn`s in dev (`extractSlots`).
+- A **top-level** `<AgentInterface.SidebarHeader>` is _ignored_ when `<AgentInterface.Sidebar>` is
+ also present (put the header _inside_ the Sidebar instead) — also a dev warning.
+
+The full list of static members and whether each is a top-level slot:
+
+| Member | Top-level slot? | Role |
+| --------------------------------- | ------------------- | -------------------------------------------------- |
+| `AgentInterface.Sidebar` | ✅ `sidebar` | Replace the whole sidebar; you compose its insides |
+| `AgentInterface.SidebarHeader` | ✅ `sidebarHeader`¹ | Default sidebar's header (logo + name + collapse) |
+| `AgentInterface.MobileHeader` | ✅ `mobileHeader` | Top bar on mobile |
+| `AgentInterface.ThreadHeader` | ✅ `threadHeader` | Thread region header (actions, workspace toggle) |
+| `AgentInterface.Welcome` | ✅ `welcome` | Empty-state hero (`WelcomeScreen`) |
+| `AgentInterface.Composer` | ✅ `composer` | Message input |
+| `AgentInterface.Workspace` | ✅ `workspace` | Per-thread artifact rail |
+| `AgentInterface.Route` | ✅ `routes[]` | Custom routable view (see Routing) |
+| `AgentInterface.SidebarContent` | ❌ building block | Scrollable region inside a custom Sidebar |
+| `AgentInterface.SidebarSeparator` | ❌ building block | Divider inside a custom Sidebar |
+| `AgentInterface.SidebarItem` | ❌ building block | Styled nav row (also exported standalone) |
+| `AgentInterface.ArtifactNav` | ❌ building block | Artifact-category nav rows |
+| `AgentInterface.NewChatButton` | ❌ building block | "New chat" affordance |
+| `AgentInterface.ThreadList` | ❌ building block | Date-grouped thread history |
+| `AgentInterface.Messages` | ❌ building block | The message list itself |
+| `AgentInterface.MessageLoading` | ❌ building block | Streaming loader row |
+| `AgentInterface.ScrollArea` | ❌ building block | Auto-scroll container |
+
+¹ Only honored at top level when no `Sidebar` slot is present; otherwise nest it inside `Sidebar`.
+
+---
+
+## Public API reference
+
+### `<AgentInterface>` props
+
+Defined as `AgentInterfaceProps` in `AgentInterface.tsx`. It `extends Omit<ChatProviderProps,
+"children">`, so the data props below are **forwarded to react-headless's `<ChatProvider>`**.
+
+**Forwarded to `ChatProvider`** (from `@openuidev/react-headless`):
+
+| Prop | Type | Notes |
+| -------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------- |
+| `storage` | `ChatStorage` | Thread persistence (`listThreads`, `getMessages`, …) and optional `artifact` storage for the browser |
+| `llm` | LLM transport | The streaming send adapter |
+| `artifactRenderers` | `AppRenderer[]` | Tool-name → renderer (`parser`/`preview`/`actual`); drives inline previews + detailed view |
+| `artifactCategories` | `{ name; filter: { type: string[] } }[]` | Splits the artifact browser & workspace into sections |
+
+> ⚠️ Only those four `ChatProviderProps` are actually forwarded (they're destructured explicitly in
+> `AgentInterface.tsx`). Other `ChatProviderProps` are accepted by the _type_ but not passed through.
+
+**AgentInterface-specific:**
+
+| Prop | Type | Default | Notes |
+| ---------------------- | ------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------- |
+| `componentLibrary` | `Library` (react-lang) | — | Auto-derive assistant (and user) message rendering via GenUI when `components.AssistantMessage` is absent |
+| `components` | `{ AssistantMessage?; UserMessage? }` | — | Explicit render overrides; take precedence over `componentLibrary` |
+| `theme` | `ThemeProps` | — | Passed to `<ThemeProvider>` |
+| `disableThemeProvider` | `boolean` | `false` | Skip the internal `<ThemeProvider>` wrapper |
+| `logoUrl` | `string` | `""` | Brand logo (default `SidebarHeader` + `MobileHeader`) |
+| `agentName` | `string` | `""` | Agent display name |
+| `starters` | `ConversationStarterProps[]` | — | Global starters inherited by Welcome (if active) or the Composer |
+| `starterVariant` | `"short" \| "long"` | — | Layout variant for inherited starters |
+| `path` | `string` | — | **Controlled** current path (pair with `onNavigate`); `undefined` = thread view |
+| `defaultPath` | `string` | — | **Uncontrolled** initial path (ignored when `onNavigate` is set) |
+| `onNavigate` | `(next: string \| undefined) => void` | — | Presence selects controlled mode |
+| `children` | `ReactNode` | — | Slots (see above) |
+
+### Custom message components
+
+```ts
+type AssistantMessageComponent = React.ComponentType<{
+ message: AssistantMessage;
+ isStreaming: boolean;
+}>;
+type UserMessageComponent = React.ComponentType<{ message: UserMessage }>;
+```
+
+Provided via `components`, these **fully replace** the default rendering (including the container
+and avatar). Resolution order, per message kind:
+`components.X` → GenUI (if `componentLibrary`) → built-in default.
+
+### Named exports (from `index.ts`)
+
+| Export | Kind | Purpose |
+| ------------------------------------------------- | ---------------- | ------------------------------------------ |
+| `AgentInterface` | component | The compound root |
+| `AgentInterfaceProps`, `AgentInterfaceComponents` | types | Root props / override map |
+| `SidebarItem`, `SidebarItemProps` | component + type | Standalone nav row |
+| `ArtifactNav`, `ArtifactNavProps` | component + type | Artifact-category nav |
+| `useNav`, `NavContextValue` | hook + type | Read/drive navigation from inside the tree |
+| `RouteProps` | type | `<AgentInterface.Route>` props |
+| `WorkspaceProps` | type | `<AgentInterface.Workspace>` props |
+| `artifactListPath`, `artifactViewPath` | functions | Build reserved `artifacts/…` paths |
+
+---
+
+## Render tree & provider stack
+
+`AgentInterface.tsx` mounts the providers; `Container.tsx` mounts the UI-state providers; the body
+(`AgentInterfaceBody`) does the view switch.
+
+```
+<ThemeProvider> (skipped if disableThemeProvider)
+ └ <ChatProvider> react-headless: threads, artifacts, detailed-view stores
+ └ <NavProvider> path + navigate (controlled/uncontrolled)
+ └ <StartersProvider> global starters + variant
+ └ AgentInterfaceBody → <Container>
+ └ <AgentInterfaceStoreProvider> sidebar/workspace open, agentName, logoUrl
+ └ <ShellStoreProvider> library-wide shell store (see State model)
+ └ <LayoutContextProvider> "mobile" | "tray" | "fullscreen"
+ └ <Tooltip.Provider> single shared Radix tooltip provider (delay 250ms)
+ └ .openui-agent-container
+ ├ <SidebarContainer> … (default sidebar OR your <Sidebar> slot)
+ └ view switch:
+ ├ reserved `artifacts/…` → ArtifactBrowserPage | ArtifactViewPage
+ ├ matched <Route> → route children
+ └ thread view (path===undefined):
+ <ThreadContainer>
+ MobileHeader · ThreadHeader · [Welcome] ·
+ <ScrollArea><Messages/></ScrollArea> · Composer
+ <Workspace/> (rail, thread view only)
+ └ slots.rest (unrecognized children, rendered as-is)
+```
+
+The **view switch** (in `AgentInterfaceBody`) has a strict priority:
+
+1. **Reserved `artifacts/` paths** are matched _before_ user routes (`parseArtifactPath`).
+2. Then an exact-match user `<Route path="…">`.
+3. Otherwise (`path === undefined`) the normal thread view, which is the **only** view that also
+ renders the `Workspace` rail.
+
+---
+
+## Composition modes (A / B / C)
+
+Most slots support three levels of customization (the codebase comments call them Modes A/B/C):
+
+- **Mode A — omit it.** The default renders. (`Default` story.)
+- **Mode B — pass props.** Tweak the default without rebuilding it, e.g.
+ `<AgentInterface.SidebarHeader logo={…} agentName={…} collapseButton={false} />`
+ (`CustomSidebarHeader` story).
+- **Mode C — pass children.** You own the entire inside; Mode B props are ignored (and dev-warns if
+ both are passed). e.g. `<AgentInterface.Sidebar>…</AgentInterface.Sidebar>` (`FullSidebarOverride`),
+ `<AgentInterface.Workspace>…</AgentInterface.Workspace>` (`WorkspaceCustomChildren`),
+ `<AgentInterface.Welcome>…</AgentInterface.Welcome>` (`WelcomeCustomChildren`).
+
+When you go Mode C on the Sidebar, compose it from the building-block members:
+`SidebarHeader`, `SidebarContent`, `SidebarSeparator`, `SidebarItem`, `ArtifactNav`, `NewChatButton`,
+`ThreadList`.
+
+---
+
+## State & data model
+
+### External (react-headless) — the data
+
+Mounted by `<ChatProvider>`. Read via hooks:
+
+- `useThread(selector)` — `messages`, `isRunning`, `isLoadingMessages`, `threadError`,
+ `processMessage`, `cancelMessage`.
+- `useThreadList(selector)` — thread history + `selectThread`.
+- `useArtifactList()` / `useArtifactCategories()` / `useArtifactRendererRegistry()` /
+ `useArtifactStorage()` — the artifact registry & config.
+- `useDetailedView(viewId)` / `useDetailedViewStore()` / `useActiveDetailedView()` — the side-panel
+ open/active state.
+- `MessageProvider` wraps each message so deep children can read it.
+
+### Internal — UI/chrome state
+
+Two **separate** zustand stores are mounted in `Container.tsx`. They are _not_ the same store and
+serve different consumers:
+
+| Store | File | Holds | Read with | Used by |
+| ----------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------ |
+| **AgentInterfaceStore** | `_shared/store/store.tsx` | `isSidebarOpen` (default **true**), `isWorkspaceOpen` (default **false**), `agentName`, `logoUrl` | `useAgentInterfaceStore` | All AgentInterface chrome (sidebar, workspace toggles, header) |
+| **ShellStore** | `../_shared/store/store.tsx` (library-wide, shared with `OpenUIChat`) | `isSidebarOpen`, `isWorkspaceOpen` (default **true**), `agentName`, `logoUrl`, `showAssistantLogo` | `useShellStore` | The GenUI assistant-message components, which read `agentName`/`logoUrl`/`showAssistantLogo` from here |
+
+Both are seeded from the same `logoUrl`/`agentName` and kept in sync to props via effects, but
+their `isWorkspaceOpen` defaults differ and they are **not** cross-synced. See
+[Gotchas](#gotchas--known-rough-edges).
+
+Plus three React contexts:
+
+- **`NavContext`** (`_shared/navContext.tsx`) — `{ path, navigate }`. `useNav()` (throws outside the
+ tree) and `useOptionalNav()` (returns `null`).
+- **`StartersContext`** (`_shared/startersContext.tsx`) — inherited `starters` + `starterVariant`.
+- **`LayoutContext`** (`../../context/LayoutContext`) — `"mobile" | "tray" | "fullscreen"`, derived
+ from the container's measured width.
+- **`SidebarVisualStateContext`** (`Sidebar.tsx`) — the sidebar's animation state machine
+ (`expanded`/`collapsing`/`collapsed`/`expanding`) so items know when to show collapsed tooltips.
+
+---
+
+## Navigation & routing
+
+Navigation is a single `path: string | undefined` string held by `NavProvider`, with the standard
+controlled/uncontrolled split:
+
+- **Uncontrolled** (default): internal state starts at `defaultPath`.
+- **Controlled**: pass `onNavigate` (its presence flips the switch) and own `path` yourself.
+ (`Routing` and `ControlledRouting` stories.)
+
+`path === undefined` ⇒ the thread view. Any other string is matched in this order:
+
+1. **Reserved artifact paths** (`_shared/artifactPaths.ts`), matched first:
+ - `artifacts/{category}` → searchable list (`ArtifactBrowserPage`)
+ - `artifacts/{category}/{id}` → full-page view (`ArtifactViewPage`)
+ - `{category}` is URI-encoded, or the literal `all` when no categories are configured.
+ - Build them with `artifactListPath(name?)` / `artifactViewPath(name, id)`; parse with
+ `parseArtifactPath`. **Controlled consumers must round-trip these paths verbatim.**
+2. **User `<AgentInterface.Route path="…">`** — exact match only (no params/wildcards in v1). The
+ route's children replace the _entire_ thread region (header, messages, composer all hidden).
+ Multiple `Route` siblings are supported.
+
+`SidebarItem` integrates with nav: give it a `path` and it calls `navigate(path)` on click and
+auto-selects when `nav.path === path` (override with the `selected` prop). On mobile it also closes
+the sidebar after navigating.
+
+---
+
+## Message rendering pipeline
+
+Entry point is `<Messages>` (in `Thread.tsx`), rendered inside `<ScrollArea>`:
+
+```
+<Messages>
+ messages.map → <MessageProvider><RenderMessage …/></MessageProvider>
+ if isRunning → loader (<MessageLoading/>)
+ else if threadError → <ThreadError/> (Callout, "Something went wrong")
+```
+
+`RenderMessage` (memoized) switches on `message.role`:
+
+- **`tool`** → renders `null` (tool output is rendered _inline under its parent assistant message_).
+- **`assistant`** → `components.AssistantMessage` if provided, else
+ `AssistantMessageContainer › AssistantMessageContent`.
+- **`user`** → `components.UserMessage` if provided, else `UserMessageContainer › UserMessageContent`.
+- **other roles** (`system`/`developer`/`reasoning`/`activity`) → skipped.
+
+### Assistant content + tool calls
+
+`AssistantMessageContent`:
+
+1. Renders `message.content` via `<MarkDownRenderer>`.
+2. Renders each `message.toolCalls[]` as a `<ToolCallComponent>` (the call bubble).
+3. **Pairs tool results**: scans `allMessages` for the run of consecutive `role: "tool"` messages
+ immediately after this assistant message, matches each `toolMessage.toolCallId` back to a
+ `toolCall`, and dispatches to `<ToolMessageRenderer>` (falling back to `<ToolResult>` when no
+ renderer matches). _(This pairing is O(n) per message and is a known cleanup target — see
+ Gotchas.)_
+
+### Tool → artifact renderer dispatch
+
+`ToolMessageRenderer` (`_shared/tool-renderer/`) looks up `toolCall.function.name` in the
+`artifactRenderers` registry:
+
+- **No match** → renders the `fallback` (`<ToolResult>`).
+- **Match** → `<RendererInstance>`, which:
+ 1. runs `renderer.parser({ args, response }, { isStreaming })` → `{ props, meta } | null`,
+ 2. if `meta` is present, registers the artifact in ThreadContext (so it appears in the Workspace
+ rail) and unregisters on unmount,
+ 3. renders `renderer.preview(props, controls)` **inline** + a `<DetailedViewPanel>` containing
+ `renderer.actual(props, controls)` for the side panel.
+
+`RendererInstance` carefully keeps an open detailed view alive as a streamed artifact's `viewId`
+transitions from a temporary `useId()` to its real `${id}:${version}`, and re-points the active view
+when an edit bumps the version onto a _new_ instance.
+
+### User content
+
+`UserMessageContent.tsx` handles the **full AG-UI `InputContent` union** (`text | image | audio |
+video | document | binary`):
+
+- String content → stripped of `<content>`/`<context>` sentinel wrappers (`separateContentAndContext`).
+- Array content → each part resolved by `resolveInputPart()` into a render-ready descriptor, then
+ rendered in array order (preserving text/media interleave).
+- **Security is built in**: every URL is vetted by `sanitizeUrl` (only `http(s):` + allowlisted
+ `data:`), base64 `data:` URIs by `buildDataUri` (`ALLOWED_DATA_MIME` = image/audio/video + PDF
+ only — `text/html` and arbitrary `application/*` are deliberately excluded as XSS surface).
+- Media renders as `<img>`/`<audio>`/`<video>` (lazy, with `onError` → file chip); everything else,
+ or any failed/blocked source, degrades to a **downloadable file chip** rather than being dropped.
+- A `default: never` exhaustiveness guard makes any new union member a compile error.
+
+---
+
+## Artifacts, the Workspace rail & DetailedView
+
+There are two distinct artifact surfaces, easy to confuse:
+
+- **Workspace rail** (`Workspace.tsx`) — a per-thread, right-edge list of artifacts _registered by
+ the current thread's tool calls_ (via `RendererInstance` → ThreadContext). Renders **nothing**
+ while the registry is empty, so drop-in users without `artifactRenderers` never see it. It has
+ All / Artifacts / Apps tabs (an "Apps" category is detected by `category.name.toLowerCase() ===
+"apps"`), an animated tab indicator, and a mobile drawer. Clicking an item opens its DetailedView;
+ the rail auto-closes while a DetailedView is open. Shown only in the thread view; hidden on mobile
+ and on Route/artifact pages.
+- **Artifact browser** (`ArtifactBrowserPage` / `ArtifactViewPage`) — a _global_, storage-backed,
+ searchable browser at the reserved `artifacts/…` paths, driven by `storage.artifact`. The
+ `ArtifactNav` sidebar entries link into it.
+
+**DetailedView** is the resizable side panel. On desktop, `ThreadContainer` splits into a chat panel
+
+- a `ResizableSeparator` + the detailed-view panel (`useDetailedViewResize` drives the drag and
+ writes width directly to the panel ref). On mobile it becomes an overlay (`DetailedViewOverlay`).
+ `DetailedViewPanel` portals its content into `DetailedViewPortalTarget`.
+
+An `AppRenderer` (consumer-defined) is the unit that powers all of this:
+
+```ts
+{
+ type: "th_dashboard",
+ toolName: "th_dashboard:create", // matched against toolCall.function.name
+ parser: ({ args, response }, { isStreaming }) =>
+ response ? { props, meta: { id, version, heading } } : null,
+ preview: (props, controls) => <InlineCard …/>, // shown inline in the thread
+ actual: (props, controls) => <FullView …/>, // shown in the detailed-view panel
+}
+```
+
+> The `type` strings (`th_dashboard` / `th_report` / `th_presentation`) and the `${type}:create`
+> tool-name convention are **consumer conventions** mirrored on the agent side — they are documented
+> by the stories, not enforced by the library.
+
+---
+
+## Layout & responsiveness
+
+`Container.tsx` measures its own width (`useElementSize`) and derives a layout mode:
+
+```
+width < 768 → "mobile" (.openui-agent-container--mobile)
+width > 768 → "fullscreen"
+width === 768 (exact) → "tray" (only a 1px window; rarely hit, has no CSS; see Gotchas)
+```
+
+The breakpoint is currently a **hardcoded `768`** with a `// TODO: revisit this logic`.
+
+Responsiveness is **class-driven, not media-query-driven.** The dominant mechanism is the ancestor
+selector `.openui-agent-container--mobile &` (plus `--detailed-view-active`), used throughout the
+SCSS. There are only two real `@media` queries in the whole component (and one of them is currently
+a no-op). If you need responsive behavior, prefer the layout class over adding a breakpoint.
+
+---
+
+## Styling & theming
+
+### Tokens
+
+Every SCSS partial starts with `@use "../../cssUtils" as cssUtils;` and references **design tokens**
+as Sass aliases that compile to CSS custom properties:
+
+```scss
+padding: cssUtils.$space-m; // → var(--openui-space-m)
+color: cssUtils.$text-neutral-primary; // → var(--openui-...)
+border-radius: cssUtils.$radius-xl;
+@include cssUtils.typography($family, $variant); // font shorthand
+```
+
+- The token prefix is **`openui`** (not `crayon`). `cssUtils.scss` + `openui-defaults.scss` are
+ **auto-generated** — don't hand-edit them. They emit `:root` custom properties (including a
+ `prefers-color-scheme: dark` block) plus the `$alias` Sass layer.
+- **Color discipline is total:** there are _zero_ hardcoded hex/rgb/oklch values in the component.
+ Always go through a token. Radii, shadows, and most spacing are tokenized too.
+- **Theme** consumers override `--openui-*` custom properties (via `theme` → `<ThemeProvider>`, or
+ their own CSS).
+
+### Build / aggregation
+
+```
+AgentInterface/agentInterface.scss @use's the 11 root + components/ partials (sidebar, threadlist,
+ thread, mobileHeader, resizableSeparator, conversationStarter,
+ welcomeScreen, components/composer, components/desktopWelcomeComposer,
+ artifactBrowser, workspaceSidebar) + the .openui-agent-container rules
+ → components/index.scss @forward "./AgentInterface/agentInterface.scss"; (line 44)
+ → components/index.css the shipped aggregate
+```
+
+Two things that chain does **not** include:
+
+- The **detailed-view** styles (`_shared/detailed-view/*.scss`) actually ship via the _library-wide_
+ `components/_shared/shared.scss` (forwarded at `components/index.scss` line 61), **not** via
+ `agentInterface.scss`.
+- `AgentInterface/_shared/shared.scss` is currently **orphaned** — nothing `@use`s / `@forward`s it.
+
+There is **no** `src/styles/agentInterface.scss` entry, so AgentInterface ships only inside the
+aggregate `components/index.css` — it has no granular per-component CSS twin, and is therefore **not
+importable on its own** via the `./layered/styles/*` granular paths. (See Gotchas.)
+
+### Layered CSS opt-in
+
+The `@layer openui { … }` wrapping is applied **at build time** by `cp-css.js` (it mirrors the
+unlayered output into `dist/layered/**`). **Do not write `@layer` in source SCSS** — none exists
+today, and that's correct.
+
+### Conventions when adding styles
+
+- State via **BEM modifiers** (`--collapsed`, `--selected`, `--active`, `--animating`) and
+ **data-attributes** (`[data-sidebar-visual-state]`, `[data-drafting]`, `[data-overflow-*]`).
+- `:has()` is used for cross-component layout coordination.
+- Hoist local layout/motion constants as `$vars` at the top of the partial (see `sidebar.scss`,
+ `workspaceSidebar.scss`, `composer.scss` for the pattern).
+- New partial? Add a `@use "./yourFile.scss";` line to `agentInterface.scss`.
+
+---
+
+## Directory guide
+
+```
+AgentInterface/
+├ AgentInterface.tsx Root: props, extractSlots, provider stack, AgentInterfaceBody view switch
+├ Container.tsx Flex shell; width→layout mode; mounts the two stores + LayoutContext + Tooltip.Provider
+├ Route.tsx Slot marker for routable views (renders null; consumed by parent)
+├ Sidebar.tsx SidebarContainer/Header/Content/Separator + collapse/expand state machine
+├ SidebarItem.tsx Styled, nav-aware clickable row (exported)
+├ SidebarSlot.tsx The <AgentInterface.Sidebar> slot marker
+├ SidebarTooltip.tsx Collapsed-sidebar tooltip (right/center, fixed offset)
+├ ThreadList.tsx Date-grouped thread history + per-thread menu
+├ Thread.tsx ThreadContainer, ScrollArea, Messages, RenderMessage, ThreadHeader, ThreadError, loader
+├ UserMessageContent.tsx Full AG-UI InputContent union renderer (+ URL/data allowlists, file chips)
+├ MobileHeader.tsx Mobile top bar
+├ NewChatButton.tsx New-chat affordance
+├ Composer.tsx Thin re-export of components/Composer
+├ ConversationStarter.tsx Starter chips ("short" | "long" variant)
+├ WelcomeScreen.tsx Empty-state hero (title/description/image/starters or children)
+├ Workspace.tsx Per-thread artifact rail (tabs, sections, mobile drawer)
+├ ArtifactBrowserPage.tsx Global searchable artifact list (also exports preview/format helpers)
+├ ArtifactNav.tsx Sidebar category nav into the browser (exported)
+├ ArtifactViewPage.tsx Full-page artifact view
+├ ResizableSeparator.tsx Keyboard+ARIA resize handle for the detailed-view split
+├ useDetailedViewResize.ts Drag/keyboard resize logic (writes panel width imperatively)
+├ components/ Composer + DesktopWelcomeComposer (and their SCSS)
+├ _shared/
+│ ├ store/ AgentInterfaceStore (sidebar/workspace/agentName/logoUrl)
+│ ├ navContext.tsx NavProvider / useNav / useOptionalNav
+│ ├ startersContext.tsx StartersProvider / useStartersFromContext
+│ ├ artifactPaths.ts Reserved artifacts/… path build+parse
+│ ├ tool-renderer/ ToolMessageRenderer + RendererInstance
+│ ├ detailed-view/ DetailedViewOverlay/Panel/PortalTarget
+│ ├ types/ AssistantMessageComponent / UserMessageComponent
+│ ├ utils/ misc helpers
+│ └ AgentInterfaceTooltip.tsx, GalleryHorizontalEndIcon.tsx
+├ *.scss Co-located styles (aggregated by agentInterface.scss)
+└ stories/ Storybook — the de-facto usage reference
+```
+
+> Note: `_shared/` here is **AgentInterface-local**. The sibling `components/_shared/` is a
+> **library-wide** shared dir (used by `OpenUIChat` too). Container pulls the `ShellStore`
+> from the library-wide one; everything else AgentInterface uses comes from its own local `_shared`.
+
+---
+
+## Extending the component
+
+**Add a new top-level slot**
+
+1. Create the component and export it.
+2. Attach it as a static member at the bottom of `AgentInterface.tsx`
+ (`AgentInterface.MyThing = MyThing;`) and add it to the `AgentInterfaceComponent` interface.
+3. Add `[MyThing, "myThing"]` to `SLOT_KEY_BY_TYPE` and a `myThing?: ReactElement` field to
+ `ExtractedSlots`.
+4. Render `slots.myThing ?? <Default/>` in the appropriate branch of `AgentInterfaceBody`.
+
+**Add a custom message renderer** — pass `components={{ AssistantMessage, UserMessage }}` (replaces
+default rendering entirely), or a `componentLibrary` for GenUI auto-derivation.
+
+**Add an artifact type** — define an `AppRenderer` (`type` + `toolName` + `parser`/`preview`/`actual`),
+pass it in `artifactRenderers`, and optionally group it via `artifactCategories`. The agent emits a
+tool call named `toolName`; the rest is automatic (inline preview, workspace entry, detailed view).
+
+**Add a route** — drop `<AgentInterface.Route path="/x">…</AgentInterface.Route>` as a child and
+navigate to `/x` (e.g. a `SidebarItem path="/x"`).
+
+---
+
+## Gotchas & known rough edges
+
+These are real, current sharp edges — worth knowing before you touch the area. Deeper analysis and
+prioritization live in `.workspace/2026-06-21-agentinterface-study.md` and
+`.workspace/2026-06-21-usermessagecontent-research.md`.
+
+- **Slot identity** — see the warning above; `memo`/HOC/duplicate-module wrapping silently drops a
+ slot. Use the canonical `AgentInterface.*` members.
+- **Two stores** — `AgentInterfaceStore` vs library `ShellStore` are mounted side by side with
+ diverging `isWorkspaceOpen` defaults and no cross-sync. Read from the right one (chrome →
+ `useAgentInterfaceStore`; assistant-message logo/name → `useShellStore`).
+- **Local vs library `_shared`** — `tool-renderer`, `detailed-view`, `types`, `utils` exist in both
+ `AgentInterface/_shared/` and the library-wide `components/_shared/`. They overlap; confirm which
+ one you're importing.
+- **Hardcoded values** — the `768` breakpoint (`Container.tsx`), the "reading column" widths
+ (`880`/`800`px repeated across several partials), chat-resize clamps (`useDetailedViewResize.ts`,
+ where `MIN === INITIAL` so the panel can't shrink below its initial width), motion durations/
+ easings, the z-index ladder, and a duplicated scrollbar block are all candidates to lift into
+ shared tokens/props.
+- **English-only strings & aria-labels** — placeholders, `"New Chat"`, workspace tab labels, date
+ groups, and many aria-labels are baked English with no i18n surface. `ArtifactNav` even derives a
+ category's icon-background class by matching the English label.
+- **`logoUrl`/`agentName` default to `""`** — omitting them yields an empty-looking header.
+- **`prefers-reduced-motion`** is not honored anywhere despite heavy animation.
+- **`tray` layout** (exact integer width `768`) adds no CSS class and is only reachable in a 1px
+ window — `width` is `element.clientWidth` (an integer), so `768` is attainable but rare. Treat with care.
+- **Typography token (fixed in `4c801739`)** — earlier code passed the invalid
+ `typography(primary, default)` (there is no `primary` category, so it emitted no `font`).
+ `thread.scss` and `artifactBrowser.scss` now correctly use `typography(body, default)`. Other
+ components outside AgentInterface may still carry the invalid call — a separate per-site sweep.
+
+> ⚠️ Historical note: an earlier study claimed `UserMessageContent` was incomplete (text+binary
+> only). That is **no longer true** — `UserMessageContent.tsx` now implements the full `InputContent`
+> union with allowlists and chip fallbacks, and it is wired into `Thread.tsx`. Trust the code.
+
+---
+
+## Local development
+
+- **Stories / visual reference:** `stories/AgentInterface.stories.tsx` (run the package's Storybook).
+ The stories use mock LLM/storage helpers from `__test-helpers/mockChat`.
+- **Styles:** edit the co-located `*.scss`; new partials must be `@use`d from `agentInterface.scss`.
+ Never edit the generated `cssUtils.scss` / `openui-defaults.scss`.
+- **Tokens:** if you need a value, check for an existing `$space-*` / `$radius-*` / `$text-*` token
+ before introducing a literal.
+
+```
+
+```
diff --git a/packages/react-ui/src/components/AgentInterface/ResizableSeparator.tsx b/packages/react-ui/src/components/AgentInterface/ResizableSeparator.tsx
new file mode 100644
index 000000000..7337c3f0c
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/ResizableSeparator.tsx
@@ -0,0 +1,145 @@
+import clsx from "clsx";
+import { useEffect, useRef, useState } from "react";
+import type { ResizeAriaValues } from "./useDetailedViewResize";
+
+interface ResizableSeparatorProps {
+ /** Mouse drag: receives the pointer's absolute clientX. */
+ onResize: (clientX: number) => void;
+ /** Keyboard resize: receives a relative px delta (±Infinity snaps to min/max). */
+ onResizeStep: (deltaPx: number) => void;
+ onDragStart: () => void;
+ onDragEnd: () => void;
+ /** Returns the current size as ARIA percentages, or null if unmeasurable. */
+ getAriaValues: () => ResizeAriaValues | null;
+ /** id of the panel this separator resizes (for aria-controls). */
+ controlsId?: string;
+ ariaLabel?: string;
+ className?: string;
+}
+
+// Keyboard resize step sizes in px (Shift = coarse).
+const KEYBOARD_STEP = 16;
+const KEYBOARD_STEP_LARGE = 64;
+
+/**
+ * A draggable, keyboard-operable vertical separator for resizing panels.
+ * Used between chat and detailed-view panels in desktop mode.
+ *
+ * Implements the WAI-ARIA window-splitter pattern: focusable, `role="separator"`,
+ * Left/Right (Shift for larger steps) to resize, Home/End to snap to min/max.
+ */
+export const ResizableSeparator = ({
+ onResize,
+ onResizeStep,
+ onDragStart,
+ onDragEnd,
+ getAriaValues,
+ controlsId,
+ ariaLabel = "Resize panel",
+ className,
+}: ResizableSeparatorProps) => {
+ const isDraggingRef = useRef(false);
+ const onResizeRef = useRef(onResize);
+ const onDragStartRef = useRef(onDragStart);
+ const onDragEndRef = useRef(onDragEnd);
+
+ const [aria, setAria] = useState<ResizeAriaValues | null>(null);
+ // Refresh the reflected ARIA values from the latest measurement.
+ const syncAria = () => setAria(getAriaValues());
+ const syncAriaRef = useRef(syncAria);
+ syncAriaRef.current = syncAria;
+
+ // Keep callback refs up to date without triggering effect re-runs
+ useEffect(() => {
+ onResizeRef.current = onResize;
+ onDragStartRef.current = onDragStart;
+ onDragEndRef.current = onDragEnd;
+ }, [onResize, onDragStart, onDragEnd]);
+
+ // Populate ARIA values on mount so a focusable separator always exposes
+ // aria-valuenow (refreshed on focus/resize thereafter).
+ useEffect(() => {
+ syncAriaRef.current();
+ }, []);
+
+ // Global mouse event handlers for drag behavior.
+ // Uses refs instead of dependencies to avoid re-creating listeners.
+ useEffect(() => {
+ const handleMouseMove = (e: MouseEvent) => {
+ if (isDraggingRef.current) {
+ e.preventDefault();
+ onResizeRef.current(e.clientX);
+ }
+ };
+
+ const handleMouseUp = () => {
+ if (isDraggingRef.current) {
+ isDraggingRef.current = false;
+ onDragEndRef.current();
+ // Reset cursor styles
+ document.body.style.cursor = "";
+ document.body.style.userSelect = "";
+ // Reflect the dragged-to size for assistive tech.
+ syncAriaRef.current();
+ }
+ };
+
+ document.addEventListener("mousemove", handleMouseMove);
+ document.addEventListener("mouseup", handleMouseUp);
+
+ return () => {
+ document.removeEventListener("mousemove", handleMouseMove);
+ document.removeEventListener("mouseup", handleMouseUp);
+ };
+ }, []); // Empty deps - handlers use refs to access latest callbacks
+
+ const handleMouseDown = () => {
+ isDraggingRef.current = true;
+ onDragStartRef.current();
+ document.body.style.cursor = "col-resize";
+ document.body.style.userSelect = "none";
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
+ let delta: number | null = null;
+ switch (e.key) {
+ case "ArrowLeft":
+ delta = -(e.shiftKey ? KEYBOARD_STEP_LARGE : KEYBOARD_STEP);
+ break;
+ case "ArrowRight":
+ delta = e.shiftKey ? KEYBOARD_STEP_LARGE : KEYBOARD_STEP;
+ break;
+ case "Home":
+ delta = -Infinity; // snap to smallest chat panel
+ break;
+ case "End":
+ delta = Infinity; // snap to largest chat panel
+ break;
+ default:
+ return;
+ }
+ e.preventDefault();
+ onResizeStep(delta);
+ syncAria();
+ };
+
+ return (
+ <div
+ role="separator"
+ aria-orientation="vertical"
+ aria-label={ariaLabel}
+ aria-controls={controlsId}
+ aria-valuenow={aria?.now}
+ aria-valuemin={aria?.min}
+ aria-valuemax={aria?.max}
+ aria-valuetext={aria ? `${aria.now}%` : undefined}
+ tabIndex={0}
+ className={clsx("openui-agent-resizable-separator", className)}
+ onMouseDown={handleMouseDown}
+ onKeyDown={handleKeyDown}
+ onFocus={syncAria}
+ >
+ <div className="openui-agent-resizable-separator__handle" />
+ </div>
+ );
+};
diff --git a/packages/react-ui/src/components/AgentInterface/Route.tsx b/packages/react-ui/src/components/AgentInterface/Route.tsx
new file mode 100644
index 000000000..28c67231e
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/Route.tsx
@@ -0,0 +1,21 @@
+import type { ReactNode } from "react";
+
+export interface RouteProps {
+ /** Exact path match (no wildcards or params in v1). */
+ path: string;
+ /** Content shown in the thread region when this route is active. */
+ children?: ReactNode;
+}
+
+/**
+ * Slot marker for a routable view. Never rendered directly — the parent
+ * <AgentInterface> extracts all Routes from its children, finds the one
+ * whose `path` matches the current nav state, and renders that Route's
+ * children in place of the entire thread region (MobileHeader, ThreadHeader,
+ * ScrollArea/Messages, Composer all hidden).
+ *
+ * Use multiple <AgentInterface.Route> siblings to define separate views.
+ * When no Route matches, the thread region renders normally.
+ */
+export const Route = (_props: RouteProps) => null;
+Route.displayName = "AgentInterface.Route";
diff --git a/packages/react-ui/src/components/Shell/Sidebar.tsx b/packages/react-ui/src/components/AgentInterface/Sidebar.tsx
similarity index 56%
rename from packages/react-ui/src/components/Shell/Sidebar.tsx
rename to packages/react-ui/src/components/AgentInterface/Sidebar.tsx
index 343b83cba..af244dec2 100644
--- a/packages/react-ui/src/components/Shell/Sidebar.tsx
+++ b/packages/react-ui/src/components/AgentInterface/Sidebar.tsx
@@ -1,10 +1,11 @@
-import { useActiveArtifact } from "@openuidev/react-headless";
+import { useActiveDetailedView } from "@openuidev/react-headless";
import clsx from "clsx";
-import { PanelLeftClose, PanelLeftOpen } from "lucide-react";
+import { PanelLeft } from "lucide-react";
import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useLayoutContext } from "../../context/LayoutContext";
import { IconButton } from "../IconButton";
-import { useShellStore } from "../_shared/store";
+import { AgentInterfaceTooltip } from "./_shared/AgentInterfaceTooltip";
+import { useAgentInterfaceStore } from "./_shared/store";
const SIDEBAR_FADE_DURATION_MS = 90;
const SIDEBAR_RESIZE_DURATION_MS = 160;
@@ -18,14 +19,6 @@ const SidebarVisualStateContext = createContext<{
export const useOptionalSidebarVisualState = () => useContext(SidebarVisualStateContext);
-const useSidebarVisualState = () => {
- const context = useOptionalSidebarVisualState();
- if (!context) {
- throw new Error("useSidebarVisualState must be used within SidebarContainer");
- }
- return context;
-};
-
export const SidebarContainer = ({
children,
className,
@@ -33,11 +26,11 @@ export const SidebarContainer = ({
children?: React.ReactNode;
className?: string;
}) => {
- const { isSidebarOpen, setIsSidebarOpen } = useShellStore((state) => ({
+ const { isSidebarOpen, setIsSidebarOpen } = useAgentInterfaceStore((state) => ({
isSidebarOpen: state.isSidebarOpen,
setIsSidebarOpen: state.setIsSidebarOpen,
}));
- const { isArtifactActive } = useActiveArtifact();
+ const { isDetailedViewActive } = useActiveDetailedView();
const { layout } = useLayoutContext() || {};
const isMobile = layout === "mobile";
const [isCollapsedLayout, setIsCollapsedLayout] = useState(!isSidebarOpen);
@@ -64,8 +57,6 @@ export const SidebarContainer = ({
const justSwitchedLayout = previousIsMobileRef.current !== isMobile;
previousIsMobileRef.current = isMobile;
- // On viewport breakpoint change, force sidebar open state and let the effect
- // re-run with the new `isSidebarOpen` to drive the animation.
if (justSwitchedLayout) {
const targetOpen = !isMobile;
if (isSidebarOpen !== targetOpen) {
@@ -133,8 +124,8 @@ export const SidebarContainer = ({
<SidebarVisualStateContext.Provider value={contextValue}>
{isMobile && (
<div
- className={clsx("openui-shell-sidebar-container__overlay", {
- "openui-shell-sidebar-container__overlay--collapsed": !isSidebarOpen,
+ className={clsx("openui-agent-sidebar-container__overlay", {
+ "openui-agent-sidebar-container__overlay--collapsed": !isSidebarOpen,
})}
onClick={() => {
setIsSidebarOpen(false);
@@ -143,10 +134,10 @@ export const SidebarContainer = ({
)}
<div
className={clsx(
- "openui-shell-sidebar-container",
+ "openui-agent-sidebar-container",
{
- "openui-shell-sidebar-container--collapsed": isCollapsedLayout,
- "openui-shell-sidebar-container--hidden": isArtifactActive && !isMobile,
+ "openui-agent-sidebar-container--collapsed": isCollapsedLayout,
+ "openui-agent-sidebar-container--hidden": isDetailedViewActive && !isMobile,
},
className,
)}
@@ -163,46 +154,96 @@ export const SidebarContainer = ({
);
};
+export interface SidebarHeaderProps {
+ className?: string;
+ logo?: React.ReactNode;
+ agentName?: React.ReactNode;
+ collapseButton?: React.ReactNode | false;
+ children?: React.ReactNode;
+}
+
export const SidebarHeader = ({
- children,
className,
-}: {
- children?: React.ReactNode;
- className?: string;
-}) => {
- const { agentName, logoUrl, setIsSidebarOpen, isSidebarOpen } = useShellStore((state) => ({
+ logo,
+ agentName: agentNameProp,
+ collapseButton,
+ children,
+}: SidebarHeaderProps) => {
+ const {
+ agentName: ctxAgentName,
+ logoUrl,
+ setIsSidebarOpen,
+ isSidebarOpen,
+ } = useAgentInterfaceStore((state) => ({
agentName: state.agentName,
logoUrl: state.logoUrl,
setIsSidebarOpen: state.setIsSidebarOpen,
isSidebarOpen: state.isSidebarOpen,
}));
- const { isCollapsedLayout, visualState } = useSidebarVisualState();
- const showExpandedIcon = visualState === "expanded" || visualState === "collapsing";
+ const sidebarVisualState = useOptionalSidebarVisualState();
+ const isCollapsedLayout = sidebarVisualState?.isCollapsedLayout ?? !isSidebarOpen;
+
+ if (children != null) {
+ if (
+ typeof process !== "undefined" &&
+ process.env?.["NODE_ENV"] !== "production" &&
+ (logo !== undefined || agentNameProp !== undefined || collapseButton !== undefined)
+ ) {
+ console.warn(
+ "[AgentInterface] <AgentInterface.SidebarHeader> received both children and override props; children win.",
+ );
+ }
+ return (
+ <div
+ className={clsx(
+ "openui-agent-sidebar-header",
+ { "openui-agent-sidebar-header--collapsed": isCollapsedLayout },
+ className,
+ )}
+ >
+ {children}
+ </div>
+ );
+ }
+
+ const defaultLogo = logoUrl ? (
+ <img src={logoUrl} alt={ctxAgentName} className="openui-agent-sidebar-header__logo" />
+ ) : null;
+ const defaultAgentName = (
+ <div className="openui-agent-sidebar-header__agent-name">{ctxAgentName}</div>
+ );
+ const defaultCollapseButton = (
+ <AgentInterfaceTooltip
+ content={isCollapsedLayout ? "Open sidebar" : "Close sidebar"}
+ side="right"
+ >
+ <IconButton
+ icon={<PanelLeft size="1em" strokeWidth={2} />}
+ onClick={(e) => {
+ e.stopPropagation();
+ setIsSidebarOpen(!isSidebarOpen);
+ }}
+ size="small"
+ variant="tertiary"
+ aria-label={isSidebarOpen ? "Collapse sidebar" : "Expand sidebar"}
+ className="openui-agent-sidebar-header__toggle-button"
+ />
+ </AgentInterfaceTooltip>
+ );
return (
<div
className={clsx(
- "openui-shell-sidebar-header",
- { "openui-shell-sidebar-header--collapsed": isCollapsedLayout },
+ "openui-agent-sidebar-header",
+ { "openui-agent-sidebar-header--collapsed": isCollapsedLayout },
className,
)}
>
- <div className="openui-shell-sidebar-header__top-row">
- <img src={logoUrl} alt={agentName} className="openui-shell-sidebar-header__logo" />
- <div className="openui-shell-sidebar-header__agent-name">{agentName}</div>
- <IconButton
- icon={showExpandedIcon ? <PanelLeftClose size="1em" /> : <PanelLeftOpen size="1em" />}
- onClick={(e) => {
- e.stopPropagation();
- setIsSidebarOpen(!isSidebarOpen);
- }}
- size="small"
- variant="tertiary"
- aria-label={isSidebarOpen ? "Collapse sidebar" : "Expand sidebar"}
- className="openui-shell-sidebar-header__toggle-button"
- />
+ <div className="openui-agent-sidebar-header__top-row">
+ {logo ?? defaultLogo}
+ {agentNameProp ?? defaultAgentName}
+ {collapseButton === false ? null : (collapseButton ?? defaultCollapseButton)}
</div>
- {children}
</div>
);
};
@@ -214,15 +255,15 @@ export const SidebarContent = ({
children?: React.ReactNode;
className?: string;
}) => {
- const { isCollapsedLayout } = useSidebarVisualState();
+ const isSidebarOpen = useAgentInterfaceStore((state) => state.isSidebarOpen);
+ const sidebarVisualState = useOptionalSidebarVisualState();
+ const isCollapsedLayout = sidebarVisualState?.isCollapsedLayout ?? !isSidebarOpen;
return (
<div
- className={clsx(
- "openui-shell-sidebar-content",
- { "openui-shell-sidebar-content--collapsed": isCollapsedLayout },
- className,
- )}
+ className={clsx("openui-agent-sidebar-content", className, {
+ "openui-agent-sidebar-content--collapsed": isCollapsedLayout,
+ })}
>
{children}
</div>
@@ -230,5 +271,5 @@ export const SidebarContent = ({
};
export const SidebarSeparator = () => {
- return null;
+ return <div className="openui-agent-sidebar-separator" />;
};
diff --git a/packages/react-ui/src/components/AgentInterface/SidebarItem.tsx b/packages/react-ui/src/components/AgentInterface/SidebarItem.tsx
new file mode 100644
index 000000000..c6abe85b6
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/SidebarItem.tsx
@@ -0,0 +1,86 @@
+import clsx from "clsx";
+import type { ComponentPropsWithoutRef, MouseEventHandler, ReactNode } from "react";
+import { useLayoutContext } from "../../context/LayoutContext";
+import { useOptionalSidebarVisualState } from "./Sidebar";
+import { SidebarTooltip } from "./SidebarTooltip";
+import { useOptionalNav } from "./_shared/navContext";
+import { useAgentInterfaceStore } from "./_shared/store";
+
+export interface SidebarItemProps extends Omit<ComponentPropsWithoutRef<"button">, "children"> {
+ /** Leading icon. */
+ icon?: ReactNode;
+ /** Trailing content — badges, counts, etc. Rendered right-aligned. */
+ trailing?: ReactNode;
+ /**
+ * Selected/active state. Defaults to `currentPath === path` when `path` is
+ * provided. Pass explicitly to override the auto-derivation.
+ */
+ selected?: boolean;
+ /**
+ * Path this item navigates to. When provided, clicking the item calls
+ * `navigate(path)` and the item auto-selects when current path matches.
+ * Works in both controlled and uncontrolled <AgentInterface>.
+ */
+ path?: string;
+ children: ReactNode;
+}
+
+/**
+ * Styled clickable item for use inside <AgentInterface.Sidebar>. Visually
+ * matches the ThreadList row so custom nav items blend with the default
+ * thread list.
+ */
+export const SidebarItem = ({
+ icon,
+ trailing,
+ selected,
+ path,
+ className,
+ children,
+ onClick,
+ ...rest
+}: SidebarItemProps) => {
+ const nav = useOptionalNav();
+ const layoutCtx = useLayoutContext();
+ const setIsSidebarOpen = useAgentInterfaceStore((s) => s.setIsSidebarOpen);
+ const sidebarVisualState = useOptionalSidebarVisualState();
+ const isCollapsedLayout = sidebarVisualState?.isCollapsedLayout ?? false;
+
+ const isActive = selected !== undefined ? selected : path !== undefined && nav?.path === path;
+
+ const handleClick: MouseEventHandler<HTMLButtonElement> = (e) => {
+ onClick?.(e);
+ if (e.defaultPrevented) return;
+ if (path !== undefined && nav) {
+ nav.navigate(path);
+ if (layoutCtx?.layout === "mobile") {
+ setIsSidebarOpen(false);
+ }
+ }
+ };
+
+ const button = (
+ <button
+ type="button"
+ className={clsx(
+ "openui-agent-sidebar-item",
+ { "openui-agent-sidebar-item--selected": isActive },
+ className,
+ )}
+ onClick={handleClick}
+ {...rest}
+ >
+ {icon !== undefined && <span className="openui-agent-sidebar-item__icon">{icon}</span>}
+ <span className="openui-agent-sidebar-item__label">{children}</span>
+ {trailing !== undefined && (
+ <span className="openui-agent-sidebar-item__trailing">{trailing}</span>
+ )}
+ </button>
+ );
+
+ return (
+ <SidebarTooltip content={children} disabled={!isCollapsedLayout}>
+ {button}
+ </SidebarTooltip>
+ );
+};
diff --git a/packages/react-ui/src/components/AgentInterface/SidebarSlot.tsx b/packages/react-ui/src/components/AgentInterface/SidebarSlot.tsx
new file mode 100644
index 000000000..7f7189699
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/SidebarSlot.tsx
@@ -0,0 +1,19 @@
+import type { ReactNode } from "react";
+
+export interface SidebarSlotProps {
+ children?: ReactNode;
+}
+
+/**
+ * Slot marker for the entire sidebar region. Never rendered directly — the
+ * parent <AgentInterface> extracts its children and arranges them inside the
+ * SidebarContainer in place of the default sidebar arrangement.
+ *
+ * Mode A: omitted → default sidebar renders (SidebarHeader + SidebarContent
+ * with SidebarSeparator + ThreadList).
+ * Mode C: provided with children → children replace the entire sidebar's
+ * inner content (user composes SidebarHeader, SidebarSeparator,
+ * ThreadList, etc. as needed).
+ */
+export const SidebarSlot = (_props: SidebarSlotProps) => null;
+SidebarSlot.displayName = "AgentInterface.Sidebar";
diff --git a/packages/react-ui/src/components/AgentInterface/SidebarTooltip.tsx b/packages/react-ui/src/components/AgentInterface/SidebarTooltip.tsx
new file mode 100644
index 000000000..c674dfd5b
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/SidebarTooltip.tsx
@@ -0,0 +1,29 @@
+import * as Tooltip from "@radix-ui/react-tooltip";
+import type { ReactElement, ReactNode } from "react";
+
+export interface SidebarTooltipProps {
+ children: ReactElement;
+ content: ReactNode;
+ disabled?: boolean;
+}
+
+export const SidebarTooltip = ({ children, content, disabled = false }: SidebarTooltipProps) => {
+ if (disabled) return children;
+
+ // Provider is hoisted once into <Container> so delay/skip-delay are shared.
+ return (
+ <Tooltip.Root>
+ <Tooltip.Trigger asChild>{children}</Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content
+ className="openui-agent-sidebar-tooltip"
+ side="right"
+ align="center"
+ sideOffset={8}
+ >
+ {content}
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ );
+};
diff --git a/packages/react-ui/src/components/Shell/Thread.tsx b/packages/react-ui/src/components/AgentInterface/Thread.tsx
similarity index 52%
rename from packages/react-ui/src/components/Shell/Thread.tsx
rename to packages/react-ui/src/components/AgentInterface/Thread.tsx
index df22d6717..04ede2081 100644
--- a/packages/react-ui/src/components/Shell/Thread.tsx
+++ b/packages/react-ui/src/components/AgentInterface/Thread.tsx
@@ -1,20 +1,34 @@
-import type { AssistantMessage, Message, ToolMessage } from "@openuidev/react-headless";
-import { MessageProvider, useActiveArtifact, useThread } from "@openuidev/react-headless";
+import type { AssistantMessage, Message } from "@openuidev/react-headless";
+import {
+ MessageProvider,
+ useActiveDetailedView,
+ useArtifactList,
+ useThread,
+ useToolActivities,
+} from "@openuidev/react-headless";
import clsx from "clsx";
-import React, { memo, useRef } from "react";
+import React, { memo, useId, useRef } from "react";
import { useLayoutContext } from "../../context/LayoutContext";
import { ScrollVariant, useScrollToBottom } from "../../hooks/useScrollToBottom";
-import { separateContentAndContext } from "../../utils/contentParser";
-import { ArtifactOverlay, ArtifactPortalTarget } from "../_shared/artifact";
-import { useShellStore } from "../_shared/store";
-import type { AssistantMessageComponent, UserMessageComponent } from "../_shared/types";
+import {
+ DetailedViewOverlay,
+ DetailedViewPanel,
+ DetailedViewPortalTarget,
+} from "./_shared/detailed-view";
+import { useAgentInterfaceLabels } from "./_shared/labelsContext";
+import { useAgentInterfaceStore } from "./_shared/store";
+import { TimelineEntry } from "./_shared/tool-renderer";
+import type { AssistantMessageComponent, UserMessageComponent } from "./_shared/types";
+
import { Callout } from "../Callout";
+import { IconButton } from "../IconButton";
import { MarkDownRenderer } from "../MarkDownRenderer";
import { MessageLoading as MessageLoadingComponent } from "../MessageLoading";
-import { ToolCallComponent } from "../ToolCall";
-import { ToolResult } from "../ToolResult";
import { ResizableSeparator } from "./ResizableSeparator";
-import { useArtifactResize } from "./useArtifactResize";
+import { UserMessageContent } from "./UserMessageContent";
+import { AgentInterfaceTooltip } from "./_shared/AgentInterfaceTooltip";
+import { GalleryHorizontalEndIcon } from "./_shared/GalleryHorizontalEndIcon";
+import { useDetailedViewResize } from "./useDetailedViewResize";
export const ThreadContainer = ({
children,
@@ -25,9 +39,9 @@ export const ThreadContainer = ({
}) => {
const { layout } = useLayoutContext();
const isMobile = layout === "mobile";
- const { isArtifactActive } = useActiveArtifact();
+ const { isDetailedViewActive } = useActiveDetailedView();
- const { setIsSidebarOpen } = useShellStore((state) => ({
+ const { setIsSidebarOpen } = useAgentInterfaceStore((state) => ({
setIsSidebarOpen: state.setIsSidebarOpen,
}));
@@ -36,53 +50,64 @@ export const ThreadContainer = ({
const {
containerRef,
chatPanelRef,
- artifactPanelRef,
+ detailedViewPanelRef,
isDragging,
handleResize,
+ handleResizeStep,
handleDragStart,
handleDragEnd,
- } = useArtifactResize({
- isArtifactActive,
+ getResizeAria,
+ } = useDetailedViewResize({
+ isDetailedViewActive,
isMobile,
setIsSidebarOpen,
});
+ const chatPanelId = useId();
+ const detailPanelId = useId();
+
return (
<div
- className={clsx("openui-shell-thread-container", className, {
- "openui-shell-thread-container--artifact-active": isArtifactActive,
+ className={clsx("openui-agent-thread-container", className, {
+ "openui-agent-thread-container--detailed-view-active": isDetailedViewActive,
})}
style={{
visibility: isLoadingMessages ? "hidden" : undefined,
}}
>
- <div className="openui-shell-thread-wrapper" ref={containerRef}>
+ <div className="openui-agent-thread-wrapper" ref={containerRef}>
{/* Chat panel - always visible */}
<div
ref={chatPanelRef}
- className={clsx("openui-shell-thread-chat-panel", {
- "openui-shell-thread-chat-panel--animating": !isDragging,
+ id={chatPanelId}
+ className={clsx("openui-agent-thread-chat-panel", {
+ "openui-agent-thread-chat-panel--animating": !isDragging,
})}
>
{children}
- {isMobile && <ArtifactOverlay />}
+ {isMobile && <DetailedViewOverlay />}
</div>
- {/* Desktop only: Resizable separator and artifact panel */}
- {!isMobile && isArtifactActive && (
+ {/* Desktop only: Resizable separator and detailed-view panel */}
+ {!isMobile && isDetailedViewActive && (
<>
<ResizableSeparator
onResize={handleResize}
+ onResizeStep={handleResizeStep}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
+ getAriaValues={getResizeAria}
+ controlsId={`${chatPanelId} ${detailPanelId}`}
+ ariaLabel="Resize chat panel"
/>
<div
- ref={artifactPanelRef}
- className={clsx("openui-shell-thread-artifact-panel", {
- "openui-shell-thread-artifact-panel--animating": !isDragging,
+ ref={detailedViewPanelRef}
+ id={detailPanelId}
+ className={clsx("openui-agent-thread-detailed-view-panel", {
+ "openui-agent-thread-detailed-view-panel--animating": !isDragging,
})}
>
- <ArtifactPortalTarget />
+ <DetailedViewPortalTarget />
</div>
</>
)}
@@ -95,7 +120,8 @@ export const ScrollArea = ({
children,
className,
scrollVariant = "user-message-anchor",
- userMessageSelector,
+ userMessageSelector = ".openui-agent-thread-message-user",
+ scrollOnLoad = true,
}: {
children?: React.ReactNode;
className?: string;
@@ -107,6 +133,11 @@ export const ScrollArea = ({
* Selector for the user message
*/
userMessageSelector?: string;
+ /**
+ * When false, do not auto-scroll on initial load / conversation switch
+ * (auto-scroll then only happens while a response is generating).
+ */
+ scrollOnLoad?: boolean;
}) => {
const ref = useRef<HTMLDivElement>(null);
@@ -121,16 +152,17 @@ export const ScrollArea = ({
userMessageSelector,
isRunning,
isLoadingMessages,
+ scrollOnLoad,
});
return (
- <div className="openui-shell-thread-scroll-container">
+ <div className="openui-agent-thread-scroll-container">
<div
ref={ref}
className={clsx(
- "openui-shell-thread-scroll-area",
+ "openui-agent-thread-scroll-area",
{
- "openui-shell-thread-scroll-area--user-message-anchor":
+ "openui-agent-thread-scroll-area--user-message-anchor":
scrollVariant === "user-message-anchor",
},
className,
@@ -149,25 +181,9 @@ export const AssistantMessageContainer = ({
children?: React.ReactNode;
className?: string;
}) => {
- const { logoUrl, showAssistantLogo } = useShellStore((store) => ({
- logoUrl: store.logoUrl,
- showAssistantLogo: store.showAssistantLogo,
- }));
-
return (
- <div
- className={clsx("openui-shell-thread-message-assistant", className, {
- "openui-shell-thread-message-assistant--without-logo": !showAssistantLogo,
- })}
- >
- {showAssistantLogo && (
- <img
- src={logoUrl}
- alt="Assistant"
- className="openui-shell-thread-message-assistant__logo"
- />
- )}
- <div className="openui-shell-thread-message-assistant__content">{children}</div>
+ <div className={clsx("openui-agent-thread-message-assistant", className)}>
+ <div className="openui-agent-thread-message-assistant__content">{children}</div>
</div>
);
};
@@ -180,8 +196,8 @@ export const UserMessageContainer = ({
className?: string;
}) => {
return (
- <div className={clsx("openui-shell-thread-message-user", className)}>
- <div className="openui-shell-thread-message-user__content">{children}</div>
+ <div className={clsx("openui-agent-thread-message-user", className)}>
+ <div className="openui-agent-thread-message-user__content">{children}</div>
</div>
);
};
@@ -189,80 +205,36 @@ export const UserMessageContainer = ({
const AssistantMessageContent = ({
message,
allMessages,
+ isLast,
}: {
message: AssistantMessage;
allMessages: Message[];
+ isLast: boolean;
}) => {
- // Find tool result messages that correspond to this message's tool calls
- const getToolName = (toolCallId: string) => {
- const toolCall = message.toolCalls?.find((tc) => tc.id === toolCallId);
- return toolCall?.function.name;
- };
-
- // Collect tool messages that follow this assistant message
- const toolMessages: ToolMessage[] = [];
- const msgIndex = allMessages.findIndex((m) => m.id === message.id);
- if (msgIndex !== -1) {
- for (let i = msgIndex + 1; i < allMessages.length; i++) {
- const m = allMessages[i];
- if (m && m.role === "tool") {
- toolMessages.push(m as ToolMessage);
- } else {
- break;
- }
- }
- }
+ // One id-keyed pairing of calls↔results with real status — no positional break,
+ // no grouped-not-paired flow, running state from the data.
+ const activities = useToolActivities(message, allMessages);
return (
<>
{message.content && (
<MarkDownRenderer
textMarkdown={message.content}
- className="openui-shell-thread-message-assistant__text"
+ className="openui-agent-thread-message-assistant__text"
/>
)}
- {message.toolCalls?.map((toolCall) => (
- <ToolCallComponent key={toolCall.id} toolCall={toolCall} />
- ))}
- {toolMessages.map((tm) => (
- <ToolResult key={tm.id} message={tm} toolName={getToolName(tm.toolCallId)} />
+ {activities.map((activity, idx) => (
+ <TimelineEntry
+ key={activity.id}
+ activity={activity}
+ isLast={isLast && idx === activities.length - 1}
+ detailedViewPanel={DetailedViewPanel}
+ />
))}
</>
);
};
-const UserMessageContent = ({ message }: { message: Message }) => {
- if (message.role !== "user") return null;
- const content = message.content;
- if (typeof content === "string") {
- // Strip XML wrapper tags (<content>, <context>) so the bubble shows clean text
- const { content: humanText } = separateContentAndContext(content);
- return <>{humanText}</>;
- }
- // InputContent[] — render text parts
- return (
- <>
- {content?.map((part, i) => {
- if (part.type === "text") {
- return <span key={i}>{part.text}</span>;
- }
- // Binary content — could be image, file, etc.
- if (part.type === "binary" && part.url) {
- return (
- <img
- key={i}
- src={part.url}
- alt=""
- className="openui-shell-thread-message-user__image"
- />
- );
- }
- return null;
- })}
- </>
- );
-};
-
export const RenderMessage = memo(
({
message,
@@ -271,6 +243,7 @@ export const RenderMessage = memo(
assistantMessage: CustomAssistantMessage,
userMessage: CustomUserMessage,
isStreaming,
+ isLast,
}: {
message: Message;
className?: string;
@@ -278,6 +251,8 @@ export const RenderMessage = memo(
assistantMessage?: AssistantMessageComponent;
userMessage?: UserMessageComponent;
isStreaming: boolean;
+ /** Whether this is the last *assistant* message (drives the running shimmer). */
+ isLast: boolean;
}) => {
if (message.role === "tool") {
// Tool messages are rendered inline with their parent assistant message
@@ -290,7 +265,7 @@ export const RenderMessage = memo(
}
return (
<AssistantMessageContainer className={className}>
- <AssistantMessageContent message={message} allMessages={allMessages} />
+ <AssistantMessageContent message={message} allMessages={allMessages} isLast={isLast} />
</AssistantMessageContainer>
);
}
@@ -313,7 +288,7 @@ export const RenderMessage = memo(
export const MessageLoading = () => {
return (
- <div className="openui-shell-thread-message-loading">
+ <div className="openui-agent-thread-message-loading">
<MessageLoadingComponent />
</div>
);
@@ -324,7 +299,7 @@ export const ThreadError = () => {
if (!threadError) return null;
return (
- <div className="openui-shell-thread-error">
+ <div className="openui-agent-thread-error">
<Callout
variant="danger"
title="Something went wrong"
@@ -349,8 +324,18 @@ export const Messages = ({
const isRunning = useThread((s) => s.isRunning);
const threadError = useThread((s) => s.threadError);
+ // Scan for the last *assistant* message (not the last message index) so the
+ // running shimmer survives trailing tool messages.
+ let lastAssistantIndex = -1;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (messages[i]?.role === "assistant") {
+ lastAssistantIndex = i;
+ break;
+ }
+ }
+
return (
- <div className={clsx("openui-shell-thread-messages", className)}>
+ <div className={clsx("openui-agent-thread-messages", className)}>
{messages.map((message, i) => {
return (
<MessageProvider key={message.id} message={message}>
@@ -359,7 +344,8 @@ export const Messages = ({
allMessages={messages}
assistantMessage={assistantMessage}
userMessage={userMessage}
- isStreaming={isRunning && i === messages.length - 1}
+ isStreaming={isRunning && i === lastAssistantIndex}
+ isLast={i === lastAssistantIndex}
/>
</MessageProvider>
);
@@ -377,7 +363,43 @@ export const ThreadHeader = ({
children?: React.ReactNode;
className?: string;
}) => {
- return <div className={clsx("openui-shell-thread-header", className)}>{children}</div>;
+ return (
+ <div className={clsx("openui-agent-thread-header", className)}>
+ <div className="openui-agent-thread-header__title">{/* Thread title hidden for now. */}</div>
+ <div className="openui-agent-thread-header__actions">
+ {children}
+ <WorkspaceToggleButton />
+ </div>
+ </div>
+ );
+};
+
+const WorkspaceToggleButton = () => {
+ const artifacts = useArtifactList();
+ const { isDetailedViewActive } = useActiveDetailedView();
+ const { workspaceToggle } = useAgentInterfaceLabels();
+ const { isWorkspaceOpen, setIsWorkspaceOpen } = useAgentInterfaceStore((state) => ({
+ isWorkspaceOpen: state.isWorkspaceOpen,
+ setIsWorkspaceOpen: state.setIsWorkspaceOpen,
+ }));
+ const hasArtifacts = Object.keys(artifacts).length > 0;
+
+ if (!hasArtifacts || isDetailedViewActive) return null;
+
+ return (
+ <AgentInterfaceTooltip content={workspaceToggle} side="left">
+ <IconButton
+ icon={<GalleryHorizontalEndIcon size="1em" />}
+ onClick={() => {
+ if (hasArtifacts) setIsWorkspaceOpen(!isWorkspaceOpen);
+ }}
+ size="small"
+ variant="tertiary"
+ aria-label={isWorkspaceOpen ? "Collapse workspace" : "Expand workspace"}
+ className="openui-agent-thread-header__workspace-toggle-button"
+ />
+ </AgentInterfaceTooltip>
+ );
};
// Re-export Composer from components
diff --git a/packages/react-ui/src/components/Shell/ThreadList.tsx b/packages/react-ui/src/components/AgentInterface/ThreadList.tsx
similarity index 75%
rename from packages/react-ui/src/components/Shell/ThreadList.tsx
rename to packages/react-ui/src/components/AgentInterface/ThreadList.tsx
index e15acbcaa..e62c619dd 100644
--- a/packages/react-ui/src/components/Shell/ThreadList.tsx
+++ b/packages/react-ui/src/components/AgentInterface/ThreadList.tsx
@@ -2,13 +2,13 @@ import type { Thread } from "@openuidev/react-headless";
import { useThreadList } from "@openuidev/react-headless";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import clsx from "clsx";
-import { EllipsisVerticalIcon, Trash2Icon } from "lucide-react";
-import { Fragment, useEffect } from "react";
+import { EllipsisIcon, Trash2Icon } from "lucide-react";
+import { Fragment, useEffect, useState } from "react";
import { useLayoutContext } from "../../context/LayoutContext";
-import { useShellStore } from "../_shared/store";
import { Button } from "../Button";
import { IconButton } from "../IconButton";
-import { useTheme } from "../ThemeProvider";
+import { useOptionalNav } from "./_shared/navContext";
+import { useAgentInterfaceStore } from "./_shared/store";
export const ThreadButton = ({
id,
@@ -22,49 +22,55 @@ export const ThreadButton = ({
const selectThread = useThreadList((s) => s.selectThread);
const deleteThread = useThreadList((s) => s.deleteThread);
const selectedThreadId = useThreadList((s) => s.selectedThreadId);
- const { portalThemeClassName } = useTheme();
- const { isSidebarOpen, setIsSidebarOpen } = useShellStore((state) => ({
+ const { isSidebarOpen, setIsSidebarOpen } = useAgentInterfaceStore((state) => ({
isSidebarOpen: state.isSidebarOpen,
setIsSidebarOpen: state.setIsSidebarOpen,
}));
const { layout } = useLayoutContext();
+ const nav = useOptionalNav();
+ const [isActionsOpen, setIsActionsOpen] = useState(false);
return (
<div
className={clsx(
- "openui-shell-thread-button",
+ "openui-agent-thread-button",
{
- "openui-shell-thread-button--selected": selectedThreadId === id,
+ "openui-agent-thread-button--selected": selectedThreadId === id,
+ "openui-agent-thread-button--actions-open": isActionsOpen,
},
className,
)}
>
<button
- className="openui-shell-thread-button-title"
+ className="openui-agent-thread-button-title"
onClick={() => {
if (layout === "mobile") {
setIsSidebarOpen(!isSidebarOpen);
}
selectThread(id);
+ // Auto-clear any active route so the thread view surfaces.
+ if (nav && nav.path !== undefined) {
+ nav.navigate(undefined);
+ }
}}
>
{title}
</button>
- <DropdownMenu.Root>
+ <DropdownMenu.Root open={isActionsOpen} onOpenChange={setIsActionsOpen}>
<DropdownMenu.Trigger asChild>
<IconButton
- icon={<EllipsisVerticalIcon size="1em" />}
- aria-label={`More actions for ${title}`}
+ className="openui-agent-thread-button-dropdown-trigger"
+ icon={<EllipsisIcon size="1em" />}
+ size="2-extra-small"
variant="tertiary"
- size={layout === "mobile" ? "small" : "extra-small"}
- className="openui-shell-thread-button-dropdown-trigger"
+ aria-label="Thread actions"
/>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
- className={clsx("openui-shell-thread-button-dropdown-menu", portalThemeClassName)}
+ className="openui-agent-thread-button-dropdown-menu"
side="bottom"
- align="end"
+ align="start"
sideOffset={4}
>
<DropdownMenu.Item
@@ -74,12 +80,11 @@ export const ThreadButton = ({
}}
>
<Button
- type="button"
- variant="tertiary"
buttonType="destructive"
- size="small"
- iconLeft={<Trash2Icon size={14} />}
- className="openui-shell-thread-button-dropdown-menu-item"
+ className="openui-agent-thread-button-dropdown-menu-item"
+ iconLeft={<Trash2Icon size="1em" />}
+ size="extra-small"
+ variant="tertiary"
>
Delete
</Button>
@@ -153,12 +158,12 @@ export const ThreadList = ({ className }: { className?: string }) => {
};
return (
- <div className={clsx("openui-shell-thread-list", className)}>
+ <div className={clsx("openui-agent-thread-list", className)}>
{Object.entries(groupedThreads)
.filter(([_, groupThreads]) => groupThreads.length > 0)
.map(([group, groupThreads]) => (
<Fragment key={group}>
- <div className="openui-shell-thread-list-group">
+ <div className="openui-agent-thread-list-group">
{groupLabels[group as keyof typeof groupLabels]}
</div>
{groupThreads.map((thread) => (
diff --git a/packages/react-ui/src/components/AgentInterface/UserMessageContent.tsx b/packages/react-ui/src/components/AgentInterface/UserMessageContent.tsx
new file mode 100644
index 000000000..02fc015da
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/UserMessageContent.tsx
@@ -0,0 +1,281 @@
+import type { InputContent, Message } from "@openuidev/react-headless";
+import clsx from "clsx";
+import { useState } from "react";
+import { separateContentAndContext } from "../../utils/sentinelParser";
+
+/**
+ * Renders the content of a user message.
+ *
+ * Handles the full AG-UI `InputContent` union (`@ag-ui/core` ≥ 0.0.53):
+ * `text | image | audio | video | document | binary`.
+ * - `image | audio | video | document` carry a `source` object
+ * (`{ type: "data" | "url", value, mimeType? }`).
+ * - `binary` is the lower-level variant (`{ mimeType, url?, data?, filename? }`),
+ * routed to the right element by `mimeType`.
+ *
+ * Each part is resolved to a single render-ready descriptor in
+ * {@link resolveInputPart}: media → `<img>/<audio>/<video>`, everything else →
+ * a downloadable file chip. Every source (url + base64 `data`) is vetted against
+ * a scheme/mime allowlist, and unusable/failed sources degrade to a chip rather
+ * than being silently dropped. A `default: never` guard surfaces any future
+ * union member at compile time.
+ */
+
+type ResolvedKind = "text" | "image" | "audio" | "video" | "file";
+
+interface ResolvedPart {
+ kind: ResolvedKind;
+ /** Safe URL for an element `src`/`href`; `""` when no usable/allowed source. */
+ src: string;
+ filename?: string;
+ /** alt / aria label text. */
+ label: string;
+ /** Raw text for `kind === "text"`. */
+ text?: string;
+ mimeType?: string;
+}
+
+// --- Security: vet sources before they reach the DOM. ---
+const ALLOWED_URL_SCHEMES = ["http:", "https:"];
+// `data:` is only embedded for media we render inline + PDFs we offer to
+// download. Notably excludes text/html and arbitrary application/* (XSS surface).
+const ALLOWED_DATA_MIME = /^(?:image|audio|video)\/|^application\/pdf$/i;
+
+const isSafeBase64 = (v: string) => /^[A-Za-z0-9+/]+={0,2}$/.test(v.replace(/\s/g, ""));
+
+/** Build a vetted `data:` URI, or `""` if the mime/payload isn't allowed. */
+function buildDataUri(mimeType: string | undefined, value: string): string {
+ if (!mimeType || !ALLOWED_DATA_MIME.test(mimeType)) return "";
+ if (!isSafeBase64(value)) return "";
+ return `data:${mimeType};base64,${value}`;
+}
+
+/** Vet a source URL: allow http(s) + allowlisted `data:`, reject javascript:/etc. */
+function sanitizeUrl(raw: string): string {
+ const s = raw.trim();
+ if (s.startsWith("data:")) {
+ const semi = s.indexOf(";");
+ const mime = semi > 5 ? s.slice(5, semi) : "";
+ return ALLOWED_DATA_MIME.test(mime) ? s : "";
+ }
+ try {
+ // Absolute URL — gate on protocol.
+ return ALLOWED_URL_SCHEMES.includes(new URL(s).protocol) ? s : "";
+ } catch {
+ // Relative URL (no scheme) — same-origin, can't carry a dangerous scheme.
+ return s;
+ }
+}
+
+/** mimeType → modality, used to route a `binary` part (which has no `type`). */
+function modalityFromMime(mime: string): ResolvedKind {
+ if (mime.startsWith("image/")) return "image";
+ if (mime.startsWith("audio/")) return "audio";
+ if (mime.startsWith("video/")) return "video";
+ return "file";
+}
+
+/** mimeType → short badge label for the file chip. */
+function fileBadge(mime: string | undefined): string {
+ if (!mime) return "FILE";
+ if (mime.includes("pdf")) return "PDF";
+ if (mime.includes("sheet") || mime.includes("excel")) return "XLS";
+ if (mime.includes("presentation") || mime.includes("powerpoint")) return "PPT";
+ if (mime.includes("word") || mime.includes("document")) return "DOC";
+ if (mime.startsWith("text/")) return "TXT";
+ if (mime.startsWith("image/")) return "IMG";
+ if (mime.startsWith("audio/")) return "AUD";
+ if (mime.startsWith("video/")) return "VID";
+ return "FILE";
+}
+
+/** Best-effort filename from an optional `metadata` bag (image/audio/video/document). */
+function metaFilename(metadata: unknown): string | undefined {
+ if (metadata && typeof metadata === "object" && "filename" in metadata) {
+ const f = (metadata as Record<string, unknown>)["filename"];
+ if (typeof f === "string" && f.length > 0) return f;
+ }
+ return undefined;
+}
+
+/** Resolve a media-style `source` ({ type:"data"|"url", value, mimeType }) to a vetted src. */
+function resolveSource(source: { type: "data" | "url"; value: string; mimeType?: string }): string {
+ return source.type === "url"
+ ? sanitizeUrl(source.value)
+ : buildDataUri(source.mimeType, source.value);
+}
+
+/** Resolve any `InputContent` part to a render-ready descriptor. */
+export function resolveInputPart(part: InputContent): ResolvedPart {
+ switch (part.type) {
+ case "text":
+ return { kind: "text", src: "", text: part.text, label: part.text };
+
+ case "image":
+ case "audio":
+ case "video": {
+ // { type; source: { type:"data"|"url"; value; mimeType? }; metadata? }
+ const filename = metaFilename(part.metadata);
+ return {
+ kind: part.type,
+ src: resolveSource(part.source),
+ filename,
+ mimeType: part.source.mimeType,
+ label: filename ?? `${part.type} attachment`,
+ };
+ }
+
+ case "document": {
+ // Same source shape as media, but presented as a downloadable file chip.
+ const filename = metaFilename(part.metadata);
+ const mimeType = part.source.mimeType;
+ return {
+ kind: "file",
+ src: resolveSource(part.source),
+ filename,
+ mimeType,
+ label: filename ?? mimeType ?? "File",
+ };
+ }
+
+ case "binary": {
+ // { mimeType; url?; data?; filename?; id? }
+ const { mimeType } = part;
+ const src = part.url
+ ? sanitizeUrl(part.url)
+ : part.data
+ ? buildDataUri(mimeType, part.data)
+ : "";
+ return {
+ kind: modalityFromMime(mimeType),
+ src,
+ filename: part.filename,
+ mimeType,
+ label: part.filename ?? mimeType ?? "File",
+ };
+ }
+
+ default: {
+ // Exhaustiveness guard — surfaces new union members at compile time.
+ const _exhaustive: never = part;
+ void _exhaustive;
+ return { kind: "file", src: "", label: "Unsupported attachment" };
+ }
+ }
+}
+
+const FileChip = ({ part, broken = false }: { part: ResolvedPart; broken?: boolean }) => {
+ const name = part.filename ?? part.mimeType ?? "Attachment";
+ const body = (
+ <span
+ className={clsx("openui-agent-thread-message-user__chip", {
+ "openui-agent-thread-message-user__chip--broken": broken,
+ })}
+ >
+ <span className="openui-agent-thread-message-user__chip-badge" aria-hidden="true">
+ {fileBadge(part.mimeType)}
+ </span>
+ <span className="openui-agent-thread-message-user__chip-name">{name}</span>
+ </span>
+ );
+
+ // Offer a download when we have a usable source.
+ return part.src ? (
+ <a
+ href={part.src}
+ download={part.filename ?? ""}
+ rel="noreferrer"
+ target="_blank"
+ className="openui-agent-thread-message-user__chip-link"
+ aria-label={`Download ${name}`}
+ >
+ {body}
+ </a>
+ ) : (
+ body
+ );
+};
+
+const MediaPart = ({ part }: { part: ResolvedPart }) => {
+ const [error, setError] = useState(false);
+
+ // No usable/allowed source, or a media element failed to load → file chip
+ // (never silently drop, never show a broken-media glyph).
+ if (!part.src || (error && part.kind !== "file")) {
+ return <FileChip part={part} broken={Boolean(part.src) && error} />;
+ }
+
+ switch (part.kind) {
+ case "image":
+ return (
+ <img
+ src={part.src}
+ alt={part.label}
+ loading="lazy"
+ className="openui-agent-thread-message-user__image"
+ onError={() => setError(true)}
+ />
+ );
+ case "audio":
+ return (
+ <figure className="openui-agent-thread-message-user__media">
+ <audio
+ controls
+ preload="metadata"
+ src={part.src}
+ className="openui-agent-thread-message-user__audio"
+ aria-label={part.label}
+ onError={() => setError(true)}
+ />
+ {part.filename && (
+ <figcaption className="openui-agent-thread-message-user__filename">
+ {part.filename}
+ </figcaption>
+ )}
+ </figure>
+ );
+ case "video":
+ return (
+ <video
+ controls
+ preload="metadata"
+ src={part.src}
+ className="openui-agent-thread-message-user__video"
+ aria-label={part.label}
+ onError={() => setError(true)}
+ />
+ );
+ default:
+ return <FileChip part={part} />;
+ }
+};
+
+export const UserMessageContent = ({ message }: { message: Message }) => {
+ if (message.role !== "user") return null;
+ const content = message.content;
+
+ if (typeof content === "string") {
+ // Strip XML wrapper tags (<content>, <context>) so the bubble shows clean text.
+ const { content: humanText } = separateContentAndContext(content);
+ return <>{humanText}</>;
+ }
+
+ if (!content?.length) return null;
+
+ // Render parts in array order to preserve the user's text/media interleave.
+ return (
+ <>
+ {content.map((part, i) => {
+ const resolved = resolveInputPart(part);
+ if (resolved.kind === "text") {
+ return resolved.text?.trim() ? (
+ <span key={i} className="openui-agent-thread-message-user__text">
+ {resolved.text}
+ </span>
+ ) : null;
+ }
+ return <MediaPart key={i} part={resolved} />;
+ })}
+ </>
+ );
+};
diff --git a/packages/react-ui/src/components/Shell/WelcomeScreen.tsx b/packages/react-ui/src/components/AgentInterface/WelcomeScreen.tsx
similarity index 74%
rename from packages/react-ui/src/components/Shell/WelcomeScreen.tsx
rename to packages/react-ui/src/components/AgentInterface/WelcomeScreen.tsx
index edff6e183..f0c258c98 100644
--- a/packages/react-ui/src/components/Shell/WelcomeScreen.tsx
+++ b/packages/react-ui/src/components/AgentInterface/WelcomeScreen.tsx
@@ -2,7 +2,8 @@ import { useThread } from "@openuidev/react-headless";
import clsx from "clsx";
import { ReactNode } from "react";
import { ConversationStarterProps } from "../../types/ConversationStarter";
-import { isChatEmpty } from "../_shared/utils";
+import { useStartersFromContext } from "./_shared/startersContext";
+import { isChatEmpty } from "./_shared/utils";
import { DesktopWelcomeComposer } from "./components";
import { ConversationStarter, ConversationStarterVariant } from "./ConversationStarter";
@@ -65,7 +66,13 @@ const isImageUrl = (image: { url: string } | ReactNode): image is { url: string
};
export const WelcomeScreen = (props: WelcomeScreenProps) => {
- const { className, starters = [], starterVariant = "long" } = props;
+ const { className } = props;
+ const fromCtx = useStartersFromContext();
+
+ const ownStarters = "starters" in props ? props.starters : undefined;
+ const ownVariant = "starterVariant" in props ? props.starterVariant : undefined;
+ const starters = ownStarters ?? fromCtx.starters ?? [];
+ const starterVariant = ownVariant ?? fromCtx.starterVariant ?? "long";
const messages = useThread((s) => s.messages);
const isLoadingMessages = useThread((s) => s.isLoadingMessages);
@@ -77,7 +84,7 @@ export const WelcomeScreen = (props: WelcomeScreenProps) => {
// Check if children are provided
if ("children" in props && props.children) {
- return <div className={clsx("openui-shell-welcome-screen", className)}>{props.children}</div>;
+ return <div className={clsx("openui-agent-welcome-screen", className)}>{props.children}</div>;
}
// Props-based content
@@ -88,7 +95,7 @@ export const WelcomeScreen = (props: WelcomeScreenProps) => {
if (isImageUrl(image)) {
return (
- <img src={image.url} alt={title || ""} className="openui-shell-welcome-screen__image" />
+ <img src={image.url} alt={title || ""} className="openui-agent-welcome-screen__image" />
);
}
@@ -98,32 +105,32 @@ export const WelcomeScreen = (props: WelcomeScreenProps) => {
return (
<div
className={clsx(
- "openui-shell-welcome-screen",
- "openui-shell-welcome-screen--with-composer",
+ "openui-agent-welcome-screen",
+ "openui-agent-welcome-screen--with-composer",
className,
)}
>
- <div className="openui-shell-welcome-screen__header">
+ <div className="openui-agent-welcome-screen__header">
{image && (
- <div className="openui-shell-welcome-screen__image-container">{renderImage()}</div>
+ <div className="openui-agent-welcome-screen__image-container">{renderImage()}</div>
)}
{(title || description) && (
- <div className="openui-shell-welcome-screen__content">
- {title && <h2 className="openui-shell-welcome-screen__title">{title}</h2>}
+ <div className="openui-agent-welcome-screen__content">
+ {title && <h2 className="openui-agent-welcome-screen__title">{title}</h2>}
{description && (
- <p className="openui-shell-welcome-screen__description">{description}</p>
+ <p className="openui-agent-welcome-screen__description">{description}</p>
)}
</div>
)}
</div>
{/* Desktop-only welcome composer */}
- <div className="openui-shell-welcome-screen__composer-starters-container">
- <div className="openui-shell-welcome-screen__desktop-composer">
+ <div className="openui-agent-welcome-screen__composer-starters-container">
+ <div className="openui-agent-welcome-screen__desktop-composer">
<DesktopWelcomeComposer />
</div>
{/* Desktop-only conversation starters */}
{starters.length > 0 && (
- <div className="openui-shell-welcome-screen__desktop-starters">
+ <div className="openui-agent-welcome-screen__desktop-starters">
<ConversationStarter starters={starters} variant={starterVariant} />
</div>
)}
diff --git a/packages/react-ui/src/components/AgentInterface/Workspace.tsx b/packages/react-ui/src/components/AgentInterface/Workspace.tsx
new file mode 100644
index 000000000..5365570c8
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/Workspace.tsx
@@ -0,0 +1,198 @@
+import {
+ useActiveDetailedView,
+ useArtifactCategories,
+ useArtifactList,
+ useDetailedView,
+ useDetailedViewStore,
+ type ArtifactEntry,
+} from "@openuidev/react-headless";
+import clsx from "clsx";
+import { useEffect, type ReactNode } from "react";
+import { useLayoutContext } from "../../context/LayoutContext";
+import {
+ formatArtifactUpdatedAt,
+ useArtifactIcon,
+ useArtifactTypeLabel,
+} from "./ArtifactBrowserPage";
+import { useAgentInterfaceStore } from "./_shared/store";
+
+export interface WorkspaceProps {
+ className?: string;
+ /** Mode C — replaces the entire rail (you own the chrome and visibility). */
+ children?: ReactNode;
+}
+
+/**
+ * Per-thread workspace rail (right edge of the layout) listing the artifacts
+ * registered in the active thread.
+ *
+ * - Renders nothing while the registry is empty — drop-in users without
+ * artifact renderers never see it. Visibility is controlled by the header
+ * workspace toggle.
+ * - Lists every registered artifact, grouped into one section per
+ * `artifactCategories` entry configured on `<AgentInterface>`; a single
+ * "Artifacts" section lists everything when no categories are configured.
+ * There are no tabs or filtering — the rail shows it all.
+ * - Item click activates the corresponding DetailedView; the rail closes while
+ * a DetailedView is open.
+ * - Rendered only in the thread view — hidden on Route pages and the
+ * artifact browser. Hidden on mobile.
+ *
+ * Modes: A (omit → default above) and C (children replace the rail).
+ *
+ * @category Components
+ */
+export const Workspace = ({ className, children }: WorkspaceProps) => {
+ if (children != null) return <>{children}</>;
+ return <DefaultWorkspace className={className} />;
+};
+
+const DefaultWorkspace = ({ className }: { className?: string }) => {
+ const { isWorkspaceOpen, setIsWorkspaceOpen } = useAgentInterfaceStore((state) => ({
+ isWorkspaceOpen: state.isWorkspaceOpen,
+ setIsWorkspaceOpen: state.setIsWorkspaceOpen,
+ }));
+ const { isDetailedViewActive } = useActiveDetailedView();
+ const { layout } = useLayoutContext();
+ const categories = useArtifactCategories();
+ const all = useArtifactList();
+ const entries = latestPerId(all);
+ const shouldShowWorkspace = isWorkspaceOpen && !isDetailedViewActive;
+
+ useEffect(() => {
+ if (isDetailedViewActive && isWorkspaceOpen) {
+ setIsWorkspaceOpen(false);
+ }
+ }, [isDetailedViewActive, isWorkspaceOpen, setIsWorkspaceOpen]);
+
+ // Nothing renders while the registry is empty; the header controls open state.
+ if (entries.length === 0) return null;
+
+ return (
+ <>
+ {layout === "mobile" && (
+ <div
+ className={clsx("openui-agent-workspace-sidebar__overlay", {
+ "openui-agent-workspace-sidebar__overlay--collapsed": !shouldShowWorkspace,
+ })}
+ onClick={() => setIsWorkspaceOpen(false)}
+ />
+ )}
+ <div
+ className={clsx(
+ "openui-agent-workspace-sidebar",
+ { "openui-agent-workspace-sidebar--collapsed": !shouldShowWorkspace },
+ className,
+ )}
+ >
+ {/* No top bar / tabs for now — the rail shows every section. */}
+ <div className="openui-agent-workspace-sidebar__content">
+ {categories.length > 0 ? (
+ <WorkspaceSections categories={categories} entries={entries} />
+ ) : (
+ <WorkspaceSection entries={entries} />
+ )}
+ </div>
+ </div>
+ </>
+ );
+};
+
+const WorkspaceSections = ({
+ categories,
+ entries,
+}: {
+ categories: ReturnType<typeof useArtifactCategories>;
+ entries: ReadonlyArray<ArtifactEntry>;
+}) => {
+ // Show every category that has registered entries — no tab filtering.
+ const visibleCategories = categories.filter((category) =>
+ entries.some((entry) => entryMatchesCategory(entry, category)),
+ );
+ // Entries matching no configured category are still shown (never dropped),
+ // in a fallback section after the categorized ones.
+ const uncategorized = entries.filter(
+ (entry) => !categories.some((category) => entryMatchesCategory(entry, category)),
+ );
+
+ return (
+ <>
+ {visibleCategories.map((category) => (
+ <WorkspaceSection
+ key={category.name}
+ entries={entries.filter((entry) => entryMatchesCategory(entry, category))}
+ />
+ ))}
+ {uncategorized.length > 0 && (
+ <WorkspaceSection key="__uncategorized__" entries={uncategorized} />
+ )}
+ </>
+ );
+};
+
+const WorkspaceSection = ({
+ entries,
+ emptyHint,
+}: {
+ entries: ReadonlyArray<ArtifactEntry>;
+ emptyHint?: string;
+}) => {
+ if (entries.length === 0) {
+ if (!emptyHint) return null;
+ return <div className="openui-agent-workspace-sidebar__section-empty">{emptyHint}</div>;
+ }
+
+ return (
+ <ul className="openui-agent-workspace-sidebar__list">
+ {entries.map((entry) => (
+ <WorkspaceItem key={entry.id} entry={entry} />
+ ))}
+ </ul>
+ );
+};
+
+const WorkspaceItem = ({ entry }: { entry: ArtifactEntry }) => {
+ const viewId = `${entry.id}:${entry.version}`;
+ const { isActive } = useDetailedView(viewId);
+ const store = useDetailedViewStore();
+ const onClick = () => store.getState().setActiveDetailedView(viewId);
+ const icon = useArtifactIcon(entry.type);
+ const updatedAt = formatArtifactUpdatedAt(entry.updatedAt);
+ const metadata = [useArtifactTypeLabel(entry.type), updatedAt].filter(Boolean).join(" · ");
+
+ return (
+ <li>
+ <button
+ type="button"
+ onClick={onClick}
+ aria-pressed={isActive}
+ className={clsx("openui-agent-workspace-sidebar__item", {
+ "openui-agent-workspace-sidebar__item--active": isActive,
+ })}
+ >
+ <span className="openui-agent-workspace-sidebar__item-icon">{icon}</span>
+ <span className="openui-agent-workspace-sidebar__item-body">
+ <span className="openui-agent-workspace-sidebar__item-label">{entry.heading}</span>
+ {metadata && (
+ <span className="openui-agent-workspace-sidebar__item-meta">{metadata}</span>
+ )}
+ </span>
+ </button>
+ </li>
+ );
+};
+
+/** Picks the latest version (highest version number, kept as the last element after sort). */
+function latestPerId<T extends { id: string; version: number }>(
+ registry: Record<string, T[]>,
+): T[] {
+ return Object.values(registry)
+ .map((versions) => versions[versions.length - 1])
+ .filter((entry): entry is T => entry !== undefined);
+}
+
+type ArtifactCategory = ReturnType<typeof useArtifactCategories>[number];
+
+function entryMatchesCategory(entry: ArtifactEntry, category: ArtifactCategory) {
+ return category.filter.type.includes(entry.type);
+}
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/AgentInterfaceTooltip.tsx b/packages/react-ui/src/components/AgentInterface/_shared/AgentInterfaceTooltip.tsx
new file mode 100644
index 000000000..b4fce469f
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/AgentInterfaceTooltip.tsx
@@ -0,0 +1,33 @@
+import * as Tooltip from "@radix-ui/react-tooltip";
+import type { ReactElement, ReactNode } from "react";
+
+export interface AgentInterfaceTooltipProps {
+ children: ReactElement;
+ content: ReactNode;
+ side?: "top" | "right" | "bottom" | "left";
+ align?: "start" | "center" | "end";
+ sideOffset?: number;
+}
+
+export const AgentInterfaceTooltip = ({
+ children,
+ content,
+ side = "bottom",
+ align = "center",
+ sideOffset = 8,
+}: AgentInterfaceTooltipProps) => (
+ // Provider is hoisted once into <Container> so delay/skip-delay are shared.
+ <Tooltip.Root>
+ <Tooltip.Trigger asChild>{children}</Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content
+ className="openui-agent-tooltip"
+ side={side}
+ align={align}
+ sideOffset={sideOffset}
+ >
+ {content}
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+);
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/GalleryHorizontalEndIcon.tsx b/packages/react-ui/src/components/AgentInterface/_shared/GalleryHorizontalEndIcon.tsx
new file mode 100644
index 000000000..9a42dbf29
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/GalleryHorizontalEndIcon.tsx
@@ -0,0 +1,24 @@
+import type { SVGProps } from "react";
+
+export const GalleryHorizontalEndIcon = ({
+ size = "1em",
+ ...props
+}: SVGProps<SVGSVGElement> & { size?: number | string }) => (
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden="true"
+ focusable="false"
+ {...props}
+ >
+ <path d="M2.5 19.323A2 2 0 0 1 2 18V6a2 2 0 0 1 .5-1.323" />
+ <path d="M6.5 19.823A2 2 0 0 1 6 18.49V5.5a2 2 0 0 1 .268-1" />
+ <rect x="10" y="4" width="12" height="16" rx="2" />
+ </svg>
+);
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/artifactPaths.ts b/packages/react-ui/src/components/AgentInterface/_shared/artifactPaths.ts
new file mode 100644
index 000000000..d8a6b392f
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/artifactPaths.ts
@@ -0,0 +1,40 @@
+/**
+ * Reserved nav paths for the artifact browser.
+ *
+ * `artifacts/{category}` → searchable artifact list for a category
+ * `artifacts/{category}/{id}` → full-page artifact view
+ *
+ * `{category}` is the URI-encoded category name, or the literal `all` when no
+ * `artifactCategories` are configured. The `artifacts/` prefix is reserved:
+ * AgentInterface matches it before consulting user-defined `<Route>`s, and
+ * controlled-mode `onNavigate` consumers must round-trip these paths.
+ */
+
+export const ARTIFACTS_PATH_PREFIX = "artifacts/";
+export const UNCATEGORIZED_SEGMENT = "all";
+
+export const artifactListPath = (categoryName?: string): string =>
+ `${ARTIFACTS_PATH_PREFIX}${categoryName !== undefined ? encodeURIComponent(categoryName) : UNCATEGORIZED_SEGMENT}`;
+
+export const artifactViewPath = (categoryName: string | undefined, artifactId: string): string =>
+ `${artifactListPath(categoryName)}/${encodeURIComponent(artifactId)}`;
+
+export type ParsedArtifactPath =
+ | { kind: "list"; categoryName?: string }
+ | { kind: "view"; categoryName?: string; artifactId: string };
+
+export function parseArtifactPath(path: string): ParsedArtifactPath | null {
+ if (!path.startsWith(ARTIFACTS_PATH_PREFIX)) return null;
+ const rest = path.slice(ARTIFACTS_PATH_PREFIX.length);
+ if (!rest) return null;
+
+ const [categorySegment, idSegment, ...extra] = rest.split("/");
+ if (!categorySegment || extra.length > 0) return null;
+
+ const categoryName =
+ categorySegment === UNCATEGORIZED_SEGMENT ? undefined : decodeURIComponent(categorySegment);
+
+ if (idSegment === undefined) return { kind: "list", categoryName };
+ if (!idSegment) return null;
+ return { kind: "view", categoryName, artifactId: decodeURIComponent(idSegment) };
+}
diff --git a/packages/react-ui/src/components/_shared/artifact/ArtifactOverlay.tsx b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/DetailedViewOverlay.tsx
similarity index 60%
rename from packages/react-ui/src/components/_shared/artifact/ArtifactOverlay.tsx
rename to packages/react-ui/src/components/AgentInterface/_shared/detailed-view/DetailedViewOverlay.tsx
index 803041324..1fae70837 100644
--- a/packages/react-ui/src/components/_shared/artifact/ArtifactOverlay.tsx
+++ b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/DetailedViewOverlay.tsx
@@ -1,36 +1,36 @@
-import { useActiveArtifact } from "@openuidev/react-headless";
+import { useActiveDetailedView } from "@openuidev/react-headless";
import clsx from "clsx";
import { forwardRef, useCallback, useEffect, useRef, useState } from "react";
-import { useMultipleRefs } from "../../../hooks/useMultipleRefs";
-import { ArtifactPortalTarget } from "./ArtifactPortalTarget";
+import { useMultipleRefs } from "../../../../hooks/useMultipleRefs";
+import { DetailedViewPortalTarget } from "./DetailedViewPortalTarget";
/**
- * Props for {@link ArtifactOverlay}.
+ * Props for {@link DetailedViewOverlay}.
*
* @category Components
*/
-export type ArtifactOverlayProps = {
+export type DetailedViewOverlayProps = {
/** Additional CSS class name(s) applied to the overlay container. */
className?: string;
};
/**
- * Shared overlay wrapper for the artifact portal target.
- * Used by CopilotShell, BottomTray, and Shell (mobile) layouts.
+ * Shared overlay wrapper for the detailed-view portal target.
+ * Used by the AgentInterface chat surface.
* Renders an absolute-positioned overlay with slide-in/slide-out animations.
*
* @category Components
*/
-export const ArtifactOverlay = forwardRef<HTMLDivElement, ArtifactOverlayProps>(
+export const DetailedViewOverlay = forwardRef<HTMLDivElement, DetailedViewOverlayProps>(
({ className }, ref) => {
- const { isArtifactActive } = useActiveArtifact();
- const [shouldRender, setShouldRender] = useState(isArtifactActive);
+ const { isDetailedViewActive } = useActiveDetailedView();
+ const [shouldRender, setShouldRender] = useState(isDetailedViewActive);
const [isExiting, setIsExiting] = useState(false);
const internalRef = useRef<HTMLDivElement>(null);
const mergedRef = useMultipleRefs<HTMLDivElement>(ref, internalRef);
useEffect(() => {
- if (isArtifactActive) {
+ if (isDetailedViewActive) {
// Opening: mount immediately, cancel any in-progress exit
setShouldRender(true);
setIsExiting(false);
@@ -38,7 +38,7 @@ export const ArtifactOverlay = forwardRef<HTMLDivElement, ArtifactOverlayProps>(
// Closing: start exit animation, defer unmount
setIsExiting(true);
}
- }, [isArtifactActive]); // eslint-disable-line react-hooks/exhaustive-deps
+ }, [isDetailedViewActive]); // eslint-disable-line react-hooks/exhaustive-deps
const handleAnimationEnd = useCallback(
(e: React.AnimationEvent<HTMLDivElement>) => {
@@ -58,16 +58,16 @@ export const ArtifactOverlay = forwardRef<HTMLDivElement, ArtifactOverlayProps>(
<div
ref={mergedRef}
className={clsx(
- "openui-artifact-overlay",
- { "openui-artifact-overlay--exiting": isExiting },
+ "openui-detailed-view-overlay",
+ { "openui-detailed-view-overlay--exiting": isExiting },
className,
)}
onAnimationEnd={handleAnimationEnd}
>
- <ArtifactPortalTarget />
+ <DetailedViewPortalTarget />
</div>
);
},
);
-ArtifactOverlay.displayName = "ArtifactOverlay";
+DetailedViewOverlay.displayName = "DetailedViewOverlay";
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/DetailedViewPanel.tsx b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/DetailedViewPanel.tsx
new file mode 100644
index 000000000..b4a12609a
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/DetailedViewPanel.tsx
@@ -0,0 +1,135 @@
+import { useDetailedView, useDetailedViewPortalTarget } from "@openuidev/react-headless";
+import clsx from "clsx";
+import { X } from "lucide-react";
+import { Component, forwardRef, useEffect, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { IconButton } from "../../../IconButton";
+import { useTheme } from "../../../ThemeProvider/ThemeProvider";
+
+/** @internal */
+type DetailedViewErrorBoundaryProps = {
+ children: ReactNode;
+ fallback?: ReactNode;
+};
+
+type DetailedViewErrorBoundaryState = {
+ hasError: boolean;
+};
+
+/** @internal */
+class DetailedViewErrorBoundary extends Component<
+ DetailedViewErrorBoundaryProps,
+ DetailedViewErrorBoundaryState
+> {
+ constructor(props: DetailedViewErrorBoundaryProps) {
+ super(props);
+ this.state = { hasError: false };
+ }
+
+ static getDerivedStateFromError(): DetailedViewErrorBoundaryState {
+ return { hasError: true };
+ }
+
+ override render() {
+ if (this.state.hasError) {
+ return this.props.fallback ?? null;
+ }
+ return this.props.children;
+ }
+}
+
+/**
+ * Props for {@link DetailedViewPanel}.
+ *
+ * @category Components
+ */
+export type DetailedViewPanelProps = {
+ /** Detailed-view id this panel renders content for. Must match the id passed to `useDetailedView(viewId)`. */
+ viewId: string;
+ /** Content rendered inside the panel when this view is active. */
+ children: ReactNode;
+ /** Display title for the panel header and aria-label. Defaults to `"Detailed view"`. */
+ title?: string;
+ /** Additional CSS class name(s) applied to the panel container. */
+ className?: string;
+ /** Fallback UI rendered if children throw during rendering. Defaults to `null`. */
+ errorFallback?: ReactNode;
+ /**
+ * Controls the panel header.
+ * - `true` (default): built-in header with title + close button
+ * - `false`: no header, raw children only
+ * - `ReactNode`: custom header replacing the built-in one
+ */
+ header?: boolean | ReactNode;
+};
+
+/** @internal */
+const DefaultHeader = ({ title, onClose }: { title: string; onClose: () => void }) => (
+ <div className="openui-detailed-view-panel__header">
+ <span className="openui-detailed-view-panel__title">{title}</span>
+ <IconButton
+ variant="tertiary"
+ size="small"
+ icon={<X size="1em" />}
+ onClick={onClose}
+ aria-label="Close detailed-view panel"
+ />
+ </div>
+);
+
+/**
+ * Portals detailed-view content into the nearest {@link DetailedViewPortalTarget}.
+ *
+ * Renders nothing when the view is inactive or no portal target is mounted.
+ * Wraps children in an error boundary and applies theme-scoped class names.
+ *
+ * Requires `<DetailedViewPortalTarget />` to be mounted in the layout.
+ *
+ * @category Components
+ */
+export const DetailedViewPanel = forwardRef<HTMLDivElement, DetailedViewPanelProps>(
+ ({ viewId, children, title, className, errorFallback, header = true }, ref) => {
+ const { isActive, close } = useDetailedView(viewId);
+ const { node: panelNode } = useDetailedViewPortalTarget();
+ const { portalThemeClassName } = useTheme();
+
+ useEffect(() => {
+ if (!isActive || panelNode) return;
+
+ const timer = setTimeout(() => {
+ console.warn(
+ "[OpenUI] DetailedViewPanel: view is active but no render target is mounted. " +
+ "Ensure <DetailedViewPortalTarget /> is rendered in your layout.",
+ );
+ }, 100);
+ return () => clearTimeout(timer);
+ }, [isActive, panelNode]);
+
+ if (!isActive || !panelNode) return null;
+
+ const handleClose = () => close();
+
+ let headerContent: ReactNode = null;
+ if (header === true) {
+ headerContent = <DefaultHeader title={title ?? "Detailed view"} onClose={handleClose} />;
+ } else if (header !== false) {
+ headerContent = header;
+ }
+
+ return createPortal(
+ <div
+ ref={ref}
+ id={`openui-detailed-view-panel-${viewId}`}
+ className={clsx("openui-detailed-view-panel", portalThemeClassName, className)}
+ role="region"
+ aria-label={title ?? "Detailed view panel"}
+ >
+ {headerContent}
+ <DetailedViewErrorBoundary fallback={errorFallback}>{children}</DetailedViewErrorBoundary>
+ </div>,
+ panelNode,
+ );
+ },
+);
+
+DetailedViewPanel.displayName = "DetailedViewPanel";
diff --git a/packages/react-ui/src/components/_shared/artifact/ArtifactPortalTarget.tsx b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/DetailedViewPortalTarget.tsx
similarity index 64%
rename from packages/react-ui/src/components/_shared/artifact/ArtifactPortalTarget.tsx
rename to packages/react-ui/src/components/AgentInterface/_shared/detailed-view/DetailedViewPortalTarget.tsx
index f768fcbda..256bb05eb 100644
--- a/packages/react-ui/src/components/_shared/artifact/ArtifactPortalTarget.tsx
+++ b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/DetailedViewPortalTarget.tsx
@@ -1,25 +1,25 @@
-import { useArtifactPortalTarget } from "@openuidev/react-headless";
+import { useDetailedViewPortalTarget } from "@openuidev/react-headless";
import { forwardRef, useCallback, useRef } from "react";
/**
- * Props for {@link ArtifactPortalTarget}.
+ * Props for {@link DetailedViewPortalTarget}.
*/
-export type ArtifactPortalTargetProps = {
+export type DetailedViewPortalTargetProps = {
/** Additional CSS class name(s) applied to the container element. */
className?: string;
};
/**
- * Registers a DOM node as the render target for {@link ArtifactPanel} portals.
+ * Registers a DOM node as the render target for {@link DetailedViewPanel} portals.
*
* Mount exactly one instance in your layout. Renders a `<div>` with
* `display: contents` so it doesn't affect layout flow.
*
* @category Components
*/
-export const ArtifactPortalTarget = forwardRef<HTMLDivElement, ArtifactPortalTargetProps>(
+export const DetailedViewPortalTarget = forwardRef<HTMLDivElement, DetailedViewPortalTargetProps>(
({ className }, ref) => {
- const { setNode } = useArtifactPortalTarget();
+ const { setNode } = useDetailedViewPortalTarget();
const forwardedRef = useRef(ref);
forwardedRef.current = ref;
@@ -40,4 +40,4 @@ export const ArtifactPortalTarget = forwardRef<HTMLDivElement, ArtifactPortalTar
},
);
-ArtifactPortalTarget.displayName = "ArtifactPortalTarget";
+DetailedViewPortalTarget.displayName = "DetailedViewPortalTarget";
diff --git a/packages/react-ui/src/components/_shared/artifact/artifactOverlay.scss b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/detailedViewOverlay.scss
similarity index 52%
rename from packages/react-ui/src/components/_shared/artifact/artifactOverlay.scss
rename to packages/react-ui/src/components/AgentInterface/_shared/detailed-view/detailedViewOverlay.scss
index af9a729ce..5a6d565c8 100644
--- a/packages/react-ui/src/components/_shared/artifact/artifactOverlay.scss
+++ b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/detailedViewOverlay.scss
@@ -1,6 +1,6 @@
-@use "../../../cssUtils" as cssUtils;
+@use "../../../../cssUtils" as cssUtils;
-.openui-artifact-overlay {
+.openui-detailed-view-overlay {
position: absolute;
top: 0;
left: 0;
@@ -8,14 +8,14 @@
bottom: 0;
z-index: 10;
background-color: cssUtils.$foreground;
- animation: openui-artifact-overlay-slide-in 0.3s cubic-bezier(0.4, 0, 0.2, 1);
+ animation: openui-detailed-view-overlay-slide-in 0.3s cubic-bezier(0.4, 0, 0.2, 1);
&--exiting {
- animation: openui-artifact-overlay-slide-out 0.2s cubic-bezier(0.4, 0, 0.2, 1) forwards;
+ animation: openui-detailed-view-overlay-slide-out 0.2s cubic-bezier(0.4, 0, 0.2, 1) forwards;
}
}
-@keyframes openui-artifact-overlay-slide-in {
+@keyframes openui-detailed-view-overlay-slide-in {
from {
opacity: 0;
transform: translateY(20px);
@@ -27,7 +27,7 @@
}
}
-@keyframes openui-artifact-overlay-slide-out {
+@keyframes openui-detailed-view-overlay-slide-out {
from {
opacity: 1;
transform: translateY(0);
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/detailedViewPanel.scss b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/detailedViewPanel.scss
new file mode 100644
index 000000000..251a23a2b
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/detailedViewPanel.scss
@@ -0,0 +1,31 @@
+@use "../../../../cssUtils" as cssUtils;
+
+.openui-detailed-view-panel {
+ flex: 1 1 0%;
+ height: 100%;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+}
+
+.openui-detailed-view-panel__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: cssUtils.$space-m;
+ padding: cssUtils.$space-m cssUtils.$space-m cssUtils.$space-m cssUtils.$space-l;
+ border-bottom: 1px solid cssUtils.$border-default;
+ background-color: cssUtils.$foreground;
+ position: sticky;
+ top: 0;
+ z-index: 1;
+}
+
+.openui-detailed-view-panel__title {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-primary;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ min-width: 0;
+}
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/index.ts b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/index.ts
new file mode 100644
index 000000000..7e986aebb
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/detailed-view/index.ts
@@ -0,0 +1,3 @@
+export * from "./DetailedViewOverlay";
+export * from "./DetailedViewPanel";
+export * from "./DetailedViewPortalTarget";
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/index.ts b/packages/react-ui/src/components/AgentInterface/_shared/index.ts
new file mode 100644
index 000000000..f1cab8d7d
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/index.ts
@@ -0,0 +1,5 @@
+export * from "./detailed-view";
+export * from "./store";
+export * from "./tool-renderer";
+export * from "./types";
+export * from "./utils";
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/labelsContext.tsx b/packages/react-ui/src/components/AgentInterface/_shared/labelsContext.tsx
new file mode 100644
index 000000000..5e58817f3
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/labelsContext.tsx
@@ -0,0 +1,74 @@
+import { createContext, useContext, useMemo, type ReactNode } from "react";
+
+/** Per-tab labels for the per-thread Workspace rail. */
+export interface WorkspaceTabLabels {
+ all?: string;
+ artifacts?: string;
+ apps?: string;
+}
+
+/**
+ * Consumer-overridable display strings for the artifact browser + workspace.
+ * Every field is optional; omitted values fall back to the English defaults.
+ * Pass via `<AgentInterface labels={...}>`.
+ */
+export interface AgentInterfaceLabels {
+ /**
+ * Fallback title/nav label for the artifact browser when no category is
+ * configured (a configured category always uses its own `name`). Default
+ * `"Artifacts"`.
+ */
+ defaultCategory?: string;
+ /** Tooltip on the workspace toggle button. Default `"Apps & Artifacts"`. */
+ workspaceToggle?: string;
+ /** Labels for the workspace rail tabs. Defaults: `All` / `Artifacts` / `Apps`. */
+ tabs?: WorkspaceTabLabels;
+}
+
+/** Fully-resolved labels (defaults applied) — what consumers of the hook get. */
+export interface ResolvedLabels {
+ defaultCategory: string;
+ workspaceToggle: string;
+ tabs: { all: string; artifacts: string; apps: string };
+}
+
+const DEFAULT_LABELS: ResolvedLabels = {
+ defaultCategory: "Artifacts",
+ workspaceToggle: "Apps & Artifacts",
+ tabs: { all: "All", artifacts: "Artifacts", apps: "Apps" },
+};
+
+const LabelsContext = createContext<ResolvedLabels>(DEFAULT_LABELS);
+
+export interface LabelsProviderProps {
+ labels?: AgentInterfaceLabels;
+ children: ReactNode;
+}
+
+export const LabelsProvider = ({ labels, children }: LabelsProviderProps) => {
+ const value = useMemo<ResolvedLabels>(
+ () => ({
+ defaultCategory: labels?.defaultCategory ?? DEFAULT_LABELS.defaultCategory,
+ workspaceToggle: labels?.workspaceToggle ?? DEFAULT_LABELS.workspaceToggle,
+ tabs: {
+ all: labels?.tabs?.all ?? DEFAULT_LABELS.tabs.all,
+ artifacts: labels?.tabs?.artifacts ?? DEFAULT_LABELS.tabs.artifacts,
+ apps: labels?.tabs?.apps ?? DEFAULT_LABELS.tabs.apps,
+ },
+ }),
+ [
+ labels?.defaultCategory,
+ labels?.workspaceToggle,
+ labels?.tabs?.all,
+ labels?.tabs?.artifacts,
+ labels?.tabs?.apps,
+ ],
+ );
+ return <LabelsContext.Provider value={value}>{children}</LabelsContext.Provider>;
+};
+
+/**
+ * Resolved (default-merged) consumer labels for the artifact browser + workspace.
+ * Works without a provider (returns the English defaults).
+ */
+export const useAgentInterfaceLabels = (): ResolvedLabels => useContext(LabelsContext);
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/navContext.tsx b/packages/react-ui/src/components/AgentInterface/_shared/navContext.tsx
new file mode 100644
index 000000000..af5707823
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/navContext.tsx
@@ -0,0 +1,67 @@
+import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
+
+export interface NavContextValue {
+ /** Current path. `undefined` means the thread region is active (no Route matched). */
+ path: string | undefined;
+ /** Switch path. Pass `undefined` to clear and return to the thread view. */
+ navigate: (next: string | undefined) => void;
+}
+
+const NavContext = createContext<NavContextValue | null>(null);
+
+export interface NavProviderProps {
+ /** Controlled current path. Provide together with `onNavigate`. */
+ path?: string;
+ /** Initial path for uncontrolled mode. Ignored when `onNavigate` is provided. */
+ defaultPath?: string;
+ /** Called when navigation occurs. Presence determines controlled mode. */
+ onNavigate?: (next: string | undefined) => void;
+ children: ReactNode;
+}
+
+/**
+ * Standard controlled/uncontrolled split:
+ * - `onNavigate` provided → controlled. Parent owns state; `path` prop is the source of truth.
+ * - `onNavigate` absent → uncontrolled. Internal state starts at `defaultPath`.
+ */
+export const NavProvider = ({ path, defaultPath, onNavigate, children }: NavProviderProps) => {
+ const isControlled = onNavigate !== undefined;
+ const [internalPath, setInternalPath] = useState<string | undefined>(defaultPath);
+
+ const currentPath = isControlled ? path : internalPath;
+
+ const navigate = useCallback(
+ (next: string | undefined) => {
+ if (isControlled) {
+ onNavigate?.(next);
+ } else {
+ setInternalPath(next);
+ }
+ },
+ [isControlled, onNavigate],
+ );
+
+ const value = useMemo<NavContextValue>(
+ () => ({ path: currentPath, navigate }),
+ [currentPath, navigate],
+ );
+
+ return <NavContext.Provider value={value}>{children}</NavContext.Provider>;
+};
+
+/**
+ * Read the current navigation state from inside <AgentInterface>.
+ *
+ * Returns `{ path, navigate }`. Call `navigate(undefined)` to return to the
+ * thread view (clears any active route).
+ */
+export const useNav = (): NavContextValue => {
+ const ctx = useContext(NavContext);
+ if (!ctx) {
+ throw new Error("useNav() must be used inside <AgentInterface>");
+ }
+ return ctx;
+};
+
+/** Returns the nav context if mounted, otherwise null. Internal use. */
+export const useOptionalNav = (): NavContextValue | null => useContext(NavContext);
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/shared.scss b/packages/react-ui/src/components/AgentInterface/_shared/shared.scss
new file mode 100644
index 000000000..b7532c8e4
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/shared.scss
@@ -0,0 +1,2 @@
+@forward "./detailed-view/detailedViewOverlay.scss";
+@forward "./detailed-view/detailedViewPanel.scss";
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/startersContext.tsx b/packages/react-ui/src/components/AgentInterface/_shared/startersContext.tsx
new file mode 100644
index 000000000..77fb01ff7
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/startersContext.tsx
@@ -0,0 +1,22 @@
+import { createContext, useContext, type ReactNode } from "react";
+import type { ConversationStarterProps } from "../../../types/ConversationStarter";
+import type { ConversationStarterVariant } from "../ConversationStarter";
+
+export interface StartersContextValue {
+ starters?: ConversationStarterProps[];
+ starterVariant?: ConversationStarterVariant;
+}
+
+const StartersContext = createContext<StartersContextValue>({});
+
+export const StartersProvider = ({
+ starters,
+ starterVariant,
+ children,
+}: StartersContextValue & { children: ReactNode }) => (
+ <StartersContext.Provider value={{ starters, starterVariant }}>
+ {children}
+ </StartersContext.Provider>
+);
+
+export const useStartersFromContext = () => useContext(StartersContext);
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/store/index.ts b/packages/react-ui/src/components/AgentInterface/_shared/store/index.ts
new file mode 100644
index 000000000..f5990c259
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/store/index.ts
@@ -0,0 +1 @@
+export * from "./store";
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/store/store.tsx b/packages/react-ui/src/components/AgentInterface/_shared/store/store.tsx
new file mode 100644
index 000000000..8bb6d5db0
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/store/store.tsx
@@ -0,0 +1,69 @@
+import { createContext, useContext, useEffect, useMemo } from "react";
+import { create } from "zustand";
+import { useShallow } from "zustand/react/shallow";
+
+interface AgentInterfaceState {
+ isSidebarOpen: boolean;
+ isWorkspaceOpen: boolean;
+ agentName: string;
+ logoUrl: string;
+ setIsSidebarOpen: (isOpen: boolean) => void;
+ setIsWorkspaceOpen: (isOpen: boolean) => void;
+ setAgentName: (name: string) => void;
+ setLogoUrl: (url: string) => void;
+}
+
+export const createAgentInterfaceStore = ({
+ logoUrl,
+ agentName,
+}: {
+ logoUrl: string;
+ agentName: string;
+}) =>
+ create<AgentInterfaceState>((set) => ({
+ isSidebarOpen: true,
+ isWorkspaceOpen: false,
+ agentName: agentName,
+ logoUrl: logoUrl,
+ setIsSidebarOpen: (isOpen: boolean) => set({ isSidebarOpen: isOpen }),
+ setIsWorkspaceOpen: (isOpen: boolean) => set({ isWorkspaceOpen: isOpen }),
+ setAgentName: (name: string) => set({ agentName: name }),
+ setLogoUrl: (url: string) => set({ logoUrl: url }),
+ }));
+
+export const AgentInterfaceStoreContext = createContext<ReturnType<
+ typeof createAgentInterfaceStore
+> | null>(null);
+
+export const useAgentInterfaceStore = <T,>(selector: (state: AgentInterfaceState) => T): T => {
+ const store = useContext(AgentInterfaceStoreContext);
+ if (!store) {
+ throw new Error("useAgentInterfaceStore must be used within AgentInterfaceStoreProvider");
+ }
+
+ return store(useShallow(selector));
+};
+
+export const AgentInterfaceStoreProvider = ({
+ children,
+ agentName,
+ logoUrl,
+}: {
+ children: React.ReactNode;
+ logoUrl: string;
+ agentName: string;
+}) => {
+ const shellStore = useMemo(() => createAgentInterfaceStore({ agentName, logoUrl }), []);
+
+ useEffect(() => {
+ const { setAgentName, setLogoUrl } = shellStore.getState();
+ setAgentName(agentName);
+ setLogoUrl(logoUrl);
+ }, [agentName, logoUrl]);
+
+ return (
+ <AgentInterfaceStoreContext.Provider value={shellStore}>
+ {children}
+ </AgentInterfaceStoreContext.Provider>
+ );
+};
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/tool-renderer/index.ts b/packages/react-ui/src/components/AgentInterface/_shared/tool-renderer/index.ts
new file mode 100644
index 000000000..65b0287dc
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/tool-renderer/index.ts
@@ -0,0 +1,14 @@
+// The AgentInterface tool-renderer now re-exports the single canonical module
+// (the two byte-near-identical copies were collapsed into one). AgentInterface's
+// threads inject their own detailed-view panel where needed.
+export {
+ TimelineEntry,
+ ToolActivityRenderer,
+ ToolCallEntry,
+ ToolCallErrorFallback,
+ ToolMessageRenderer,
+ type TimelineEntryProps,
+ type ToolCallEntryProps,
+ type ToolDetailedViewPanel,
+ type ToolMessageRendererProps,
+} from "../../../_shared/tool-renderer";
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/types/index.ts b/packages/react-ui/src/components/AgentInterface/_shared/types/index.ts
new file mode 100644
index 000000000..869f4ea5f
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/types/index.ts
@@ -0,0 +1,34 @@
+import type { AssistantMessage, UserMessage } from "@openuidev/react-headless";
+
+/**
+ * Custom component for rendering assistant messages.
+ * When provided, replaces the default assistant message rendering entirely
+ * (including the container with avatar).
+ *
+ * @example
+ * const MyAssistantMessage: AssistantMessageComponent = ({ message }) => (
+ * <div className="my-assistant-message">
+ * <ReactMarkdown>{message.content ?? ""}</ReactMarkdown>
+ * </div>
+ * );
+ */
+export type AssistantMessageComponent = React.ComponentType<{
+ message: AssistantMessage;
+ isStreaming: boolean;
+}>;
+
+/**
+ * Custom component for rendering user messages.
+ * When provided, replaces the default user message rendering entirely
+ * (including the container).
+ *
+ * @example
+ * const MyUserMessage: UserMessageComponent = ({ message }) => (
+ * <div className="my-user-message">
+ * {typeof message.content === "string" ? message.content : "..."}
+ * </div>
+ * );
+ */
+export type UserMessageComponent = React.ComponentType<{
+ message: UserMessage;
+}>;
diff --git a/packages/react-ui/src/components/AgentInterface/_shared/utils/index.ts b/packages/react-ui/src/components/AgentInterface/_shared/utils/index.ts
new file mode 100644
index 000000000..9a588ec6c
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/_shared/utils/index.ts
@@ -0,0 +1,11 @@
+import { Message } from "@openuidev/react-headless";
+
+export const isChatEmpty = ({
+ isLoadingMessages,
+ messages,
+}: {
+ isLoadingMessages: boolean | undefined;
+ messages: Message[];
+}) => {
+ return !isLoadingMessages && messages.length === 0;
+};
diff --git a/packages/react-ui/src/components/AgentInterface/agentInterface.scss b/packages/react-ui/src/components/AgentInterface/agentInterface.scss
new file mode 100644
index 000000000..998ecd27a
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/agentInterface.scss
@@ -0,0 +1,142 @@
+@use "../../cssUtils" as cssUtils;
+@use "./sidebar.scss";
+@use "./threadlist.scss";
+@use "./thread.scss";
+@use "./mobileHeader.scss";
+@use "./resizableSeparator.scss";
+@use "./conversationStarter.scss";
+@use "./welcomeScreen.scss";
+@use "./components/desktopWelcomeComposer.scss";
+@use "./components/composer.scss";
+@use "./artifactBrowser.scss";
+@use "./workspaceSidebar.scss";
+@use "./_shared/shared.scss";
+
+.openui-agent-container {
+ display: flex;
+ position: relative;
+ height: 100dvh;
+ width: 100dvw;
+ overflow: hidden;
+
+ background: cssUtils.$foreground;
+ box-sizing: border-box;
+ & * {
+ box-sizing: border-box;
+ }
+
+ &.openui-agent-container--mobile {
+ padding: 0;
+ }
+}
+
+.openui-agent-sidebar-actions {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-xl;
+
+ .openui-agent-container--mobile & {
+ gap: 0;
+ }
+}
+
+.openui-agent-sidebar-primary-actions,
+.openui-agent-sidebar-artifact-nav {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-s-m;
+
+ .openui-agent-container--mobile & {
+ gap: cssUtils.$space-xl;
+ }
+}
+
+.openui-agent-container--mobile .openui-agent-sidebar-artifact-nav {
+ margin-top: cssUtils.$space-2xl;
+ padding: 0 cssUtils.$space-m-l;
+}
+
+.openui-agent-new-chat-button {
+ @include cssUtils.button-reset;
+ @include cssUtils.typography(label, small);
+
+ width: 100%;
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-xs;
+ justify-content: flex-start;
+ color: cssUtils.$text-neutral-primary;
+ border-radius: calc(cssUtils.$radius-s + 1px);
+ cursor: pointer;
+ overflow: hidden;
+ transition: background-color 90ms cubic-bezier(0.22, 1, 0.36, 1);
+
+ &:not(&--collapsed):hover {
+ background-color: cssUtils.$highlight;
+ }
+
+ &--collapsed:hover {
+ background-color: transparent;
+
+ .openui-agent-new-chat-button__icon {
+ background-color: cssUtils.$highlight;
+ }
+ }
+
+ &__icon {
+ width: 28px;
+ height: 28px;
+ margin: cssUtils.$space-3xs;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ border: 1px solid cssUtils.$border-default;
+ border-radius: cssUtils.$radius-s;
+ background-color: cssUtils.$foreground;
+ color: cssUtils.$text-neutral-primary;
+ font-size: 16px;
+ transition:
+ background-color 90ms cubic-bezier(0.22, 1, 0.36, 1),
+ border-color 90ms cubic-bezier(0.22, 1, 0.36, 1),
+ color 90ms cubic-bezier(0.22, 1, 0.36, 1),
+ box-shadow 90ms cubic-bezier(0.22, 1, 0.36, 1);
+ }
+
+ &__label {
+ opacity: 1;
+ white-space: nowrap;
+ transition: opacity 90ms cubic-bezier(0.22, 1, 0.36, 1);
+ }
+
+ &--collapsed {
+ width: 32px;
+ gap: 0;
+
+ .openui-agent-new-chat-button__label {
+ width: 0;
+ opacity: 0;
+ overflow: hidden;
+ }
+ }
+}
+
+.openui-agent-new-chat-floating-button {
+ position: absolute;
+ left: cssUtils.$space-m-l;
+ bottom: cssUtils.$space-l;
+ z-index: 1;
+}
+
+.openui-agent-tooltip,
+.openui-agent-sidebar-tooltip {
+ @include cssUtils.typography(label, extra-small);
+
+ z-index: 10000;
+ padding: cssUtils.$space-xs cssUtils.$space-s;
+ border: 1px solid cssUtils.$border-default;
+ border-radius: cssUtils.$radius-m;
+ background-color: cssUtils.$inverted-background;
+ color: cssUtils.$text-accent-primary;
+ box-shadow: cssUtils.$shadow-m;
+}
diff --git a/packages/react-ui/src/components/AgentInterface/artifactBrowser.scss b/packages/react-ui/src/components/AgentInterface/artifactBrowser.scss
new file mode 100644
index 000000000..e24d18e5d
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/artifactBrowser.scss
@@ -0,0 +1,287 @@
+@use "../../cssUtils" as cssUtils;
+
+.openui-agent-artifact-browser {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-m;
+ height: 100%;
+ width: 100%;
+ padding: 0 cssUtils.$space-l 80px;
+ box-sizing: border-box;
+ overflow-y: auto;
+ overflow-x: hidden;
+}
+
+.openui-agent-artifact-browser__content {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-l;
+ width: 100%;
+ min-width: 0;
+ max-width: 800px;
+ margin: 0 auto;
+}
+
+.openui-agent-artifact-browser__header {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: cssUtils.$space-xl;
+ padding: 72px cssUtils.$space-m cssUtils.$space-m;
+ background-color: cssUtils.$foreground;
+ min-width: 0;
+
+ &::after {
+ content: "";
+ position: absolute;
+ right: 0;
+ bottom: calc(-1 * #{cssUtils.$space-xl});
+ left: 0;
+ height: cssUtils.$space-xl;
+ background: linear-gradient(to bottom, cssUtils.$foreground 0%, transparent 100%);
+ pointer-events: none;
+ }
+}
+
+.openui-agent-artifact-browser__title {
+ @include cssUtils.typography(heading, large);
+ color: cssUtils.$text-neutral-primary;
+ font-weight: 500;
+ margin: 0;
+ padding-left: 4px;
+ min-width: 0;
+}
+
+.openui-agent-artifact-browser__search {
+ @include cssUtils.typography(body, default);
+
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-s;
+ width: 240px;
+ max-width: 50%;
+ min-width: 0;
+ padding: calc(cssUtils.$space-xs - 1px) calc(cssUtils.$space-xs - 1px)
+ calc(cssUtils.$space-xs - 1px) calc(cssUtils.$space-m - 1px);
+ border: 1px solid cssUtils.$border-interactive;
+ border-radius: cssUtils.$radius-m;
+ box-sizing: border-box;
+ background-color: cssUtils.$highlight-subtle;
+ color: cssUtils.$text-neutral-secondary;
+ transition:
+ box-shadow 0.16s ease,
+ border-color 0.16s ease,
+ background-color 0.16s ease;
+
+ &:focus-within {
+ border-color: cssUtils.$border-interactive-emphasis;
+ box-shadow: 0 0 0 2.5px cssUtils.$border-default;
+ }
+
+ &:not(:focus-within):hover {
+ border-color: cssUtils.$border-interactive;
+ }
+}
+
+.openui-agent-artifact-browser__search-input {
+ @include cssUtils.typography(body, default);
+
+ border: none;
+ outline: none;
+ background: transparent;
+ flex: 1;
+ width: 100%;
+ min-width: 0;
+ color: cssUtils.$text-neutral-primary;
+
+ &::placeholder {
+ color: cssUtils.$text-neutral-secondary;
+ }
+}
+
+.openui-agent-artifact-browser__list {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-m;
+ width: 100%;
+ min-width: 0;
+}
+
+.openui-agent-artifact-browser__item {
+ @include cssUtils.button-reset;
+ @include cssUtils.typography(body, default);
+
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-m-l;
+ width: 100%;
+ min-width: 0;
+ max-width: 100%;
+ padding: cssUtils.$space-s;
+ border: 0;
+ border-radius: cssUtils.$radius-2xl;
+ background-color: transparent;
+ color: cssUtils.$text-neutral-primary;
+ text-align: left;
+ cursor: pointer;
+ transition: background-color 0.16s ease;
+
+ &:hover {
+ background-color: cssUtils.$highlight;
+ }
+
+ &:focus-visible {
+ outline: 2px solid cssUtils.$border-accent;
+ outline-offset: 2px;
+ }
+}
+
+.openui-agent-artifact-browser__item-icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ width: 52px;
+ height: 52px;
+ border-radius: cssUtils.$radius-m;
+ background-color: cssUtils.$highlight;
+ color: cssUtils.$text-neutral-secondary;
+ font-size: 24px;
+ overflow: hidden;
+
+ // The consumer's icon/illustration node fills the box if it wants to.
+ > * {
+ max-width: 100%;
+ max-height: 100%;
+ }
+}
+
+.openui-agent-artifact-browser__item-meta {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ justify-content: center;
+ gap: cssUtils.$space-s;
+ min-width: 0;
+ max-width: 100%;
+ overflow: hidden;
+ padding: 0;
+}
+
+.openui-agent-artifact-browser__item-title {
+ @include cssUtils.typography(label, default);
+
+ display: block;
+ width: 100%;
+ min-width: 0;
+ max-width: 100%;
+ white-space: normal;
+ word-break: break-word;
+ overflow-wrap: anywhere;
+}
+
+.openui-agent-artifact-browser__item-updated-at {
+ @include cssUtils.typography(label, small);
+
+ color: cssUtils.$text-neutral-secondary;
+}
+
+.openui-agent-artifact-browser__loading,
+.openui-agent-artifact-browser__error {
+ @include cssUtils.typography(body, default);
+
+ color: cssUtils.$text-neutral-secondary;
+ padding: cssUtils.$space-s 0;
+}
+
+.openui-agent-artifact-browser__empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: cssUtils.$space-l;
+ min-height: 320px;
+ padding: cssUtils.$space-3xl 0;
+ text-align: center;
+}
+
+.openui-agent-artifact-browser__empty-illustration {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ align-self: center;
+ margin: cssUtils.$space-m-l;
+ color: cssUtils.$text-neutral-tertiary;
+ font-size: 48px;
+}
+
+.openui-agent-artifact-browser__empty-text {
+ @include cssUtils.typography(body, default);
+
+ color: cssUtils.$text-neutral-primary;
+}
+
+.openui-agent-artifact-browser__load-more {
+ display: flex;
+}
+
+@media (max-width: 560px) {
+ .openui-agent-artifact-browser {
+ padding: 0 cssUtils.$space-m-l 80px;
+ }
+
+ .openui-agent-artifact-browser__header {
+ align-items: stretch;
+ flex-direction: column;
+ padding: cssUtils.$space-xl 0 cssUtils.$space-m;
+ }
+
+ .openui-agent-artifact-browser__search {
+ width: 100%;
+ max-width: none;
+ }
+}
+
+.openui-agent-artifact-view {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ overflow: hidden;
+}
+
+.openui-agent-artifact-view__header {
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-m;
+ padding: cssUtils.$space-m-l cssUtils.$space-m-l cssUtils.$space-m;
+ border-bottom: 1px solid cssUtils.$border-default;
+ flex-shrink: 0;
+
+ .openui-agent-container--mobile & {
+ display: none;
+ }
+}
+
+.openui-agent-artifact-view__title {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-primary;
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.openui-agent-artifact-view__content {
+ flex: 1;
+ overflow-y: auto;
+}
+
+.openui-agent-artifact-view__loading,
+.openui-agent-artifact-view__error {
+ @include cssUtils.typography(body, default);
+ color: cssUtils.$text-neutral-secondary;
+ padding: cssUtils.$space-l;
+}
diff --git a/packages/react-ui/src/components/Shell/components/Composer.tsx b/packages/react-ui/src/components/AgentInterface/components/Composer.tsx
similarity index 66%
rename from packages/react-ui/src/components/Shell/components/Composer.tsx
rename to packages/react-ui/src/components/AgentInterface/components/Composer.tsx
index 0ce1e6fca..18f808eda 100644
--- a/packages/react-ui/src/components/Shell/components/Composer.tsx
+++ b/packages/react-ui/src/components/AgentInterface/components/Composer.tsx
@@ -1,7 +1,7 @@
import { useThread } from "@openuidev/react-headless";
import clsx from "clsx";
import { ArrowUp, Square } from "lucide-react";
-import { useLayoutEffect, useRef } from "react";
+import { useCallback, useLayoutEffect, useRef, useState } from "react";
import { useComposerState } from "../../../hooks/useComposerState";
import { IconButton } from "../../IconButton";
@@ -17,6 +17,18 @@ export const Composer = ({ className, placeholder = "Type your query here" }: Co
const isRunning = useThread((s) => s.isRunning);
const isLoadingMessages = useThread((s) => s.isLoadingMessages);
const inputRef = useRef<HTMLTextAreaElement>(null);
+ const [hasInputOverflowTop, setHasInputOverflowTop] = useState(false);
+ const [hasInputOverflowBottom, setHasInputOverflowBottom] = useState(false);
+
+ const updateInputOverflow = useCallback(() => {
+ const input = inputRef.current;
+ if (!input) return;
+
+ const maxScrollTop = input.scrollHeight - input.clientHeight;
+
+ setHasInputOverflowTop(maxScrollTop > 0 && input.scrollTop > 0);
+ setHasInputOverflowBottom(maxScrollTop > 0 && input.scrollTop < maxScrollTop - 1);
+ }, []);
const handleSubmit = () => {
if (!textContent.trim() || isRunning || isLoadingMessages) {
@@ -38,11 +50,12 @@ export const Composer = ({ className, placeholder = "Type your query here" }: Co
// Reset to 0 (not "auto") so scrollHeight reflects content, not container
input.style.height = "0px";
input.style.height = `${Math.max(input.scrollHeight, 24)}px`;
- }, [textContent]);
+ updateInputOverflow();
+ }, [textContent, updateInputOverflow]);
return (
<div
- className={clsx("openui-shell-thread-composer", className)}
+ className={clsx("openui-agent-thread-composer", className)}
data-drafting={textContent.length > 0 || undefined}
onClick={(e) => {
if (!(e.target as HTMLElement).closest("button, a, [role='button']")) {
@@ -50,12 +63,17 @@ export const Composer = ({ className, placeholder = "Type your query here" }: Co
}
}}
>
- <div className="openui-shell-thread-composer__input-wrapper">
+ <div
+ className="openui-agent-thread-composer__input-wrapper"
+ data-overflow-top={hasInputOverflowTop || undefined}
+ data-overflow-bottom={hasInputOverflowBottom || undefined}
+ >
<textarea
ref={inputRef}
value={textContent}
onChange={(e) => setTextContent(e.target.value)}
- className="openui-shell-thread-composer__input"
+ onScroll={updateInputOverflow}
+ className="openui-agent-thread-composer__input"
placeholder={placeholder}
rows={1}
onKeyDown={(e) => {
@@ -65,14 +83,14 @@ export const Composer = ({ className, placeholder = "Type your query here" }: Co
}
}}
/>
- <div className="openui-shell-thread-composer__action-bar">
+ <div className="openui-agent-thread-composer__action-bar">
<IconButton
onClick={isRunning ? cancelMessage : handleSubmit}
icon={isRunning ? <Square size="1em" fill="currentColor" /> : <ArrowUp size="1em" />}
size="extra-small"
variant="primary"
aria-label={isRunning ? "Cancel message" : "Send message"}
- className="openui-shell-thread-composer__submit-button"
+ className="openui-agent-thread-composer__submit-button"
/>
</div>
</div>
diff --git a/packages/react-ui/src/components/Shell/components/DesktopWelcomeComposer.tsx b/packages/react-ui/src/components/AgentInterface/components/DesktopWelcomeComposer.tsx
similarity index 89%
rename from packages/react-ui/src/components/Shell/components/DesktopWelcomeComposer.tsx
rename to packages/react-ui/src/components/AgentInterface/components/DesktopWelcomeComposer.tsx
index d97168390..1acb6f403 100644
--- a/packages/react-ui/src/components/Shell/components/DesktopWelcomeComposer.tsx
+++ b/packages/react-ui/src/components/AgentInterface/components/DesktopWelcomeComposer.tsx
@@ -45,14 +45,14 @@ export const DesktopWelcomeComposer = ({
return (
<div
- className={clsx("openui-shell-desktop-welcome-composer", className)}
+ className={clsx("openui-agent-desktop-welcome-composer", className)}
data-drafting={textContent.length > 0 || undefined}
>
<textarea
ref={inputRef}
value={textContent}
onChange={(e) => setTextContent(e.target.value)}
- className="openui-shell-desktop-welcome-composer__input"
+ className="openui-agent-desktop-welcome-composer__input"
placeholder={placeholder}
rows={1}
onKeyDown={(e) => {
@@ -62,7 +62,7 @@ export const DesktopWelcomeComposer = ({
}
}}
/>
- <div className="openui-shell-desktop-welcome-composer__action-bar">
+ <div className="openui-agent-desktop-welcome-composer__action-bar">
<IconButton
onClick={isRunning ? cancelMessage : handleSubmit}
disabled={!textContent.trim() && !isRunning}
@@ -70,7 +70,7 @@ export const DesktopWelcomeComposer = ({
icon={isRunning ? <Square size="1em" fill="currentColor" /> : <ArrowUp size="1em" />}
size="extra-small"
variant="primary"
- className="openui-shell-desktop-welcome-composer__submit-button"
+ className="openui-agent-desktop-welcome-composer__submit-button"
/>
</div>
</div>
diff --git a/packages/react-ui/src/components/AgentInterface/components/composer.scss b/packages/react-ui/src/components/AgentInterface/components/composer.scss
new file mode 100644
index 000000000..ea04348c6
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/components/composer.scss
@@ -0,0 +1,106 @@
+@use "../../../cssUtils" as cssUtils;
+
+$thread-content-inline-padding: cssUtils.$space-m-l;
+$thread-content-max-width: calc(
+ 880px + #{$thread-content-inline-padding} + #{$thread-content-inline-padding}
+);
+
+.openui-agent-thread-composer {
+ max-width: $thread-content-max-width;
+ width: 100%;
+ margin: 0 auto cssUtils.$space-l;
+ padding: 0 $thread-content-inline-padding;
+
+ .openui-agent-container--mobile & {
+ margin: 0;
+ padding: cssUtils.$space-m cssUtils.$space-m cssUtils.$space-m-l;
+ }
+
+ .openui-agent-thread-container--detailed-view-active & {
+ padding: 0 $thread-content-inline-padding;
+ }
+
+ &__input-wrapper {
+ background-color: cssUtils.$foreground;
+ border: 1px solid cssUtils.$border-interactive;
+ border-radius: cssUtils.$radius-3xl;
+ box-shadow: cssUtils.$shadow-l;
+ overflow: clip;
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-s;
+ padding: cssUtils.$space-m;
+
+ &[data-overflow-top],
+ &[data-overflow-bottom] {
+ --openui-agent-thread-composer-mask-top: 0px;
+ --openui-agent-thread-composer-mask-bottom: 0px;
+
+ .openui-agent-thread-composer__input {
+ mask-image: linear-gradient(
+ to bottom,
+ transparent 0,
+ black var(--openui-agent-thread-composer-mask-top),
+ black calc(100% - var(--openui-agent-thread-composer-mask-bottom)),
+ transparent 100%
+ );
+ -webkit-mask-image: linear-gradient(
+ to bottom,
+ transparent 0,
+ black var(--openui-agent-thread-composer-mask-top),
+ black calc(100% - var(--openui-agent-thread-composer-mask-bottom)),
+ transparent 100%
+ );
+ }
+ }
+
+ &[data-overflow-top] {
+ --openui-agent-thread-composer-mask-top: #{cssUtils.$space-xl};
+ }
+
+ &[data-overflow-bottom] {
+ --openui-agent-thread-composer-mask-bottom: #{cssUtils.$space-xl};
+ }
+ }
+
+ &__input {
+ scrollbar-width: thin;
+ scrollbar-color: cssUtils.$elevated transparent;
+
+ &::-webkit-scrollbar {
+ width: 6px;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background-color: cssUtils.$elevated;
+ border-radius: cssUtils.$radius-full;
+ }
+
+ padding: 0 cssUtils.$space-3xs;
+ resize: none;
+ max-height: 200px;
+ outline: none;
+ border: none;
+ background: transparent;
+ overflow-y: auto;
+ @include cssUtils.typography(body, default);
+ color: cssUtils.$text-neutral-primary;
+
+ &::placeholder {
+ color: cssUtils.$text-neutral-secondary;
+ }
+ }
+
+ &__action-bar {
+ display: flex;
+ align-items: center;
+ }
+
+ &__submit-button {
+ margin-left: auto;
+ }
+}
diff --git a/packages/react-ui/src/components/Shell/components/desktopWelcomeComposer.scss b/packages/react-ui/src/components/AgentInterface/components/desktopWelcomeComposer.scss
similarity index 88%
rename from packages/react-ui/src/components/Shell/components/desktopWelcomeComposer.scss
rename to packages/react-ui/src/components/AgentInterface/components/desktopWelcomeComposer.scss
index c99dd7696..cb615bb4c 100644
--- a/packages/react-ui/src/components/Shell/components/desktopWelcomeComposer.scss
+++ b/packages/react-ui/src/components/AgentInterface/components/desktopWelcomeComposer.scss
@@ -1,15 +1,15 @@
@use "../../../cssUtils" as cssUtils;
-.openui-shell-desktop-welcome-composer {
+.openui-agent-desktop-welcome-composer {
background-color: cssUtils.$foreground;
border: 1px solid cssUtils.$border-interactive;
- border-radius: cssUtils.$radius-3xl;
- box-shadow: cssUtils.$shadow-m;
+ border-radius: cssUtils.$radius-2xl;
+ box-shadow: cssUtils.$shadow-s;
overflow: clip;
display: flex;
flex-direction: column;
gap: cssUtils.$space-m;
- padding: cssUtils.$space-s-m;
+ padding: cssUtils.$space-m;
width: 100%;
max-width: 800px;
diff --git a/packages/react-ui/src/components/Shell/components/index.ts b/packages/react-ui/src/components/AgentInterface/components/index.ts
similarity index 100%
rename from packages/react-ui/src/components/Shell/components/index.ts
rename to packages/react-ui/src/components/AgentInterface/components/index.ts
diff --git a/packages/react-ui/src/components/Shell/conversationStarter.scss b/packages/react-ui/src/components/AgentInterface/conversationStarter.scss
similarity index 84%
rename from packages/react-ui/src/components/Shell/conversationStarter.scss
rename to packages/react-ui/src/components/AgentInterface/conversationStarter.scss
index f9ec548ff..915435ee8 100644
--- a/packages/react-ui/src/components/Shell/conversationStarter.scss
+++ b/packages/react-ui/src/components/AgentInterface/conversationStarter.scss
@@ -1,13 +1,11 @@
@use "../../cssUtils" as cssUtils;
-$center-align-spacing: calc(32px + cssUtils.$space-s);
-
// Container styles
-.openui-shell-conversation-starter {
+.openui-agent-conversation-starter {
width: 100%;
max-width: 880px;
margin: 0 auto;
- padding: 0 $center-align-spacing cssUtils.$space-m;
+ padding: 0 0 cssUtils.$space-m;
box-sizing: border-box;
max-height: 480px;
overflow: hidden;
@@ -19,7 +17,7 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
max-height 0.2s ease,
padding-bottom 0.2s ease;
- // Short variant - horizontal wrapping buttons
+ // Short variant - horizontal pill buttons
&--short {
display: block;
}
@@ -29,6 +27,7 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
display: flex;
flex-direction: column;
gap: cssUtils.$space-2xs;
+ margin-bottom: cssUtils.$space-m;
}
&__carousel-content {
@@ -36,19 +35,18 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
}
// Mobile adjustments
- .openui-shell-container--mobile & {
+ .openui-agent-container--mobile & {
padding: 0 cssUtils.$space-l;
}
- // Artifact active adjustments
- .openui-shell-thread-container--artifact-active & {
- padding-left: 0;
- padding-right: cssUtils.$space-m;
+ // Detailed-view active adjustments
+ .openui-agent-thread-container--detailed-view-active & {
+ padding: 0;
}
}
-// Short variant item (pill-style buttons that wrap)
-.openui-shell-conversation-starter-item-short {
+// Short variant item (pill-style buttons)
+.openui-agent-conversation-starter-item-short {
display: flex;
align-items: center;
gap: cssUtils.$space-xs;
@@ -99,7 +97,7 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
}
// Long variant item (list-style with icon and arrow)
-.openui-shell-conversation-starter-item-long {
+.openui-agent-conversation-starter-item-long {
display: flex;
align-items: center;
gap: cssUtils.$space-000;
@@ -159,7 +157,7 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
&:not(:disabled):hover {
background-color: cssUtils.$sunk;
- .openui-shell-conversation-starter-item-long__arrow {
+ .openui-agent-conversation-starter-item-long__arrow {
opacity: 1;
}
}
diff --git a/packages/react-ui/src/components/CopilotShell/dependencies.ts b/packages/react-ui/src/components/AgentInterface/dependencies.ts
similarity index 64%
rename from packages/react-ui/src/components/CopilotShell/dependencies.ts
rename to packages/react-ui/src/components/AgentInterface/dependencies.ts
index 3028df8d3..e4d19ab26 100644
--- a/packages/react-ui/src/components/CopilotShell/dependencies.ts
+++ b/packages/react-ui/src/components/AgentInterface/dependencies.ts
@@ -1,5 +1,5 @@
import buttonDeps from "../Button/dependencies";
import iconButtonDeps from "../IconButton/dependencies";
-const dependencies = ["Shell", ...iconButtonDeps, ...buttonDeps];
+const dependencies = ["AgentInterface", ...iconButtonDeps, ...buttonDeps];
export default dependencies;
diff --git a/packages/react-ui/src/components/AgentInterface/index.ts b/packages/react-ui/src/components/AgentInterface/index.ts
new file mode 100644
index 000000000..c949461ac
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/index.ts
@@ -0,0 +1,12 @@
+export { artifactListPath, artifactViewPath } from "./_shared/artifactPaths";
+export type { AgentInterfaceLabels, WorkspaceTabLabels } from "./_shared/labelsContext";
+export { useNav } from "./_shared/navContext";
+export type { NavContextValue } from "./_shared/navContext";
+export { AgentInterface } from "./AgentInterface";
+export type { AgentInterfaceComponents, AgentInterfaceProps } from "./AgentInterface";
+export { ArtifactNav } from "./ArtifactNav";
+export type { ArtifactNavProps } from "./ArtifactNav";
+export type { RouteProps } from "./Route";
+export { SidebarItem } from "./SidebarItem";
+export type { SidebarItemProps } from "./SidebarItem";
+export type { WorkspaceProps } from "./Workspace";
diff --git a/packages/react-ui/src/components/AgentInterface/mobileHeader.scss b/packages/react-ui/src/components/AgentInterface/mobileHeader.scss
new file mode 100644
index 000000000..e2aa2571d
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/mobileHeader.scss
@@ -0,0 +1,42 @@
+@use "../../cssUtils" as cssUtils;
+
+.openui-agent-mobile-header {
+ display: none;
+
+ .openui-agent-container--mobile & {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: cssUtils.$space-m;
+ padding: cssUtils.$space-l cssUtils.$space-m-l cssUtils.$space-m;
+ background-color: cssUtils.$foreground;
+ }
+}
+
+.openui-agent-mobile-header-logo-container {
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-m;
+ flex: 1;
+ min-width: 0;
+}
+
+.openui-agent-mobile-header-logo {
+ width: 32px;
+ height: 32px;
+ border-radius: cssUtils.$radius-m;
+}
+
+.openui-agent-mobile-header-agent-name {
+ @include cssUtils.typography(label, large);
+ color: cssUtils.$text-neutral-primary;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.openui-agent-mobile-header-actions {
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-s;
+}
diff --git a/packages/react-ui/src/components/Shell/resizableSeparator.scss b/packages/react-ui/src/components/AgentInterface/resizableSeparator.scss
similarity index 82%
rename from packages/react-ui/src/components/Shell/resizableSeparator.scss
rename to packages/react-ui/src/components/AgentInterface/resizableSeparator.scss
index 2688b827d..2526c1fc0 100644
--- a/packages/react-ui/src/components/Shell/resizableSeparator.scss
+++ b/packages/react-ui/src/components/AgentInterface/resizableSeparator.scss
@@ -1,6 +1,6 @@
@use "../../cssUtils" as cssUtils;
-.openui-shell-resizable-separator {
+.openui-agent-resizable-separator {
width: 1px;
background-color: cssUtils.$border-default;
cursor: col-resize;
@@ -24,7 +24,13 @@
background-color: cssUtils.$border-interactive-emphasis;
}
- &:hover &__handle {
+ &:focus-visible {
+ outline: 2px solid cssUtils.$border-interactive-emphasis;
+ outline-offset: 1px;
+ }
+
+ &:hover &__handle,
+ &:focus-visible &__handle {
opacity: 1;
}
diff --git a/packages/react-ui/src/components/AgentInterface/sidebar.scss b/packages/react-ui/src/components/AgentInterface/sidebar.scss
new file mode 100644
index 000000000..86ea7715d
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/sidebar.scss
@@ -0,0 +1,342 @@
+@use "../../cssUtils" as cssUtils;
+
+$sidebar-width: 272px;
+$sidebar-padding-y: cssUtils.$space-m-l;
+$sidebar-padding-x: cssUtils.$space-s-m;
+$sidebar-header-inline-offset: 0px;
+$sidebar-collapsed-control-size: 32px;
+$sidebar-logo-size: 30px;
+$sidebar-collapsed-width: calc(
+ #{$sidebar-collapsed-control-size} + #{$sidebar-padding-x} + #{$sidebar-padding-x} +
+ #{$sidebar-header-inline-offset}
+);
+$sidebar-mobile-width: 294px;
+$sidebar-mobile-padding-y: cssUtils.$space-l;
+$sidebar-mobile-padding-x: cssUtils.$space-000;
+$sidebar-fade-duration: 90ms;
+$sidebar-resize-duration: 160ms;
+$sidebar-mobile-slide-duration: 400ms;
+$sidebar-motion-ease: cubic-bezier(0.22, 1, 0.36, 1);
+
+.openui-agent-sidebar-container {
+ border-right: 1px solid cssUtils.$border-default;
+ height: 100%;
+ width: $sidebar-width;
+ padding: $sidebar-padding-y $sidebar-padding-x;
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-2xl;
+ background-color: cssUtils.$highlight-subtle;
+ z-index: 999;
+ transition:
+ width $sidebar-resize-duration $sidebar-motion-ease,
+ height $sidebar-resize-duration $sidebar-motion-ease,
+ transform $sidebar-resize-duration $sidebar-motion-ease,
+ background-color $sidebar-resize-duration $sidebar-motion-ease;
+
+ .openui-agent-container--mobile & {
+ width: $sidebar-mobile-width;
+ padding: $sidebar-mobile-padding-y $sidebar-mobile-padding-x;
+ position: absolute;
+ left: 0;
+ top: 0;
+ z-index: 1000;
+ background-color: cssUtils.$foreground;
+ border-radius: 0;
+ transition: left $sidebar-mobile-slide-duration $sidebar-motion-ease;
+ }
+
+ &--collapsed {
+ width: $sidebar-collapsed-width;
+ transform: translateX(0);
+ background-color: cssUtils.$foreground;
+ cursor: e-resize;
+
+ .openui-agent-container--mobile & {
+ width: $sidebar-mobile-width;
+ height: 100%;
+ left: -$sidebar-mobile-width;
+ transform: none;
+ cursor: default;
+ }
+ }
+
+ &--hidden {
+ display: none;
+ }
+
+ &[data-sidebar-visual-state="collapsing"],
+ &[data-sidebar-visual-state="expanding"] {
+ .openui-agent-sidebar-content,
+ .openui-agent-new-chat-button__label,
+ .openui-agent-sidebar-item__label,
+ .openui-agent-sidebar-item__trailing,
+ .openui-agent-sidebar-header__agent-name {
+ opacity: 0;
+ pointer-events: none;
+ }
+ }
+}
+
+.openui-agent-sidebar-header {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-s;
+
+ .openui-agent-container--mobile & {
+ padding: 0 cssUtils.$space-m-l;
+ }
+
+ &__top-row {
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-s;
+ min-height: $sidebar-collapsed-control-size;
+ transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
+
+ .openui-agent-container--mobile & {
+ gap: cssUtils.$space-m;
+ }
+ }
+
+ &__logo {
+ display: block;
+ width: $sidebar-logo-size;
+ height: $sidebar-logo-size;
+ margin-left: 1px;
+ align-self: flex-start;
+ flex-shrink: 0;
+ border-radius: cssUtils.$radius-s;
+ transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
+
+ .openui-agent-container--mobile & {
+ width: 36px;
+ height: 36px;
+ margin-left: 0;
+ border-radius: cssUtils.$radius-m;
+ }
+ }
+
+ &__agent-name {
+ @include cssUtils.typography(label, small);
+ flex-grow: 1;
+ color: cssUtils.$text-neutral-primary;
+ transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
+
+ .openui-agent-sidebar-container--collapsed & {
+ display: none;
+ }
+
+ .openui-agent-container--mobile & {
+ @include cssUtils.typography(label, large);
+ }
+ }
+
+ &--collapsed {
+ align-items: flex-start;
+
+ .openui-agent-sidebar-header__top-row {
+ display: block;
+ position: relative;
+ width: $sidebar-collapsed-control-size;
+ min-height: $sidebar-collapsed-control-size;
+ align-items: flex-start;
+ }
+
+ .openui-agent-sidebar-header__logo,
+ .openui-agent-sidebar-header__toggle-button {
+ position: absolute;
+ top: 0;
+ left: 0;
+ }
+
+ .openui-agent-sidebar-header__toggle-button {
+ opacity: 0;
+ pointer-events: none;
+ }
+ }
+}
+
+.openui-agent-sidebar-content {
+ width: calc(#{$sidebar-width} - (#{$sidebar-padding-x} * 2));
+
+ .openui-agent-container--mobile & {
+ width: 100%;
+ padding: 0 cssUtils.$space-m-l;
+ }
+
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-m;
+ overflow: hidden;
+ opacity: 1;
+ transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
+
+ &--collapsed {
+ width: 100%;
+ align-items: flex-start;
+ opacity: 0;
+ pointer-events: none;
+ }
+}
+
+.openui-agent-sidebar-separator {
+ height: 1px;
+ width: 100%;
+ background-color: cssUtils.$border-default;
+}
+
+.openui-agent-sidebar-header__toggle-button {
+ transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
+
+ .openui-agent-container--mobile & {
+ display: none;
+ }
+}
+
+.openui-agent-sidebar-container[data-sidebar-visual-state="collapsed"]:hover {
+ .openui-agent-sidebar-header__logo {
+ opacity: 0;
+ pointer-events: none;
+ }
+
+ .openui-agent-sidebar-header__toggle-button {
+ opacity: 1;
+ pointer-events: auto;
+ }
+}
+
+.openui-agent-sidebar-container__overlay {
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ background-color: cssUtils.$overlay;
+ transition: opacity $sidebar-resize-duration $sidebar-motion-ease;
+ z-index: 99;
+
+ &--collapsed {
+ opacity: 0;
+ pointer-events: none;
+ }
+}
+
+.openui-agent-sidebar-item {
+ @include cssUtils.button-reset;
+ @include cssUtils.typography(label, small);
+
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-xs;
+ width: 100%;
+ border-radius: calc(cssUtils.$radius-s + 1px);
+ color: cssUtils.$text-neutral-primary;
+ text-align: left;
+ cursor: pointer;
+ white-space: nowrap;
+ overflow: hidden;
+ padding-right: cssUtils.$space-xs;
+ transition: background-color $sidebar-fade-duration $sidebar-motion-ease;
+
+ .openui-agent-container--mobile & {
+ @include cssUtils.typography(label, default);
+
+ gap: cssUtils.$space-s-m;
+ }
+
+ &:not(:disabled):hover {
+ background-color: cssUtils.$highlight;
+ }
+
+ &--selected,
+ &--selected:not(:disabled):hover {
+ background-color: cssUtils.$sunk;
+ }
+
+ .openui-agent-sidebar-container--collapsed & {
+ width: $sidebar-collapsed-control-size;
+ gap: 0;
+ padding-right: 0;
+ background-color: transparent;
+
+ &:not(:disabled):hover {
+ background-color: transparent;
+
+ .openui-agent-sidebar-item__icon {
+ background-color: cssUtils.$highlight;
+ }
+ }
+
+ &.openui-agent-sidebar-item--selected {
+ background-color: transparent;
+
+ .openui-agent-sidebar-item__icon {
+ background-color: cssUtils.$sunk;
+ }
+ }
+
+ &.openui-agent-sidebar-item--selected:not(:disabled):hover {
+ .openui-agent-sidebar-item__icon {
+ background-color: cssUtils.$sunk;
+ }
+ }
+ }
+}
+
+.openui-agent-sidebar-item__icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: $sidebar-collapsed-control-size;
+ height: $sidebar-collapsed-control-size;
+ flex-shrink: 0;
+ border: 1px solid transparent;
+ border-radius: cssUtils.$radius-s;
+ font-size: 16px;
+ color: cssUtils.$text-neutral-primary;
+ transition:
+ background-color $sidebar-fade-duration $sidebar-motion-ease,
+ border-color $sidebar-fade-duration $sidebar-motion-ease,
+ color $sidebar-fade-duration $sidebar-motion-ease,
+ box-shadow $sidebar-fade-duration $sidebar-motion-ease;
+}
+
+.openui-agent-sidebar-item__label {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ opacity: 1;
+ transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
+
+ .openui-agent-sidebar-container--collapsed & {
+ width: 0;
+ opacity: 0;
+ }
+}
+
+.openui-agent-sidebar-item__trailing {
+ @include cssUtils.typography(number, extra-small);
+
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 16px;
+ height: 18px;
+ padding: 0 cssUtils.$space-xs;
+ flex-shrink: 0;
+ border-radius: cssUtils.$radius-xs;
+ background-color: cssUtils.$highlight-strong;
+ color: cssUtils.$text-neutral-secondary;
+ opacity: 1;
+ transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
+
+ .openui-agent-container--mobile & {
+ @include cssUtils.typography(number, small);
+ }
+
+ .openui-agent-sidebar-container--collapsed & {
+ width: 0;
+ opacity: 0;
+ }
+}
diff --git a/packages/react-ui/src/components/AgentInterface/stories/AgentInterface.stories.tsx b/packages/react-ui/src/components/AgentInterface/stories/AgentInterface.stories.tsx
new file mode 100644
index 000000000..0d528be07
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/stories/AgentInterface.stories.tsx
@@ -0,0 +1,931 @@
+import type { Message } from "@openuidev/react-headless";
+import {
+ ArrowLeft,
+ BookOpen,
+ HelpCircle,
+ MessageSquare,
+ Settings,
+ Share,
+ Sparkles,
+ Star,
+ Zap,
+} from "lucide-react";
+import { useState } from "react";
+import { makeMockLLM, makeMockStorage, mockSSEResponse } from "../../../__test-helpers/mockChat";
+import { Button } from "../../Button";
+import { IconButton } from "../../IconButton";
+import { AgentInterface } from "../AgentInterface";
+import { useNav } from "../_shared/navContext";
+import logoUrl from "./thesysdev_logo.jpeg";
+
+function getLastUserContent(messages: Message[]): string {
+ const lastUser = [...messages].reverse().find((m) => m.role === "user");
+ if (!lastUser) return "";
+ return typeof lastUser.content === "string" ? lastUser.content : "";
+}
+
+const populatedStorage = makeMockStorage({
+ listThreads: async () => {
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ return {
+ threads: [
+ { id: "1", title: "First chat", createdAt: Date.now() },
+ { id: "2", title: "Second chat", createdAt: Date.now() },
+ { id: "3", title: "Third chat", createdAt: Date.now() },
+ ],
+ };
+ },
+ getMessages: async (threadId) => {
+ if (!threadId) return [];
+ return [
+ { id: crypto.randomUUID(), role: "user", content: "Hello" },
+ {
+ id: crypto.randomUUID(),
+ role: "assistant",
+ content: "Hi! How can I help today?",
+ },
+ ] as Message[];
+ },
+});
+
+const emptyStorage = makeMockStorage({});
+
+const defaultLLM = makeMockLLM({
+ send: async () => {
+ await new Promise((r) => setTimeout(r, 100));
+ return mockSSEResponse("This is a response from the AI assistant.", 1000);
+ },
+});
+
+const echoLLM = makeMockLLM({
+ send: async ({ messages }) => {
+ const content = getLastUserContent(messages);
+ return mockSSEResponse(`You asked: "${content}"`, 1000);
+ },
+});
+
+const SAMPLE_STARTERS = [
+ {
+ displayText: "Help me get started",
+ prompt: "Help me get started",
+ icon: <Sparkles size={16} />,
+ },
+ {
+ displayText: "What can you do?",
+ prompt: "What can you do?",
+ },
+ {
+ displayText: "Tell me about your features",
+ prompt: "Tell me about your features",
+ icon: <MessageSquare size={16} />,
+ },
+];
+
+const COMPOSER_STARTERS = [
+ ...SAMPLE_STARTERS,
+ {
+ displayText: "Show me examples",
+ prompt: "Show me examples",
+ icon: <BookOpen size={16} />,
+ },
+ {
+ displayText: "What's new?",
+ prompt: "What's new?",
+ icon: <Star size={16} />,
+ },
+ {
+ displayText: "Open settings",
+ prompt: "Open settings",
+ icon: <Settings size={16} />,
+ },
+];
+
+const LONG_STARTERS = [
+ {
+ displayText: "Help me get started with this application and guide me through the features",
+ prompt: "Help me get started",
+ icon: <Sparkles size={16} />,
+ },
+ {
+ displayText: "What can you do? I'd like to know all your capabilities",
+ prompt: "What can you do?",
+ icon: <Zap size={16} />,
+ },
+];
+
+export default {
+ title: "Components/AgentInterface",
+ tags: ["dev"],
+};
+
+/** Bare default — everything renders from AgentInterface's internals. */
+export const Default = {
+ render: () => (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ />
+ ),
+};
+
+/** Override only the composer at top level — sidebar + thread defaults persist. */
+export const CustomComposer = {
+ render: () => (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ >
+ <AgentInterface.Composer>
+ <div style={{ padding: 16, background: "#f0f0f0", borderRadius: 8 }}>
+ Custom composer placeholder — replaces the default input.
+ </div>
+ </AgentInterface.Composer>
+ </AgentInterface>
+ ),
+};
+
+/** Tweak just the sidebar header — Mode B props on SidebarHeader. */
+export const CustomSidebarHeader = {
+ render: () => (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ >
+ <AgentInterface.SidebarHeader
+ logo={<div style={{ fontSize: 24 }}>🚀</div>}
+ agentName={<strong style={{ color: "#7c3aed" }}>Custom Brand</strong>}
+ collapseButton={false}
+ />
+ </AgentInterface>
+ ),
+};
+
+/** Full sidebar override — user composes the inside. */
+export const FullSidebarOverride = {
+ render: () => (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ >
+ <AgentInterface.Sidebar>
+ <AgentInterface.SidebarHeader logo={<div style={{ fontSize: 24 }}>🚀</div>} />
+ <div style={{ padding: 12, fontSize: 12, color: "#666" }}>Custom nav section</div>
+ <AgentInterface.SidebarSeparator />
+ <AgentInterface.ThreadList />
+ </AgentInterface.Sidebar>
+ </AgentInterface>
+ ),
+};
+
+/** Welcome screen with title, image, and inherited starters. */
+export const WithWelcome = {
+ render: () => (
+ <AgentInterface
+ storage={emptyStorage}
+ llm={echoLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI Assistant"
+ starters={SAMPLE_STARTERS}
+ starterVariant="long"
+ >
+ <AgentInterface.Welcome
+ title="OpenUI Assistant"
+ description="Everything you'll need, in one place"
+ image={{ url: logoUrl }}
+ />
+ </AgentInterface>
+ ),
+};
+
+/** Composer-only starters (no Welcome) — chips above the input. */
+export const ComposerStarters = {
+ render: () => (
+ <AgentInterface
+ storage={emptyStorage}
+ llm={echoLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ starters={COMPOSER_STARTERS}
+ />
+ ),
+};
+
+/** Custom thread header — Mode C children on ThreadHeader. */
+export const WithThreadHeader = {
+ render: () => (
+ <AgentInterface storage={emptyStorage} llm={echoLLM} logoUrl={logoUrl} agentName="OpenUI">
+ <AgentInterface.ThreadHeader>
+ <IconButton icon={<Share size={16} />} variant="tertiary" size="small" aria-label="Share" />
+ </AgentInterface.ThreadHeader>
+ </AgentInterface>
+ ),
+};
+
+/** Custom mobile header — Mode B props with an extra actions button. */
+export const CustomMobileHeader = {
+ render: () => (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ >
+ <AgentInterface.MobileHeader
+ actions={
+ <IconButton
+ icon={<Share size={16} />}
+ aria-label="Share"
+ size="medium"
+ variant="secondary"
+ />
+ }
+ />
+ </AgentInterface>
+ ),
+};
+
+/** Long-variant starters with welcome. */
+export const LongStarters = {
+ render: () => (
+ <AgentInterface
+ storage={emptyStorage}
+ llm={echoLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI Assistant"
+ starters={LONG_STARTERS}
+ starterVariant="long"
+ >
+ <AgentInterface.Welcome
+ title="Welcome"
+ description="Pick a starter or type your own."
+ image={{ url: logoUrl }}
+ />
+ </AgentInterface>
+ ),
+};
+
+/** Welcome Mode C — fully custom hero content (title/image/starters props ignored). */
+export const WelcomeCustomChildren = {
+ render: () => (
+ <AgentInterface
+ storage={emptyStorage}
+ llm={echoLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI Assistant"
+ >
+ <AgentInterface.Welcome>
+ <div style={{ textAlign: "center", padding: "48px 24px" }}>
+ <div
+ style={{
+ width: 96,
+ height: 96,
+ margin: "0 auto 16px",
+ borderRadius: 24,
+ background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ }}
+ >
+ <Sparkles size={48} color="white" />
+ </div>
+ <h2 style={{ margin: "0 0 8px", fontSize: 28, fontWeight: 600 }}>Fully custom hero</h2>
+ <p style={{ margin: 0, color: "rgba(0,0,0,0.5)", fontSize: 16 }}>
+ When Welcome has children, all Mode B props (title/description/image/starters) are
+ ignored.
+ </p>
+ </div>
+ </AgentInterface.Welcome>
+ </AgentInterface>
+ ),
+};
+
+/** SidebarHeader Mode C — children fully replace the header (top row gone). */
+export const SidebarHeaderCustomChildren = {
+ render: () => (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ >
+ <AgentInterface.SidebarHeader>
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ padding: "12px 16px",
+ background: "#7c3aed",
+ color: "white",
+ borderRadius: 8,
+ margin: 8,
+ }}
+ >
+ <Sparkles size={20} />
+ <strong>Branded header</strong>
+ </div>
+ </AgentInterface.SidebarHeader>
+ </AgentInterface>
+ ),
+};
+
+/** MobileHeader Mode C — replaces the whole bar. (Resize narrow to see.) */
+export const MobileHeaderCustomChildren = {
+ render: () => (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ >
+ <AgentInterface.MobileHeader>
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ padding: "8px 16px",
+ background: "#111827",
+ color: "white",
+ width: "100%",
+ fontWeight: 600,
+ }}
+ >
+ Custom mobile bar
+ </div>
+ </AgentInterface.MobileHeader>
+ </AgentInterface>
+ ),
+};
+
+/** Explicit `components` — replace AssistantMessage + UserMessage rendering. */
+export const CustomMessageComponents = {
+ render: () => (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ components={{
+ AssistantMessage: ({ message, isStreaming }) => (
+ <div
+ style={{
+ padding: 12,
+ margin: "8px 16px",
+ background: "#eef2ff",
+ borderRadius: 12,
+ borderLeft: "3px solid #4f46e5",
+ }}
+ >
+ <strong style={{ color: "#4f46e5" }}>
+ Assistant{isStreaming ? " (streaming)" : ""}
+ </strong>
+ <div style={{ marginTop: 4 }}>
+ {typeof message.content === "string" ? message.content : "[non-text content]"}
+ </div>
+ </div>
+ ),
+ UserMessage: ({ message }) => (
+ <div
+ style={{
+ padding: 12,
+ margin: "8px 16px",
+ background: "#fef3c7",
+ borderRadius: 12,
+ borderLeft: "3px solid #d97706",
+ textAlign: "right",
+ }}
+ >
+ <strong style={{ color: "#d97706" }}>You</strong>
+ <div style={{ marginTop: 4 }}>
+ {typeof message.content === "string" ? message.content : "[non-text content]"}
+ </div>
+ </div>
+ ),
+ }}
+ />
+ ),
+};
+
+/** Starters override: Welcome's own `starters` prop wins over the top-level. */
+export const StartersOverrideAtWelcome = {
+ render: () => (
+ <AgentInterface
+ storage={emptyStorage}
+ llm={echoLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI Assistant"
+ starters={[{ displayText: "Top-level starter (should NOT show)", prompt: "x" }]}
+ >
+ <AgentInterface.Welcome
+ title="Welcome"
+ description="Welcome's own starters override the top-level."
+ image={{ url: logoUrl }}
+ starters={SAMPLE_STARTERS}
+ starterVariant="long"
+ />
+ </AgentInterface>
+ ),
+};
+
+/**
+ * Hierarchical-ownership warning: top-level SidebarHeader is IGNORED when
+ * <AgentInterface.Sidebar> is also at top level. Open the console to see the
+ * dev warning. The branded header inside Sidebar is what actually renders.
+ */
+export const HierarchicalOwnershipWarning = {
+ render: () => (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ >
+ {/* This top-level SidebarHeader is ignored (dev warning logged) */}
+ <AgentInterface.SidebarHeader logo={<div>🚫 Should not render</div>} agentName="Ignored" />
+ <AgentInterface.Sidebar>
+ <AgentInterface.SidebarHeader logo={<div style={{ fontSize: 22 }}>✅</div>} />
+ <AgentInterface.SidebarSeparator />
+ <AgentInterface.ThreadList />
+ </AgentInterface.Sidebar>
+ </AgentInterface>
+ ),
+};
+
+/**
+ * SidebarItem alongside ThreadList. Custom nav items inherit the same visual
+ * language (hover, selected, padding) as ThreadList entries, so they blend
+ * naturally above or below the thread history.
+ */
+const SidebarItemsStory = () => {
+ const [section, setSection] = useState<"home" | "favorites" | "docs">("home");
+
+ return (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ >
+ <AgentInterface.Sidebar>
+ <AgentInterface.SidebarHeader />
+
+ {/* Top section: custom SidebarItems with icons + selected state */}
+ <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
+ <AgentInterface.SidebarItem
+ icon={<Sparkles size={14} />}
+ selected={section === "home"}
+ onClick={() => setSection("home")}
+ >
+ Home
+ </AgentInterface.SidebarItem>
+ <AgentInterface.SidebarItem
+ icon={<Star size={14} />}
+ selected={section === "favorites"}
+ onClick={() => setSection("favorites")}
+ trailing={3}
+ >
+ Favorites
+ </AgentInterface.SidebarItem>
+ <AgentInterface.SidebarItem
+ icon={<BookOpen size={14} />}
+ selected={section === "docs"}
+ onClick={() => setSection("docs")}
+ >
+ Docs
+ </AgentInterface.SidebarItem>
+ </div>
+
+ {/* Default ThreadList below */}
+ <AgentInterface.SidebarContent>
+ <AgentInterface.ThreadList />
+ </AgentInterface.SidebarContent>
+
+ {/* Footer items */}
+ <div
+ style={{
+ marginTop: "auto",
+ padding: "8px 0",
+ display: "flex",
+ flexDirection: "column",
+ gap: 2,
+ }}
+ >
+ <AgentInterface.SidebarItem icon={<Settings size={14} />}>
+ Settings
+ </AgentInterface.SidebarItem>
+ <AgentInterface.SidebarItem icon={<HelpCircle size={14} />}>
+ Help & feedback
+ </AgentInterface.SidebarItem>
+ </div>
+ </AgentInterface.Sidebar>
+ </AgentInterface>
+ );
+};
+
+export const SidebarItems = {
+ render: () => <SidebarItemsStory />,
+};
+
+/**
+ * Routing with `<AgentInterface.Route>` and `SidebarItem.path`. The thread
+ * region is fully replaced by the matched Route's content. Demonstrates two
+ * ways to return to the thread:
+ * 1. Explicit "Back to chat" button calling `navigate(undefined)` from
+ * inside the route page (see SettingsPage / DocsPage).
+ * 2. Implicit — clicking any thread in the sidebar's ThreadList
+ * auto-clears the path (ThreadButton calls navigate(undefined) internally).
+ */
+const BackToChatButton = () => {
+ const { navigate } = useNav();
+ return (
+ <Button
+ variant="secondary"
+ size="small"
+ iconLeft={<ArrowLeft size={14} />}
+ onClick={() => navigate(undefined)}
+ >
+ Back to chat
+ </Button>
+ );
+};
+
+const RoutePage = ({ title, body }: { title: string; body: string }) => (
+ <div
+ style={{
+ display: "flex",
+ flexDirection: "column",
+ gap: 12,
+ padding: 24,
+ height: "100%",
+ overflowY: "auto",
+ }}
+ >
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
+ <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>{title}</h1>
+ <BackToChatButton />
+ </div>
+ <p style={{ margin: 0, color: "rgba(0,0,0,0.6)" }}>{body}</p>
+ </div>
+);
+
+const RoutingStory = () => (
+ <AgentInterface storage={populatedStorage} llm={defaultLLM} logoUrl={logoUrl} agentName="OpenUI">
+ <AgentInterface.Sidebar>
+ <AgentInterface.SidebarHeader />
+
+ <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
+ <AgentInterface.SidebarItem path="/settings" icon={<Settings size={14} />}>
+ Settings
+ </AgentInterface.SidebarItem>
+ <AgentInterface.SidebarItem path="/docs" icon={<BookOpen size={14} />}>
+ Docs
+ </AgentInterface.SidebarItem>
+ <AgentInterface.SidebarItem path="/help" icon={<HelpCircle size={14} />}>
+ Help
+ </AgentInterface.SidebarItem>
+ </div>
+
+ <AgentInterface.SidebarContent>
+ <AgentInterface.ThreadList />
+ </AgentInterface.SidebarContent>
+ </AgentInterface.Sidebar>
+
+ <AgentInterface.Route path="/settings">
+ <RoutePage
+ title="Settings"
+ body="This entire thread region is replaced when the active path matches the Route. Click 'Back to chat' to call navigate(undefined), or click any thread in the sidebar to auto-clear the path."
+ />
+ </AgentInterface.Route>
+
+ <AgentInterface.Route path="/docs">
+ <RoutePage
+ title="Docs"
+ body="Routes are siblings under <AgentInterface>. Exact-string match (no wildcards). When no Route matches, the thread view re-emerges with its defaults."
+ />
+ </AgentInterface.Route>
+
+ <AgentInterface.Route path="/help">
+ <RoutePage
+ title="Help"
+ body="Multiple Routes are supported. Each is a top-level <AgentInterface.Route> with a unique path."
+ />
+ </AgentInterface.Route>
+ </AgentInterface>
+);
+
+export const Routing = {
+ render: () => <RoutingStory />,
+};
+
+/**
+ * Same routing setup but in *controlled* mode — `path` + `onNavigate` come
+ * from parent state. Useful when syncing with Next.js / React Router / your
+ * own custom router. Defaults to `/settings` so the route content shows
+ * immediately on mount.
+ */
+const ControlledRoutingStory = () => {
+ const [path, setPath] = useState<string | undefined>("/settings");
+
+ return (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ path={path}
+ onNavigate={setPath}
+ >
+ <AgentInterface.Sidebar>
+ <AgentInterface.SidebarHeader />
+
+ <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
+ <AgentInterface.SidebarItem path="/settings" icon={<Settings size={14} />}>
+ Settings
+ </AgentInterface.SidebarItem>
+ <AgentInterface.SidebarItem path="/docs" icon={<BookOpen size={14} />}>
+ Docs
+ </AgentInterface.SidebarItem>
+ </div>
+
+ <AgentInterface.SidebarContent>
+ <AgentInterface.ThreadList />
+ </AgentInterface.SidebarContent>
+
+ <div style={{ padding: 8, fontSize: 11, color: "#666" }}>
+ current path: {path === undefined ? "(thread)" : path}
+ </div>
+ </AgentInterface.Sidebar>
+
+ <AgentInterface.Route path="/settings">
+ <RoutePage title="Settings (controlled)" body="Parent owns `path` state." />
+ </AgentInterface.Route>
+
+ <AgentInterface.Route path="/docs">
+ <RoutePage title="Docs (controlled)" body="Sync with your router here." />
+ </AgentInterface.Route>
+ </AgentInterface>
+ );
+};
+
+export const ControlledRouting = {
+ render: () => <ControlledRoutingStory />,
+};
+
+/**
+ * Global artifact browser. `artifactCategories` split the sidebar nav into
+ * "Apps" + "Artifacts"; clicking one opens the searchable artifact list
+ * (reserved path `artifacts/{category}`); clicking an artifact opens the
+ * full-page view with Back + "Go to thread".
+ */
+const MOCK_ARTIFACT_TYPES = [
+ { type: "th_dashboard", titlePrefix: "Sales dashboard" },
+ { type: "th_report", titlePrefix: "Quarterly report" },
+ { type: "th_presentation", titlePrefix: "Market overview" },
+] as const;
+
+const MOCK_LONG_ARTIFACT_TITLES: Record<number, string> = {
+ 3: "Executive market overview presentation for global sales leadership",
+ 4: "Sales dashboard with regional revenue attribution and pipeline movement",
+ 8: "Quarterly report covering customer expansion, renewals, and churn signals",
+};
+
+const MOCK_ARTIFACTS = Array.from({ length: 12 }, (_, i) => {
+ const artifactType = MOCK_ARTIFACT_TYPES[i % MOCK_ARTIFACT_TYPES.length]!;
+ const title = MOCK_LONG_ARTIFACT_TITLES[i + 1] ?? `${artifactType.titlePrefix} ${i + 1}`;
+
+ return {
+ id: `artifact-${i + 1}`,
+ title,
+ type: artifactType.type,
+ threadId: String((i % 3) + 1),
+ updatedAt: new Date(Date.UTC(2026, 5, 16, 9, 30 - i * 7)).toISOString(),
+ content: {
+ heading: title,
+ body: `Stored content for artifact ${i + 1}.`,
+ },
+ };
+});
+
+const mockArtifactStorage = {
+ list: async ({ name, type }: { name?: string; type?: string[]; cursor?: string } = {}) => {
+ await new Promise((r) => setTimeout(r, 300));
+ const filtered = MOCK_ARTIFACTS.filter(
+ (a) =>
+ (!name || a.title.toLowerCase().includes(name.toLowerCase())) &&
+ (!type || type.includes(a.type)),
+ );
+ return {
+ artifacts: filtered.map(({ content: _c, ...summary }) => summary),
+ nextCursor: undefined,
+ };
+ },
+ get: async (id: string) => {
+ await new Promise((r) => setTimeout(r, 300));
+ const found = MOCK_ARTIFACTS.find((a) => a.id === id);
+ if (!found) throw new Error(`Artifact ${id} not found`);
+ return found;
+ },
+ update: async ({ id }: { id: string; content: unknown }) => {
+ const { content: _c, ...summary } = MOCK_ARTIFACTS.find((a) => a.id === id)!;
+ return summary;
+ },
+};
+
+const storedArtifactRenderer = (type: string) => ({
+ type,
+ toolName: `${type}:create`,
+ parser: ({ response }: { args: unknown; response: unknown }) => {
+ const content = response as { heading: string; body: string } | null;
+ if (!content?.heading) return null;
+ return { props: content, meta: { id: content.heading, version: 1, heading: content.heading } };
+ },
+ preview: (props: { heading: string }) => <div>{props.heading}</div>,
+ actual: (props: { heading: string; body: string }) => (
+ <div style={{ padding: 24 }}>
+ <h2 style={{ marginTop: 0 }}>{props.heading}</h2>
+ <p>{props.body}</p>
+ <p style={{ color: "rgba(0,0,0,0.4)", fontSize: 13 }}>
+ Rendered from storage via the type-matched artifact renderer.
+ </p>
+ </div>
+ ),
+});
+
+const ARTIFACT_RENDERERS = [
+ storedArtifactRenderer("th_dashboard"),
+ storedArtifactRenderer("th_report"),
+ storedArtifactRenderer("th_presentation"),
+];
+
+const ARTIFACT_CATEGORIES = [
+ { name: "Apps", filter: { type: ["th_dashboard"] } },
+ { name: "Artifacts", filter: { type: ["th_report", "th_presentation"] } },
+];
+
+export const ArtifactBrowser = {
+ render: () => (
+ <AgentInterface
+ storage={{ ...makeMockStorage(), artifact: mockArtifactStorage }}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ artifactRenderers={ARTIFACT_RENDERERS}
+ artifactCategories={ARTIFACT_CATEGORIES}
+ />
+ ),
+};
+
+/** Without categories: a single "Artifacts" sidebar item browsing everything. */
+export const ArtifactBrowserUncategorized = {
+ render: () => (
+ <AgentInterface
+ storage={{ ...makeMockStorage(), artifact: mockArtifactStorage }}
+ llm={defaultLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ artifactRenderers={ARTIFACT_RENDERERS}
+ />
+ ),
+};
+
+/**
+ * Per-thread Workspace rail. Send a message (or click the starter) — the
+ * mock LLM replies with a `dashboard:create` tool call; the matched artifact
+ * renderer registers an entry in the ThreadContext. Use the header Workspace
+ * button to open the rail, then click the entry to open its DetailedView.
+ */
+const toolCallSSE = (toolName: string, args: object, result: object): Promise<Response> => {
+ const events = [
+ { type: "TEXT_MESSAGE_CONTENT", delta: "Sure — here's your dashboard. " },
+ { type: "TOOL_CALL_START", toolCallId: "tc-1", toolCallName: toolName },
+ { type: "TOOL_CALL_ARGS", toolCallId: "tc-1", delta: JSON.stringify(args) },
+ { type: "TOOL_CALL_END", toolCallId: "tc-1" },
+ { type: "TOOL_CALL_RESULT", toolCallId: "tc-1", content: JSON.stringify(result) },
+ ];
+ const body = events.map((e) => `data: ${JSON.stringify(e)}\n\n`).join("") + "data: [DONE]\n\n";
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ const stream = new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode(body));
+ controller.close();
+ },
+ });
+ resolve(new Response(stream));
+ }, 400);
+ });
+};
+
+let dashboardCount = 0;
+
+const workspaceLLM = makeMockLLM({
+ send: async () => {
+ dashboardCount += 1;
+ const heading = `Revenue dashboard ${dashboardCount}`;
+ return toolCallSSE(
+ "dashboard:create",
+ { heading },
+ { heading, body: `Widgets and charts for ${heading}.` },
+ );
+ },
+});
+
+const dashboardRenderer = {
+ type: "th_dashboard",
+ toolName: "dashboard:create",
+ parser: ({ response }: { args: unknown; response: unknown }) => {
+ if (typeof response !== "string") return null;
+ try {
+ const content = JSON.parse(response) as { heading: string; body: string };
+ if (!content.heading) return null;
+ return {
+ props: content,
+ meta: { id: content.heading, version: 1, heading: content.heading },
+ };
+ } catch {
+ return null;
+ }
+ },
+ preview: (props: { heading: string }, controls: { open: () => void; isActive: boolean }) => (
+ <button
+ type="button"
+ onClick={controls.open}
+ style={{
+ display: "block",
+ padding: "10px 14px",
+ margin: "8px 0",
+ border: "1px solid #ddd",
+ borderRadius: 8,
+ cursor: "pointer",
+ background: controls.isActive ? "#eef2ff" : "#fff",
+ }}
+ >
+ 📊 {props.heading} — click to open
+ </button>
+ ),
+ actual: (props: { heading: string; body: string }) => (
+ <div style={{ padding: 16 }}>
+ <h3 style={{ marginTop: 0 }}>{props.heading}</h3>
+ <p>{props.body}</p>
+ </div>
+ ),
+};
+
+export const WithWorkspace = {
+ render: () => (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={workspaceLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ artifactRenderers={[dashboardRenderer]}
+ artifactCategories={ARTIFACT_CATEGORIES}
+ starters={[
+ {
+ displayText: "Create a revenue dashboard",
+ prompt: "Create a revenue dashboard",
+ icon: <Sparkles size={16} />,
+ },
+ ]}
+ />
+ ),
+};
+
+/** Workspace Mode C — children replace the rail entirely. */
+export const WorkspaceCustomChildren = {
+ render: () => (
+ <AgentInterface
+ storage={populatedStorage}
+ llm={workspaceLLM}
+ logoUrl={logoUrl}
+ agentName="OpenUI"
+ artifactRenderers={[dashboardRenderer]}
+ >
+ <AgentInterface.Workspace>
+ <div
+ style={{
+ width: 240,
+ padding: 16,
+ borderLeft: "1px solid #eee",
+ background: "#fafafa",
+ }}
+ >
+ <strong>My custom rail</strong>
+ <p style={{ fontSize: 13, color: "#666" }}>
+ Replaces the default Workspace (always visible — you own the chrome).
+ </p>
+ </div>
+ </AgentInterface.Workspace>
+ </AgentInterface>
+ ),
+};
diff --git a/packages/react-ui/src/components/BottomTray/stories/thesysdev_logo.jpeg b/packages/react-ui/src/components/AgentInterface/stories/thesysdev_logo.jpeg
similarity index 100%
rename from packages/react-ui/src/components/BottomTray/stories/thesysdev_logo.jpeg
rename to packages/react-ui/src/components/AgentInterface/stories/thesysdev_logo.jpeg
diff --git a/packages/react-ui/src/components/Shell/thread.scss b/packages/react-ui/src/components/AgentInterface/thread.scss
similarity index 57%
rename from packages/react-ui/src/components/Shell/thread.scss
rename to packages/react-ui/src/components/AgentInterface/thread.scss
index c3d7fd7f1..e00e04655 100644
--- a/packages/react-ui/src/components/Shell/thread.scss
+++ b/packages/react-ui/src/components/AgentInterface/thread.scss
@@ -4,10 +4,10 @@
// Thread Layout Structure
// =============================================================================
// The thread container uses a flexbox layout that supports both:
-// 1. Desktop: Resizable side-by-side chat and artifact panels
-// 2. Mobile: Full-width chat with absolute-positioned artifact overlay
+// 1. Desktop: Resizable side-by-side chat and detailed-view panels
+// 2. Mobile: Full-width chat with absolute-positioned detailed-view overlay
-.openui-shell-thread-container {
+.openui-agent-thread-container {
flex: 1;
overflow: hidden;
display: flex;
@@ -17,30 +17,30 @@
// Hide conversation starters and welcome-screen starters while the user is
// drafting in any composer inside the thread. The drafting flag is set on the
// composer root via `data-drafting`; nothing in JS reads it.
-.openui-shell-thread-container:has([data-drafting]),
-.openui-shell-welcome-screen:has([data-drafting]) {
- .openui-shell-conversation-starter,
- .openui-shell-welcome-screen__desktop-starters {
+.openui-agent-thread-container:has([data-drafting]),
+.openui-agent-welcome-screen:has([data-drafting]) {
+ .openui-agent-conversation-starter,
+ .openui-agent-welcome-screen__desktop-starters {
opacity: 0;
pointer-events: none;
}
}
-.openui-shell-conversation-starter,
-.openui-shell-welcome-screen__desktop-starters {
+.openui-agent-conversation-starter,
+.openui-agent-welcome-screen__desktop-starters {
transition: opacity 150ms ease;
}
-// Wrapper for horizontal layout (chat + separator + artifact)
-.openui-shell-thread-wrapper {
+// Wrapper for horizontal layout (chat + separator + detailed view)
+.openui-agent-thread-wrapper {
flex: 1;
display: flex;
overflow: hidden;
height: 100%;
}
-// Chat panel (left side on desktop, full-width when no artifact)
-.openui-shell-thread-chat-panel {
+// Chat panel (left side on desktop, full-width when no detailed view)
+.openui-agent-thread-chat-panel {
display: flex;
flex-direction: column;
overflow: hidden;
@@ -49,13 +49,18 @@
flex-shrink: 0;
position: relative;
+ .openui-agent-container--mobile & {
+ width: 100%;
+ min-width: 0;
+ }
+
&--animating {
transition: width 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}
}
-// Artifact panel (right side on desktop, fills remaining space)
-.openui-shell-thread-artifact-panel {
+// Detailed-view panel (right side on desktop, fills remaining space)
+.openui-agent-thread-detailed-view-panel {
display: flex;
flex-direction: column;
overflow: auto;
@@ -69,7 +74,7 @@
scrollbar-color: cssUtils.$highlight-strong transparent;
&::-webkit-scrollbar {
- width: cssUtils.$space-xs;
+ width: 6px;
}
&::-webkit-scrollbar-track {
@@ -110,8 +115,14 @@
// =============================================================================
$center-align-spacing: calc(32px + cssUtils.$space-s);
-
-.openui-shell-thread-scroll-container {
+$top-mask-height: calc(cssUtils.$space-l + cssUtils.$space-3xs);
+$bottom-mask-height: calc(cssUtils.$space-2xl + cssUtils.$space-2xl);
+$thread-content-inline-padding: cssUtils.$space-m-l;
+$thread-content-max-width: calc(
+ 880px + #{$thread-content-inline-padding} + #{$thread-content-inline-padding}
+);
+
+.openui-agent-thread-scroll-container {
display: flex;
width: 100%;
flex-grow: 1;
@@ -124,10 +135,10 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
top: 0;
left: 0;
right: 0;
- height: cssUtils.$space-xl;
- background: linear-gradient(to bottom, cssUtils.$background 0%, transparent 100%);
+ height: $top-mask-height;
+ background: linear-gradient(to bottom, cssUtils.$foreground 0%, transparent 100%);
pointer-events: none;
- z-index: 1;
+ z-index: 2;
}
&::after {
@@ -136,49 +147,37 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
left: 0;
right: 0;
bottom: 0;
- height: cssUtils.$space-xl;
- background: linear-gradient(to top, cssUtils.$background 0%, transparent 100%);
+ height: $bottom-mask-height;
+ background: linear-gradient(to top, cssUtils.$foreground 0%, transparent 100%);
pointer-events: none;
z-index: 1;
}
// When WelcomeScreen is present, don't grow so WelcomeScreen can take the space
- .openui-shell-thread-container:has(.openui-shell-welcome-screen) & {
+ .openui-agent-thread-container:has(.openui-agent-welcome-screen) & {
flex-grow: 0;
}
}
-.openui-shell-thread-scroll-area {
+.openui-agent-thread-scroll-area {
width: 100%;
height: 100%;
overflow: auto;
- padding: cssUtils.$space-m $center-align-spacing cssUtils.$space-xl;
- scroll-padding-top: cssUtils.$space-2xl;
- scrollbar-width: thin;
- scrollbar-color: cssUtils.$border-default transparent;
+ padding: cssUtils.$space-m 0;
+ scroll-padding-top: calc($top-mask-height + cssUtils.$space-3xs);
- &::-webkit-scrollbar {
- width: cssUtils.$space-xs;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background: cssUtils.$border-default;
- border-radius: calc(cssUtils.$radius-2xs + cssUtils.$space-3xs);
- }
-
- &::-webkit-scrollbar-thumb:hover {
- background: cssUtils.$text-neutral-secondary;
+ .openui-agent-thread-container:not(:has(.openui-agent-thread-header)):not(
+ :has(.openui-agent-welcome-screen)
+ )
+ & {
+ padding-top: cssUtils.$space-2xl;
}
scrollbar-width: thin;
scrollbar-color: cssUtils.$highlight-strong transparent;
&::-webkit-scrollbar {
- width: cssUtils.$space-xs;
+ width: 6px;
}
&::-webkit-scrollbar-track {
@@ -195,23 +194,21 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
}
// When WelcomeScreen is present, lets remove the padding temporarily
- .openui-shell-thread-container:has(.openui-shell-welcome-screen) & {
+ .openui-agent-thread-container:has(.openui-agent-welcome-screen) & {
padding: 0;
}
- .openui-shell-container--mobile & {
- padding: cssUtils.$space-l;
- scroll-padding-top: cssUtils.$space-l;
+ .openui-agent-container--mobile & {
+ padding: cssUtils.$space-l 0;
}
- // When artifact is active, reduce padding to maximize space
- .openui-shell-thread-container--artifact-active & {
- padding-left: 0;
- padding-right: cssUtils.$space-m;
+ // When detailed view is active, reduce padding to maximize space
+ .openui-agent-thread-container--detailed-view-active & {
+ padding-right: 0;
}
&--user-message-anchor {
- & .openui-shell-thread-messages > *:last-child {
+ & .openui-agent-thread-messages > *:last-child {
min-height: calc(-200px + 100dvh);
}
}
@@ -221,32 +218,33 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
// Messages
// =============================================================================
-.openui-shell-thread-messages {
- max-width: 880px;
+.openui-agent-thread-messages {
+ width: 100%;
+ max-width: $thread-content-max-width;
margin: 0 auto;
- padding-top: cssUtils.$space-l;
+ padding: 0 $thread-content-inline-padding;
display: flex;
flex-direction: column;
gap: calc(2 * cssUtils.$space-l);
+
+ .openui-agent-thread-container--detailed-view-active & {
+ padding: 0 $thread-content-inline-padding;
+ }
}
-.openui-shell-thread-message-assistant {
+.openui-agent-thread-message-assistant {
width: 100%;
display: flex;
gap: cssUtils.$space-s;
padding-right: $center-align-spacing;
overflow: hidden;
- &--without-logo {
- padding-left: $center-align-spacing;
- }
-
- .openui-shell-container--mobile & {
+ .openui-agent-container--mobile & {
padding: 0;
}
- // When artifact is active, minimize spacing and hide logo
- .openui-shell-thread-container--artifact-active & {
+ // When detailed view is active, minimize spacing.
+ .openui-agent-thread-container--detailed-view-active & {
gap: 0;
padding-right: 0;
}
@@ -261,59 +259,113 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
}
&__text {
- @include cssUtils.typography(primary, default);
+ @include cssUtils.typography(body, default);
color: cssUtils.$text-neutral-primary;
&:first-child {
margin-top: cssUtils.$space-xs;
}
}
-
- &__logo {
- width: 32px;
- height: 32px;
- border-radius: cssUtils.$radius-m;
-
- .openui-shell-container--mobile & {
- display: none;
- }
-
- .openui-shell-thread-container--artifact-active & {
- display: none;
- }
- }
}
-.openui-shell-thread-message-user {
+.openui-agent-thread-message-user {
display: flex;
justify-content: flex-end;
- padding: 0 $center-align-spacing;
+ padding: 0;
- .openui-shell-container--mobile & {
+ .openui-agent-container--mobile & {
padding: 0;
}
- .openui-shell-thread-container--artifact-active & {
+ .openui-agent-thread-container--detailed-view-active & {
padding-left: 0;
padding-right: 0;
}
&__content {
- @include cssUtils.typography(primary, default);
- padding: cssUtils.$space-s cssUtils.$space-m;
+ @include cssUtils.typography(body, default);
+ padding: cssUtils.$space-s cssUtils.$space-m calc(cssUtils.$space-s + 1px) cssUtils.$space-m;
background-color: cssUtils.$chat-user-response-bg;
color: cssUtils.$chat-user-response-text;
border-radius: cssUtils.$radius-xl;
+ white-space: pre-wrap;
overflow-wrap: break-word;
max-width: 100%;
height: fit-content;
}
+
+ // Attachments rendered inside the user bubble (images, audio/video, file chips)
+ &__image,
+ &__video {
+ display: block;
+ max-width: min(320px, 100%);
+ max-height: 320px;
+ border-radius: cssUtils.$radius-l;
+ object-fit: cover;
+ }
+
+ &__media {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-xs;
+ margin: 0;
+ }
+
+ &__audio {
+ display: block;
+ width: 280px;
+ max-width: 100%;
+ }
+
+ &__filename {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-secondary;
+ }
+
+ &__chip {
+ display: inline-flex;
+ align-items: center;
+ gap: cssUtils.$space-s;
+ padding: cssUtils.$space-xs cssUtils.$space-s;
+ border: 1px solid cssUtils.$border-default;
+ border-radius: cssUtils.$radius-m;
+ background-color: cssUtils.$background;
+
+ &--broken {
+ opacity: 0.6;
+ }
+ }
+
+ &__chip-badge {
+ @include cssUtils.typography(label, small);
+ flex-shrink: 0;
+ padding: 2px cssUtils.$space-xs;
+ border-radius: cssUtils.$radius-xs;
+ background-color: cssUtils.$chat-user-response-bg;
+ color: cssUtils.$chat-user-response-text;
+ }
+
+ &__chip-name {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-primary;
+ overflow-wrap: anywhere;
+ }
+
+ &__chip-link {
+ display: inline-flex;
+ color: inherit;
+ text-decoration: none;
+ }
}
-.openui-shell-thread-error {
+.openui-agent-thread-error {
padding: 0 $center-align-spacing;
min-height: auto !important;
- .openui-shell-container--mobile & {
+ .openui-agent-container--mobile & {
+ padding: 0;
+ }
+
+ .openui-agent-thread-container--detailed-view-active & {
padding: 0;
}
}
@@ -321,22 +373,51 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
// =============================================================================
// Thread Header
// =============================================================================
+$thread-header-action-min-height: 32px;
-.openui-shell-thread-header {
+.openui-agent-thread-header {
display: flex;
align-items: center;
- justify-content: flex-end;
- padding: cssUtils.$space-m cssUtils.$space-s cssUtils.$space-xs;
+ justify-content: space-between;
+ gap: cssUtils.$space-m;
+ padding: cssUtils.$space-m-l cssUtils.$space-m-l cssUtils.$space-xs;
flex-shrink: 0;
- .openui-shell-container--mobile & {
+ .openui-agent-container--mobile & {
+ display: none;
+ }
+
+ &__title {
+ @include cssUtils.typography(label, small);
+
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ color: cssUtils.$text-neutral-primary;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ &__actions {
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-s;
+ flex-shrink: 0;
+ min-height: $thread-header-action-min-height;
+ }
+
+ .openui-agent-thread-container--detailed-view-active &__workspace-toggle-button {
display: none;
}
}
-.openui-shell-thread-message-loading {
+.openui-agent-thread-message-loading {
display: flex;
padding: 0 $center-align-spacing;
+
+ .openui-agent-thread-container--detailed-view-active & {
+ padding: 0;
+ }
}
// =============================================================================
diff --git a/packages/react-ui/src/components/AgentInterface/threadlist.scss b/packages/react-ui/src/components/AgentInterface/threadlist.scss
new file mode 100644
index 000000000..c8308649d
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/threadlist.scss
@@ -0,0 +1,109 @@
+@use "../../cssUtils" as cssUtils;
+
+.openui-agent-thread-list {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-2xs;
+ overflow: auto;
+
+ .openui-agent-container--mobile & {
+ gap: cssUtils.$space-s;
+ }
+}
+
+.openui-agent-thread-list-group {
+ display: flex;
+ padding-left: cssUtils.$space-s-m;
+ padding-bottom: cssUtils.$space-xs;
+ color: cssUtils.$text-neutral-tertiary;
+ @include cssUtils.typography(label, small);
+
+ .openui-agent-container--mobile & {
+ @include cssUtils.typography(label, default);
+
+ padding-left: cssUtils.$space-xs;
+ }
+}
+
+.openui-agent-thread-button {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ width: 100%;
+ border-radius: calc(cssUtils.$radius-s + 1px);
+
+ &--selected {
+ background-color: cssUtils.$sunk;
+ }
+
+ &--actions-open {
+ background-color: cssUtils.$highlight-subtle;
+ }
+
+ &:hover {
+ background-color: cssUtils.$highlight-subtle;
+
+ .openui-agent-thread-button-dropdown-trigger {
+ opacity: 1;
+ }
+ }
+
+ &--selected:hover {
+ background-color: cssUtils.$sunk;
+ }
+
+ &--selected.openui-agent-thread-button--actions-open {
+ background-color: cssUtils.$sunk;
+ }
+}
+
+.openui-agent-thread-button-title {
+ @include cssUtils.button-reset;
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-primary;
+ padding: calc(cssUtils.$space-s - 0.75px) cssUtils.$space-s-m;
+ width: 100%;
+ text-align: left;
+ cursor: pointer;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ overflow: hidden;
+
+ .openui-agent-container--mobile & {
+ @include cssUtils.typography(label, default);
+
+ padding: cssUtils.$space-s-m;
+ }
+}
+
+.openui-agent-thread-button-dropdown-trigger {
+ margin-right: cssUtils.$space-2xs;
+ opacity: 0;
+
+ .openui-agent-container--mobile & {
+ opacity: 1;
+ }
+
+ &[data-state="open"] {
+ opacity: 1;
+ background-color: cssUtils.$highlight;
+ border-color: cssUtils.$border-interactive;
+ }
+}
+
+.openui-agent-thread-button-dropdown-menu {
+ display: flex;
+ flex-direction: column;
+ min-width: 180px;
+ padding: cssUtils.$space-xs;
+ border: 1px solid cssUtils.$border-default;
+ border-radius: cssUtils.$radius-l;
+ background-color: cssUtils.$foreground;
+ transform: translateX(-4px);
+ z-index: 9999;
+}
+
+.openui-agent-thread-button-dropdown-menu-item {
+ outline: none;
+ width: 100%;
+}
diff --git a/packages/react-ui/src/components/AgentInterface/useDetailedViewResize.ts b/packages/react-ui/src/components/AgentInterface/useDetailedViewResize.ts
new file mode 100644
index 000000000..ade9a3c84
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/useDetailedViewResize.ts
@@ -0,0 +1,142 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+
+interface UseDetailedViewResizeProps {
+ isDetailedViewActive: boolean;
+ isMobile: boolean;
+ setIsSidebarOpen: (isOpen: boolean) => void;
+}
+
+/** Chat-panel width as percentages of the container, for the resize separator's ARIA. */
+export interface ResizeAriaValues {
+ now: number;
+ min: number;
+ max: number;
+}
+
+interface UseDetailedViewResizeReturn {
+ containerRef: React.RefObject<HTMLDivElement | null>;
+ chatPanelRef: React.RefObject<HTMLDivElement | null>;
+ detailedViewPanelRef: React.RefObject<HTMLDivElement | null>;
+ isDragging: boolean;
+ handleResize: (clientX: number) => void;
+ /** Resize by a relative px delta (keyboard). Pass ±Infinity to snap to min/max. */
+ handleResizeStep: (deltaPx: number) => void;
+ handleDragStart: () => void;
+ handleDragEnd: () => void;
+ getResizeAria: () => ResizeAriaValues | null;
+}
+
+const INITIAL_CHAT_WIDTH = 420;
+const MIN_CHAT_WIDTH = 420;
+const MAX_CHAT_WIDTH_RATIO = 0.8;
+
+/**
+ * Custom hook to manage detailed-view panel resizing logic (desktop only).
+ * Handles:
+ * - Chat panel width constraints
+ * - Resize drag events
+ * - Sidebar state when detailed view is active/inactive
+ */
+export const useDetailedViewResize = ({
+ isDetailedViewActive,
+ isMobile,
+ setIsSidebarOpen,
+}: UseDetailedViewResizeProps): UseDetailedViewResizeReturn => {
+ const [isDragging, setIsDragging] = useState(false);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const chatPanelRef = useRef<HTMLDivElement>(null);
+ const detailedViewPanelRef = useRef<HTMLDivElement>(null);
+ // Current chat-panel width in px. Kept in sync with style.width so keyboard
+ // steps and ARIA can read it without measuring (which would be wrong mid-transition).
+ const widthRef = useRef<number>(INITIAL_CHAT_WIDTH);
+
+ // Handle sidebar visibility and panel widths when detailed-view state changes
+ useEffect(() => {
+ if (isMobile) return;
+
+ if (isDetailedViewActive) {
+ // Desktop view active: close sidebar and set chat width to 420px
+ setIsSidebarOpen(false);
+ if (chatPanelRef.current) {
+ chatPanelRef.current.style.width = `${INITIAL_CHAT_WIDTH}px`;
+ }
+ widthRef.current = INITIAL_CHAT_WIDTH;
+ } else {
+ // Desktop view inactive: open sidebar and reset chat width
+ setIsSidebarOpen(true);
+ if (chatPanelRef.current) {
+ chatPanelRef.current.style.width = "100%";
+ }
+ // Reset so the next time the separator mounts it reads the initial width
+ // (its mount-time ARIA sync runs before this effect re-sets it on reopen).
+ widthRef.current = INITIAL_CHAT_WIDTH;
+ }
+ }, [isDetailedViewActive, isMobile, setIsSidebarOpen]);
+
+ const setChatWidth = useCallback((width: number) => {
+ if (!chatPanelRef.current) return;
+ chatPanelRef.current.style.width = `${width}px`;
+ widthRef.current = width;
+ }, []);
+
+ const handleResize = useCallback(
+ (clientX: number) => {
+ if (!containerRef.current) return;
+
+ const containerRect = containerRef.current.getBoundingClientRect();
+ // Guard against a zero-width container (hidden / not yet laid out):
+ // otherwise maxWidthPx is 0 and the clamp collapses the panel to 0px.
+ if (containerRect.width <= 0) return;
+ const newWidthPx = clientX - containerRect.left;
+
+ // Constrain width between min and max
+ const maxWidthPx = containerRect.width * MAX_CHAT_WIDTH_RATIO;
+ setChatWidth(Math.min(Math.max(newWidthPx, MIN_CHAT_WIDTH), maxWidthPx));
+ },
+ [setChatWidth],
+ );
+
+ // Keyboard resize: nudge by a relative delta. ±Infinity snaps to min/max.
+ const handleResizeStep = useCallback(
+ (deltaPx: number) => {
+ if (!containerRef.current) return;
+
+ const containerWidth = containerRef.current.getBoundingClientRect().width;
+ if (containerWidth <= 0) return;
+ const maxWidthPx = containerWidth * MAX_CHAT_WIDTH_RATIO;
+ setChatWidth(Math.min(Math.max(widthRef.current + deltaPx, MIN_CHAT_WIDTH), maxWidthPx));
+ },
+ [setChatWidth],
+ );
+
+ const getResizeAria = useCallback((): ResizeAriaValues | null => {
+ if (!containerRef.current) return null;
+ const containerWidth = containerRef.current.getBoundingClientRect().width;
+ if (containerWidth <= 0) return null;
+ return {
+ now: Math.round((widthRef.current / containerWidth) * 100),
+ min: Math.round((MIN_CHAT_WIDTH / containerWidth) * 100),
+ max: Math.round(MAX_CHAT_WIDTH_RATIO * 100),
+ };
+ }, []);
+
+ const handleDragStart = useCallback(() => {
+ setIsDragging(true);
+ }, []);
+
+ const handleDragEnd = useCallback(() => {
+ setIsDragging(false);
+ }, []);
+
+ return {
+ containerRef,
+ chatPanelRef,
+ detailedViewPanelRef,
+ isDragging,
+ handleResize,
+ handleResizeStep,
+ handleDragStart,
+ handleDragEnd,
+ getResizeAria,
+ };
+};
diff --git a/packages/react-ui/src/components/Shell/welcomeScreen.scss b/packages/react-ui/src/components/AgentInterface/welcomeScreen.scss
similarity index 72%
rename from packages/react-ui/src/components/Shell/welcomeScreen.scss
rename to packages/react-ui/src/components/AgentInterface/welcomeScreen.scss
index 1a85a1bac..41a317340 100644
--- a/packages/react-ui/src/components/Shell/welcomeScreen.scss
+++ b/packages/react-ui/src/components/AgentInterface/welcomeScreen.scss
@@ -2,7 +2,7 @@
$center-align-spacing: calc(32px + cssUtils.$space-s);
-.openui-shell-welcome-screen {
+.openui-agent-welcome-screen {
display: flex;
flex-direction: column;
gap: cssUtils.$space-l;
@@ -13,15 +13,15 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
height: 100%;
max-width: 880px;
margin: 0 auto;
- padding: cssUtils.$space-2xl $center-align-spacing;
+ padding: cssUtils.$space-m $center-align-spacing cssUtils.$space-2xl;
// Mobile adjustments
- .openui-shell-container--mobile & {
- padding: cssUtils.$space-2xl cssUtils.$space-l;
+ .openui-agent-container--mobile & {
+ padding: cssUtils.$space-l;
}
- // Artifact active adjustments
- .openui-shell-thread-container--artifact-active & {
+ // Detailed-view active adjustments
+ .openui-agent-thread-container--detailed-view-active & {
padding-left: 0;
padding-right: cssUtils.$space-m;
}
@@ -55,7 +55,7 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
display: flex;
flex-direction: column;
align-items: center;
- gap: cssUtils.$space-s;
+ gap: cssUtils.$space-m;
text-align: center;
}
@@ -64,14 +64,16 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
@include cssUtils.typography(heading, medium);
color: cssUtils.$text-neutral-primary;
margin: 0;
+ font-weight: 500;
}
// Description text
&__description {
- @include cssUtils.typography(body, small);
+ @include cssUtils.typography(heading, medium);
color: cssUtils.$text-neutral-secondary;
margin: 0;
- max-width: 400px;
+ max-width: 800px;
+ font-weight: 500;
}
&__composer-starters-container {
@@ -88,7 +90,7 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
width: 100%;
// Hide on mobile - keep the regular Composer on mobile
- .openui-shell-container--mobile & {
+ .openui-agent-container--mobile & {
display: none;
}
}
@@ -104,17 +106,17 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
transform 0.2s ease;
// Hide on mobile - keep the external ConversationStarter on mobile
- .openui-shell-container--mobile & {
+ .openui-agent-container--mobile & {
display: none;
}
// Reset padding since welcome screen already has padding
- .openui-shell-conversation-starter {
+ .openui-agent-conversation-starter {
padding: 0;
}
// Center align short variant buttons
- .openui-shell-conversation-starter--short {
+ .openui-agent-conversation-starter--short {
justify-content: center;
}
}
@@ -125,7 +127,7 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
gap: cssUtils.$space-2xl;
// On mobile, use normal gap
- .openui-shell-container--mobile & {
+ .openui-agent-container--mobile & {
gap: cssUtils.$space-l;
}
}
@@ -133,30 +135,30 @@ $center-align-spacing: calc(32px + cssUtils.$space-s);
// Hide the regular Composer when welcome screen with desktop composer is present (desktop only)
// This uses CSS :has() to detect the welcome screen and hide the default composer
-.openui-shell-thread-container:has(.openui-shell-welcome-screen--with-composer) {
- .openui-shell-thread-composer {
+.openui-agent-thread-container:has(.openui-agent-welcome-screen--with-composer) {
+ .openui-agent-thread-composer {
display: none;
}
// But show it on mobile
- .openui-shell-container--mobile & .openui-shell-thread-composer {
+ .openui-agent-container--mobile & .openui-agent-thread-composer {
display: block;
}
}
// Alternative approach using parent mobile class for better specificity
-.openui-shell-container:not(.openui-shell-container--mobile) {
- .openui-shell-thread-container:has(.openui-shell-welcome-screen--with-composer) {
- .openui-shell-thread-composer {
+.openui-agent-container:not(.openui-agent-container--mobile) {
+ .openui-agent-thread-container:has(.openui-agent-welcome-screen--with-composer) {
+ .openui-agent-thread-composer {
display: none;
}
}
// Hide the external ConversationStarter when desktop starters exist
// Use :not() to exclude the one inside the welcome screen
- .openui-shell-thread-container:has(.openui-shell-welcome-screen__desktop-starters) {
- .openui-shell-conversation-starter:not(
- .openui-shell-welcome-screen__desktop-starters .openui-shell-conversation-starter
+ .openui-agent-thread-container:has(.openui-agent-welcome-screen__desktop-starters) {
+ .openui-agent-conversation-starter:not(
+ .openui-agent-welcome-screen__desktop-starters .openui-agent-conversation-starter
) {
display: none;
}
diff --git a/packages/react-ui/src/components/AgentInterface/workspaceSidebar.scss b/packages/react-ui/src/components/AgentInterface/workspaceSidebar.scss
new file mode 100644
index 000000000..adab4993e
--- /dev/null
+++ b/packages/react-ui/src/components/AgentInterface/workspaceSidebar.scss
@@ -0,0 +1,269 @@
+@use "../../cssUtils" as cssUtils;
+
+$workspace-sidebar-width: 280px;
+$workspace-sidebar-mobile-width: 294px;
+$workspace-sidebar-padding: cssUtils.$space-m;
+$workspace-sidebar-mobile-slide-duration: 400ms;
+$workspace-sidebar-motion-ease: cubic-bezier(0.22, 1, 0.36, 1);
+
+.openui-agent-workspace-sidebar {
+ border-left: 1px solid cssUtils.$border-default;
+ height: 100%;
+ width: $workspace-sidebar-width;
+ flex-shrink: 0;
+ padding: $workspace-sidebar-padding;
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-m;
+ background-color: cssUtils.$foreground;
+ overflow: hidden;
+ transition:
+ width 300ms cubic-bezier(0.22, 1, 0.36, 1),
+ padding 300ms cubic-bezier(0.22, 1, 0.36, 1),
+ border-color 300ms cubic-bezier(0.22, 1, 0.36, 1),
+ transform $workspace-sidebar-mobile-slide-duration $workspace-sidebar-motion-ease;
+
+ .openui-agent-container--mobile & {
+ position: absolute;
+ top: 0;
+ right: 0;
+ z-index: 1000;
+ height: 100%;
+ width: $workspace-sidebar-mobile-width;
+ padding-top: cssUtils.$space-m-l;
+ transform: translateX(0);
+ }
+
+ &--collapsed {
+ width: 0;
+ padding: 0;
+ border-left: 0;
+ transition:
+ width 300ms cubic-bezier(0.22, 1, 0.36, 1) 140ms,
+ padding 300ms cubic-bezier(0.22, 1, 0.36, 1) 140ms,
+ border-color 300ms cubic-bezier(0.22, 1, 0.36, 1) 140ms;
+
+ .openui-agent-container--mobile & {
+ width: $workspace-sidebar-mobile-width;
+ padding: cssUtils.$space-m-l $workspace-sidebar-padding $workspace-sidebar-padding;
+ border-left: 1px solid cssUtils.$border-default;
+ transform: translateX(100%);
+ }
+ }
+
+ &__header {
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-s;
+ flex-shrink: 0;
+ opacity: 1;
+ transition: opacity 160ms ease-out 220ms;
+
+ .openui-agent-workspace-sidebar--collapsed & {
+ opacity: 0;
+ transition: opacity 120ms ease-out;
+ }
+ }
+
+ &__tabs {
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-3xs;
+ flex: 1;
+ min-width: 0;
+ height: 40px;
+ opacity: 1;
+ transition: opacity 160ms ease-out 220ms;
+
+ .openui-agent-workspace-sidebar--collapsed & {
+ opacity: 0;
+ transition: opacity 120ms ease-out;
+ }
+ }
+
+ &__tab-indicator {
+ position: absolute;
+ top: 0;
+ left: 0;
+ border-radius: cssUtils.$radius-s;
+ background-color: cssUtils.$highlight;
+ pointer-events: none;
+ transition:
+ transform 180ms cubic-bezier(0.22, 1, 0.36, 1),
+ width 180ms cubic-bezier(0.22, 1, 0.36, 1),
+ height 180ms cubic-bezier(0.22, 1, 0.36, 1),
+ opacity 120ms ease;
+
+ .openui-agent-workspace-sidebar--collapsed & {
+ opacity: 0 !important;
+ transition: opacity 120ms ease-out;
+ }
+ }
+
+ &__tab {
+ @include cssUtils.button-reset;
+ @include cssUtils.typography(label, small);
+
+ position: relative;
+ height: 32px;
+ z-index: 1;
+ flex: 0 0 auto;
+ padding: cssUtils.$space-xs cssUtils.$space-s-m;
+ border-radius: cssUtils.$radius-m;
+ color: cssUtils.$text-neutral-secondary;
+ cursor: pointer;
+
+ .openui-agent-container--mobile & {
+ @include cssUtils.typography(label, default);
+ border-radius: cssUtils.$radius-l;
+ }
+
+ &:hover {
+ color: cssUtils.$text-neutral-primary;
+ }
+
+ &--active {
+ color: cssUtils.$text-neutral-primary;
+ }
+ }
+
+ &__content {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-l;
+ overflow-y: auto;
+ overflow-x: hidden;
+ flex: 1;
+ min-height: 0;
+ opacity: 1;
+ transition: opacity 180ms ease-out 220ms;
+
+ scrollbar-width: thin;
+ scrollbar-color: cssUtils.$highlight-strong transparent;
+
+ &::-webkit-scrollbar {
+ width: 6px;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background-color: cssUtils.$highlight-strong;
+ border-radius: cssUtils.$radius-full;
+ }
+
+ .openui-agent-workspace-sidebar--collapsed & {
+ opacity: 0;
+ transition: opacity 120ms ease-out;
+ }
+ }
+
+ &__empty {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-tertiary;
+ padding: cssUtils.$space-s cssUtils.$space-2xs;
+ }
+
+ &__section-empty {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-tertiary;
+ padding: cssUtils.$space-2xs;
+ font-style: italic;
+ }
+
+ &__list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-xs;
+ }
+
+ &__item {
+ @include cssUtils.button-reset;
+
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: cssUtils.$space-m;
+ padding: cssUtils.$space-s cssUtils.$space-s;
+ border-radius: cssUtils.$radius-xl;
+ color: cssUtils.$text-neutral-primary;
+ cursor: pointer;
+ transition: background-color 0.15s ease;
+ text-align: left;
+
+ &:hover {
+ background-color: cssUtils.$highlight;
+ }
+
+ &:active {
+ background-color: cssUtils.$highlight;
+ }
+
+ &--active {
+ background-color: cssUtils.$highlight;
+ }
+ }
+
+ &__item-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ font-size: 20px;
+ color: cssUtils.$text-neutral-secondary;
+
+ .openui-agent-workspace-sidebar__item--active & {
+ color: cssUtils.$text-accent-primary;
+ }
+ }
+
+ &__item-label {
+ @include cssUtils.typography(label, default);
+
+ width: 100%;
+ min-width: 0;
+ overflow-wrap: anywhere;
+ }
+
+ &__item-body {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ gap: cssUtils.$space-xs;
+ width: 100%;
+ min-width: 0;
+ padding-left: cssUtils.$space-2xs;
+ padding-bottom: cssUtils.$space-2xs;
+ overflow: hidden;
+ }
+
+ &__item-meta {
+ @include cssUtils.typography(label, small);
+
+ width: 100%;
+ min-width: 0;
+ overflow: hidden;
+ color: cssUtils.$text-neutral-secondary;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+}
+
+.openui-agent-workspace-sidebar__overlay {
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ background-color: cssUtils.$overlay;
+ transition: opacity $workspace-sidebar-mobile-slide-duration $workspace-sidebar-motion-ease;
+ z-index: 99;
+
+ &--collapsed {
+ opacity: 0;
+ pointer-events: none;
+ }
+}
diff --git a/packages/react-ui/src/components/BottomTray/Container.tsx b/packages/react-ui/src/components/BottomTray/Container.tsx
deleted file mode 100644
index 2226ca54a..000000000
--- a/packages/react-ui/src/components/BottomTray/Container.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import clsx from "clsx";
-import { LayoutContextProvider } from "../../context/LayoutContext";
-import { ShellStoreProvider } from "../_shared/store";
-
-interface ContainerProps {
- children?: React.ReactNode;
- logoUrl: string;
- agentName: string;
- className?: string;
- showAssistantLogo?: boolean;
- /** Control the open state of the tray */
- isOpen?: boolean;
-}
-
-export const Container = ({
- children,
- logoUrl,
- agentName,
- className,
- showAssistantLogo = false,
- isOpen = false,
-}: ContainerProps) => {
- return (
- <ShellStoreProvider
- logoUrl={logoUrl}
- agentName={agentName}
- showAssistantLogo={showAssistantLogo}
- >
- <LayoutContextProvider layout="tray">
- <div
- className={clsx(
- "openui-bottom-tray-container",
- {
- "openui-bottom-tray-container--open": isOpen,
- "openui-bottom-tray-container--closed": !isOpen,
- },
- className,
- )}
- >
- {children}
- </div>
- </LayoutContextProvider>
- </ShellStoreProvider>
- );
-};
diff --git a/packages/react-ui/src/components/BottomTray/ConversationStarter.tsx b/packages/react-ui/src/components/BottomTray/ConversationStarter.tsx
deleted file mode 100644
index a82d262f0..000000000
--- a/packages/react-ui/src/components/BottomTray/ConversationStarter.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-import { useThread } from "@openuidev/react-headless";
-import clsx from "clsx";
-import { ArrowUp, Lightbulb } from "lucide-react";
-import { Fragment, ReactNode, isValidElement } from "react";
-import { ConversationStarterIcon, ConversationStarterProps } from "../../types/ConversationStarter";
-import { Carousel, CarouselContent } from "../Carousel";
-import { isChatEmpty } from "../_shared/utils";
-
-export type ConversationStarterVariant = "short" | "long";
-
-interface ConversationStarterItemProps extends ConversationStarterProps {
- onClick: (prompt: string) => void;
- variant: ConversationStarterVariant;
-}
-
-/**
- * Renders the appropriate icon based on the icon prop value
- * - undefined: Show default lightbulb icon
- * - ReactNode: Show the provided icon (use <></> or React.Fragment for no icon)
- */
-const renderIcon = (icon: ConversationStarterIcon | undefined): ReactNode => {
- if (icon === undefined) {
- return <Lightbulb size={16} />;
- }
- return icon;
-};
-
-const hasRenderableIcon = (icon: ReactNode): boolean => {
- if (icon === null || icon === undefined || icon === false) {
- return false;
- }
-
- if (isValidElement<{ children?: ReactNode }>(icon) && icon.type === Fragment) {
- return Boolean(icon.props.children);
- }
-
- return true;
-};
-
-const ConversationStarterItem = ({
- displayText,
- prompt,
- onClick,
- variant,
- icon,
-}: ConversationStarterItemProps) => {
- const renderedIcon = renderIcon(icon);
- const shouldRenderIcon = hasRenderableIcon(renderedIcon);
-
- if (variant === "short") {
- return (
- <button
- type="button"
- className="openui-bottom-tray-conversation-starter-item-short"
- onClick={() => onClick(prompt)}
- >
- {shouldRenderIcon && (
- <span className="openui-bottom-tray-conversation-starter-item-short__icon">
- {renderedIcon}
- </span>
- )}
- <span className="openui-bottom-tray-conversation-starter-item-short__text">
- {displayText}
- </span>
- </button>
- );
- }
-
- // Long variant (detailed list style)
- return (
- <button
- type="button"
- className="openui-bottom-tray-conversation-starter-item-long"
- onClick={() => onClick(prompt)}
- >
- <div className="openui-bottom-tray-conversation-starter-item-long__content">
- {shouldRenderIcon && (
- <span className="openui-bottom-tray-conversation-starter-item-long__icon">
- {renderedIcon}
- </span>
- )}
- <span className="openui-bottom-tray-conversation-starter-item-long__text">
- {displayText}
- </span>
- </div>
- <span className="openui-bottom-tray-conversation-starter-item-long__arrow">
- <ArrowUp size={16} />
- </span>
- </button>
- );
-};
-
-export interface ConversationStarterContainerProps {
- starters: ConversationStarterProps[];
- className?: string;
- /**
- * Variant of the conversation starter
- * - "short": Pill-style horizontal buttons (default)
- * - "long": List items with icons and hover arrow
- */
- variant?: ConversationStarterVariant;
-}
-
-export const ConversationStarter = ({
- starters,
- className,
- variant = "short",
-}: ConversationStarterContainerProps) => {
- const processMessage = useThread((s) => s.processMessage);
- const isRunning = useThread((s) => s.isRunning);
- const messages = useThread((s) => s.messages);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- const handleClick = (prompt: string) => {
- if (isRunning) return;
- processMessage({
- role: "user",
- content: prompt,
- });
- };
-
- // Only show when there are no messages
- if (!isChatEmpty({ isLoadingMessages, messages })) {
- return null;
- }
-
- if (starters.length === 0) {
- return null;
- }
-
- if (variant === "short") {
- return (
- <Carousel
- showButtons={false}
- className={clsx(
- "openui-bottom-tray-conversation-starter",
- "openui-bottom-tray-conversation-starter--short",
- className,
- )}
- >
- <CarouselContent className="openui-bottom-tray-conversation-starter__carousel-content">
- {starters.map((item, index) => (
- <ConversationStarterItem
- key={`${item.displayText}-${index}`}
- displayText={item.displayText}
- prompt={item.prompt}
- icon={item.icon}
- onClick={handleClick}
- variant={variant}
- />
- ))}
- </CarouselContent>
- </Carousel>
- );
- }
-
- return (
- <div
- className={clsx(
- "openui-bottom-tray-conversation-starter",
- `openui-bottom-tray-conversation-starter--${variant}`,
- className,
- )}
- >
- {starters.map((item, index) => (
- <Fragment key={`${item.displayText}-${index}`}>
- <ConversationStarterItem
- displayText={item.displayText}
- prompt={item.prompt}
- icon={item.icon}
- onClick={handleClick}
- variant={variant}
- />
- </Fragment>
- ))}
- </div>
- );
-};
-
-export default ConversationStarter;
diff --git a/packages/react-ui/src/components/BottomTray/Header.tsx b/packages/react-ui/src/components/BottomTray/Header.tsx
deleted file mode 100644
index 55b71561a..000000000
--- a/packages/react-ui/src/components/BottomTray/Header.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import { useThreadList } from "@openuidev/react-headless";
-import clsx from "clsx";
-import { SquarePen, X } from "lucide-react";
-import { ReactNode } from "react";
-import { IconButton } from "../IconButton";
-import { useShellStore } from "../_shared/store";
-import { ThreadListContainer } from "./ThreadListContainer";
-
-export const BottomTrayNewChatButton = () => {
- const switchToNewThread = useThreadList((s) => s.switchToNewThread);
-
- return (
- <IconButton
- icon={<SquarePen size="1em" />}
- onClick={switchToNewThread}
- variant="tertiary"
- aria-label="New chat"
- className="openui-bottom-tray-header-new-chat-button"
- />
- );
-};
-
-interface HeaderProps {
- className?: string;
- /** Custom content to render on the rightmost side of the logo container */
- rightChildren?: ReactNode;
- /** Callback when minimize button is clicked */
- onMinimize?: () => void;
- /** Hide the minimize button */
- hideMinimizeButton?: boolean;
- /** Custom new chat button */
- hideNewChatButton?: boolean;
- /** Hide the thread list container */
- hideThreadListContainer?: boolean;
-}
-
-export const Header = ({
- className,
- rightChildren,
- onMinimize,
- hideMinimizeButton = false,
- hideNewChatButton = false,
- hideThreadListContainer = false,
-}: HeaderProps) => {
- const { logoUrl, agentName } = useShellStore((state) => ({
- logoUrl: state.logoUrl,
- agentName: state.agentName,
- }));
-
- return (
- <div className={clsx("openui-bottom-tray-header", className)}>
- <div className="openui-bottom-tray-header-logo-container">
- <img className="openui-bottom-tray-header-logo" src={logoUrl} alt="Logo" />
- <span className="openui-bottom-tray-header-agent-name">{agentName}</span>
- </div>
- <div className="openui-bottom-tray-header-actions">
- {rightChildren}
- {!hideThreadListContainer && <ThreadListContainer />}
- {!hideNewChatButton && <BottomTrayNewChatButton />}
- {!hideMinimizeButton && onMinimize && (
- <IconButton
- icon={<X size="1em" />}
- onClick={onMinimize}
- variant="tertiary"
- aria-label="Minimize chat"
- className="openui-bottom-tray-header-minimize"
- />
- )}
- </div>
- </div>
- );
-};
diff --git a/packages/react-ui/src/components/BottomTray/Thread.tsx b/packages/react-ui/src/components/BottomTray/Thread.tsx
deleted file mode 100644
index 0a9578d13..000000000
--- a/packages/react-ui/src/components/BottomTray/Thread.tsx
+++ /dev/null
@@ -1,274 +0,0 @@
-import type { AssistantMessage, Message, ToolMessage } from "@openuidev/react-headless";
-import { MessageProvider, useThread } from "@openuidev/react-headless";
-import clsx from "clsx";
-import React, { memo, useRef } from "react";
-import { ScrollVariant, useScrollToBottom } from "../../hooks/useScrollToBottom";
-import { ArtifactOverlay } from "../_shared/artifact";
-import type { AssistantMessageComponent, UserMessageComponent } from "../_shared/types";
-import { MarkDownRenderer } from "../MarkDownRenderer";
-import { MessageLoading as MessageLoadingComponent } from "../MessageLoading";
-import { ToolCallComponent } from "../ToolCall";
-import { ToolResult } from "../ToolResult";
-
-export const ThreadContainer = ({
- children,
- className,
-}: {
- children?: React.ReactNode;
- className?: string;
-}) => {
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- return (
- <div
- className={clsx("openui-bottom-tray-thread-container", className)}
- style={{
- visibility: isLoadingMessages ? "hidden" : undefined,
- }}
- >
- {children}
- <ArtifactOverlay />
- </div>
- );
-};
-
-export const ScrollArea = ({
- children,
- className,
- scrollVariant = "user-message-anchor",
- userMessageSelector = ".openui-bottom-tray-thread-message-user",
-}: {
- children?: React.ReactNode;
- className?: string;
- /**
- * Scroll to bottom once the last message is added
- */
- scrollVariant?: ScrollVariant;
- /**
- * Selector for the user message
- */
- userMessageSelector?: string;
-}) => {
- const ref = useRef<HTMLDivElement>(null);
-
- const messages = useThread((s) => s.messages);
- const isRunning = useThread((s) => s.isRunning);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- useScrollToBottom({
- ref,
- lastMessage: messages[messages.length - 1] || { id: "" },
- scrollVariant,
- userMessageSelector,
- isRunning,
- isLoadingMessages,
- });
-
- return (
- <div className="openui-bottom-tray-thread-scroll-container">
- <div
- ref={ref}
- className={clsx(
- "openui-bottom-tray-thread-scroll-area",
- {
- "openui-bottom-tray-thread-scroll-area--user-message-anchor":
- scrollVariant === "user-message-anchor",
- },
- className,
- )}
- >
- {children}
- </div>
- </div>
- );
-};
-
-export const AssistantMessageContainer = ({
- children,
- className,
-}: {
- children?: React.ReactNode;
- className?: string;
-}) => {
- return (
- <div className={clsx("openui-bottom-tray-thread-message-assistant", className)}>
- <div className="openui-bottom-tray-thread-message-assistant__content">{children}</div>
- </div>
- );
-};
-
-export const UserMessageContainer = ({
- children,
- className,
-}: {
- children?: React.ReactNode;
- className?: string;
-}) => {
- return (
- <div className={clsx("openui-bottom-tray-thread-message-user", className)}>
- <div className="openui-bottom-tray-thread-message-user__content">{children}</div>
- </div>
- );
-};
-
-const AssistantMessageContent = ({
- message,
- allMessages,
-}: {
- message: AssistantMessage;
- allMessages: Message[];
-}) => {
- const getToolName = (toolCallId: string) => {
- const toolCall = message.toolCalls?.find((tc) => tc.id === toolCallId);
- return toolCall?.function.name;
- };
-
- const toolMessages: ToolMessage[] = [];
- const msgIndex = allMessages.findIndex((m) => m.id === message.id);
- if (msgIndex !== -1) {
- for (let i = msgIndex + 1; i < allMessages.length; i++) {
- const m = allMessages[i];
- if (m && m.role === "tool") {
- toolMessages.push(m as ToolMessage);
- } else {
- break;
- }
- }
- }
-
- return (
- <>
- {message.content && (
- <MarkDownRenderer
- textMarkdown={message.content}
- className="openui-bottom-tray-thread-message-assistant__text"
- />
- )}
- {message.toolCalls?.map((toolCall) => (
- <ToolCallComponent key={toolCall.id} toolCall={toolCall} />
- ))}
- {toolMessages.map((tm) => (
- <ToolResult key={tm.id} message={tm} toolName={getToolName(tm.toolCallId)} />
- ))}
- </>
- );
-};
-
-const UserMessageContent = ({ message }: { message: Message }) => {
- if (message.role !== "user") return null;
- const content = message.content;
- if (typeof content === "string") {
- return <>{content}</>;
- }
- return (
- <>
- {content?.map((part, i) => {
- if (part.type === "text") {
- return <span key={i}>{part.text}</span>;
- }
- if (part.type === "binary" && part.url) {
- return (
- <img
- key={i}
- src={part.url}
- alt=""
- className="openui-bottom-tray-thread-message-user__image"
- />
- );
- }
- return null;
- })}
- </>
- );
-};
-
-export const RenderMessage = memo(
- ({
- message,
- className,
- allMessages,
- assistantMessage: CustomAssistantMessage,
- userMessage: CustomUserMessage,
- isStreaming,
- }: {
- message: Message;
- className?: string;
- allMessages: Message[];
- assistantMessage?: AssistantMessageComponent;
- userMessage?: UserMessageComponent;
- isStreaming: boolean;
- }) => {
- if (message.role === "tool") {
- return null;
- }
-
- if (message.role === "assistant") {
- if (CustomAssistantMessage) {
- return <CustomAssistantMessage message={message} isStreaming={isStreaming} />;
- }
- return (
- <AssistantMessageContainer className={className}>
- <AssistantMessageContent message={message} allMessages={allMessages} />
- </AssistantMessageContainer>
- );
- }
-
- if (message.role === "user") {
- if (CustomUserMessage) {
- return <CustomUserMessage message={message} />;
- }
- return (
- <UserMessageContainer className={className}>
- <UserMessageContent message={message} />
- </UserMessageContainer>
- );
- }
-
- return null;
- },
-);
-
-export const MessageLoading = () => {
- return (
- <div className="openui-bottom-tray-thread-message-loading">
- <MessageLoadingComponent />
- </div>
- );
-};
-
-export const Messages = ({
- className,
- loader,
- assistantMessage,
- userMessage,
-}: {
- className?: string;
- loader?: React.ReactNode;
- assistantMessage?: AssistantMessageComponent;
- userMessage?: UserMessageComponent;
-}) => {
- const messages = useThread((s) => s.messages);
- const isRunning = useThread((s) => s.isRunning);
-
- return (
- <div className={clsx("openui-bottom-tray-thread-messages", className)}>
- {messages.map((message, i) => {
- return (
- <MessageProvider key={message.id} message={message}>
- <RenderMessage
- message={message}
- allMessages={messages}
- assistantMessage={assistantMessage}
- userMessage={userMessage}
- isStreaming={isRunning && i === messages.length - 1}
- />
- </MessageProvider>
- );
- })}
- {isRunning && <div>{loader}</div>}
- </div>
- );
-};
-
-// Re-export Composer from components
-export { Composer } from "./components";
diff --git a/packages/react-ui/src/components/BottomTray/ThreadListContainer.tsx b/packages/react-ui/src/components/BottomTray/ThreadListContainer.tsx
deleted file mode 100644
index 1e43da432..000000000
--- a/packages/react-ui/src/components/BottomTray/ThreadListContainer.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import { useThreadList } from "@openuidev/react-headless";
-import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
-import clsx from "clsx";
-import { EllipsisVerticalIcon, MenuIcon, Trash2Icon } from "lucide-react";
-import { useEffect } from "react";
-import { Button } from "../Button";
-import { IconButton } from "../IconButton";
-import { useTheme } from "../ThemeProvider";
-
-const ThreadItem = ({
- title,
- isSelected,
- onSelect,
- onDelete,
-}: {
- title: string;
- isSelected: boolean;
- onSelect: () => void;
- onDelete: () => void;
-}) => {
- const { portalThemeClassName } = useTheme();
- return (
- <div
- className={clsx("openui-bottom-tray-thread-item", {
- "openui-bottom-tray-thread-item--selected": isSelected,
- })}
- >
- <button className="openui-bottom-tray-thread-item-title" onClick={onSelect}>
- {title}
- </button>
- <DropdownMenu.Root>
- <DropdownMenu.Trigger asChild>
- <IconButton
- icon={<EllipsisVerticalIcon size="1em" />}
- aria-label={`More actions for ${title}`}
- variant="tertiary"
- size="extra-small"
- className="openui-bottom-tray-thread-item-menu-trigger"
- />
- </DropdownMenu.Trigger>
- <DropdownMenu.Portal>
- <DropdownMenu.Content
- className={clsx("openui-bottom-tray-thread-item-menu", portalThemeClassName)}
- side="right"
- align="start"
- sideOffset={4}
- >
- <DropdownMenu.Item
- asChild
- onSelect={(e) => {
- e.stopPropagation();
- onDelete();
- }}
- >
- <Button
- type="button"
- variant="tertiary"
- buttonType="destructive"
- size="small"
- iconLeft={<Trash2Icon size={14} />}
- className="openui-bottom-tray-thread-item-menu-action"
- >
- Delete
- </Button>
- </DropdownMenu.Item>
- </DropdownMenu.Content>
- </DropdownMenu.Portal>
- </DropdownMenu.Root>
- </div>
- );
-};
-
-export const ThreadListContainer = () => {
- const threads = useThreadList((s) => s.threads);
- const selectedThreadId = useThreadList((s) => s.selectedThreadId);
- const loadThreads = useThreadList((s) => s.loadThreads);
- const selectThread = useThreadList((s) => s.selectThread);
- const deleteThread = useThreadList((s) => s.deleteThread);
- const { portalThemeClassName } = useTheme();
-
- useEffect(() => {
- loadThreads();
- }, [loadThreads]);
-
- return (
- <DropdownMenu.Root>
- <DropdownMenu.Trigger asChild>
- <IconButton
- icon={<MenuIcon size="1em" />}
- variant="tertiary"
- aria-label="Thread list"
- className="openui-bottom-tray-thread-list-trigger"
- />
- </DropdownMenu.Trigger>
- <DropdownMenu.Portal>
- <DropdownMenu.Content
- className={clsx("openui-bottom-tray-thread-list-dropdown", portalThemeClassName)}
- side="bottom"
- align="end"
- sideOffset={8}
- >
- <div className="openui-bottom-tray-thread-list-header">All threads</div>
- <div className="openui-bottom-tray-thread-list-items">
- {threads.map((thread) => (
- <ThreadItem
- key={thread.id}
- title={thread.title}
- isSelected={selectedThreadId === thread.id}
- onSelect={() => selectThread(thread.id)}
- onDelete={() => deleteThread(thread.id)}
- />
- ))}
- {threads.length === 0 && (
- <div className="openui-bottom-tray-thread-list-empty">No threads yet</div>
- )}
- </div>
- </DropdownMenu.Content>
- </DropdownMenu.Portal>
- </DropdownMenu.Root>
- );
-};
diff --git a/packages/react-ui/src/components/BottomTray/Trigger.tsx b/packages/react-ui/src/components/BottomTray/Trigger.tsx
deleted file mode 100644
index bfd7b4533..000000000
--- a/packages/react-ui/src/components/BottomTray/Trigger.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import clsx from "clsx";
-import { ChevronDown } from "lucide-react";
-import React, { forwardRef } from "react";
-
-interface TriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
- /** Whether the tray is currently open (used for mobile styling) */
- isOpen?: boolean;
-}
-
-export const Trigger = forwardRef<HTMLButtonElement, TriggerProps>(
- (
- { children, className, isOpen = false, "aria-label": ariaLabel = "Open chat", ...rest },
- ref,
- ) => {
- return (
- <button
- ref={ref}
- className={clsx(
- "openui-bottom-tray-trigger",
- { "openui-bottom-tray-trigger--open": isOpen },
- className,
- )}
- aria-label={ariaLabel}
- {...rest}
- >
- {children || <ChevronDown size={24} />}
- </button>
- );
- },
-);
diff --git a/packages/react-ui/src/components/BottomTray/WelcomeScreen.tsx b/packages/react-ui/src/components/BottomTray/WelcomeScreen.tsx
deleted file mode 100644
index b1a1afe98..000000000
--- a/packages/react-ui/src/components/BottomTray/WelcomeScreen.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-import { useThread } from "@openuidev/react-headless";
-import clsx from "clsx";
-import { ReactNode } from "react";
-import { isChatEmpty } from "../_shared/utils";
-
-interface WelcomeScreenBaseProps {
- /**
- * Additional CSS class name
- */
- className?: string;
-}
-
-interface WelcomeScreenWithContentProps extends WelcomeScreenBaseProps {
- /**
- * The greeting/title text to display
- */
- title?: string;
- /**
- * Optional description text to add more context
- */
- description?: string;
- /**
- * Image to display - can be a URL object or a ReactNode
- * - { url: string }: Renders an <img> tag with default styling (64x64, object-fit: cover, rounded)
- * - ReactNode: Renders the provided element directly (for custom icons, styled images, etc.)
- */
- image?: { url: string } | ReactNode;
- /**
- * Children are not allowed when using props-based content
- */
- children?: never;
-}
-
-interface WelcomeScreenWithChildrenProps extends WelcomeScreenBaseProps {
- /**
- * Custom content to render inside the welcome screen
- * When children are provided, title, description, and image are ignored
- */
- children: ReactNode;
- title?: never;
- description?: never;
- image?: never;
-}
-
-export type WelcomeScreenProps = WelcomeScreenWithContentProps | WelcomeScreenWithChildrenProps;
-
-/**
- * Type guard to check if image is a URL object
- */
-const isImageUrl = (image: { url: string } | ReactNode): image is { url: string } => {
- return typeof image === "object" && image !== null && "url" in image;
-};
-
-export const WelcomeScreen = (props: WelcomeScreenProps) => {
- const { className } = props;
-
- const messages = useThread((s) => s.messages);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- // Only show when there are no messages
- if (!isChatEmpty({ isLoadingMessages, messages })) {
- return null;
- }
-
- // Check if children are provided
- if ("children" in props && props.children) {
- return (
- <div className={clsx("openui-bottom-tray-welcome-screen", className)}>{props.children}</div>
- );
- }
-
- // Props-based content
- const { title, description, image } = props as WelcomeScreenWithContentProps;
-
- const renderImage = () => {
- if (!image) return null;
-
- if (isImageUrl(image)) {
- return (
- <img
- src={image.url}
- alt={title || ""}
- className="openui-bottom-tray-welcome-screen__image"
- />
- );
- }
-
- return image;
- };
-
- return (
- <div className={clsx("openui-bottom-tray-welcome-screen", className)}>
- {image && (
- <div className="openui-bottom-tray-welcome-screen__image-container">{renderImage()}</div>
- )}
- {(title || description) && (
- <div className="openui-bottom-tray-welcome-screen__content">
- {title && <h2 className="openui-bottom-tray-welcome-screen__title">{title}</h2>}
- {description && (
- <p className="openui-bottom-tray-welcome-screen__description">{description}</p>
- )}
- </div>
- )}
- </div>
- );
-};
-
-export default WelcomeScreen;
diff --git a/packages/react-ui/src/components/BottomTray/bottomTray.scss b/packages/react-ui/src/components/BottomTray/bottomTray.scss
deleted file mode 100644
index 73e3eed67..000000000
--- a/packages/react-ui/src/components/BottomTray/bottomTray.scss
+++ /dev/null
@@ -1,11 +0,0 @@
-// BottomTray component styles
-// This file imports all individual style modules for the BottomTray component
-
-@use "./container.scss";
-@use "./trigger.scss";
-@use "./header.scss";
-@use "./threadList.scss";
-@use "./thread.scss";
-@use "./components/composer.scss";
-@use "./conversationStarter.scss";
-@use "./welcomeScreen.scss";
diff --git a/packages/react-ui/src/components/BottomTray/components/Composer.tsx b/packages/react-ui/src/components/BottomTray/components/Composer.tsx
deleted file mode 100644
index 291010c1f..000000000
--- a/packages/react-ui/src/components/BottomTray/components/Composer.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { useThread } from "@openuidev/react-headless";
-import clsx from "clsx";
-import { ArrowUp, Square } from "lucide-react";
-import { useLayoutEffect, useRef } from "react";
-import { useComposerState } from "../../../hooks/useComposerState";
-import { IconButton } from "../../IconButton";
-
-export interface ComposerProps {
- className?: string;
- placeholder?: string;
-}
-
-export const Composer = ({ className, placeholder = "Type your message..." }: ComposerProps) => {
- const { textContent, setTextContent } = useComposerState();
- const processMessage = useThread((s) => s.processMessage);
- const cancelMessage = useThread((s) => s.cancelMessage);
- const isRunning = useThread((s) => s.isRunning);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
- const inputRef = useRef<HTMLTextAreaElement>(null);
-
- const handleSubmit = () => {
- if (!textContent.trim() || isRunning || isLoadingMessages) {
- return;
- }
-
- processMessage({
- role: "user",
- content: textContent,
- });
-
- setTextContent("");
- };
-
- useLayoutEffect(() => {
- const input = inputRef.current;
- if (!input) return;
-
- // Reset to 0 (not "auto") so scrollHeight reflects content, not container
- input.style.height = "0px";
- input.style.height = `${Math.max(input.scrollHeight, 24)}px`;
- }, [textContent]);
-
- return (
- <div
- className={clsx("openui-bottom-tray-thread-composer", className)}
- data-drafting={textContent.length > 0 || undefined}
- onClick={(e) => {
- if (!(e.target as HTMLElement).closest("button, a, [role='button']")) {
- inputRef.current?.focus();
- }
- }}
- >
- <div className="openui-bottom-tray-thread-composer__input-wrapper">
- <textarea
- ref={inputRef}
- value={textContent}
- onChange={(e) => setTextContent(e.target.value)}
- className="openui-bottom-tray-thread-composer__input"
- placeholder={placeholder}
- rows={1}
- onKeyDown={(e) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- handleSubmit();
- }
- }}
- />
- <div className="openui-bottom-tray-thread-composer__action-bar">
- <IconButton
- onClick={isRunning ? cancelMessage : handleSubmit}
- icon={isRunning ? <Square size="1em" fill="currentColor" /> : <ArrowUp size="1em" />}
- size="extra-small"
- variant="primary"
- className="openui-bottom-tray-thread-composer__submit-button"
- />
- </div>
- </div>
- </div>
- );
-};
-
-export default Composer;
diff --git a/packages/react-ui/src/components/BottomTray/components/composer.scss b/packages/react-ui/src/components/BottomTray/components/composer.scss
deleted file mode 100644
index d21e42aa9..000000000
--- a/packages/react-ui/src/components/BottomTray/components/composer.scss
+++ /dev/null
@@ -1,62 +0,0 @@
-@use "../../../cssUtils" as cssUtils;
-
-.openui-bottom-tray-thread-composer {
- box-sizing: border-box;
- flex-shrink: 0;
- width: 100%;
- margin: 0 0 cssUtils.$space-m;
- padding: 0 cssUtils.$space-m;
-
- &__input-wrapper {
- background-color: cssUtils.$foreground;
- border: 1px solid cssUtils.$border-interactive;
- border-radius: cssUtils.$radius-2xl;
- box-shadow: cssUtils.$shadow-m;
- overflow: clip;
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-s;
- padding: cssUtils.$space-s-m;
- }
-
- &__input {
- scrollbar-width: thin;
- scrollbar-color: cssUtils.$elevated transparent;
-
- &::-webkit-scrollbar {
- width: 6px;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background-color: cssUtils.$elevated;
- border-radius: cssUtils.$radius-full;
- }
-
- padding: 0 cssUtils.$space-3xs;
- resize: none;
- max-height: 200px;
- outline: none;
- border: none;
- background: transparent;
- overflow-y: auto;
- @include cssUtils.typography(body, default);
- color: cssUtils.$text-neutral-primary;
-
- &::placeholder {
- color: cssUtils.$text-neutral-secondary;
- }
- }
-
- &__action-bar {
- display: flex;
- align-items: center;
- }
-
- &__submit-button {
- margin-left: auto;
- }
-}
diff --git a/packages/react-ui/src/components/BottomTray/components/index.ts b/packages/react-ui/src/components/BottomTray/components/index.ts
deleted file mode 100644
index c054e9045..000000000
--- a/packages/react-ui/src/components/BottomTray/components/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { Composer } from "./Composer";
-export type { ComposerProps } from "./Composer";
diff --git a/packages/react-ui/src/components/BottomTray/container.scss b/packages/react-ui/src/components/BottomTray/container.scss
deleted file mode 100644
index 1187eedee..000000000
--- a/packages/react-ui/src/components/BottomTray/container.scss
+++ /dev/null
@@ -1,66 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-bottom-tray-container {
- display: flex;
- position: fixed;
- // Leave space for the 56px trigger + spacing (16px bottom + 56px height + 12px gap = 84px)
- bottom: 84px;
- right: cssUtils.$space-l;
- height: calc(90% - 84px);
- max-height: 768px;
- width: 448px;
- overflow: hidden;
- flex-direction: column;
-
- // Cone animation: expand from bottom-right (where trigger is)
- transform-origin: bottom right;
- transition:
- transform 0.25s ease-in-out,
- opacity 0.25s ease-in-out,
- clip-path 0.25s ease-in-out;
-
- border: 1px solid cssUtils.$border-default;
- border-radius: cssUtils.$radius-4xl;
- box-shadow: cssUtils.$shadow-2xl;
-
- background: cssUtils.$chat-container-bg;
- box-sizing: border-box;
- & * {
- box-sizing: border-box;
- }
-
- // Open state - fully expanded
- &--open {
- transform: scale(1);
- opacity: 1;
- clip-path: ellipse(150% 150% at 100% 100%);
- }
-
- // Closed state - collapsed to trigger point with cone clip
- &--closed {
- transform: scale(0.1);
- opacity: 0;
- pointer-events: none;
- clip-path: ellipse(0% 0% at 100% 100%);
- }
-
- // Mobile fullscreen
- @media (max-width: 768px) {
- right: 0;
- left: 0;
- top: 0;
- bottom: 0;
- width: 100dvw;
- height: 100dvh;
- max-height: none;
- max-width: none;
- border-radius: 0;
- border: none;
-
- // On mobile, expand from bottom-right corner where trigger was
- &--closed {
- transform: scale(0.1);
- clip-path: ellipse(0% 0% at 100% 100%);
- }
- }
-}
diff --git a/packages/react-ui/src/components/BottomTray/conversationStarter.scss b/packages/react-ui/src/components/BottomTray/conversationStarter.scss
deleted file mode 100644
index 9cf48fa62..000000000
--- a/packages/react-ui/src/components/BottomTray/conversationStarter.scss
+++ /dev/null
@@ -1,158 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-// Container styles
-.openui-bottom-tray-conversation-starter {
- display: flex;
- flex-shrink: 0;
- width: 100%;
- padding: 0 cssUtils.$space-m;
- margin-bottom: cssUtils.$space-s;
- box-sizing: border-box;
- max-height: 480px;
- overflow: hidden;
- opacity: 1;
- transform: translateY(0);
- transition:
- opacity 0.2s ease,
- transform 0.2s ease,
- max-height 0.2s ease,
- margin-bottom 0.2s ease;
-
- // Short variant - horizontal pill buttons
- &--short {
- display: block;
- }
-
- // Long variant - vertical list items
- &--long {
- flex-direction: column;
- gap: cssUtils.$space-2xs;
- }
-
- &__carousel-content {
- gap: cssUtils.$space-xs;
- }
-}
-
-// Short variant item (pill-style buttons)
-.openui-bottom-tray-conversation-starter-item-short {
- display: flex;
- align-items: center;
- gap: cssUtils.$space-xs;
- width: fit-content;
- flex: 0 0 auto;
- padding: cssUtils.$space-s cssUtils.$space-s-m;
- background-color: cssUtils.$foreground;
- border: 1px solid cssUtils.$border-interactive;
- border-radius: cssUtils.$radius-l;
- cursor: pointer;
- transition: all 0.15s ease;
- @include cssUtils.typography(body, small);
- color: cssUtils.$text-neutral-primary;
- text-align: left;
-
- // Icon container
- &__icon {
- display: flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- color: cssUtils.$text-neutral-primary;
-
- & > svg {
- width: 14px;
- height: 14px;
- }
- }
-
- // Text
- &__text {
- flex: 1;
- white-space: nowrap;
- }
-
- &:not(:disabled):hover {
- background-color: cssUtils.$highlight;
- border-color: cssUtils.$border-interactive-emphasis;
- }
-
- &:not(:disabled):active {
- background-color: cssUtils.$highlight-subtle;
- }
-
- @media (max-width: 480px) {
- padding: cssUtils.$space-s cssUtils.$space-s-m;
- }
-}
-
-// Long variant item (list-style with icon and arrow)
-.openui-bottom-tray-conversation-starter-item-long {
- display: flex;
- align-items: center;
- gap: cssUtils.$space-000;
- width: 100%;
- padding: cssUtils.$space-xs cssUtils.$space-s-m;
- background-color: transparent;
- border: none;
- border-radius: cssUtils.$radius-l;
- cursor: pointer;
- transition: background-color 0.15s ease;
- @include cssUtils.typography(body, default);
- color: cssUtils.$text-neutral-primary;
- text-align: left;
- overflow: hidden;
-
- // Content wrapper (icon + text)
- &__content {
- display: flex;
- align-items: flex-start;
- gap: cssUtils.$space-xs;
- flex: 1;
- min-width: 0;
- }
-
- // Icon container - aligned to top with padding to align with first line of text
- &__icon {
- display: flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- padding-top: cssUtils.$space-2xs;
- color: cssUtils.$text-neutral-primary;
- }
-
- // Text - allows wrapping for long content
- &__text {
- flex: 1;
- min-width: 0;
- line-height: 1.5;
- // Text wraps naturally, no truncation
- }
-
- // Arrow icon (shown on hover)
- &__arrow {
- display: flex;
- align-self: flex-start;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- padding-top: cssUtils.$space-2xs;
- opacity: 0;
- transition: opacity 0.15s ease;
- color: cssUtils.$text-neutral-primary;
- }
-
- // Hover state
- &:not(:disabled):hover {
- background-color: cssUtils.$sunk;
-
- .openui-bottom-tray-conversation-starter-item-long__arrow {
- opacity: 1;
- }
- }
-
- // Active/pressed state
- &:not(:disabled):active {
- background-color: cssUtils.$highlight-subtle;
- }
-}
diff --git a/packages/react-ui/src/components/BottomTray/dependencies.ts b/packages/react-ui/src/components/BottomTray/dependencies.ts
deleted file mode 100644
index 3028df8d3..000000000
--- a/packages/react-ui/src/components/BottomTray/dependencies.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import buttonDeps from "../Button/dependencies";
-import iconButtonDeps from "../IconButton/dependencies";
-
-const dependencies = ["Shell", ...iconButtonDeps, ...buttonDeps];
-export default dependencies;
diff --git a/packages/react-ui/src/components/BottomTray/header.scss b/packages/react-ui/src/components/BottomTray/header.scss
deleted file mode 100644
index a7fc6b7bb..000000000
--- a/packages/react-ui/src/components/BottomTray/header.scss
+++ /dev/null
@@ -1,38 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-bottom-tray-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: cssUtils.$space-m;
- border-radius: cssUtils.$radius-4xl cssUtils.$radius-4xl 0 0;
-
- // Mobile
- @media (max-width: 768px) {
- border-radius: 0;
- }
-}
-
-.openui-bottom-tray-header-logo-container {
- display: flex;
- align-items: center;
- gap: cssUtils.$space-s;
- @include cssUtils.typography(title, medium);
-}
-
-.openui-bottom-tray-header-logo {
- width: 32px;
- height: 32px;
- border-radius: cssUtils.$radius-m;
-}
-
-.openui-bottom-tray-header-agent-name {
- @include cssUtils.typography(title, medium);
- color: cssUtils.$text-neutral-primary;
-}
-
-.openui-bottom-tray-header-actions {
- display: flex;
- align-items: center;
- gap: cssUtils.$space-2xs;
-}
diff --git a/packages/react-ui/src/components/BottomTray/index.ts b/packages/react-ui/src/components/BottomTray/index.ts
deleted file mode 100644
index 4306ca7ac..000000000
--- a/packages/react-ui/src/components/BottomTray/index.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export * from "./Container";
-export * from "./ConversationStarter";
-export * from "./Header";
-export * from "./Thread";
-export * from "./Trigger";
-export * from "./WelcomeScreen";
diff --git a/packages/react-ui/src/components/BottomTray/stories/BottomTray.mdx b/packages/react-ui/src/components/BottomTray/stories/BottomTray.mdx
deleted file mode 100644
index 3d725d49b..000000000
--- a/packages/react-ui/src/components/BottomTray/stories/BottomTray.mdx
+++ /dev/null
@@ -1,361 +0,0 @@
-import { Meta } from "@storybook/blocks";
-import * as BottomTrayStories from "./BottomTray.stories";
-
-<Meta of={BottomTrayStories} />
-
-# BottomTray
-
-The BottomTray is a **composable chat interface** that appears as a floating panel in the bottom-right corner of your application. It uses a composition pattern, giving you full control over placement and styling.
-
-## Component Structure
-
-```
-ChatProvider
-├── Trigger (floating button to open/close)
-└── Container (the tray panel)
- └── ThreadContainer
- ├── Header (logo, agent name, actions)
- ├── WelcomeScreen (optional, shown when empty)
- ├── ScrollArea (scrollable message area)
- │ └── Messages
- ├── ConversationStarter (optional, shown when empty)
- └── Composer (text input)
-```
-
-## Basic Usage
-
-```tsx
-import { useState } from "react";
-import { ChatProvider, useThreadListManager, useThreadManager } from "@openuidev/react-headless";
-import {
- Composer,
- Container,
- ConversationStarter,
- Header,
- MessageLoading,
- Messages,
- ScrollArea,
- ThreadContainer,
- Trigger,
- WelcomeScreen,
-} from "@openuidev/react-ui";
-
-function MyApp() {
- const [isOpen, setIsOpen] = useState(false);
-
- // Set up thread list management
- const threadListManager = useThreadListManager({
- createThread: async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- isRunning: false,
- }),
- fetchThreadList: async () => {
- // Fetch threads from your backend
- return [];
- },
- deleteThread: async (id) => {
- // Delete thread from your backend
- },
- updateThread: async (thread) => thread,
- onSwitchToNew: () => {},
- onSelectThread: (threadId) => {},
- });
-
- // Set up thread management
- const threadManager = useThreadManager({
- threadId: threadListManager.selectedThreadId,
- loadThread: async (threadId) => {
- // Return empty for new thread, otherwise load messages
- if (!threadId) return [];
- // Fetch messages from your backend
- return [];
- },
- onProcessMessage: async ({ message, threadManager }) => {
- // Send message to your AI backend
- // Return assistant response
- return [
- {
- id: crypto.randomUUID(),
- role: "assistant",
- type: "response",
- message: [{ type: "text", text: "Response from AI" }],
- },
- ];
- },
- responseTemplates: [],
- });
-
- const hasMessages = threadManager.messages.length > 0;
-
- return (
- <ChatProvider threadListManager={threadListManager} threadManager={threadManager}>
- {/* Trigger - floating button */}
- <Trigger onClick={() => setIsOpen(!isOpen)} isOpen={isOpen} />
-
- {/* Container - the tray panel */}
- <Container logoUrl="/path/to/logo.png" agentName="AI Assistant" isOpen={isOpen}>
- <ThreadContainer>
- <Header onMinimize={() => setIsOpen(false)} />
-
- {/* WelcomeScreen - shown when no messages */}
- {!hasMessages && (
- <WelcomeScreen
- title="Hi, I'm AI Assistant"
- description="I can help you with your questions."
- image={
- <img
- src="/path/to/logo.png"
- alt="AI Assistant"
- style={{ width: 64, height: 64, borderRadius: 16, objectFit: "cover" }}
- />
- }
- />
- )}
-
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter
- starters={[
- { displayText: "Help me get started", prompt: "Help me get started" },
- { displayText: "What can you do?", prompt: "What can you do?" },
- ]}
- />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- );
-}
-```
-
-## Components
-
-### Trigger
-
-The floating button that opens/closes the tray. Positioned fixed in the bottom-right corner.
-
-```tsx
-<Trigger
- onClick={() => setIsOpen(!isOpen)}
- isOpen={isOpen} // Controls shrink animation when open
- className="custom-class" // Optional custom styling
->
- {/* Optional custom content, defaults to chevron icon */}
- 💬 Need Help?
-</Trigger>
-```
-
-### Container
-
-The main tray panel. Controls visibility with `isOpen` prop.
-
-```tsx
-<Container
- logoUrl="/logo.png" // Logo shown in header
- agentName="AI Assistant" // Name shown in header
- isOpen={isOpen} // Controls open/closed animation
- className="custom-class" // Optional custom styling
->
- {children}
-</Container>
-```
-
-### ThreadContainer
-
-Wrapper for thread content. Manages layout and artifact panels.
-
-```tsx
-<ThreadContainer
- isArtifactActive={false} // Show artifact panel
- renderArtifact={() => <div />} // Artifact content
->
- {children}
-</ThreadContainer>
-```
-
-### Header
-
-Header with logo, agent name, thread list, new chat button, and minimize.
-
-```tsx
-<Header
- onMinimize={() => setIsOpen(false)} // Minimize callback
- hideMinimizeButton={false} // Hide X button
- hideNewChatButton={false} // Hide new chat button
- hideThreadListContainer={false} // Hide thread list
- rightChildren={<CustomActions />} // Custom actions
-/>
-```
-
-### ScrollArea
-
-Scrollable container for messages with auto-scroll behavior.
-
-```tsx
-<ScrollArea
- scrollVariant="user-message-anchor" // Scroll behavior
- userMessageSelector=".user-message" // CSS selector for user messages
->
- <Messages loader={<MessageLoading />} />
-</ScrollArea>
-```
-
-### ConversationStarter
-
-Clickable prompts shown when thread is empty. Automatically hides when messages exist.
-
-```tsx
-<ConversationStarter
- variant="short" // "short" (pill buttons) or "long" (list items)
- starters={[
- {
- displayText: "Help me get started",
- prompt: "Help me get started",
- icon: <Sparkles size={16} />,
- },
- { displayText: "What can you do?", prompt: "What can you do?" }, // Default lightbulb icon
- { displayText: "No icon example", prompt: "No icon", icon: <></> }, // No icon (use empty fragment)
- ]}
-/>
-```
-
-**Props:**
-
-- `variant` - `"short"` (pill-style buttons) or `"long"` (list items with separators)
-- `starters` - Array of objects with:
- - `displayText` - Text shown on the button
- - `prompt` - Message sent when clicked
- - `icon` - Optional: `ReactNode` for custom icon, `undefined` for default lightbulb, `<></>` (empty fragment) for no icon
-
-### WelcomeScreen
-
-A centered welcome message shown when the thread is empty. Supports either props-based content or custom children.
-
-**Props-based usage with URL:**
-
-```tsx
-{
- !hasMessages && (
- <WelcomeScreen
- title="Hi, I'm AI Assistant"
- description="I can help you with your questions."
- image={{ url: "/path/to/logo.png" }}
- />
- );
-}
-```
-
-**Props-based usage with styled image:**
-
-```tsx
-{
- !hasMessages && (
- <WelcomeScreen
- title="Hi, I'm AI Assistant"
- description="I can help you with your questions."
- image={
- <img
- src="/path/to/logo.png"
- alt="AI Assistant"
- style={{ width: 64, height: 64, borderRadius: 16, objectFit: "cover" }}
- />
- }
- />
- );
-}
-```
-
-**Props-based usage with custom icon:**
-
-```tsx
-{
- !hasMessages && (
- <WelcomeScreen
- title="Hi, I'm AI Assistant"
- description="I can help you with your questions."
- image={<Sparkles size={32} />}
- />
- );
-}
-```
-
-**Custom children usage:**
-
-```tsx
-{
- !hasMessages && (
- <WelcomeScreen>
- <div style={{ textAlign: "center" }}>
- <MyCustomLogo />
- <h2>Welcome!</h2>
- <p>Custom welcome content</p>
- </div>
- </WelcomeScreen>
- );
-}
-```
-
-**Props:**
-
-- `title` - Greeting/title text (optional)
-- `description` - Description text (optional)
-- `image` - Image to display: `{ url: string }` for simple URL (renders with default 64x64 size, rounded corners), or `ReactNode` for custom styled elements (optional)
-- `children` - Custom content (mutually exclusive with title/description/image)
-- `className` - Additional CSS class (optional)
-
-**Note:** You must conditionally render WelcomeScreen based on `hasMessages` state.
-
-### Composer
-
-Text input with submit button. Handles enter key and running state.
-
-```tsx
-<Composer className="custom-class" />
-```
-
-## Customization Examples
-
-### Custom Trigger Content
-
-```tsx
-<Trigger onClick={() => setIsOpen(!isOpen)} isOpen={isOpen}>
- <img src="/custom-icon.png" alt="Chat" />
-</Trigger>
-```
-
-### Without ConversationStarter
-
-Simply omit the component:
-
-```tsx
-<ThreadContainer>
- <Header onMinimize={() => setIsOpen(false)} />
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <Composer />
-</ThreadContainer>
-```
-
-### Minimal Header
-
-```tsx
-<Header onMinimize={() => setIsOpen(false)} hideNewChatButton hideThreadListContainer />
-```
-
-## Animation
-
-The tray uses a **cone animation** that expands from the trigger button:
-
-- Opens with scale + clip-path animation from bottom-right
-- Trigger shrinks when tray is open
-- Smooth spring easing for natural feel
-
-## Mobile Behavior
-
-- Tray goes fullscreen on mobile (less than 768px)
-- Trigger hides when tray is open on mobile
-- Touch-friendly interactions
diff --git a/packages/react-ui/src/components/BottomTray/stories/BottomTray.stories.tsx b/packages/react-ui/src/components/BottomTray/stories/BottomTray.stories.tsx
deleted file mode 100644
index e05841b88..000000000
--- a/packages/react-ui/src/components/BottomTray/stories/BottomTray.stories.tsx
+++ /dev/null
@@ -1,474 +0,0 @@
-import { ChatProvider, Message } from "@openuidev/react-headless";
-import { MessageSquare, Sparkles, Zap } from "lucide-react";
-import { useState } from "react";
-import {
- Composer,
- Container,
- ConversationStarter,
- Header,
- MessageLoading,
- Messages,
- ScrollArea,
- ThreadContainer,
- Trigger,
- WelcomeScreen,
-} from "../../BottomTray";
-// @ts-ignore
-import styles from "./style.module.scss";
-import logoUrl from "./thesysdev_logo.jpeg";
-
-function mockSSEResponse(text: string, delayMs = 500): Promise<Response> {
- return new Promise((resolve) => {
- setTimeout(() => {
- const events = `data: ${JSON.stringify({ type: "TEXT_MESSAGE_CONTENT", delta: text })}\n\ndata: [DONE]\n\n`;
- const stream = new ReadableStream({
- start(controller) {
- controller.enqueue(new TextEncoder().encode(events));
- controller.close();
- },
- });
- resolve(new Response(stream));
- }, delayMs);
- });
-}
-
-export default {
- title: "Components/BottomTray",
- tags: ["dev"],
- argTypes: {
- defaultOpen: {
- control: "boolean",
- description: "Whether the tray starts open",
- },
- variant: {
- control: "select",
- options: ["short", "long"],
- description: "Conversation starter variant",
- },
- },
-};
-
-const BottomTrayStory = ({
- defaultOpen = false,
- variant = "short",
-}: {
- defaultOpen?: boolean;
- variant?: "short" | "long";
-}) => {
- const [isOpen, setIsOpen] = useState(defaultOpen);
-
- return (
- <div className={styles.container}>
- <div className={styles.content}>
- <h1>Bottom Tray Example (Composable)</h1>
- <p>
- The chat interface uses a <strong>composition pattern</strong>. The trigger button is
- separate from the container, giving you full control over placement and styling.
- </p>
- <p>
- <strong>Try it:</strong> Click the pill button (bottom-right) or the custom button below
- to toggle the tray.
- </p>
- <button onClick={() => setIsOpen(!isOpen)} className={styles.toggleButton}>
- {isOpen ? "Close" : "Open"} Tray
- </button>
- </div>
-
- <ChatProvider
- processMessage={async ({ threadId, messages, abortController }) => {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- return mockSSEResponse("This is a response from the bottom tray assistant!", 0);
- }}
- fetchThreadList={async () => {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- return {
- threads: [
- { id: "1", title: "test", createdAt: Date.now() },
- { id: "2", title: "test 2", createdAt: Date.now() },
- { id: "3", title: "test 3", createdAt: Date.now() },
- ],
- };
- }}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "test",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t) => t}
- loadThread={async (threadId) => {
- if (!threadId) return [];
- return [
- {
- id: crypto.randomUUID(),
- role: "user",
- content: "Hello",
- },
- {
- id: crypto.randomUUID(),
- role: "assistant",
- content: "Hello! How can I help you today?",
- },
- ] as Message[];
- }}
- >
- {/* Trigger is always visible - toggles the tray (hidden on mobile when open) */}
- <Trigger onClick={() => setIsOpen(!isOpen)} isOpen={isOpen} />
-
- {/* Container is controlled externally */}
- <Container logoUrl={logoUrl} agentName="OpenUI Assistant" isOpen={isOpen}>
- <ThreadContainer>
- <Header onMinimize={() => setIsOpen(false)} />
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter
- variant={variant}
- starters={[
- {
- displayText: "Tell me about my portfolio",
- prompt:
- "Tell me about the latest stock market trends and how they affect my portfolio",
- icon: <Sparkles size={16} />,
- },
- {
- displayText:
- "Who is the president of Venezuela and where is he currently located (icon was not passed)",
- prompt: "Who is the president of Venezuela and where is he currently located?",
- // icon undefined = shows default lightbulb
- },
- {
- displayText: "Tell me about major stock (no icon with empty fragment)",
- prompt: "Tell me about major stock",
- icon: <></>, // Empty fragment = no icon
- },
- ]}
- />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- </div>
- );
-};
-
-export const Default = {
- args: {
- defaultOpen: false,
- variant: "short",
- },
- render: (args: any) => <BottomTrayStory {...args} />,
-};
-
-export const OpenByDefault = {
- args: {
- defaultOpen: true,
- variant: "short",
- },
- render: (args: any) => <BottomTrayStory {...args} />,
-};
-
-export const LongVariant = {
- args: {
- defaultOpen: true,
- variant: "long",
- },
- render: (args: any) => <BottomTrayStory {...args} />,
-};
-
-// Example with custom trigger
-const CustomTriggerStory = ({
- defaultOpen = false,
- variant = "short",
-}: {
- defaultOpen?: boolean;
- variant?: "short" | "long";
-}) => {
- const [isOpen, setIsOpen] = useState(defaultOpen);
-
- return (
- <div className={styles.container}>
- <div className={styles.content}>
- <h1>Custom Trigger Example</h1>
- <p>Use a fully custom trigger with your own styling and content.</p>
- </div>
-
- <ChatProvider
- processMessage={async () => {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- return mockSSEResponse("This is a response from the assistant!", 0);
- }}
- fetchThreadList={async () => {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- return {
- threads: [
- { id: "1", title: "test", createdAt: Date.now() },
- { id: "2", title: "test 2", createdAt: Date.now() },
- ],
- };
- }}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "test",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t) => t}
- loadThread={async (threadId) => {
- if (!threadId) return [];
- return [
- { id: crypto.randomUUID(), role: "user", content: "Hello" },
- {
- id: crypto.randomUUID(),
- role: "assistant",
- content: "Hello! How can I help you today?",
- },
- ] as Message[];
- }}
- >
- {/* Custom trigger - always visible, toggles tray (hidden on mobile when open) */}
- <Trigger
- onClick={() => setIsOpen(!isOpen)}
- isOpen={isOpen}
- className={styles.customTrigger}
- >
- 💬 Need Help?
- </Trigger>
-
- <Container logoUrl={logoUrl} agentName="Support" isOpen={isOpen}>
- <ThreadContainer>
- <Header onMinimize={() => setIsOpen(false)} />
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter
- variant={variant}
- starters={[
- {
- displayText:
- "Help me understand what features are available and how to get started with this application",
- prompt:
- "Help me understand what features are available and how to get started with this application",
- icon: <Zap size={16} />,
- },
- {
- displayText:
- "What can you help me with today? I need assistance with multiple tasks",
- prompt: "What can you help me with today? I need assistance with multiple tasks",
- icon: <MessageSquare size={16} />,
- },
- {
- displayText: "No icon example - this is a shorter prompt",
- prompt: "No icon example - this is a shorter prompt",
- icon: <></>, // Empty fragment = no icon
- },
- ]}
- />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- </div>
- );
-};
-
-export const CustomTrigger = {
- args: {
- defaultOpen: false,
- variant: "short",
- },
- render: (args: any) => <CustomTriggerStory {...args} />,
-};
-
-export const CustomTriggerLongVariant = {
- args: {
- defaultOpen: true,
- variant: "long",
- },
- render: (args: any) => <CustomTriggerStory {...args} />,
-};
-
-// Example with WelcomeScreen
-const WelcomeScreenStory = ({
- defaultOpen = true,
- variant = "short",
-}: {
- defaultOpen?: boolean;
- variant?: "short" | "long";
-}) => {
- const [isOpen, setIsOpen] = useState(defaultOpen);
-
- return (
- <div className={styles.container}>
- <div className={styles.content}>
- <h1>Welcome Screen Example</h1>
- <p>This example shows the WelcomeScreen component with title, description, and logo.</p>
- </div>
-
- <ChatProvider
- processMessage={async ({ messages }) => {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- const lastUser = messages.filter((m) => m.role === "user").pop();
- const content = typeof lastUser?.content === "string" ? lastUser.content : "";
- return mockSSEResponse(`You asked: "${content}"`, 0);
- }}
- fetchThreadList={async () => ({ threads: [] })}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t) => t}
- loadThread={async () => []}
- >
- <Trigger onClick={() => setIsOpen(!isOpen)} isOpen={isOpen} />
-
- <Container logoUrl={logoUrl} agentName="OpenUI Assistant" isOpen={isOpen}>
- <ThreadContainer>
- <Header onMinimize={() => setIsOpen(false)} />
-
- <WelcomeScreen
- title="Hi, I'm OpenUI Assistant"
- description="I can help you with questions about your account, products, and more."
- image={{ url: logoUrl }}
- />
-
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter
- variant={variant}
- starters={[
- {
- displayText: "Help me get started",
- prompt: "Help me get started",
- icon: <Sparkles size={16} />,
- },
- {
- displayText: "What can you do?",
- prompt: "What can you do?",
- },
- ]}
- />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- </div>
- );
-};
-
-export const WithWelcomeScreen = {
- args: {
- defaultOpen: true,
- variant: "short",
- },
- render: (args: any) => <WelcomeScreenStory {...args} />,
-};
-
-export const WithWelcomeScreenLongVariant = {
- args: {
- defaultOpen: true,
- variant: "long",
- },
- render: (args: any) => <WelcomeScreenStory {...args} />,
-};
-
-// Example with custom children in WelcomeScreen
-const CustomWelcomeScreenStory = ({
- defaultOpen = true,
- variant = "short",
-}: {
- defaultOpen?: boolean;
- variant?: "short" | "long";
-}) => {
- const [isOpen, setIsOpen] = useState(defaultOpen);
-
- return (
- <div className={styles.container}>
- <div className={styles.content}>
- <h1>Custom Welcome Screen Example</h1>
- <p>This example shows WelcomeScreen with custom children instead of props.</p>
- </div>
-
- <ChatProvider
- processMessage={async ({ messages }) => {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- const lastUser = messages.filter((m) => m.role === "user").pop();
- const content = typeof lastUser?.content === "string" ? lastUser.content : "";
- return mockSSEResponse(`You asked: "${content}"`, 0);
- }}
- fetchThreadList={async () => ({ threads: [] })}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t) => t}
- loadThread={async () => []}
- >
- <Trigger onClick={() => setIsOpen(!isOpen)} isOpen={isOpen} />
-
- <Container logoUrl={logoUrl} agentName="OpenUI Assistant" isOpen={isOpen}>
- <ThreadContainer>
- <Header onMinimize={() => setIsOpen(false)} />
-
- <WelcomeScreen>
- <div style={{ textAlign: "center" }}>
- <div
- style={{
- width: 80,
- height: 80,
- borderRadius: 16,
- background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- margin: "0 auto 16px",
- }}
- >
- <Sparkles size={40} color="white" />
- </div>
- <h2 style={{ margin: "0 0 8px", fontSize: 20, fontWeight: 600 }}>
- Welcome to AI Assistant
- </h2>
- <p style={{ margin: 0, color: "rgba(0,0,0,0.5)", fontSize: 14 }}>
- Your personal AI helper for all your questions
- </p>
- </div>
- </WelcomeScreen>
-
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter
- variant={variant}
- starters={[
- {
- displayText: "Help me get started",
- prompt: "Help me get started",
- icon: <Sparkles size={16} />,
- },
- {
- displayText: "What can you do?",
- prompt: "What can you do?",
- },
- ]}
- />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- </div>
- );
-};
-
-export const WithCustomWelcomeScreen = {
- args: {
- defaultOpen: true,
- variant: "short",
- },
- render: (args: any) => <CustomWelcomeScreenStory {...args} />,
-};
diff --git a/packages/react-ui/src/components/BottomTray/stories/style.module.scss b/packages/react-ui/src/components/BottomTray/stories/style.module.scss
deleted file mode 100644
index 8e8f95d4b..000000000
--- a/packages/react-ui/src/components/BottomTray/stories/style.module.scss
+++ /dev/null
@@ -1,59 +0,0 @@
-@use "../../../cssUtils" as cssUtils;
-
-.container {
- display: flex;
- min-height: 100vh;
- background: cssUtils.$background;
- position: relative;
-}
-
-.content {
- flex-grow: 1;
- padding: cssUtils.$space-2xl;
-
- h1 {
- @include cssUtils.typography(heading, large);
- color: cssUtils.$text-neutral-primary;
- margin-bottom: cssUtils.$space-l;
- }
-
- p {
- @include cssUtils.typography(body, default);
- color: cssUtils.$text-neutral-secondary;
- margin-bottom: cssUtils.$space-m;
- }
-}
-
-.toggleButton {
- @include cssUtils.typography(label, default);
- padding: cssUtils.$space-s cssUtils.$space-l;
- background: cssUtils.$sunk-light;
- color: cssUtils.$text-neutral-primary;
- border: 1px solid cssUtils.$border-interactive;
- border-radius: cssUtils.$radius-m;
- cursor: pointer;
- transition: all 0.2s ease;
-
- &:hover {
- background: cssUtils.$highlight;
- }
-
- &:active {
- background: cssUtils.$highlight-subtle;
- }
-}
-
-.customTrigger {
- // Override default trigger styles
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
- padding: cssUtils.$space-m cssUtils.$space-xl;
- font-size: 1.1rem;
- font-weight: 700;
- border: none;
-
- &:hover {
- background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
- transform: translateY(-4px);
- box-shadow: cssUtils.$shadow-3xl;
- }
-}
diff --git a/packages/react-ui/src/components/BottomTray/thread.scss b/packages/react-ui/src/components/BottomTray/thread.scss
deleted file mode 100644
index bf55597f1..000000000
--- a/packages/react-ui/src/components/BottomTray/thread.scss
+++ /dev/null
@@ -1,129 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-bottom-tray-thread-container {
- display: flex;
- flex: 1;
- overflow: hidden;
- flex-direction: column;
- position: relative;
-}
-
-// Hide conversation starters while the user is drafting in the composer.
-// The drafting flag is set on the composer root via `data-drafting`.
-.openui-bottom-tray-thread-container:has([data-drafting]) {
- .openui-bottom-tray-conversation-starter {
- opacity: 0;
- pointer-events: none;
- }
-}
-
-.openui-bottom-tray-conversation-starter {
- transition: opacity 150ms ease;
-}
-
-.openui-bottom-tray-thread-scroll-container {
- width: 100%;
- flex: 1;
- position: relative;
- overflow: hidden;
-
- &::before {
- content: "";
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- height: cssUtils.$space-xl;
- background: linear-gradient(to bottom, cssUtils.$background 0%, transparent 100%);
- pointer-events: none;
- z-index: 1;
- }
-
- &::after {
- content: "";
- position: absolute;
- left: 0;
- right: 0;
- bottom: 0;
- height: cssUtils.$space-xl;
- background: linear-gradient(to top, cssUtils.$background 0%, transparent 100%);
- pointer-events: none;
- z-index: 1;
- }
-}
-
-.openui-bottom-tray-thread-scroll-area {
- width: 100%;
- height: 100%;
- overflow: auto;
- padding: cssUtils.$space-m;
- scroll-padding-top: calc(cssUtils.$space-m + cssUtils.$space-xs);
- scrollbar-width: thin;
- scrollbar-color: cssUtils.$highlight-strong transparent;
-
- &::-webkit-scrollbar {
- width: cssUtils.$space-xs;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background-color: cssUtils.$highlight-strong;
- border-radius: cssUtils.$radius-full;
-
- &:hover {
- background-color: cssUtils.$highlight-intense;
- }
- }
-
- &--user-message-anchor {
- & .openui-bottom-tray-thread-messages > *:last-child {
- min-height: calc(-200px + 100dvh);
- }
- }
-}
-
-.openui-bottom-tray-thread-messages {
- margin: 0 auto;
- padding-top: cssUtils.$space-s;
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-xl;
-}
-
-.openui-bottom-tray-thread-message-assistant {
- width: 100%;
- overflow: hidden;
-
- &__content {
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-s;
- overflow: hidden;
- overflow-wrap: break-word;
- flex-grow: 1;
- }
-
- &__text {
- @include cssUtils.typography(primary, default);
- color: cssUtils.$text-neutral-primary;
- }
-}
-
-.openui-bottom-tray-thread-message-user {
- display: flex;
- justify-content: flex-end;
-
- &__content {
- @include cssUtils.typography(primary, default);
- padding: cssUtils.$space-s cssUtils.$space-m;
- background-color: cssUtils.$chat-user-response-bg;
- color: cssUtils.$chat-user-response-text;
- border-radius: cssUtils.$radius-xl;
- overflow-wrap: break-word;
- max-width: 100%;
- height: fit-content;
- }
-}
diff --git a/packages/react-ui/src/components/BottomTray/threadList.scss b/packages/react-ui/src/components/BottomTray/threadList.scss
deleted file mode 100644
index fd576ddeb..000000000
--- a/packages/react-ui/src/components/BottomTray/threadList.scss
+++ /dev/null
@@ -1,145 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-// Thread List Dropdown
-.openui-bottom-tray-thread-list-dropdown {
- display: flex;
- flex-direction: column;
- min-width: 240px;
- max-width: 320px;
- max-height: 296px;
- padding: cssUtils.$space-xs;
- border: 1px solid cssUtils.$border-default;
- border-radius: cssUtils.$radius-2xl;
- background-color: cssUtils.$foreground;
- box-shadow: cssUtils.$shadow-l;
- z-index: 9999;
- overflow: hidden;
-}
-
-.openui-bottom-tray-thread-list-header {
- @include cssUtils.typography(label, small);
- color: cssUtils.$text-neutral-tertiary;
- padding: cssUtils.$space-xs cssUtils.$space-s;
- padding-bottom: cssUtils.$space-s;
-}
-
-.openui-bottom-tray-thread-list-items {
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-3xs;
- overflow-y: auto;
-}
-
-.openui-bottom-tray-thread-list-empty {
- @include cssUtils.typography(body, small);
- color: cssUtils.$text-neutral-secondary;
- padding: cssUtils.$space-m;
- text-align: center;
-}
-
-.openui-bottom-tray-thread-list-trigger {
- &[data-state="open"],
- &[aria-expanded="true"] {
- background-color: cssUtils.$highlight;
- border-color: cssUtils.$border-interactive;
- }
-}
-
-// Thread Item
-.openui-bottom-tray-thread-item {
- display: flex;
- align-items: center;
- justify-content: space-between;
- width: 100%;
- border-radius: calc(cssUtils.$radius-s + 1px);
- border: 1px solid transparent;
- transition: all 0.12s ease;
-
- &--selected {
- background-color: cssUtils.$highlight;
- }
-
- &:hover {
- background-color: cssUtils.$highlight;
-
- .openui-bottom-tray-thread-item-menu-trigger {
- opacity: 1;
- }
- }
-
- &:has(.openui-bottom-tray-thread-item-menu-trigger[data-state="open"]) {
- background-color: cssUtils.$highlight;
-
- .openui-bottom-tray-thread-item-menu-trigger {
- opacity: 1;
- }
- }
-}
-
-.openui-bottom-tray-thread-item-title {
- @include cssUtils.button-reset;
- @include cssUtils.typography(body, small);
- color: cssUtils.$text-neutral-primary;
- padding: calc(cssUtils.$space-xs - 1.75px) cssUtils.$space-s;
- width: 100%;
- text-align: left;
- cursor: pointer;
- white-space: nowrap;
- text-overflow: ellipsis;
- overflow: hidden;
-}
-
-.openui-bottom-tray-thread-item-menu-trigger {
- opacity: 0;
-
- &:focus-visible {
- opacity: 1;
- }
-
- &[data-state="open"] {
- opacity: 1;
- background-color: cssUtils.$highlight;
- border-color: cssUtils.$border-interactive;
- }
-}
-
-.openui-bottom-tray-thread-item-menu {
- box-sizing: border-box;
- position: relative;
- z-index: 99999;
- min-width: 160px;
- overflow: hidden;
- border: 1px solid cssUtils.$border-default;
- border-radius: cssUtils.$radius-xl;
- background-color: cssUtils.$foreground;
- box-shadow: cssUtils.$shadow-m;
- color: cssUtils.$text-neutral-primary;
- transform-origin: top center;
- animation: openui-bottom-tray-thread-menu-show 0.18s ease-out forwards;
- padding: 4px;
-}
-
-.openui-bottom-tray-thread-item-menu-action {
- width: 100%;
- justify-content: flex-start;
- padding-left: cssUtils.$space-s;
- padding-right: cssUtils.$space-s;
-
- &:focus,
- &:focus-visible {
- outline: none;
- box-shadow: none;
- }
-}
-
-@keyframes openui-bottom-tray-thread-menu-show {
- from {
- opacity: 0;
- transform: scale(0.95);
- }
-
- to {
- opacity: 1;
- transform: scale(1);
- }
-}
diff --git a/packages/react-ui/src/components/BottomTray/trigger.scss b/packages/react-ui/src/components/BottomTray/trigger.scss
deleted file mode 100644
index 196d56d03..000000000
--- a/packages/react-ui/src/components/BottomTray/trigger.scss
+++ /dev/null
@@ -1,47 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-bottom-tray-trigger {
- position: fixed;
- bottom: cssUtils.$space-l;
- right: cssUtils.$space-l;
- display: flex;
- align-items: center;
- justify-content: center;
- width: 56px;
- height: 56px;
- border-radius: cssUtils.$radius-full;
- background: cssUtils.$inverted-background;
- color: cssUtils.$text-accent-primary;
- box-shadow: cssUtils.$shadow-xl;
- cursor: pointer;
- transition: all 0.1s ease;
- z-index: 1000;
- overflow: hidden;
-
- &:hover {
- background: cssUtils.$interactive-accent-hover;
- box-shadow: cssUtils.$shadow-2xl;
- transform: translateY(-2px);
- }
-
- &:active {
- transform: translateY(0);
- scale: 0.95;
- }
-
- // Desktop open state - shrink the trigger
- &--open {
- transform: scale(0.85);
- }
-
- // Mobile
- @media (max-width: 768px) {
- bottom: cssUtils.$space-m;
- right: cssUtils.$space-m;
-
- // Hide trigger on mobile when tray is open (tray goes fullscreen)
- &--open {
- display: none;
- }
- }
-}
diff --git a/packages/react-ui/src/components/BottomTray/welcomeScreen.scss b/packages/react-ui/src/components/BottomTray/welcomeScreen.scss
deleted file mode 100644
index e679c3988..000000000
--- a/packages/react-ui/src/components/BottomTray/welcomeScreen.scss
+++ /dev/null
@@ -1,50 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-bottom-tray-welcome-screen {
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-xl;
- height: 100%;
- justify-content: center;
- align-items: center;
-
- // Image container - minimal wrapper, styling handled by consumer
- &__image-container {
- display: flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- }
-
- // Default image styles when using { url: string }
- &__image {
- width: 64px;
- height: 64px;
- object-fit: cover;
- border-radius: cssUtils.$radius-xl;
- }
-
- // Content container (title + description)
- &__content {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: cssUtils.$space-s;
- text-align: center;
- }
-
- // Title/greeting text
- &__title {
- @include cssUtils.typography(heading, medium);
- color: cssUtils.$text-neutral-primary;
- margin: 0;
- }
-
- // Description text
- &__description {
- @include cssUtils.typography(body, small);
- color: cssUtils.$text-neutral-secondary;
- margin: 0;
- max-width: 280px;
- }
-}
diff --git a/packages/react-ui/src/components/CopilotShell/Container.tsx b/packages/react-ui/src/components/CopilotShell/Container.tsx
deleted file mode 100644
index 89c8885a6..000000000
--- a/packages/react-ui/src/components/CopilotShell/Container.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import clsx from "clsx";
-import { LayoutContextProvider } from "../../context/LayoutContext";
-import { ShellStoreProvider } from "../_shared/store";
-
-interface ContainerProps {
- children?: React.ReactNode;
- logoUrl: string;
- agentName: string;
- className?: string;
- showAssistantLogo?: boolean;
-}
-
-export const Container = ({
- children,
- logoUrl,
- agentName,
- className,
- showAssistantLogo = false,
-}: ContainerProps) => {
- return (
- <ShellStoreProvider
- logoUrl={logoUrl}
- agentName={agentName}
- showAssistantLogo={showAssistantLogo}
- >
- <LayoutContextProvider layout="tray">
- <div className={clsx("openui-copilot-shell-container", className)}>{children}</div>
- </LayoutContextProvider>
- </ShellStoreProvider>
- );
-};
diff --git a/packages/react-ui/src/components/CopilotShell/ConversationStarter.tsx b/packages/react-ui/src/components/CopilotShell/ConversationStarter.tsx
deleted file mode 100644
index 1d229a42b..000000000
--- a/packages/react-ui/src/components/CopilotShell/ConversationStarter.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-import { useThread } from "@openuidev/react-headless";
-import clsx from "clsx";
-import { ArrowUp, Lightbulb } from "lucide-react";
-import { Fragment, ReactNode, isValidElement } from "react";
-import { ConversationStarterIcon, ConversationStarterProps } from "../../types/ConversationStarter";
-import { Carousel, CarouselContent } from "../Carousel";
-import { isChatEmpty } from "../_shared/utils";
-
-export type ConversationStarterVariant = "short" | "long";
-
-interface ConversationStarterItemProps extends ConversationStarterProps {
- onClick: (prompt: string) => void;
- variant: ConversationStarterVariant;
-}
-
-/**
- * Renders the appropriate icon based on the icon prop value
- * - undefined: Show default lightbulb icon
- * - ReactNode: Show the provided icon (use <></> or React.Fragment for no icon)
- */
-const renderIcon = (icon: ConversationStarterIcon | undefined): ReactNode => {
- if (icon === undefined) {
- return <Lightbulb size={16} />;
- }
- return icon;
-};
-
-const hasRenderableIcon = (icon: ReactNode): boolean => {
- if (icon === null || icon === undefined || icon === false) {
- return false;
- }
-
- if (isValidElement<{ children?: ReactNode }>(icon) && icon.type === Fragment) {
- return Boolean(icon.props.children);
- }
-
- return true;
-};
-
-const ConversationStarterItem = ({
- displayText,
- prompt,
- onClick,
- variant,
- icon,
-}: ConversationStarterItemProps) => {
- const renderedIcon = renderIcon(icon);
- const shouldRenderIcon = hasRenderableIcon(renderedIcon);
-
- if (variant === "short") {
- return (
- <button
- type="button"
- className="openui-copilot-shell-conversation-starter-item-short"
- onClick={() => onClick(prompt)}
- >
- {shouldRenderIcon && (
- <span className="openui-copilot-shell-conversation-starter-item-short__icon">
- {renderedIcon}
- </span>
- )}
- <span className="openui-copilot-shell-conversation-starter-item-short__text">
- {displayText}
- </span>
- </button>
- );
- }
-
- // Long variant (detailed list style)
- return (
- <button
- type="button"
- className="openui-copilot-shell-conversation-starter-item-long"
- onClick={() => onClick(prompt)}
- >
- <div className="openui-copilot-shell-conversation-starter-item-long__content">
- {shouldRenderIcon && (
- <span className="openui-copilot-shell-conversation-starter-item-long__icon">
- {renderedIcon}
- </span>
- )}
- <span className="openui-copilot-shell-conversation-starter-item-long__text">
- {displayText}
- </span>
- </div>
- <span className="openui-copilot-shell-conversation-starter-item-long__arrow">
- <ArrowUp size={16} />
- </span>
- </button>
- );
-};
-
-export interface ConversationStarterContainerProps {
- starters: ConversationStarterProps[];
- className?: string;
- /**
- * Variant of the conversation starter
- * - "short": Pill-style horizontal buttons (default)
- * - "long": List items with icons and hover arrow
- */
- variant?: ConversationStarterVariant;
-}
-
-export const ConversationStarter = ({
- starters,
- className,
- variant = "short",
-}: ConversationStarterContainerProps) => {
- const processMessage = useThread((s) => s.processMessage);
- const isRunning = useThread((s) => s.isRunning);
- const messages = useThread((s) => s.messages);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- const handleClick = (prompt: string) => {
- if (isRunning) return;
- processMessage({
- role: "user",
- content: prompt,
- });
- };
-
- // Only show when there are no messages
- if (!isChatEmpty({ isLoadingMessages, messages })) {
- return null;
- }
-
- if (starters.length === 0) {
- return null;
- }
-
- if (variant === "short") {
- return (
- <Carousel
- showButtons={false}
- className={clsx(
- "openui-copilot-shell-conversation-starter",
- "openui-copilot-shell-conversation-starter--short",
- className,
- )}
- >
- <CarouselContent className="openui-copilot-shell-conversation-starter__carousel-content">
- {starters.map((item, index) => (
- <ConversationStarterItem
- key={`${item.displayText}-${index}`}
- displayText={item.displayText}
- prompt={item.prompt}
- icon={item.icon}
- onClick={handleClick}
- variant={variant}
- />
- ))}
- </CarouselContent>
- </Carousel>
- );
- }
-
- return (
- <div
- className={clsx(
- "openui-copilot-shell-conversation-starter",
- `openui-copilot-shell-conversation-starter--${variant}`,
- className,
- )}
- >
- {starters.map((item, index) => (
- <Fragment key={`${item.displayText}-${index}`}>
- <ConversationStarterItem
- displayText={item.displayText}
- prompt={item.prompt}
- icon={item.icon}
- onClick={handleClick}
- variant={variant}
- />
- </Fragment>
- ))}
- </div>
- );
-};
-
-export default ConversationStarter;
diff --git a/packages/react-ui/src/components/CopilotShell/Header.tsx b/packages/react-ui/src/components/CopilotShell/Header.tsx
deleted file mode 100644
index 469fe6e04..000000000
--- a/packages/react-ui/src/components/CopilotShell/Header.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { useThreadList } from "@openuidev/react-headless";
-import clsx from "clsx";
-import { SquarePen } from "lucide-react";
-import { ReactNode } from "react";
-import { IconButton } from "../IconButton";
-import { useShellStore } from "../_shared/store";
-import { ThreadListContainer } from "./ThreadListContainer";
-
-export const CopilotNewChatButton = () => {
- const switchToNewThread = useThreadList((s) => s.switchToNewThread);
-
- return (
- <IconButton
- icon={<SquarePen size="1em" />}
- onClick={switchToNewThread}
- variant="tertiary"
- aria-label="New chat"
- className="openui-copilot-shell-header-new-chat-button"
- />
- );
-};
-
-interface HeaderProps {
- className?: string;
- /** Custom content to render on the rightmost side of the logo container */
- rightChildren?: ReactNode;
- /** Hide the new chat button */
- hideNewChatButton?: boolean;
- /** Hide the thread list container */
- hideThreadListContainer?: boolean;
-}
-
-export const Header = ({
- className,
- rightChildren,
- hideNewChatButton = false,
- hideThreadListContainer = false,
-}: HeaderProps) => {
- const { logoUrl, agentName } = useShellStore((state) => ({
- logoUrl: state.logoUrl,
- agentName: state.agentName,
- }));
-
- const shouldRenderActions = rightChildren || !hideThreadListContainer || !hideNewChatButton;
-
- return (
- <div className={clsx("openui-copilot-shell-header", className)}>
- <div className="openui-copilot-shell-header-logo-container">
- <img className="openui-copilot-shell-header-logo" src={logoUrl} alt="Logo" />
- <span className="openui-copilot-shell-header-agent-name">{agentName}</span>
- </div>
- {shouldRenderActions && (
- <div className="openui-copilot-shell-header-actions">
- {rightChildren}
- {!hideThreadListContainer && <ThreadListContainer />}
- {!hideNewChatButton && <CopilotNewChatButton />}
- </div>
- )}
- </div>
- );
-};
diff --git a/packages/react-ui/src/components/CopilotShell/Thread.tsx b/packages/react-ui/src/components/CopilotShell/Thread.tsx
deleted file mode 100644
index ffc103890..000000000
--- a/packages/react-ui/src/components/CopilotShell/Thread.tsx
+++ /dev/null
@@ -1,287 +0,0 @@
-import type { AssistantMessage, Message, ToolMessage } from "@openuidev/react-headless";
-import { MessageProvider, useThread } from "@openuidev/react-headless";
-import clsx from "clsx";
-import React, { memo, useRef } from "react";
-import { ScrollVariant, useScrollToBottom } from "../../hooks/useScrollToBottom";
-import { ArtifactOverlay } from "../_shared/artifact";
-import { useShellStore } from "../_shared/store";
-import type { AssistantMessageComponent, UserMessageComponent } from "../_shared/types";
-import { MarkDownRenderer } from "../MarkDownRenderer";
-import { MessageLoading as MessageLoadingComponent } from "../MessageLoading";
-import { ToolCallComponent } from "../ToolCall";
-import { ToolResult } from "../ToolResult";
-
-export const ThreadContainer = ({
- children,
- className,
-}: {
- children?: React.ReactNode;
- className?: string;
-}) => {
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- return (
- <div
- className={clsx("openui-copilot-shell-thread-container", className)}
- style={{
- visibility: isLoadingMessages ? "hidden" : undefined,
- }}
- >
- {children}
- <ArtifactOverlay />
- </div>
- );
-};
-
-export const ScrollArea = ({
- children,
- className,
- scrollVariant = "user-message-anchor",
- userMessageSelector = ".openui-copilot-shell-thread-message-user",
-}: {
- children?: React.ReactNode;
- className?: string;
- /**
- * Scroll to bottom once the last message is added
- */
- scrollVariant?: ScrollVariant;
- /**
- * Selector for the user message
- */
- userMessageSelector?: string;
-}) => {
- const ref = useRef<HTMLDivElement>(null);
-
- const messages = useThread((s) => s.messages);
- const isRunning = useThread((s) => s.isRunning);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- useScrollToBottom({
- ref,
- lastMessage: messages[messages.length - 1] || { id: "" },
- scrollVariant,
- userMessageSelector,
- isRunning,
- isLoadingMessages,
- });
-
- return (
- <div className="openui-copilot-shell-thread-scroll-container">
- <div
- ref={ref}
- className={clsx(
- "openui-copilot-shell-thread-scroll-area",
- {
- "openui-copilot-shell-thread-scroll-area--user-message-anchor":
- scrollVariant === "user-message-anchor",
- },
- className,
- )}
- >
- {children}
- </div>
- </div>
- );
-};
-
-export const AssistantMessageContainer = ({
- children,
- className,
-}: {
- children?: React.ReactNode;
- className?: string;
-}) => {
- const { logoUrl, showAssistantLogo } = useShellStore((store) => ({
- logoUrl: store.logoUrl,
- showAssistantLogo: store.showAssistantLogo,
- }));
-
- return (
- <div className={clsx("openui-copilot-shell-thread-message-assistant", className)}>
- {showAssistantLogo && (
- <img
- src={logoUrl}
- alt="Assistant"
- className="openui-copilot-shell-thread-message-assistant__logo"
- />
- )}
- <div className="openui-copilot-shell-thread-message-assistant__content">{children}</div>
- </div>
- );
-};
-
-export const UserMessageContainer = ({
- children,
- className,
-}: {
- children?: React.ReactNode;
- className?: string;
-}) => {
- return (
- <div className={clsx("openui-copilot-shell-thread-message-user", className)}>
- <div className="openui-copilot-shell-thread-message-user__content">{children}</div>
- </div>
- );
-};
-
-const AssistantMessageContent = ({
- message,
- allMessages,
-}: {
- message: AssistantMessage;
- allMessages: Message[];
-}) => {
- const getToolName = (toolCallId: string) => {
- const toolCall = message.toolCalls?.find((tc) => tc.id === toolCallId);
- return toolCall?.function.name;
- };
-
- const toolMessages: ToolMessage[] = [];
- const msgIndex = allMessages.findIndex((m) => m.id === message.id);
- if (msgIndex !== -1) {
- for (let i = msgIndex + 1; i < allMessages.length; i++) {
- const m = allMessages[i];
- if (m && m.role === "tool") {
- toolMessages.push(m as ToolMessage);
- } else {
- break;
- }
- }
- }
-
- return (
- <>
- {message.content && (
- <MarkDownRenderer
- textMarkdown={message.content}
- className="openui-copilot-shell-thread-message-assistant__text"
- />
- )}
- {message.toolCalls?.map((toolCall) => (
- <ToolCallComponent key={toolCall.id} toolCall={toolCall} />
- ))}
- {toolMessages.map((tm) => (
- <ToolResult key={tm.id} message={tm} toolName={getToolName(tm.toolCallId)} />
- ))}
- </>
- );
-};
-
-const UserMessageContent = ({ message }: { message: Message }) => {
- if (message.role !== "user") return null;
- const content = message.content;
- if (typeof content === "string") {
- return <>{content}</>;
- }
- return (
- <>
- {content?.map((part, i) => {
- if (part.type === "text") {
- return <span key={i}>{part.text}</span>;
- }
- if (part.type === "binary" && part.url) {
- return (
- <img
- key={i}
- src={part.url}
- alt=""
- className="openui-copilot-shell-thread-message-user__image"
- />
- );
- }
- return null;
- })}
- </>
- );
-};
-
-export const RenderMessage = memo(
- ({
- message,
- className,
- allMessages,
- assistantMessage: CustomAssistantMessage,
- userMessage: CustomUserMessage,
- isStreaming,
- }: {
- message: Message;
- className?: string;
- allMessages: Message[];
- assistantMessage?: AssistantMessageComponent;
- userMessage?: UserMessageComponent;
- isStreaming: boolean;
- }) => {
- if (message.role === "tool") {
- return null;
- }
-
- if (message.role === "assistant") {
- if (CustomAssistantMessage) {
- return <CustomAssistantMessage message={message} isStreaming={isStreaming} />;
- }
- return (
- <AssistantMessageContainer className={className}>
- <AssistantMessageContent message={message} allMessages={allMessages} />
- </AssistantMessageContainer>
- );
- }
-
- if (message.role === "user") {
- if (CustomUserMessage) {
- return <CustomUserMessage message={message} />;
- }
- return (
- <UserMessageContainer className={className}>
- <UserMessageContent message={message} />
- </UserMessageContainer>
- );
- }
-
- return null;
- },
-);
-
-export const MessageLoading = () => {
- return (
- <div className="openui-copilot-shell-thread-message-loading">
- <MessageLoadingComponent />
- </div>
- );
-};
-
-export const Messages = ({
- className,
- loader,
- assistantMessage,
- userMessage,
-}: {
- className?: string;
- loader?: React.ReactNode;
- assistantMessage?: AssistantMessageComponent;
- userMessage?: UserMessageComponent;
-}) => {
- const messages = useThread((s) => s.messages);
- const isRunning = useThread((s) => s.isRunning);
-
- return (
- <div className={clsx("openui-copilot-shell-thread-messages", className)}>
- {messages.map((message, i) => {
- return (
- <MessageProvider key={message.id} message={message}>
- <RenderMessage
- message={message}
- allMessages={messages}
- assistantMessage={assistantMessage}
- userMessage={userMessage}
- isStreaming={isRunning && i === messages.length - 1}
- />
- </MessageProvider>
- );
- })}
- {isRunning && <div>{loader}</div>}
- </div>
- );
-};
-
-// Re-export Composer from components
-export { Composer } from "./components";
diff --git a/packages/react-ui/src/components/CopilotShell/ThreadListContainer.tsx b/packages/react-ui/src/components/CopilotShell/ThreadListContainer.tsx
deleted file mode 100644
index 5cd903695..000000000
--- a/packages/react-ui/src/components/CopilotShell/ThreadListContainer.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import { useThreadList } from "@openuidev/react-headless";
-import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
-import clsx from "clsx";
-import { EllipsisVerticalIcon, MenuIcon, Trash2Icon } from "lucide-react";
-import { useEffect } from "react";
-import { Button } from "../Button";
-import { IconButton } from "../IconButton";
-import { useTheme } from "../ThemeProvider";
-
-const ThreadItem = ({
- title,
- isSelected,
- onSelect,
- onDelete,
-}: {
- title: string;
- isSelected: boolean;
- onSelect: () => void;
- onDelete: () => void;
-}) => {
- const { portalThemeClassName } = useTheme();
- return (
- <div
- className={clsx("openui-copilot-shell-thread-item", {
- "openui-copilot-shell-thread-item--selected": isSelected,
- })}
- >
- <button className="openui-copilot-shell-thread-item-title" onClick={onSelect}>
- {title}
- </button>
- <DropdownMenu.Root>
- <DropdownMenu.Trigger asChild>
- <IconButton
- icon={<EllipsisVerticalIcon size="1em" />}
- aria-label={`More actions for ${title}`}
- variant="tertiary"
- size="extra-small"
- className="openui-copilot-shell-thread-item-menu-trigger"
- />
- </DropdownMenu.Trigger>
- <DropdownMenu.Portal>
- <DropdownMenu.Content
- className={clsx("openui-copilot-shell-thread-item-menu", portalThemeClassName)}
- side="right"
- align="start"
- sideOffset={4}
- >
- <DropdownMenu.Item
- asChild
- onSelect={(e) => {
- e.stopPropagation();
- onDelete();
- }}
- >
- <Button
- type="button"
- variant="tertiary"
- buttonType="destructive"
- size="small"
- iconLeft={<Trash2Icon size={14} />}
- className="openui-copilot-shell-thread-item-menu-action"
- >
- Delete
- </Button>
- </DropdownMenu.Item>
- </DropdownMenu.Content>
- </DropdownMenu.Portal>
- </DropdownMenu.Root>
- </div>
- );
-};
-
-export const ThreadListContainer = () => {
- const threads = useThreadList((s) => s.threads);
- const selectedThreadId = useThreadList((s) => s.selectedThreadId);
- const loadThreads = useThreadList((s) => s.loadThreads);
- const selectThread = useThreadList((s) => s.selectThread);
- const deleteThread = useThreadList((s) => s.deleteThread);
- const { portalThemeClassName } = useTheme();
-
- useEffect(() => {
- loadThreads();
- }, [loadThreads]);
-
- return (
- <DropdownMenu.Root>
- <DropdownMenu.Trigger asChild>
- <IconButton
- icon={<MenuIcon size="1em" />}
- variant="tertiary"
- aria-label="Thread list"
- className="openui-copilot-shell-thread-list-trigger"
- />
- </DropdownMenu.Trigger>
- <DropdownMenu.Portal>
- <DropdownMenu.Content
- className={clsx("openui-copilot-shell-thread-list-dropdown", portalThemeClassName)}
- side="bottom"
- align="end"
- sideOffset={8}
- >
- <div className="openui-copilot-shell-thread-list-header">All threads</div>
- <div className="openui-copilot-shell-thread-list-items">
- {threads.map((thread) => (
- <ThreadItem
- key={thread.id}
- title={thread.title}
- isSelected={selectedThreadId === thread.id}
- onSelect={() => selectThread(thread.id)}
- onDelete={() => deleteThread(thread.id)}
- />
- ))}
- {threads.length === 0 && (
- <div className="openui-copilot-shell-thread-list-empty">No threads yet</div>
- )}
- </div>
- </DropdownMenu.Content>
- </DropdownMenu.Portal>
- </DropdownMenu.Root>
- );
-};
diff --git a/packages/react-ui/src/components/CopilotShell/WelcomeScreen.tsx b/packages/react-ui/src/components/CopilotShell/WelcomeScreen.tsx
deleted file mode 100644
index 9fc19c133..000000000
--- a/packages/react-ui/src/components/CopilotShell/WelcomeScreen.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-import { useThread } from "@openuidev/react-headless";
-import clsx from "clsx";
-import { ReactNode } from "react";
-import { isChatEmpty } from "../_shared/utils";
-
-interface WelcomeScreenBaseProps {
- /**
- * Additional CSS class name
- */
- className?: string;
-}
-
-interface WelcomeScreenWithContentProps extends WelcomeScreenBaseProps {
- /**
- * The greeting/title text to display
- */
- title?: string;
- /**
- * Optional description text to add more context
- */
- description?: string;
- /**
- * Image to display - can be a URL object or a ReactNode
- * - { url: string }: Renders an <img> tag with default styling (64x64, object-fit: cover, rounded)
- * - ReactNode: Renders the provided element directly (for custom icons, styled images, etc.)
- */
- image?: { url: string } | ReactNode;
- /**
- * Children are not allowed when using props-based content
- */
- children?: never;
-}
-
-interface WelcomeScreenWithChildrenProps extends WelcomeScreenBaseProps {
- /**
- * Custom content to render inside the welcome screen
- * When children are provided, title, description, and image are ignored
- */
- children: ReactNode;
- title?: never;
- description?: never;
- image?: never;
-}
-
-export type WelcomeScreenProps = WelcomeScreenWithContentProps | WelcomeScreenWithChildrenProps;
-
-/**
- * Type guard to check if image is a URL object
- */
-const isImageUrl = (image: { url: string } | ReactNode): image is { url: string } => {
- return typeof image === "object" && image !== null && "url" in image;
-};
-
-export const WelcomeScreen = (props: WelcomeScreenProps) => {
- const { className } = props;
-
- const messages = useThread((s) => s.messages);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- // Only show when there are no messages
- if (!isChatEmpty({ isLoadingMessages, messages })) {
- return null;
- }
-
- // Check if children are provided
- if ("children" in props && props.children) {
- return (
- <div className={clsx("openui-copilot-shell-welcome-screen", className)}>{props.children}</div>
- );
- }
-
- // Props-based content
- const { title, description, image } = props as WelcomeScreenWithContentProps;
-
- const renderImage = () => {
- if (!image) return null;
-
- if (isImageUrl(image)) {
- return (
- <img
- src={image.url}
- alt={title || ""}
- className="openui-copilot-shell-welcome-screen__image"
- />
- );
- }
-
- return image;
- };
-
- return (
- <div className={clsx("openui-copilot-shell-welcome-screen", className)}>
- {image && (
- <div className="openui-copilot-shell-welcome-screen__image-container">{renderImage()}</div>
- )}
- {(title || description) && (
- <div className="openui-copilot-shell-welcome-screen__content">
- {title && <h2 className="openui-copilot-shell-welcome-screen__title">{title}</h2>}
- {description && (
- <p className="openui-copilot-shell-welcome-screen__description">{description}</p>
- )}
- </div>
- )}
- </div>
- );
-};
-
-export default WelcomeScreen;
diff --git a/packages/react-ui/src/components/CopilotShell/components/Composer.tsx b/packages/react-ui/src/components/CopilotShell/components/Composer.tsx
deleted file mode 100644
index 578d152bc..000000000
--- a/packages/react-ui/src/components/CopilotShell/components/Composer.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import { useThread } from "@openuidev/react-headless";
-import clsx from "clsx";
-import { ArrowUp, Square } from "lucide-react";
-import { useLayoutEffect, useRef } from "react";
-import { useComposerState } from "../../../hooks/useComposerState";
-import { IconButton } from "../../IconButton";
-
-export interface ComposerProps {
- className?: string;
- placeholder?: string;
-}
-
-export const Composer = ({ className, placeholder = "Type your message..." }: ComposerProps) => {
- const { textContent, setTextContent } = useComposerState();
- const processMessage = useThread((s) => s.processMessage);
- const cancelMessage = useThread((s) => s.cancelMessage);
- const isRunning = useThread((s) => s.isRunning);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
- const inputRef = useRef<HTMLTextAreaElement>(null);
-
- const handleSubmit = () => {
- if (!textContent.trim() || isRunning || isLoadingMessages) {
- return;
- }
-
- processMessage({
- role: "user",
- content: textContent,
- });
-
- setTextContent("");
- };
-
- useLayoutEffect(() => {
- const input = inputRef.current;
- if (!input) return;
-
- // Reset to 0 (not "auto") so scrollHeight reflects content, not container
- input.style.height = "0px";
- input.style.height = `${Math.max(input.scrollHeight, 24)}px`;
- }, [textContent]);
-
- return (
- <div
- className={clsx("openui-copilot-shell-thread-composer", className)}
- data-drafting={textContent.length > 0 || undefined}
- onClick={(e) => {
- if (!(e.target as HTMLElement).closest("button, a, [role='button']")) {
- inputRef.current?.focus();
- }
- }}
- >
- <div className="openui-copilot-shell-thread-composer__input-wrapper">
- <textarea
- ref={inputRef}
- value={textContent}
- onChange={(e) => setTextContent(e.target.value)}
- className="openui-copilot-shell-thread-composer__input"
- placeholder={placeholder}
- rows={1}
- onKeyDown={(e) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- handleSubmit();
- }
- }}
- />
- <div className="openui-copilot-shell-thread-composer__action-bar">
- <IconButton
- onClick={isRunning ? cancelMessage : handleSubmit}
- icon={isRunning ? <Square size="1em" fill="currentColor" /> : <ArrowUp size="1em" />}
- size="extra-small"
- variant="primary"
- aria-label={isRunning ? "Cancel message" : "Send message"}
- className="openui-copilot-shell-thread-composer__submit-button"
- />
- </div>
- </div>
- </div>
- );
-};
-
-export default Composer;
diff --git a/packages/react-ui/src/components/CopilotShell/components/composer.scss b/packages/react-ui/src/components/CopilotShell/components/composer.scss
deleted file mode 100644
index e79da538d..000000000
--- a/packages/react-ui/src/components/CopilotShell/components/composer.scss
+++ /dev/null
@@ -1,62 +0,0 @@
-@use "../../../cssUtils" as cssUtils;
-
-.openui-copilot-shell-thread-composer {
- box-sizing: border-box;
- flex-shrink: 0;
- width: 100%;
- margin: 0 0 cssUtils.$space-m;
- padding: 0 cssUtils.$space-m;
-
- &__input-wrapper {
- background-color: cssUtils.$foreground;
- border: 1px solid cssUtils.$border-interactive;
- border-radius: cssUtils.$radius-3xl;
- box-shadow: cssUtils.$shadow-m;
- overflow: clip;
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-s;
- padding: cssUtils.$space-s-m;
- }
-
- &__input {
- scrollbar-width: thin;
- scrollbar-color: cssUtils.$elevated transparent;
-
- &::-webkit-scrollbar {
- width: 6px;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background-color: cssUtils.$elevated;
- border-radius: cssUtils.$radius-full;
- }
-
- padding: 0 cssUtils.$space-3xs;
- resize: none;
- max-height: 200px;
- outline: none;
- border: none;
- background: transparent;
- overflow-y: auto;
- @include cssUtils.typography(body, default);
- color: cssUtils.$text-neutral-primary;
-
- &::placeholder {
- color: cssUtils.$text-neutral-secondary;
- }
- }
-
- &__action-bar {
- display: flex;
- align-items: center;
- }
-
- &__submit-button {
- margin-left: auto;
- }
-}
diff --git a/packages/react-ui/src/components/CopilotShell/components/index.ts b/packages/react-ui/src/components/CopilotShell/components/index.ts
deleted file mode 100644
index c054e9045..000000000
--- a/packages/react-ui/src/components/CopilotShell/components/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { Composer } from "./Composer";
-export type { ComposerProps } from "./Composer";
diff --git a/packages/react-ui/src/components/CopilotShell/conversationStarter.scss b/packages/react-ui/src/components/CopilotShell/conversationStarter.scss
deleted file mode 100644
index c6fb90500..000000000
--- a/packages/react-ui/src/components/CopilotShell/conversationStarter.scss
+++ /dev/null
@@ -1,158 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-// Container styles
-.openui-copilot-shell-conversation-starter {
- display: flex;
- flex-shrink: 0;
- width: 100%;
- padding: 0 cssUtils.$space-m;
- margin-bottom: cssUtils.$space-s;
- box-sizing: border-box;
- max-height: 480px;
- overflow: hidden;
- opacity: 1;
- transform: translateY(0);
- transition:
- opacity 0.2s ease,
- transform 0.2s ease,
- max-height 0.2s ease,
- margin-bottom 0.2s ease;
-
- // Short variant - horizontal pill buttons
- &--short {
- display: block;
- }
-
- // Long variant - vertical list items
- &--long {
- flex-direction: column;
- gap: cssUtils.$space-2xs;
- }
-
- &__carousel-content {
- gap: cssUtils.$space-xs;
- }
-}
-
-// Short variant item (pill-style buttons)
-.openui-copilot-shell-conversation-starter-item-short {
- display: flex;
- align-items: center;
- gap: cssUtils.$space-xs;
- width: fit-content;
- flex: 0 0 auto;
- padding: cssUtils.$space-s cssUtils.$space-s-m;
- background-color: cssUtils.$foreground;
- border: 1px solid cssUtils.$border-interactive;
- border-radius: cssUtils.$radius-l;
- cursor: pointer;
- transition: all 0.15s ease;
- @include cssUtils.typography(body, small);
- color: cssUtils.$text-neutral-primary;
- text-align: left;
-
- // Icon container
- &__icon {
- display: flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- color: cssUtils.$text-neutral-primary;
-
- & > svg {
- width: 14px;
- height: 14px;
- }
- }
-
- // Text
- &__text {
- flex: 1;
- white-space: nowrap;
- }
-
- &:not(:disabled):hover {
- background-color: cssUtils.$highlight;
- border-color: cssUtils.$border-interactive-emphasis;
- }
-
- &:not(:disabled):active {
- background-color: cssUtils.$highlight-subtle;
- }
-
- @media (max-width: 480px) {
- padding: cssUtils.$space-s cssUtils.$space-s-m;
- }
-}
-
-// Long variant item (list-style with icon and arrow)
-.openui-copilot-shell-conversation-starter-item-long {
- display: flex;
- align-items: center;
- gap: cssUtils.$space-000;
- width: 100%;
- padding: cssUtils.$space-xs cssUtils.$space-s-m;
- background-color: transparent;
- border: none;
- border-radius: cssUtils.$radius-l;
- cursor: pointer;
- transition: background-color 0.15s ease;
- @include cssUtils.typography(body, default);
- color: cssUtils.$text-neutral-primary;
- text-align: left;
- overflow: hidden;
-
- // Content wrapper (icon + text)
- &__content {
- display: flex;
- align-items: flex-start;
- gap: cssUtils.$space-xs;
- flex: 1;
- min-width: 0;
- }
-
- // Icon container - aligned to top with padding to align with first line of text
- &__icon {
- display: flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- padding-top: cssUtils.$space-2xs;
- color: cssUtils.$text-neutral-primary;
- }
-
- // Text - allows wrapping for long content
- &__text {
- flex: 1;
- min-width: 0;
- line-height: 1.5;
- // Text wraps naturally, no truncation
- }
-
- // Arrow icon (shown on hover)
- &__arrow {
- display: flex;
- align-self: flex-start;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- padding-top: cssUtils.$space-2xs;
- opacity: 0;
- transition: opacity 0.15s ease;
- color: cssUtils.$text-neutral-primary;
- }
-
- // Hover state
- &:not(:disabled):hover {
- background-color: cssUtils.$sunk;
-
- .openui-copilot-shell-conversation-starter-item-long__arrow {
- opacity: 1;
- }
- }
-
- // Active/pressed state
- &:not(:disabled):active {
- background-color: cssUtils.$highlight-subtle;
- }
-}
diff --git a/packages/react-ui/src/components/CopilotShell/copilotShell.scss b/packages/react-ui/src/components/CopilotShell/copilotShell.scss
deleted file mode 100644
index c77b040f9..000000000
--- a/packages/react-ui/src/components/CopilotShell/copilotShell.scss
+++ /dev/null
@@ -1,24 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-@use "./thread.scss";
-@use "./components/composer.scss";
-@use "./header.scss";
-@use "./conversationStarter.scss";
-@use "./threadList.scss";
-@use "./welcomeScreen.scss";
-
-.openui-copilot-shell-container {
- display: flex;
- position: relative;
- height: 100dvh;
- width: 530px;
- overflow: hidden;
-
- border: 1px solid cssUtils.$border-default;
- border-width: 0 1px;
-
- background: cssUtils.$chat-container-bg;
- box-sizing: border-box;
- & * {
- box-sizing: border-box;
- }
-}
diff --git a/packages/react-ui/src/components/CopilotShell/header.scss b/packages/react-ui/src/components/CopilotShell/header.scss
deleted file mode 100644
index e1cc75a8a..000000000
--- a/packages/react-ui/src/components/CopilotShell/header.scss
+++ /dev/null
@@ -1,32 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-copilot-shell-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: cssUtils.$space-m;
-}
-
-.openui-copilot-shell-header-logo-container {
- display: flex;
- align-items: center;
- gap: cssUtils.$space-s;
-}
-
-.openui-copilot-shell-header-logo {
- width: 32px;
- height: 32px;
- border-radius: cssUtils.$radius-m;
-}
-
-.openui-copilot-shell-header-agent-name {
- @include cssUtils.typography(label, small);
- color: cssUtils.$text-neutral-primary;
-}
-
-.openui-copilot-shell-header-actions,
-.openui-copilot-shell-header-right-content {
- display: flex;
- align-items: center;
- gap: cssUtils.$space-s;
-}
diff --git a/packages/react-ui/src/components/CopilotShell/index.ts b/packages/react-ui/src/components/CopilotShell/index.ts
deleted file mode 100644
index 7c3629b7c..000000000
--- a/packages/react-ui/src/components/CopilotShell/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export * from "./Container";
-export * from "./ConversationStarter";
-export * from "./Header";
-export * from "./Thread";
-export * from "./WelcomeScreen";
diff --git a/packages/react-ui/src/components/CopilotShell/stories/Shell.mdx b/packages/react-ui/src/components/CopilotShell/stories/Shell.mdx
deleted file mode 100644
index e67888c56..000000000
--- a/packages/react-ui/src/components/CopilotShell/stories/Shell.mdx
+++ /dev/null
@@ -1,363 +0,0 @@
-import { Meta } from "@storybook/blocks";
-import * as ShellStories from "./Shell.stories";
-
-<Meta of={ShellStories} />
-
-# CopilotShell
-
-The CopilotShell is a **composable sidebar chat interface** designed to be embedded as a side panel in your application. It uses a composition pattern, giving you full control over placement and styling.
-
-## Component Structure
-
-```
-ChatProvider
-└── Container (sidebar panel)
- └── ThreadContainer
- ├── Header (logo, agent name)
- ├── WelcomeScreen (optional, shown when empty)
- ├── ScrollArea (scrollable message area)
- │ └── Messages
- ├── ConversationStarter (optional, shown when empty)
- └── Composer (text input)
-```
-
-## Basic Usage
-
-```tsx
-import { useState } from "react";
-import { ChatProvider, useThreadListManager, useThreadManager } from "@openuidev/react-headless";
-import {
- Composer,
- Container,
- ConversationStarter,
- Header,
- MessageLoading,
- Messages,
- ScrollArea,
- ThreadContainer,
- WelcomeScreen,
-} from "@openuidev/react-ui/CopilotShell";
-
-function MyCopilot() {
- const threadListManager = useThreadListManager({
- createThread: async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- isRunning: false,
- }),
- fetchThreadList: async () => [],
- deleteThread: async () => {},
- updateThread: async (t) => t,
- onSwitchToNew: () => {},
- onSelectThread: () => {},
- });
-
- const threadManager = useThreadManager({
- threadId: threadListManager.selectedThreadId,
- loadThread: async (threadId) => {
- if (!threadId) return [];
- // Load messages for thread
- return [];
- },
- onProcessMessage: async ({ message, threadManager }) => {
- threadManager.appendMessages({ ...message, id: crypto.randomUUID() });
- // Send message to your AI backend
- // Return assistant response
- return [
- {
- id: crypto.randomUUID(),
- role: "assistant",
- type: "response",
- message: [{ type: "text", text: "Response from AI" }],
- },
- ];
- },
- responseTemplates: [],
- });
-
- const hasMessages = threadManager.messages.length > 0;
-
- return (
- <ChatProvider threadListManager={threadListManager} threadManager={threadManager}>
- <Container logoUrl="/path/to/logo.png" agentName="AI Assistant">
- <ThreadContainer>
- <Header />
-
- {/* WelcomeScreen - shown when no messages */}
- {!hasMessages && (
- <WelcomeScreen
- title="Hi, I'm AI Assistant"
- description="I can help you with your questions."
- image={
- <img
- src="/path/to/logo.png"
- alt="AI Assistant"
- style={{ width: 64, height: 64, borderRadius: 16, objectFit: "cover" }}
- />
- }
- />
- )}
-
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter
- starters={[
- { displayText: "Help me get started", prompt: "Help me get started" },
- { displayText: "What can you do?", prompt: "What can you do?" },
- ]}
- />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- );
-}
-```
-
-## Individual Components
-
-### Container
-
-The main wrapper for the CopilotShell sidebar.
-
-```tsx
-<Container
- logoUrl="/logo.png" // Logo shown in header
- agentName="AI Assistant" // Name shown in header
- className="custom-class" // Optional custom styling
->
- {children}
-</Container>
-```
-
-### ThreadContainer
-
-Wrapper for the thread content with optional artifact panel support.
-
-```tsx
-<ThreadContainer
- isArtifactActive={false} // Show artifact panel
- renderArtifact={() => <div />} // Artifact content
->
- {children}
-</ThreadContainer>
-```
-
-### Header
-
-The header with logo and agent name.
-
-```tsx
-<Header />
-```
-
-### ScrollArea
-
-Scrollable container for messages with smart scroll behavior.
-
-```tsx
-<ScrollArea
- scrollVariant="user-message-anchor" // Scroll behavior
- userMessageSelector=".openui-copilot-shell-thread-message-user" // CSS selector for user messages
->
- <Messages loader={<MessageLoading />} />
-</ScrollArea>
-```
-
-### ConversationStarter
-
-Clickable prompts shown when the thread is empty. Automatically submits the prompt as a message when clicked.
-
-```tsx
-<ConversationStarter
- variant="short" // "short" (pill buttons) or "long" (list items)
- starters={[
- {
- displayText: "Help me get started",
- prompt: "Help me get started",
- icon: <Sparkles size={16} />,
- },
- { displayText: "What can you do?", prompt: "What can you do?" }, // Default lightbulb icon
- { displayText: "No icon example", prompt: "No icon", icon: <></> }, // No icon (use empty fragment)
- ]}
- className="custom-class" // Optional custom styling
-/>
-```
-
-**Props:**
-
-- `variant` - `"short"` (pill-style buttons) or `"long"` (list items with separators)
-- `starters` - Array of objects with:
- - `displayText` - Text shown on the button
- - `prompt` - Message sent when clicked
- - `icon` - Optional: `ReactNode` for custom icon, `undefined` for default lightbulb, `<></>` (empty fragment) for no icon
-- `className` - Optional additional CSS class
-
-**Behavior:**
-
-- Only visible when there are no messages in the thread
-- Clicking a button submits the `prompt` as a user message
-- Clicks are ignored when a response is being generated
-
-### WelcomeScreen
-
-A centered welcome message shown when the thread is empty. Supports either props-based content or custom children.
-
-**Props-based usage with URL:**
-
-```tsx
-{
- !hasMessages && (
- <WelcomeScreen
- title="Hi, I'm AI Assistant"
- description="I can help you with your questions."
- image={{ url: "/path/to/logo.png" }}
- />
- );
-}
-```
-
-**Props-based usage with styled image:**
-
-```tsx
-{
- !hasMessages && (
- <WelcomeScreen
- title="Hi, I'm AI Assistant"
- description="I can help you with your questions."
- image={
- <img
- src="/path/to/logo.png"
- alt="AI Assistant"
- style={{ width: 64, height: 64, borderRadius: 16, objectFit: "cover" }}
- />
- }
- />
- );
-}
-```
-
-**Props-based usage with custom icon:**
-
-```tsx
-{
- !hasMessages && (
- <WelcomeScreen
- title="Hi, I'm AI Assistant"
- description="I can help you with your questions."
- image={<Sparkles size={32} />}
- />
- );
-}
-```
-
-**Custom children usage:**
-
-```tsx
-{
- !hasMessages && (
- <WelcomeScreen>
- <div style={{ textAlign: "center" }}>
- <MyCustomLogo />
- <h2>Welcome!</h2>
- <p>Custom welcome content</p>
- </div>
- </WelcomeScreen>
- );
-}
-```
-
-**Props:**
-
-- `title` - Greeting/title text (optional)
-- `description` - Description text (optional)
-- `image` - Image to display: `{ url: string }` for simple URL (renders with default 64x64 size, rounded corners), or `ReactNode` for custom styled elements (optional)
-- `children` - Custom content (mutually exclusive with title/description/image)
-- `className` - Additional CSS class (optional)
-
-**Note:** You must conditionally render WelcomeScreen based on `hasMessages` state.
-
-### Composer
-
-Text input for sending messages.
-
-```tsx
-<Composer className="custom-class" />
-```
-
-## Layout Integration
-
-CopilotShell is designed to be placed as a sidebar:
-
-```tsx
-function AppLayout() {
- const hasMessages = threadManager.messages.length > 0;
-
- return (
- <div style={{ display: "flex", height: "100vh" }}>
- {/* Main content area */}
- <main style={{ flex: 1 }}>{/* Your app content */}</main>
-
- {/* Copilot sidebar */}
- <aside style={{ width: 400, borderLeft: "1px solid #eee" }}>
- <ChatProvider {...}>
- <Container logoUrl={logo} agentName="Assistant">
- <ThreadContainer>
- <Header />
- {!hasMessages && (
- <WelcomeScreen
- title="Hi, I'm Assistant"
- description="How can I help you today?"
- image={
- <img
- src={logo}
- alt="Assistant"
- style={{ width: 64, height: 64, borderRadius: 16, objectFit: "cover" }}
- />
- }
- />
- )}
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={[...]} />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- </aside>
- </div>
- );
-}
-```
-
-## Comparison with BottomTray
-
-| Feature | CopilotShell | BottomTray |
-| -------- | ------------------- | ---------------------- |
-| Layout | Sidebar panel | Floating panel |
-| Position | Fixed sidebar | Bottom-right corner |
-| Trigger | Always visible | Floating button |
-| Mobile | Responsive | Fullscreen |
-| Use case | Main chat interface | Secondary/support chat |
-
-## CSS Classes
-
-All CopilotShell components use the `openui-copilot-shell-` prefix:
-
-- `.openui-copilot-shell-thread-container`
-- `.openui-copilot-shell-thread-scroll-area`
-- `.openui-copilot-shell-thread-messages`
-- `.openui-copilot-shell-thread-message-user`
-- `.openui-copilot-shell-thread-message-assistant`
-- `.openui-copilot-shell-thread-composer`
-- `.openui-copilot-shell-conversation-starter`
-- `.openui-copilot-shell-conversation-starter-item-short`
-- `.openui-copilot-shell-conversation-starter-item-long`
-- `.openui-copilot-shell-welcome-screen`
-- `.openui-copilot-shell-welcome-screen__image-container`
-- `.openui-copilot-shell-welcome-screen__content`
-- `.openui-copilot-shell-welcome-screen__title`
-- `.openui-copilot-shell-welcome-screen__description`
diff --git a/packages/react-ui/src/components/CopilotShell/stories/Shell.stories.tsx b/packages/react-ui/src/components/CopilotShell/stories/Shell.stories.tsx
deleted file mode 100644
index c20773b94..000000000
--- a/packages/react-ui/src/components/CopilotShell/stories/Shell.stories.tsx
+++ /dev/null
@@ -1,265 +0,0 @@
-import { ChatProvider, Message } from "@openuidev/react-headless";
-import { Sparkles } from "lucide-react";
-import {
- Composer,
- Container,
- ConversationStarter,
- Header,
- MessageLoading,
- Messages,
- ScrollArea,
- ThreadContainer,
- WelcomeScreen,
-} from "../../CopilotShell";
-// @ts-ignore
-import styles from "./style.module.scss";
-import logoUrl from "./thesysdev_logo.jpeg";
-
-function mockSSEResponse(text: string, delayMs = 500): Promise<Response> {
- return new Promise((resolve) => {
- setTimeout(() => {
- const events = `data: ${JSON.stringify({ type: "TEXT_MESSAGE_CONTENT", delta: text })}\n\ndata: [DONE]\n\n`;
- const stream = new ReadableStream({
- start(controller) {
- controller.enqueue(new TextEncoder().encode(events));
- controller.close();
- },
- });
- resolve(new Response(stream));
- }, delayMs);
- });
-}
-
-export default {
- title: "Components/CopilotShell",
- tags: ["dev"],
- argTypes: {
- variant: {
- control: "select",
- options: ["short", "long"],
- description: "Conversation starter variant",
- },
- },
-};
-
-const SAMPLE_STARTERS = [
- {
- displayText: "My portfolio",
- prompt: "Tell me about the latest stock market trends and how they affect my portfolio",
- icon: <Sparkles size={16} />,
- },
- {
- displayText: "Venezuela president",
- prompt: "Who is the president of Venezuela and where is he currently located?",
- // icon undefined = shows default lightbulb
- },
- {
- displayText: "Major stocks",
- prompt: "Tell me about major stock",
- icon: <></>, // Empty fragment = no icon
- },
-];
-
-export const Default = {
- args: {
- variant: "short",
- },
- render: ({ variant }: { variant: "short" | "long" }) => (
- <div className={styles.container}>
- <div className={styles.left} />
- <ChatProvider
- processMessage={async () =>
- mockSSEResponse("This is a response from the AI assistant.", 1000)
- }
- fetchThreadList={async () => {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- return {
- threads: [
- { id: "1", title: "test", createdAt: Date.now() },
- { id: "2", title: "test 2", createdAt: Date.now() },
- { id: "3", title: "test 3", createdAt: Date.now() },
- ],
- };
- }}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "test",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t) => t}
- loadThread={async (threadId) => {
- if (!threadId) return [];
- return [
- {
- id: crypto.randomUUID(),
- role: "user",
- content: "Hello",
- } as Message,
- {
- id: crypto.randomUUID(),
- role: "assistant",
- content: "Hello! How can I help you today?",
- } as Message,
- ];
- }}
- >
- <Container logoUrl={logoUrl} agentName="OpenUI">
- <ThreadContainer>
- <Header />
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={SAMPLE_STARTERS} variant={variant} />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- </div>
- ),
-};
-
-export const LongVariant = {
- args: {
- variant: "long",
- },
- render: ({ variant }: { variant: "short" | "long" }) => (
- <div className={styles.container}>
- <div className={styles.left} />
- <ChatProvider
- processMessage={async ({ messages }) => {
- const lastMsg = messages[messages.length - 1];
- const content = lastMsg && typeof lastMsg.content === "string" ? lastMsg.content : "";
- return mockSSEResponse(`You asked: "${content}"`, 1000);
- }}
- fetchThreadList={async () => ({ threads: [] })}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t) => t}
- loadThread={async () => []}
- >
- <Container logoUrl={logoUrl} agentName="OpenUI">
- <ThreadContainer>
- <Header />
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={SAMPLE_STARTERS} variant={variant} />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- </div>
- ),
-};
-
-// Example with WelcomeScreen
-export const WithWelcomeScreen = {
- args: {
- variant: "short",
- },
- render: ({ variant }: { variant: "short" | "long" }) => (
- <div className={styles.container}>
- <div className={styles.left} />
- <ChatProvider
- processMessage={async ({ messages }) => {
- const lastMsg = messages[messages.length - 1];
- const content = lastMsg && typeof lastMsg.content === "string" ? lastMsg.content : "";
- return mockSSEResponse(`You asked: "${content}"`, 1000);
- }}
- fetchThreadList={async () => ({ threads: [] })}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t) => t}
- loadThread={async () => []}
- >
- <Container logoUrl={logoUrl} agentName="OpenUI Assistant">
- <ThreadContainer>
- <Header />
- <WelcomeScreen
- title="Hi, I'm OpenUI Assistant"
- description="I can help you with questions about your account, products, and more."
- image={{ url: logoUrl }}
- />
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={SAMPLE_STARTERS} variant={variant} />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- </div>
- ),
-};
-
-// Example with custom children in WelcomeScreen
-export const WithCustomWelcomeScreen = {
- args: {
- variant: "short",
- },
- render: ({ variant }: { variant: "short" | "long" }) => (
- <div className={styles.container}>
- <div className={styles.left} />
- <ChatProvider
- processMessage={async ({ messages }) => {
- const lastMsg = messages[messages.length - 1];
- const content = lastMsg && typeof lastMsg.content === "string" ? lastMsg.content : "";
- return mockSSEResponse(`You asked: "${content}"`, 1000);
- }}
- fetchThreadList={async () => ({ threads: [] })}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t) => t}
- loadThread={async () => []}
- >
- <Container logoUrl={logoUrl} agentName="OpenUI Assistant">
- <ThreadContainer>
- <Header />
- <WelcomeScreen>
- <div style={{ textAlign: "center" }}>
- <div
- style={{
- width: 80,
- height: 80,
- borderRadius: 16,
- background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- margin: "0 auto 16px",
- }}
- >
- <Sparkles size={40} color="white" />
- </div>
- <h2 style={{ margin: "0 0 8px", fontSize: 20, fontWeight: 600 }}>
- Welcome to AI Assistant
- </h2>
- <p style={{ margin: 0, color: "rgba(0,0,0,0.5)", fontSize: 14 }}>
- Your personal AI helper for all your questions
- </p>
- </div>
- </WelcomeScreen>
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={SAMPLE_STARTERS} variant={variant} />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- </div>
- ),
-};
diff --git a/packages/react-ui/src/components/CopilotShell/stories/style.module.scss b/packages/react-ui/src/components/CopilotShell/stories/style.module.scss
deleted file mode 100644
index 825d15490..000000000
--- a/packages/react-ui/src/components/CopilotShell/stories/style.module.scss
+++ /dev/null
@@ -1,8 +0,0 @@
-.container {
- display: flex;
-}
-
-.left {
- flex-grow: 1;
- background: white;
-}
diff --git a/packages/react-ui/src/components/CopilotShell/stories/thesysdev_logo.jpeg b/packages/react-ui/src/components/CopilotShell/stories/thesysdev_logo.jpeg
deleted file mode 100644
index 755421486..000000000
Binary files a/packages/react-ui/src/components/CopilotShell/stories/thesysdev_logo.jpeg and /dev/null differ
diff --git a/packages/react-ui/src/components/CopilotShell/thread.scss b/packages/react-ui/src/components/CopilotShell/thread.scss
deleted file mode 100644
index 9f3b3bd82..000000000
--- a/packages/react-ui/src/components/CopilotShell/thread.scss
+++ /dev/null
@@ -1,139 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-copilot-shell-thread-container {
- display: flex;
- flex: 1;
- overflow: hidden;
- flex-direction: column;
- position: relative;
-}
-
-// Hide conversation starters while the user is drafting in the composer.
-// The drafting flag is set on the composer root via `data-drafting`.
-.openui-copilot-shell-thread-container:has([data-drafting]) {
- .openui-copilot-shell-conversation-starter {
- opacity: 0;
- pointer-events: none;
- }
-}
-
-.openui-copilot-shell-conversation-starter {
- transition: opacity 150ms ease;
-}
-
-.openui-copilot-shell-thread-scroll-container {
- width: 100%;
- flex: 1;
- position: relative;
- overflow: hidden;
-
- &::before {
- content: "";
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- height: cssUtils.$space-xl;
- background: linear-gradient(to bottom, cssUtils.$background 0%, transparent 100%);
- pointer-events: none;
- z-index: 1;
- }
-
- &::after {
- content: "";
- position: absolute;
- left: 0;
- right: 0;
- bottom: 0;
- height: cssUtils.$space-xl;
- background: linear-gradient(to top, cssUtils.$background 0%, transparent 100%);
- pointer-events: none;
- z-index: 1;
- }
-}
-
-.openui-copilot-shell-thread-scroll-area {
- width: 100%;
- height: 100%;
- overflow: auto;
- padding: cssUtils.$space-m-l;
- scroll-padding-top: cssUtils.$space-m-l;
- scrollbar-width: thin;
- scrollbar-color: cssUtils.$highlight-strong transparent;
-
- &::-webkit-scrollbar {
- width: cssUtils.$space-xs;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background-color: cssUtils.$highlight-strong;
- border-radius: cssUtils.$radius-full;
-
- &:hover {
- background-color: cssUtils.$highlight-intense;
- }
- }
-
- &--user-message-anchor {
- & .openui-copilot-shell-thread-messages > *:last-child {
- min-height: calc(-200px + 100dvh);
- }
- }
-}
-
-.openui-copilot-shell-thread-messages {
- width: 100%;
- max-width: 880px;
- margin: 0 auto;
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-xl;
-}
-
-.openui-copilot-shell-thread-message-assistant {
- width: 100%;
- display: flex;
- gap: cssUtils.$space-s;
- overflow: hidden;
-
- &__content {
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-s;
- overflow: hidden;
- overflow-wrap: break-word;
- flex-grow: 1;
- }
-
- &__logo {
- width: 32px;
- height: 32px;
- border-radius: cssUtils.$radius-m;
- flex-shrink: 0;
- }
-
- &__text {
- @include cssUtils.typography(primary, default);
- color: cssUtils.$text-neutral-primary;
- }
-}
-
-.openui-copilot-shell-thread-message-user {
- display: flex;
- justify-content: flex-end;
-
- &__content {
- @include cssUtils.typography(primary, default);
- padding: cssUtils.$space-s cssUtils.$space-m;
- background-color: cssUtils.$chat-user-response-bg;
- color: cssUtils.$chat-user-response-text;
- border-radius: cssUtils.$radius-xl;
- overflow-wrap: break-word;
- max-width: 100%;
- height: fit-content;
- }
-}
diff --git a/packages/react-ui/src/components/CopilotShell/threadList.scss b/packages/react-ui/src/components/CopilotShell/threadList.scss
deleted file mode 100644
index ce6175c17..000000000
--- a/packages/react-ui/src/components/CopilotShell/threadList.scss
+++ /dev/null
@@ -1,162 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-copilot-shell-thread-list-dropdown {
- display: flex;
- flex-direction: column;
- min-width: 240px;
- max-width: 320px;
- max-height: 296px;
- padding: cssUtils.$space-xs;
- border: 1px solid cssUtils.$border-default;
- border-radius: cssUtils.$radius-2xl;
- background-color: cssUtils.$foreground;
- box-shadow: cssUtils.$shadow-l;
- z-index: 9999;
- overflow: hidden;
-}
-
-.openui-copilot-shell-thread-list-header {
- @include cssUtils.typography(label, small);
- color: cssUtils.$text-neutral-tertiary;
- padding: cssUtils.$space-xs cssUtils.$space-s;
- padding-bottom: cssUtils.$space-s;
-}
-
-.openui-copilot-shell-thread-list-items {
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-3xs;
- overflow-y: auto;
- scrollbar-width: thin;
- scrollbar-color: cssUtils.$border-default transparent;
-
- &::-webkit-scrollbar {
- width: cssUtils.$space-xs;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background: cssUtils.$border-default;
- border-radius: calc(cssUtils.$radius-2xs + cssUtils.$space-3xs);
- }
-
- &::-webkit-scrollbar-thumb:hover {
- background: cssUtils.$text-neutral-secondary;
- }
-}
-
-.openui-copilot-shell-thread-list-empty {
- @include cssUtils.typography(body, small);
- color: cssUtils.$text-neutral-secondary;
- padding: cssUtils.$space-m;
- text-align: center;
-}
-
-.openui-copilot-shell-thread-list-trigger {
- &[data-state="open"],
- &[aria-expanded="true"] {
- background-color: cssUtils.$highlight;
- border-color: cssUtils.$border-interactive;
- }
-}
-
-.openui-copilot-shell-thread-item {
- display: flex;
- align-items: center;
- justify-content: space-between;
- width: 100%;
- border-radius: calc(cssUtils.$radius-s + 1px);
- border: 1px solid transparent;
- transition: all 0.12s ease;
-
- &--selected {
- background-color: cssUtils.$highlight;
- }
-
- &:hover {
- background-color: cssUtils.$highlight;
-
- .openui-copilot-shell-thread-item-menu-trigger {
- opacity: 1;
- }
- }
-
- &:has(.openui-copilot-shell-thread-item-menu-trigger[data-state="open"]) {
- background-color: cssUtils.$highlight;
-
- .openui-copilot-shell-thread-item-menu-trigger {
- opacity: 1;
- }
- }
-}
-
-.openui-copilot-shell-thread-item-title {
- @include cssUtils.button-reset;
- @include cssUtils.typography(body, small);
- color: cssUtils.$text-neutral-primary;
- padding: calc(cssUtils.$space-xs - 1.75px) cssUtils.$space-s;
- width: 100%;
- text-align: left;
- cursor: pointer;
- white-space: nowrap;
- text-overflow: ellipsis;
- overflow: hidden;
-}
-
-.openui-copilot-shell-thread-item-menu-trigger {
- opacity: 0;
-
- &:focus-visible {
- opacity: 1;
- }
-
- &[data-state="open"] {
- opacity: 1;
- background-color: cssUtils.$highlight;
- border-color: cssUtils.$border-interactive;
- }
-}
-
-.openui-copilot-shell-thread-item-menu {
- box-sizing: border-box;
- position: relative;
- z-index: 99999;
- min-width: 160px;
- overflow: hidden;
- border: 1px solid cssUtils.$border-default;
- border-radius: cssUtils.$radius-xl;
- background-color: cssUtils.$foreground;
- box-shadow: cssUtils.$shadow-m;
- color: cssUtils.$text-neutral-primary;
- transform-origin: top center;
- animation: openui-copilot-shell-thread-menu-show 0.18s ease-out forwards;
- padding: 4px;
-}
-
-.openui-copilot-shell-thread-item-menu-action {
- width: 100%;
- justify-content: flex-start;
- padding-left: cssUtils.$space-s;
- padding-right: cssUtils.$space-s;
-
- &:focus,
- &:focus-visible {
- outline: none;
- box-shadow: none;
- }
-}
-
-@keyframes openui-copilot-shell-thread-menu-show {
- from {
- opacity: 0;
- transform: scale(0.95);
- }
-
- to {
- opacity: 1;
- transform: scale(1);
- }
-}
diff --git a/packages/react-ui/src/components/CopilotShell/welcomeScreen.scss b/packages/react-ui/src/components/CopilotShell/welcomeScreen.scss
deleted file mode 100644
index 61a135941..000000000
--- a/packages/react-ui/src/components/CopilotShell/welcomeScreen.scss
+++ /dev/null
@@ -1,50 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-copilot-shell-welcome-screen {
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-xl;
- height: 100%;
- justify-content: center;
- align-items: center;
-
- // Image container - minimal wrapper, styling handled by consumer
- &__image-container {
- display: flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- }
-
- // Default image styles when using { url: string }
- &__image {
- width: 64px;
- height: 64px;
- object-fit: cover;
- border-radius: cssUtils.$radius-xl;
- }
-
- // Content container (title + description)
- &__content {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: cssUtils.$space-s;
- text-align: center;
- }
-
- // Title/greeting text
- &__title {
- @include cssUtils.typography(heading, medium);
- color: cssUtils.$text-neutral-primary;
- margin: 0;
- }
-
- // Description text
- &__description {
- @include cssUtils.typography(body, small);
- color: cssUtils.$text-neutral-secondary;
- margin: 0;
- max-width: 280px;
- }
-}
diff --git a/packages/react-ui/src/components/OpenUIChat/AssistantMessageContainer.tsx b/packages/react-ui/src/components/OpenUIChat/AssistantMessageContainer.tsx
new file mode 100644
index 000000000..4f6c035df
--- /dev/null
+++ b/packages/react-ui/src/components/OpenUIChat/AssistantMessageContainer.tsx
@@ -0,0 +1,41 @@
+import clsx from "clsx";
+import React from "react";
+import { useShellStore } from "../_shared/store";
+
+/**
+ * Wraps a GenUI assistant message with the assistant logo + content layout.
+ *
+ * Extracted from the (now-deleted) Shell so the kept `GenUIAssistantMessage`
+ * keeps rendering under `AgentInterface`. `logoUrl`/`showAssistantLogo` come
+ * from the library-wide shell store, which `AgentInterface`'s `Container`
+ * provides via `ShellStoreProvider`.
+ */
+export const AssistantMessageContainer = ({
+ children,
+ className,
+}: {
+ children?: React.ReactNode;
+ className?: string;
+}) => {
+ const { logoUrl, showAssistantLogo } = useShellStore((store) => ({
+ logoUrl: store.logoUrl,
+ showAssistantLogo: store.showAssistantLogo,
+ }));
+
+ return (
+ <div
+ className={clsx("openui-shell-thread-message-assistant", className, {
+ "openui-shell-thread-message-assistant--without-logo": !showAssistantLogo,
+ })}
+ >
+ {showAssistantLogo && (
+ <img
+ src={logoUrl}
+ alt="Assistant"
+ className="openui-shell-thread-message-assistant__logo"
+ />
+ )}
+ <div className="openui-shell-thread-message-assistant__content">{children}</div>
+ </div>
+ );
+};
diff --git a/packages/react-ui/src/components/OpenUIChat/ComposedBottomTray.tsx b/packages/react-ui/src/components/OpenUIChat/ComposedBottomTray.tsx
deleted file mode 100644
index 7ea231ab1..000000000
--- a/packages/react-ui/src/components/OpenUIChat/ComposedBottomTray.tsx
+++ /dev/null
@@ -1,153 +0,0 @@
-import { useThread } from "@openuidev/react-headless";
-import { useState } from "react";
-import {
- Container,
- ConversationStarter,
- Composer as DefaultComposer,
- Header,
- MessageLoading,
- Messages,
- ScrollArea,
- ThreadContainer,
- Trigger,
- WelcomeScreen,
-} from "../BottomTray";
-import { CustomComposerAdapter } from "./CustomComposerAdapter";
-import { ShareThread } from "./ShareThread";
-import type { SharedChatUIProps } from "./types";
-import { isChatEmpty, isWelcomeComponent } from "./utils";
-import { withChatProvider } from "./withChatProvider";
-
-interface BottomTraySpecificProps extends SharedChatUIProps {
- isOpen?: boolean;
- onOpenChange?: (isOpen: boolean) => void;
- defaultOpen?: boolean;
- headerActions?: React.ReactNode;
-}
-
-const WelcomeMessageRenderer = ({ welcomeMessage }: Pick<SharedChatUIProps, "welcomeMessage">) => {
- const messages = useThread((s) => s.messages);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- if (!welcomeMessage || !isChatEmpty({ isLoadingMessages, messages })) {
- return null;
- }
-
- if (isWelcomeComponent(welcomeMessage)) {
- const CustomWelcome = welcomeMessage;
- return (
- <WelcomeScreen>
- <CustomWelcome />
- </WelcomeScreen>
- );
- }
-
- return (
- <WelcomeScreen
- title={welcomeMessage.title}
- description={welcomeMessage.description}
- image={welcomeMessage.image}
- />
- );
-};
-
-const ConversationStartersRenderer = ({
- conversationStarters,
-}: Pick<SharedChatUIProps, "conversationStarters">) => {
- const messages = useThread((s) => s.messages);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- if (!conversationStarters || !isChatEmpty({ isLoadingMessages, messages })) {
- return null;
- }
-
- return (
- <ConversationStarter
- variant={conversationStarters.variant}
- starters={conversationStarters.options}
- />
- );
-};
-
-const BottomTrayInner = ({
- logoUrl = "https://www.openui.com/favicon.svg",
- agentName = "My Agent",
- showAssistantLogo = false,
- messageLoading: MessageLoadingComponent = MessageLoading,
- scrollVariant = "user-message-anchor",
- isOpen: controlledIsOpen,
- onOpenChange,
- defaultOpen = false,
- welcomeMessage,
- conversationStarters,
- assistantMessage,
- userMessage,
- composer: ComposerComponent,
- headerActions,
- generateShareLink,
-}: BottomTraySpecificProps) => {
- const [uncontrolledIsOpen, setUncontrolledIsOpen] = useState(defaultOpen);
-
- const isOpen = controlledIsOpen !== undefined ? controlledIsOpen : uncontrolledIsOpen;
-
- const handleOpenChange = (newIsOpen: boolean) => {
- if (controlledIsOpen === undefined) {
- setUncontrolledIsOpen(newIsOpen);
- }
- onOpenChange?.(newIsOpen);
- };
-
- const shareButton = generateShareLink ? (
- <ShareThread generateShareLink={generateShareLink} />
- ) : null;
-
- return (
- <>
- <Trigger onClick={() => handleOpenChange(!isOpen)} isOpen={isOpen}>
- {logoUrl ? (
- <img src={logoUrl} alt="Logo" className="openui-bottom-tray-trigger-logo" />
- ) : null}
- </Trigger>
-
- <Container
- logoUrl={logoUrl}
- agentName={agentName}
- showAssistantLogo={showAssistantLogo}
- isOpen={isOpen}
- >
- <ThreadContainer>
- <Header
- onMinimize={() => handleOpenChange(false)}
- rightChildren={
- <>
- {shareButton}
- {headerActions}
- </>
- }
- />
- <WelcomeMessageRenderer welcomeMessage={welcomeMessage} />
- <ScrollArea scrollVariant={scrollVariant}>
- <Messages
- loader={<MessageLoadingComponent />}
- assistantMessage={assistantMessage}
- userMessage={userMessage}
- />
- </ScrollArea>
- <ConversationStartersRenderer conversationStarters={conversationStarters} />
- {ComposerComponent ? (
- <CustomComposerAdapter composer={ComposerComponent} />
- ) : (
- <DefaultComposer />
- )}
- </ThreadContainer>
- </Container>
- </>
- );
-};
-
-export const BottomTray = withChatProvider<{
- isOpen?: boolean;
- onOpenChange?: (isOpen: boolean) => void;
- defaultOpen?: boolean;
- headerActions?: React.ReactNode;
-}>(BottomTrayInner);
diff --git a/packages/react-ui/src/components/OpenUIChat/ComposedCopilot.tsx b/packages/react-ui/src/components/OpenUIChat/ComposedCopilot.tsx
deleted file mode 100644
index 83fcefbdd..000000000
--- a/packages/react-ui/src/components/OpenUIChat/ComposedCopilot.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import { useThread } from "@openuidev/react-headless";
-import {
- Container,
- ConversationStarter,
- Composer as DefaultComposer,
- Header,
- MessageLoading,
- Messages,
- ScrollArea,
- ThreadContainer,
- WelcomeScreen,
-} from "../CopilotShell";
-import { CustomComposerAdapter } from "./CustomComposerAdapter";
-import { ShareThread } from "./ShareThread";
-import type { SharedChatUIProps } from "./types";
-import { isChatEmpty, isWelcomeComponent } from "./utils";
-import { withChatProvider } from "./withChatProvider";
-
-const WelcomeMessageRenderer = ({ welcomeMessage }: Pick<SharedChatUIProps, "welcomeMessage">) => {
- const messages = useThread((s) => s.messages);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- if (!welcomeMessage || !isChatEmpty({ isLoadingMessages, messages })) {
- return null;
- }
-
- if (isWelcomeComponent(welcomeMessage)) {
- const CustomWelcome = welcomeMessage;
- return (
- <WelcomeScreen>
- <CustomWelcome />
- </WelcomeScreen>
- );
- }
-
- return (
- <WelcomeScreen
- title={welcomeMessage.title}
- description={welcomeMessage.description}
- image={welcomeMessage.image}
- />
- );
-};
-
-const ConversationStartersRenderer = ({
- conversationStarters,
-}: Pick<SharedChatUIProps, "conversationStarters">) => {
- const messages = useThread((s) => s.messages);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- if (!conversationStarters || !isChatEmpty({ isLoadingMessages, messages })) {
- return null;
- }
-
- return (
- <ConversationStarter
- variant={conversationStarters.variant}
- starters={conversationStarters.options}
- />
- );
-};
-
-interface CopilotSpecificProps extends SharedChatUIProps {
- headerActions?: React.ReactNode;
-}
-
-const CopilotInner = ({
- logoUrl = "https://www.openui.com/favicon.svg",
- agentName = "My Agent",
- showAssistantLogo = false,
- messageLoading: MessageLoadingComponent = MessageLoading,
- scrollVariant = "user-message-anchor",
- welcomeMessage,
- conversationStarters,
- assistantMessage,
- userMessage,
- composer: ComposerComponent,
- headerActions,
- generateShareLink,
-}: CopilotSpecificProps) => {
- const shareButton = generateShareLink ? (
- <ShareThread generateShareLink={generateShareLink} />
- ) : null;
-
- return (
- <Container logoUrl={logoUrl} agentName={agentName} showAssistantLogo={showAssistantLogo}>
- <ThreadContainer>
- <Header
- rightChildren={
- <>
- {shareButton}
- {headerActions}
- </>
- }
- />
- <WelcomeMessageRenderer welcomeMessage={welcomeMessage} />
- <ScrollArea scrollVariant={scrollVariant}>
- <Messages
- loader={<MessageLoadingComponent />}
- assistantMessage={assistantMessage}
- userMessage={userMessage}
- />
- </ScrollArea>
- <ConversationStartersRenderer conversationStarters={conversationStarters} />
- {ComposerComponent ? (
- <CustomComposerAdapter composer={ComposerComponent} />
- ) : (
- <DefaultComposer />
- )}
- </ThreadContainer>
- </Container>
- );
-};
-
-export const Copilot = withChatProvider<{
- headerActions?: React.ReactNode;
-}>(CopilotInner);
diff --git a/packages/react-ui/src/components/OpenUIChat/ComposedStandalone.tsx b/packages/react-ui/src/components/OpenUIChat/ComposedStandalone.tsx
deleted file mode 100644
index 5cb5d9d96..000000000
--- a/packages/react-ui/src/components/OpenUIChat/ComposedStandalone.tsx
+++ /dev/null
@@ -1,149 +0,0 @@
-import { useThread } from "@openuidev/react-headless";
-import {
- Container,
- ConversationStarter,
- Composer as DefaultComposer,
- MessageLoading,
- Messages,
- MobileHeader,
- NewChatButton,
- ScrollArea,
- SidebarContainer,
- SidebarContent,
- SidebarHeader,
- SidebarSeparator,
- ThreadContainer,
- ThreadHeader,
- ThreadList,
- WelcomeScreen,
-} from "../Shell";
-import { CustomComposerAdapter } from "./CustomComposerAdapter";
-import { ShareThread } from "./ShareThread";
-import type { SharedChatUIProps } from "./types";
-import { isChatEmpty, isWelcomeComponent } from "./utils";
-import { withChatProvider } from "./withChatProvider";
-
-const WelcomeMessageRenderer = ({
- welcomeMessage,
- conversationStarters,
-}: Pick<SharedChatUIProps, "welcomeMessage" | "conversationStarters">) => {
- const messages = useThread((s) => s.messages);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- if (!welcomeMessage || !isChatEmpty({ isLoadingMessages, messages })) {
- return null;
- }
-
- if (isWelcomeComponent(welcomeMessage)) {
- const CustomWelcome = welcomeMessage;
- return (
- <WelcomeScreen>
- <CustomWelcome />
- </WelcomeScreen>
- );
- }
-
- return (
- <WelcomeScreen
- title={welcomeMessage.title}
- description={welcomeMessage.description}
- image={welcomeMessage.image}
- starters={conversationStarters?.options}
- starterVariant={conversationStarters?.variant}
- />
- );
-};
-
-const ConversationStartersRenderer = ({
- conversationStarters,
-}: Pick<SharedChatUIProps, "conversationStarters">) => {
- const messages = useThread((s) => s.messages);
- const isLoadingMessages = useThread((s) => s.isLoadingMessages);
-
- if (!conversationStarters || !isChatEmpty({ isLoadingMessages, messages })) {
- return null;
- }
-
- return (
- <ConversationStarter
- variant={conversationStarters.variant}
- starters={conversationStarters.options}
- />
- );
-};
-
-interface FullScreenSpecificProps extends SharedChatUIProps {
- threadHeader?: React.ReactNode;
- mobileHeaderActions?: React.ReactNode;
-}
-
-const FullScreenInner = ({
- logoUrl = "https://www.openui.com/favicon.svg",
- agentName = "My Agent",
- showAssistantLogo = false,
- messageLoading: MessageLoadingComponent = MessageLoading,
- scrollVariant = "user-message-anchor",
- welcomeMessage,
- conversationStarters,
- assistantMessage,
- userMessage,
- composer: ComposerComponent,
- threadHeader,
- mobileHeaderActions,
- generateShareLink,
-}: FullScreenSpecificProps) => {
- const shareButton = generateShareLink ? (
- <ShareThread generateShareLink={generateShareLink} />
- ) : null;
-
- return (
- <Container logoUrl={logoUrl} agentName={agentName} showAssistantLogo={showAssistantLogo}>
- <SidebarContainer>
- <SidebarHeader />
- <SidebarContent>
- <NewChatButton />
- <SidebarSeparator />
- <ThreadList />
- </SidebarContent>
- </SidebarContainer>
- <ThreadContainer>
- <MobileHeader
- rightChildren={
- <>
- {shareButton}
- {mobileHeaderActions}
- </>
- }
- />
- {(threadHeader || shareButton) && (
- <ThreadHeader>
- {threadHeader}
- {shareButton}
- </ThreadHeader>
- )}
- <WelcomeMessageRenderer
- welcomeMessage={welcomeMessage}
- conversationStarters={conversationStarters}
- />
- <ScrollArea scrollVariant={scrollVariant}>
- <Messages
- loader={<MessageLoadingComponent />}
- assistantMessage={assistantMessage}
- userMessage={userMessage}
- />
- </ScrollArea>
- <ConversationStartersRenderer conversationStarters={conversationStarters} />
- {ComposerComponent ? (
- <CustomComposerAdapter composer={ComposerComponent} />
- ) : (
- <DefaultComposer />
- )}
- </ThreadContainer>
- </Container>
- );
-};
-
-export const FullScreen = withChatProvider<{
- threadHeader?: React.ReactNode;
- mobileHeaderActions?: React.ReactNode;
-}>(FullScreenInner);
diff --git a/packages/react-ui/src/components/OpenUIChat/GenUIAssistantMessage.tsx b/packages/react-ui/src/components/OpenUIChat/GenUIAssistantMessage.tsx
index 2a3728137..7f57b7d76 100644
--- a/packages/react-ui/src/components/OpenUIChat/GenUIAssistantMessage.tsx
+++ b/packages/react-ui/src/components/OpenUIChat/GenUIAssistantMessage.tsx
@@ -1,14 +1,24 @@
"use client";
-import type { AssistantMessage, ToolMessage } from "@openuidev/react-headless";
-import { useThread } from "@openuidev/react-headless";
+import type { AssistantMessage, ToolActivity } from "@openuidev/react-headless";
+import {
+ lookupArtifactRenderer,
+ useArtifactRendererRegistry,
+ useThread,
+ useToolActivities,
+} from "@openuidev/react-headless";
import type { ActionEvent, Library } from "@openuidev/react-lang";
import { BuiltinActionType, Renderer } from "@openuidev/react-lang";
import { useCallback, useMemo } from "react";
-import { separateContentAndContext, wrapContent, wrapContext } from "../../utils/contentParser";
-import { AssistantMessageContainer } from "../Shell";
-import { BehindTheScenes, ToolCallComponent } from "../ToolCall";
-import { ToolResult } from "../ToolResult";
+import {
+ separateContentAndContext,
+ wrapContent,
+ wrapContentWithHeader,
+ wrapContext,
+} from "../../utils/sentinelParser";
+import { ToolCallTimeline } from "../ToolCall";
+import { TimelineEntry } from "../_shared/tool-renderer";
+import { AssistantMessageContainer } from "./AssistantMessageContainer";
export const GenUIAssistantMessage = ({
message,
@@ -33,8 +43,12 @@ export const GenUIAssistantMessage = ({
}, [isRunning, messages, message.id]);
// Separate openui-lang code from persisted form state
- const { content: openuiCode, contextString } = useMemo(() => {
- if (!message.content) return { content: null, contextString: null };
+ const {
+ content: openuiCode,
+ contextString,
+ contentHeader,
+ } = useMemo(() => {
+ if (!message.content) return { content: null, contextString: null, contentHeader: undefined };
return separateContentAndContext(message.content);
}, [message.content]);
@@ -50,36 +64,34 @@ export const GenUIAssistantMessage = ({
}
}, [contextString]);
- const toolMessages = useMemo(() => {
- const result: ToolMessage[] = [];
- const msgIndex = messages.findIndex((m) => m.id === message.id);
- if (msgIndex !== -1) {
- for (let i = msgIndex + 1; i < messages.length; i++) {
- const m = messages[i];
- if (m && m.role === "tool") {
- result.push(m as ToolMessage);
- } else {
- break;
- }
- }
- }
- return result;
- }, [messages, message.id]);
+ // One id-keyed pairing of calls↔results with real status (streaming /
+ // executing / complete / error).
+ const activities = useToolActivities(message, messages);
- const getToolName = (toolCallId: string) => {
- const toolCall = message.toolCalls?.find((tc) => tc.id === toolCallId);
- return toolCall?.function.name;
- };
+ // The "Behind the scenes" timeline shows the RAW request/response for EVERY
+ // tool call (forceDefault), so matched tools (artifacts, web search) stay
+ // inspectable there. Matched renderers additionally render their rich preview
+ // OUTSIDE the timeline so it's always visible and its detailed-view panel
+ // stays mounted even after the message completes.
+ const registry = useArtifactRendererRegistry();
+ const isMatched = (a: ToolActivity) =>
+ !!(registry && lookupArtifactRenderer(registry, a.toolName));
+ const matchedActivities = activities.filter(isMatched);
- // Persist form state into the message content (XML-wrapped)
+ // Persist form state into the inline-wrapped message content. The original
+ // header line (which may include `libraryVersion` and telemetry tags emitted
+ // by the backend) is reused so attrs survive the persist round-trip.
const handleStateUpdate = useCallback(
(state: Record<string, any>) => {
const code = openuiCode ?? "";
- const contextJson = JSON.stringify([state]);
- const fullMessage = code + "\n" + wrapContext(contextJson);
+ const hasState = Object.keys(state).length > 0;
+ const contentPart = wrapContentWithHeader(code, contentHeader);
+ const fullMessage = hasState
+ ? contentPart + wrapContext(JSON.stringify([state]))
+ : contentPart;
updateMessage({ ...message, content: fullMessage });
},
- [updateMessage, message, openuiCode],
+ [updateMessage, message, openuiCode, contentHeader],
);
// Build LLM-friendly message from action + form state, then dispatch
@@ -110,27 +122,23 @@ export const GenUIAssistantMessage = ({
[processMessage],
);
- const hasToolActivity =
- (message.toolCalls && message.toolCalls.length > 0) || toolMessages.length > 0;
-
return (
<AssistantMessageContainer>
- {hasToolActivity && (
- <BehindTheScenes isStreaming={isStreaming} toolCallsComplete={!!message.content}>
- {message.toolCalls?.map((toolCall, idx) => (
- <ToolCallComponent
- key={toolCall.id}
- toolCall={toolCall}
- isStreaming={isStreaming}
- toolsDone={!!message.content}
- isLast={idx === (message.toolCalls?.length ?? 0) - 1 && toolMessages.length === 0}
- />
- ))}
- {toolMessages.map((tm) => (
- <ToolResult key={tm.id} message={tm} toolName={getToolName(tm.toolCallId)} />
- ))}
- </BehindTheScenes>
+ {activities.length > 0 && (
+ // Raw request/response for ALL tool calls, collapsed by default.
+ <ToolCallTimeline activities={activities} isLast={isStreaming} forceDefault />
)}
+ {matchedActivities.map((activity) => (
+ // Matched renderers (artifact previews, web search) — always visible.
+ // No raw fallback here: the forceDefault timeline above already shows the
+ // raw card, so a null-parser renderer shouldn't double it.
+ <TimelineEntry
+ key={activity.id}
+ activity={activity}
+ isLast={isStreaming}
+ fallbackToDefault={false}
+ />
+ ))}
<Renderer
response={openuiCode}
library={library}
diff --git a/packages/react-ui/src/components/OpenUIChat/GenUIUserMessage.tsx b/packages/react-ui/src/components/OpenUIChat/GenUIUserMessage.tsx
index 6b11b2ab2..ad17e0351 100644
--- a/packages/react-ui/src/components/OpenUIChat/GenUIUserMessage.tsx
+++ b/packages/react-ui/src/components/OpenUIChat/GenUIUserMessage.tsx
@@ -3,7 +3,7 @@
import type { UserMessage } from "@openuidev/react-headless";
import { ChevronDown } from "lucide-react";
import { useState } from "react";
-import { separateContentAndContext } from "../../utils/contentParser";
+import { separateContentAndContext } from "../../utils/sentinelParser";
/**
* Extracts the first plain object from a context string.
@@ -103,7 +103,7 @@ function FormDataAccordion({ state }: { state: Record<string, any> }) {
/**
* Renders a user message, handling both plain text messages and
- * XML-formatted messages from form submissions (which contain <content> and <context> tags).
+ * inline-formatted messages from form submissions.
*/
export const GenUIUserMessage = ({ message }: { message: UserMessage }) => {
const rawContent = typeof message.content === "string" ? message.content : "";
diff --git a/packages/react-ui/src/components/OpenUIChat/assistantMessage.scss b/packages/react-ui/src/components/OpenUIChat/assistantMessage.scss
new file mode 100644
index 000000000..ab5167590
--- /dev/null
+++ b/packages/react-ui/src/components/OpenUIChat/assistantMessage.scss
@@ -0,0 +1,90 @@
+@use "../../cssUtils" as cssUtils;
+
+// User- and assistant-message layout for the GenUI messages rendered by
+// `AgentInterface` (`GenUIUserMessage`, and `GenUIAssistantMessage` →
+// `AssistantMessageContainer`). Extracted from the retired Shell's `thread.scss`
+// so the kept components keep their alignment + logo + bubble layout. The element
+// class names are preserved (`openui-shell-thread-message-{user,assistant}*` — the
+// components still emit them); the mobile / detailed-view ANCESTOR selectors were
+// retargeted from the deleted Shell's container to AgentInterface's
+// (`openui-agent-container--mobile`, `openui-agent-thread-container--detailed-view-active`).
+$center-align-spacing: calc(32px + cssUtils.$space-s);
+
+.openui-shell-thread-message-assistant {
+ width: 100%;
+ display: flex;
+ gap: cssUtils.$space-s;
+ padding-right: $center-align-spacing;
+ overflow: hidden;
+
+ &--without-logo {
+ padding-left: $center-align-spacing;
+ }
+
+ .openui-agent-container--mobile & {
+ padding: 0;
+ }
+
+ // When detailed view is active, minimize spacing and hide logo
+ .openui-agent-thread-container--detailed-view-active & {
+ gap: 0;
+ padding-right: 0;
+ }
+
+ &__content {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-s;
+ overflow: hidden;
+ overflow-wrap: break-word;
+ flex-grow: 1;
+ }
+
+ &__text {
+ @include cssUtils.typography(primary, default);
+ color: cssUtils.$text-neutral-primary;
+ &:first-child {
+ margin-top: cssUtils.$space-xs;
+ }
+ }
+
+ &__logo {
+ width: 32px;
+ height: 32px;
+ border-radius: cssUtils.$radius-m;
+
+ .openui-agent-container--mobile & {
+ display: none;
+ }
+
+ .openui-agent-thread-container--detailed-view-active & {
+ display: none;
+ }
+ }
+}
+
+.openui-shell-thread-message-user {
+ display: flex;
+ justify-content: flex-end;
+ padding: 0 $center-align-spacing;
+
+ .openui-agent-container--mobile & {
+ padding: 0;
+ }
+
+ .openui-agent-thread-container--detailed-view-active & {
+ padding-left: 0;
+ padding-right: 0;
+ }
+
+ &__content {
+ @include cssUtils.typography(primary, default);
+ padding: cssUtils.$space-s cssUtils.$space-m;
+ background-color: cssUtils.$chat-user-response-bg;
+ color: cssUtils.$chat-user-response-text;
+ border-radius: cssUtils.$radius-xl;
+ overflow-wrap: break-word;
+ max-width: 100%;
+ height: fit-content;
+ }
+}
diff --git a/packages/react-ui/src/components/OpenUIChat/composedBottomTray.scss b/packages/react-ui/src/components/OpenUIChat/composedBottomTray.scss
deleted file mode 100644
index 868397ae8..000000000
--- a/packages/react-ui/src/components/OpenUIChat/composedBottomTray.scss
+++ /dev/null
@@ -1,8 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-bottom-tray-trigger-logo {
- width: "100%";
- height: "100%";
- object-fit: "cover";
- border-radius: cssUtils.$radius-m;
-}
diff --git a/packages/react-ui/src/components/OpenUIChat/dependencies.ts b/packages/react-ui/src/components/OpenUIChat/dependencies.ts
index 51ba54b8a..7e8f507f6 100644
--- a/packages/react-ui/src/components/OpenUIChat/dependencies.ts
+++ b/packages/react-ui/src/components/OpenUIChat/dependencies.ts
@@ -1,5 +1,6 @@
-import shellDeps from "../Shell/dependencies";
+import buttonDeps from "../Button/dependencies";
+import iconButtonDeps from "../IconButton/dependencies";
-const dependencies = ["OpenUIChat", ...shellDeps];
+const dependencies = ["OpenUIChat", ...iconButtonDeps, ...buttonDeps];
export default dependencies;
diff --git a/packages/react-ui/src/components/OpenUIChat/index.ts b/packages/react-ui/src/components/OpenUIChat/index.ts
index ddbe429ee..a19a1e1d0 100644
--- a/packages/react-ui/src/components/OpenUIChat/index.ts
+++ b/packages/react-ui/src/components/OpenUIChat/index.ts
@@ -1,6 +1,3 @@
-export { BottomTray } from "./ComposedBottomTray";
-export { Copilot } from "./ComposedCopilot";
-export { FullScreen } from "./ComposedStandalone";
export { GenUIUserMessage } from "./GenUIUserMessage";
export { ShareThread } from "./ShareThread";
export type { ShareThreadProps } from "./ShareThread";
diff --git a/packages/react-ui/src/components/OpenUIChat/openUIChat.scss b/packages/react-ui/src/components/OpenUIChat/openUIChat.scss
index d3b49825c..672baad0a 100644
--- a/packages/react-ui/src/components/OpenUIChat/openUIChat.scss
+++ b/packages/react-ui/src/components/OpenUIChat/openUIChat.scss
@@ -1,2 +1,2 @@
-@forward "./composedBottomTray.scss";
+@forward "./assistantMessage.scss";
@forward "./shareThread.scss";
diff --git a/packages/react-ui/src/components/OpenUIChat/stories/OpenUIChat.mdx b/packages/react-ui/src/components/OpenUIChat/stories/OpenUIChat.mdx
deleted file mode 100644
index 93a24fd3a..000000000
--- a/packages/react-ui/src/components/OpenUIChat/stories/OpenUIChat.mdx
+++ /dev/null
@@ -1,550 +0,0 @@
-import { Meta } from "@storybook/blocks";
-
-<Meta title="Components/OpenUIChat/Docs" />
-
-# OpenUIChat
-
-OpenUIChat is a **high-level, batteries-included chat component** that provides a complete chat experience with minimal configuration. It wraps all the complexity of the composable shell components (Shell, CopilotShell, BottomTray) into a single, easy-to-use component.
-
-## When to Use OpenUIChat
-
-Use `OpenUIChat` when you want:
-
-- A quick, ready-to-use chat interface
-- Minimal boilerplate code
-- Automatic thread management
-- Built-in welcome screens and conversation starters
-
-Use the individual shell components (Shell, CopilotShell, BottomTray) when you need:
-
-- Full control over the UI composition
-- Custom layouts
-- Advanced customization
-
-## Types
-
-OpenUIChat supports three different layout types:
-
-| Type | Description |
-| ------------- | ----------------------------------------------------- |
-| `standalone` | Full-page chat with sidebar for thread list (default) |
-| `copilot` | Side panel chat without sidebar |
-| `bottom-tray` | Floating chat panel in the bottom-right corner |
-
-## Basic Usage
-
-```tsx
-import { OpenUIChat } from "@openuidev/react-ui";
-
-function App() {
- return (
- <OpenUIChat
- processMessage={async ({ messages, threadId, abortController }) => {
- // Send messages to your AI backend
- const response = await fetch("/api/chat", {
- method: "POST",
- body: JSON.stringify({ messages, threadId }),
- signal: abortController.signal,
- });
- return response;
- }}
- type="standalone"
- logoUrl="/path/to/logo.png"
- agentName="AI Assistant"
- />
- );
-}
-```
-
-## With Welcome Message and Conversation Starters
-
-```tsx
-import { OpenUIChat } from "@openuidev/react-ui";
-import { Sparkles, Zap } from "lucide-react";
-
-function App() {
- return (
- <OpenUIChat
- processMessage={...}
- type="standalone"
- logoUrl="/path/to/logo.png"
- agentName="AI Assistant"
- welcomeMessage={{
- title: "Hi, I'm AI Assistant",
- description: "I can help you with questions about your account, products, and more.",
- image: { url: "/path/to/logo.png" },
- }}
- conversationStarters={{
- variant: "short", // or "long"
- options: [
- {
- displayText: "Help me get started",
- prompt: "Help me get started",
- icon: <Sparkles size={16} />,
- },
- {
- displayText: "What can you do?",
- prompt: "What can you do?",
- // No icon = default lightbulb
- },
- {
- displayText: "Tell me about features",
- prompt: "Tell me about your features",
- icon: <Zap size={16} />,
- },
- ],
- }}
- />
- );
-}
-```
-
-## Bottom Tray Type
-
-The bottom-tray type provides a floating chat interface with a built-in trigger button (bottom-right corner):
-
-```tsx
-import { OpenUIChat } from "@openuidev/react-ui";
-
-function App() {
- return (
- <OpenUIChat
- processMessage={...}
- type="bottom-tray"
- logoUrl="/logo.png"
- agentName="AI Assistant"
- welcomeMessage={{
- title: "Need help?",
- description: "I'm here to assist you.",
- image: { url: "/logo.png" },
- }}
- conversationStarters={{
- variant: "short",
- options: [
- { displayText: "Get started", prompt: "Help me get started" },
- ],
- }}
- />
- );
-}
-```
-
-**Note:** The bottom-tray includes a built-in floating trigger button that opens/closes the tray. You don't need to add your own toggle button.
-
-### Controlled Mode (Optional)
-
-If you need programmatic control over the tray's open state:
-
-```tsx
-import { useState } from "react";
-import { OpenUIChat } from "@openuidev/react-ui";
-
-function App() {
- const [isOpen, setIsOpen] = useState(false);
-
- // Example: Open tray programmatically after some action
- const handleSomeAction = () => {
- setIsOpen(true);
- };
-
- return (
- <OpenUIChat
- processMessage={...}
- type="bottom-tray"
- isOpen={isOpen}
- onOpenChange={setIsOpen}
- logoUrl="/logo.png"
- agentName="AI Assistant"
- />
- );
-}
-```
-
-## Copilot Type
-
-The copilot type is ideal for side panel integrations:
-
-```tsx
-import { OpenUIChat } from "@openuidev/react-ui";
-
-function App() {
- return (
- <div style={{ display: "flex" }}>
- <main style={{ flex: 1 }}>
- {/* Your app content */}
- </main>
- <aside style={{ width: 400, borderLeft: "1px solid #eee" }}>
- <OpenUIChat
- processMessage={...}
- type="copilot"
- logoUrl="/logo.png"
- agentName="Assistant"
- welcomeMessage={{
- title: "Hi, I'm your copilot",
- description: "Ask me anything about your work.",
- }}
- />
- </aside>
- </div>
- );
-}
-```
-
-## Header Customization
-
-Each layout provides a way to inject custom actions into its header area.
-
-### FullScreen
-
-FullScreen has two header slots:
-
-- **`threadHeader`** — Desktop-only header bar rendered above the message area. Hidden on mobile.
-- **`mobileHeaderActions`** — Content injected into the right side of the mobile header, before the "new chat" button.
-
-```tsx
-import { FullScreen } from "@openuidev/react-ui";
-import { Button, IconButton } from "@openuidev/react-ui";
-import { ChevronDown, Share, ThumbsUp } from "lucide-react";
-
-<FullScreen
- processMessage={...}
- threadHeader={
- <>
- <Button iconLeft={<ChevronDown size={14} />} variant="secondary" size="small">
- GPT-5.5
- </Button>
- <div style={{ display: "flex", gap: "4px" }}>
- <IconButton icon={<ThumbsUp size={16} />} aria-label="Feedback" size="small" variant="secondary" />
- <Button iconLeft={<Share size={14} />} variant="secondary" size="small">Share</Button>
- </div>
- </>
- }
- mobileHeaderActions={
- <IconButton icon={<Share size={16} />} aria-label="Share" size="medium" variant="secondary" />
- }
-/>
-```
-
-### Copilot
-
-Copilot has a single header with a right-side slot:
-
-- **`headerActions`** — Content rendered on the right side of the header, next to the logo and agent name.
-
-```tsx
-import { Copilot } from "@openuidev/react-ui";
-import { IconButton } from "@openuidev/react-ui";
-import { Download, Share } from "lucide-react";
-
-<Copilot
- processMessage={...}
- headerActions={
- <>
- <IconButton icon={<Download size={16} />} aria-label="Export" size="small" variant="secondary" />
- <IconButton icon={<Share size={16} />} aria-label="Share" size="small" variant="secondary" />
- </>
- }
-/>
-```
-
-### BottomTray
-
-BottomTray has a header with built-in thread list, new chat, and minimize buttons. Custom actions are inserted before these:
-
-- **`headerActions`** — Content rendered on the right side of the header, before the thread list and new chat buttons.
-
-```tsx
-import { BottomTray } from "@openuidev/react-ui";
-import { IconButton } from "@openuidev/react-ui";
-import { Share } from "lucide-react";
-
-<BottomTray
- processMessage={...}
- headerActions={
- <IconButton icon={<Share size={16} />} aria-label="Share" size="small" variant="tertiary" />
- }
-/>
-```
-
-## Props
-
-### Core Props
-
-| Prop | Type | Description |
-| ---------------- | -------------------------------------------- | ------------------------------------- |
-| `type` | `"standalone" \| "copilot" \| "bottom-tray"` | Layout type (default: `"standalone"`) |
-| `processMessage` | `(params) => Promise<Response>` | Handler for processing messages |
-| `logoUrl` | `string` | URL for the logo image |
-| `agentName` | `string` | Name displayed in the header |
-
-### Welcome Message
-
-| Prop | Type | Description |
-| ---------------- | ---------------------- | ----------------------------- |
-| `welcomeMessage` | `WelcomeMessageConfig` | Welcome message configuration |
-
-`WelcomeMessageConfig` can be either:
-
-**Props-based configuration:**
-
-```typescript
-{
- title?: string;
- description?: string;
- image?: { url: string } | ReactNode;
- // { url: string } - Renders with default 64x64 size, rounded corners
- // ReactNode - Full control over styling (e.g., <img />, <Sparkles />)
-}
-```
-
-**Custom component:**
-
-```typescript
-React.ComponentType<any>;
-// Note: Custom components are wrapped with WelcomeScreen for proper container styling
-```
-
-### Conversation Starters
-
-| Prop | Type | Description |
-| ---------------------- | ---------------------------- | ----------------------------------- |
-| `conversationStarters` | `ConversationStartersConfig` | Conversation starters configuration |
-
-```typescript
-interface ConversationStartersConfig {
- variant?: "short" | "long";
- options: Array<{
- displayText: string;
- prompt: string;
- icon?: ReactNode; // undefined = default lightbulb, <></> = no icon
- }>;
-}
-```
-
-**Icon options:**
-
-- `undefined` (not provided) - Shows default lightbulb icon
-- `<Sparkles size={16} />` - Custom icon
-- `<></>` (empty fragment) - No icon
-
-### FullScreen Props
-
-These props only apply to the `standalone` (FullScreen) layout:
-
-| Prop | Type | Description |
-| --------------------- | ----------- | --------------------------------------------------------------- |
-| `threadHeader` | `ReactNode` | Custom content for the desktop thread header (hidden on mobile) |
-| `mobileHeaderActions` | `ReactNode` | Custom content for the right side of the mobile header |
-
-### Copilot Props
-
-These props only apply to the `copilot` layout:
-
-| Prop | Type | Description |
-| --------------- | ----------- | ----------------------------------------------- |
-| `headerActions` | `ReactNode` | Custom content for the right side of the header |
-
-### Bottom Tray Props
-
-These props only apply when `type="bottom-tray"`. The tray includes a built-in trigger button, so these are optional for controlled mode:
-
-| Prop | Type | Description |
-| --------------- | --------------------------- | ------------------------------------------------------------------------- |
-| `isOpen` | `boolean` | Controlled open state (optional) |
-| `onOpenChange` | `(isOpen: boolean) => void` | Callback when open state changes (optional) |
-| `defaultOpen` | `boolean` | Initial open state, default: `false` (optional) |
-| `headerActions` | `ReactNode` | Custom content for the right side of the header (before built-in buttons) |
-
-### Advanced Props
-
-| Prop | Type | Description |
-| ------------------------ | ------------------------------ | ------------------------------- |
-| `threadManager` | `ThreadManager` | Custom thread manager |
-| `threadListManager` | `ThreadListManager` | Custom thread list manager |
-| `responseTemplates` | `ResponseTemplate[]` | Response templates |
-| `createThread` | `(message) => Promise<Thread>` | Custom thread creation |
-| `onUpdateMessage` | `(props) => void` | Message update callback |
-| `processStreamedMessage` | `function` | Custom stream processor |
-| `theme` | `ThemeProps` | Theme configuration |
-| `scrollVariant` | `ScrollVariant` | Scroll behavior variant |
-| `disableThemeProvider` | `boolean` | Disable built-in theme provider |
-| `messageLoading` | `React.ComponentType` | Custom loading component |
-| `isArtifactActive` | `boolean` | Show artifact panel |
-| `renderArtifact` | `() => ReactNode` | Artifact content renderer |
-
-## Custom Welcome Component
-
-You can provide a custom welcome component instead of the props-based configuration. The custom component will be wrapped with `WelcomeScreen` for proper container styling:
-
-```tsx
-import { OpenUIChat } from "@openuidev/react-ui";
-import { Sparkles } from "lucide-react";
-
-const MyCustomWelcome = () => (
- <div style={{ textAlign: "center" }}>
- <div
- style={{
- width: 80,
- height: 80,
- borderRadius: 16,
- background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- margin: "0 auto 16px",
- }}
- >
- <Sparkles size={40} color="white" />
- </div>
- <h2 style={{ margin: "0 0 8px", fontSize: 20, fontWeight: 600 }}>
- Welcome to My App
- </h2>
- <p style={{ margin: 0, color: "rgba(0,0,0,0.5)", fontSize: 14 }}>
- This is a custom welcome screen
- </p>
- </div>
-);
-
-<OpenUIChat
- processMessage={...}
- welcomeMessage={MyCustomWelcome}
-/>
-```
-
-**Note:** When using a custom component, conversation starters are rendered separately below the welcome screen.
-
-## Conversation Starter Variants
-
-### Short Variant (default)
-
-Pill-style buttons that wrap horizontally:
-
-```tsx
-import { Sparkles } from "lucide-react";
-
-// In your component:
-conversationStarters={{
- variant: "short",
- options: [
- { displayText: "With custom icon", prompt: "Prompt 1", icon: <Sparkles size={16} /> },
- { displayText: "Default lightbulb", prompt: "Prompt 2" }, // icon undefined = lightbulb
- { displayText: "No icon", prompt: "Prompt 3", icon: <></> }, // empty fragment = no icon
- ],
-}}
-```
-
-### Long Variant
-
-Vertical list with separators and hover arrows:
-
-```tsx
-import { Sparkles } from "lucide-react";
-
-// In your component:
-conversationStarters={{
- variant: "long",
- options: [
- {
- displayText: "This is a longer prompt that explains more context",
- prompt: "Full prompt text",
- icon: <Sparkles size={16} />,
- },
- ],
-}}
-```
-
-## Using Custom Thread Managers
-
-For advanced use cases, you can provide your own thread managers:
-
-```tsx
-import { useThreadListManager, useThreadManager } from "@openuidev/react-headless";
-
-function App() {
- const threadListManager = useThreadListManager({
- createThread: async () => ({ ... }),
- fetchThreadList: async () => [...],
- deleteThread: async (id) => { ... },
- updateThread: async (thread) => thread,
- onSwitchToNew: () => {},
- onSelectThread: (threadId) => {},
- });
-
- const threadManager = useThreadManager({
- threadId: threadListManager.selectedThreadId,
- loadThread: async (threadId) => [...],
- onProcessMessage: async ({ message, threadManager }) => [...],
- responseTemplates: [],
- });
-
- return (
- <OpenUIChat
- threadListManager={threadListManager}
- threadManager={threadManager}
- type="standalone"
- welcomeMessage={{ title: "Hello!" }}
- />
- );
-}
-```
-
-## Theming
-
-OpenUIChat uses CSS custom properties for theming. You can customize colors, spacing, and typography:
-
-```tsx
-<OpenUIChat
- theme={{
- primaryColor: "#6366f1",
- backgroundColor: "#f8fafc",
- // ... other theme options
- }}
- processMessage={...}
-/>
-```
-
-Or disable the built-in theme provider to use your own:
-
-```tsx
-<OpenUIChat
- disableThemeProvider
- processMessage={...}
-/>
-```
-
-## Migration from Composed Components
-
-If you're currently using the individual shell components and want to migrate to OpenUIChat:
-
-**Before (using Shell components):**
-
-```tsx
-<ChatProvider threadListManager={...} threadManager={...}>
- <Container logoUrl={logo} agentName="Assistant">
- <SidebarContainer>...</SidebarContainer>
- <ThreadContainer>
- <MobileHeader />
- <WelcomeScreen title="Hello" />
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={[...]} />
- <Composer />
- </ThreadContainer>
- </Container>
-</ChatProvider>
-```
-
-**After (using OpenUIChat):**
-
-```tsx
-<OpenUIChat
- threadListManager={...}
- threadManager={...}
- type="standalone"
- logoUrl={logo}
- agentName="Assistant"
- welcomeMessage={{ title: "Hello" }}
- conversationStarters={{ options: [...] }}
-/>
-```
diff --git a/packages/react-ui/src/components/OpenUIChat/stories/OpenUIChat.stories.tsx b/packages/react-ui/src/components/OpenUIChat/stories/OpenUIChat.stories.tsx
deleted file mode 100644
index ccd7a8e43..000000000
--- a/packages/react-ui/src/components/OpenUIChat/stories/OpenUIChat.stories.tsx
+++ /dev/null
@@ -1,339 +0,0 @@
-import type { Message } from "@openuidev/react-headless";
-import { ChevronDown, Download, Share, Sparkles, ThumbsUp, Zap } from "lucide-react";
-import { useState } from "react";
-import logoUrl from "../../BottomTray/stories/thesysdev_logo.jpeg";
-import { Button } from "../../Button";
-import { IconButton } from "../../IconButton";
-import { BottomTray } from "../ComposedBottomTray.js";
-import { Copilot } from "../ComposedCopilot.js";
-import { FullScreen } from "../ComposedStandalone.js";
-import { ConversationStartersConfig, WelcomeMessageConfig } from "../types.js";
-
-export default {
- title: "Components/OpenUIChat",
- tags: ["dev"],
-};
-
-function mockSSEResponse(text: string, delayMs = 500): Promise<Response> {
- return new Promise((resolve) => {
- setTimeout(() => {
- const events = `data: ${JSON.stringify({ type: "TEXT_MESSAGE_CONTENT", delta: text })}\n\ndata: [DONE]\n\n`;
- const stream = new ReadableStream({
- start(controller) {
- controller.enqueue(new TextEncoder().encode(events));
- controller.close();
- },
- });
- resolve(new Response(stream));
- }, delayMs);
- });
-}
-
-const SAMPLE_WELCOME_MESSAGE: WelcomeMessageConfig = {
- title: "Hi, I'm OpenUI Assistant",
- description: "I can help you with questions about your account, products, and more.",
- image: { url: logoUrl },
-};
-
-const SAMPLE_STARTERS: ConversationStartersConfig = {
- variant: "short",
- options: [
- {
- displayText: "Help me get started",
- prompt: "Help me get started with OpenUI",
- icon: <Sparkles size={16} />,
- },
- {
- displayText: "What can you do?",
- prompt: "What can you do?",
- },
- {
- displayText: "Tell me about features",
- prompt: "Tell me about your features",
- icon: <Zap size={16} />,
- },
- ],
-};
-
-const LONG_STARTERS: ConversationStartersConfig = {
- variant: "long",
- options: [
- {
- displayText: "Help me get started with this application and guide me through the features",
- prompt: "Help me get started",
- icon: <Sparkles size={16} />,
- },
- {
- displayText: "What can you do? I'd like to know all your capabilities",
- prompt: "What can you do?",
- },
- {
- displayText: "Tell me about your advanced features and how I can use them effectively",
- prompt: "Tell me about your features",
- icon: <Zap size={16} />,
- },
- ],
-};
-
-const mockGenerateShareLink = async (threadId: string) => {
- await new Promise((r) => setTimeout(r, 1000));
- return `https://example.com/shared/${threadId}`;
-};
-
-const mockProcessMessage = async ({ messages }: { messages: Message[] }) => {
- const lastMsg = messages[messages.length - 1];
- const content =
- lastMsg?.role === "user" && typeof lastMsg.content === "string" ? lastMsg.content : "";
- return mockSSEResponse(`You said: "${content}". This is a response from the AI assistant.`);
-};
-
-const sharedProps = {
- processMessage: mockProcessMessage,
- fetchThreadList: async () => ({
- threads: [
- { id: "1", title: "Previous Chat 1", createdAt: Date.now() },
- { id: "2", title: "Previous Chat 2", createdAt: Date.now() },
- { id: "3", title: "Previous Chat 3", createdAt: Date.now() },
- ],
- }),
- createThread: async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- }),
- deleteThread: async () => {},
- updateThread: async (t: any) => t,
- loadThread: async (threadId: string) => {
- if (!threadId) return [];
- return [
- { id: crypto.randomUUID(), role: "user", content: "Hello" },
- {
- id: crypto.randomUUID(),
- role: "assistant",
- content: "Hello! How can I help you today?",
- },
- ] as Message[];
- },
- logoUrl,
- agentName: "OpenUI Assistant",
-};
-
-export const Default = {
- render: () => (
- <div style={{ minHeight: "100vh", background: "var(--openui-bg-fill, #f5f5f5)" }}>
- <FullScreen {...sharedProps} />
- </div>
- ),
-};
-
-export const StandaloneWithWelcome = {
- render: () => (
- <div style={{ minHeight: "100vh", background: "var(--openui-bg-fill, #f5f5f5)" }}>
- <FullScreen
- {...sharedProps}
- welcomeMessage={SAMPLE_WELCOME_MESSAGE}
- conversationStarters={SAMPLE_STARTERS}
- />
- </div>
- ),
-};
-
-export const StandaloneLongStarters = {
- render: () => (
- <div style={{ minHeight: "100vh", background: "var(--openui-bg-fill, #f5f5f5)" }}>
- <FullScreen
- {...sharedProps}
- welcomeMessage={SAMPLE_WELCOME_MESSAGE}
- conversationStarters={LONG_STARTERS}
- />
- </div>
- ),
-};
-
-export const StandaloneWithShareLink = {
- render: () => (
- <div style={{ minHeight: "100vh", background: "var(--openui-bg-fill, #f5f5f5)" }}>
- <FullScreen
- {...sharedProps}
- welcomeMessage={SAMPLE_WELCOME_MESSAGE}
- conversationStarters={SAMPLE_STARTERS}
- generateShareLink={mockGenerateShareLink}
- />
- </div>
- ),
-};
-
-export const StandaloneWithThreadHeader = {
- render: () => (
- <div style={{ minHeight: "100vh", background: "var(--openui-bg-fill, #f5f5f5)" }}>
- <FullScreen
- {...sharedProps}
- welcomeMessage={SAMPLE_WELCOME_MESSAGE}
- conversationStarters={SAMPLE_STARTERS}
- threadHeader={
- <>
- <Button iconLeft={<ChevronDown size={14} />} variant="secondary" size="small">
- GPT-5.5
- </Button>
- <div style={{ display: "flex", gap: "4px" }}>
- <IconButton
- icon={<ThumbsUp size={16} />}
- aria-label="Feedback"
- size="small"
- variant="secondary"
- />
- <IconButton
- icon={<Download size={16} />}
- aria-label="Export"
- size="small"
- variant="secondary"
- />
- <Button iconLeft={<Share size={14} />} variant="secondary" size="small">
- Share
- </Button>
- </div>
- </>
- }
- />
- </div>
- ),
-};
-
-export const CopilotDefault = {
- render: () => (
- <div style={{ minHeight: "100vh", background: "var(--openui-bg-fill, #f5f5f5)" }}>
- <Copilot {...sharedProps} />
- </div>
- ),
-};
-
-export const CopilotWithWelcome = {
- render: () => (
- <div style={{ minHeight: "100vh", background: "var(--openui-bg-fill, #f5f5f5)" }}>
- <Copilot
- {...sharedProps}
- welcomeMessage={SAMPLE_WELCOME_MESSAGE}
- conversationStarters={SAMPLE_STARTERS}
- />
- </div>
- ),
-};
-
-export const CopilotWithShareLink = {
- render: () => (
- <div style={{ minHeight: "100vh", background: "var(--openui-bg-fill, #f5f5f5)" }}>
- <Copilot
- {...sharedProps}
- welcomeMessage={SAMPLE_WELCOME_MESSAGE}
- conversationStarters={SAMPLE_STARTERS}
- generateShareLink={mockGenerateShareLink}
- />
- </div>
- ),
-};
-
-export const CopilotWithHeaderActions = {
- render: () => (
- <div style={{ minHeight: "100vh", background: "var(--openui-bg-fill, #f5f5f5)" }}>
- <Copilot
- {...sharedProps}
- welcomeMessage={SAMPLE_WELCOME_MESSAGE}
- headerActions={
- <>
- <IconButton
- icon={<Download size={16} />}
- aria-label="Export"
- size="small"
- variant="secondary"
- />
- <IconButton
- icon={<Share size={16} />}
- aria-label="Share"
- size="small"
- variant="secondary"
- />
- </>
- }
- />
- </div>
- ),
-};
-
-const BottomTrayStory = ({ defaultOpen = false, ...rest }: any) => {
- const [isOpen, setIsOpen] = useState(defaultOpen);
- return (
- <div style={{ minHeight: "100vh", background: "var(--openui-bg-fill, #f5f5f5)" }}>
- <div style={{ padding: "2rem" }}>
- <h1 style={{ marginBottom: "1rem" }}>Bottom Tray Example</h1>
- <p style={{ marginBottom: "1rem" }}>
- The chat appears as a bottom tray. Click the pill button to open/close.
- </p>
- <button
- onClick={() => setIsOpen(!isOpen)}
- style={{
- padding: "0.5rem 1rem",
- background: "var(--openui-interactive-default)",
- border: "1px solid var(--openui-stroke-interactive-el)",
- borderRadius: "8px",
- cursor: "pointer",
- }}
- >
- {isOpen ? "Close" : "Open"} Chat
- </button>
- </div>
- <BottomTray {...sharedProps} {...rest} isOpen={isOpen} onOpenChange={setIsOpen} />
- </div>
- );
-};
-
-export const BottomTrayDefault = {
- render: () => <BottomTrayStory />,
-};
-
-export const BottomTrayOpen = {
- render: () => <BottomTrayStory defaultOpen />,
-};
-
-export const BottomTrayWithWelcome = {
- render: () => (
- <BottomTrayStory
- defaultOpen
- welcomeMessage={SAMPLE_WELCOME_MESSAGE}
- conversationStarters={SAMPLE_STARTERS}
- />
- ),
-};
-
-export const BottomTrayLongStarters = {
- render: () => (
- <BottomTrayStory
- defaultOpen
- welcomeMessage={SAMPLE_WELCOME_MESSAGE}
- conversationStarters={LONG_STARTERS}
- />
- ),
-};
-
-export const BottomTrayWithShareLink = {
- render: () => (
- <BottomTrayStory
- defaultOpen
- welcomeMessage={SAMPLE_WELCOME_MESSAGE}
- conversationStarters={SAMPLE_STARTERS}
- generateShareLink={mockGenerateShareLink}
- />
- ),
-};
-
-export const BottomTrayWithHeaderActions = {
- render: () => (
- <BottomTrayStory
- defaultOpen
- welcomeMessage={SAMPLE_WELCOME_MESSAGE}
- conversationStarters={SAMPLE_STARTERS}
- headerActions={
- <IconButton icon={<Share size={16} />} aria-label="Share" size="small" variant="tertiary" />
- }
- />
- ),
-};
diff --git a/packages/react-ui/src/components/OpenUIChat/types.ts b/packages/react-ui/src/components/OpenUIChat/types.ts
index 6708d0078..9729bb019 100644
--- a/packages/react-ui/src/components/OpenUIChat/types.ts
+++ b/packages/react-ui/src/components/OpenUIChat/types.ts
@@ -87,7 +87,7 @@ export type ComposerProps = {
export type ComposerComponent = React.ComponentType<ComposerProps>;
/**
- * Shared UI props for all chat layout variants (FullScreen, Copilot, BottomTray).
+ * Shared UI props for the AgentInterface chat surface.
*/
export interface SharedChatUIProps {
logoUrl?: string;
diff --git a/packages/react-ui/src/components/OpenUIChat/withChatProvider.tsx b/packages/react-ui/src/components/OpenUIChat/withChatProvider.tsx
index 714334433..ab216af63 100644
--- a/packages/react-ui/src/components/OpenUIChat/withChatProvider.tsx
+++ b/packages/react-ui/src/components/OpenUIChat/withChatProvider.tsx
@@ -17,45 +17,24 @@ export type ChatLayoutProps<Extra = {}> = Omit<ChatProviderProps, "children"> &
ThemeWrapperProps &
Extra;
-const DummyThemeProvider = ({ children }: { children: React.ReactNode }) => {
- return children;
-};
-
-const CHAT_PROVIDER_PROP_KEYS: Set<keyof Omit<ChatProviderProps, "children">> = new Set([
- "apiUrl",
- "processMessage",
- "threadApiUrl",
- "fetchThreadList",
- "createThread",
- "deleteThread",
- "updateThread",
- "loadThread",
- "streamProtocol",
- "messageFormat",
-]);
+const DummyThemeProvider = ({ children }: { children: React.ReactNode }) => children;
export function withChatProvider<ExtraProps = {}>(WrappedComponent: React.ComponentType<any>) {
const WithChatProvider = (props: ChatLayoutProps<ExtraProps>) => {
- const innerProps: Record<string, unknown> = {};
- const chatProviderProps: Record<string, unknown> = {};
- let theme: ThemeProps | undefined;
- let disableThemeProvider = false;
-
- for (const [key, value] of Object.entries(props)) {
- if (key === "theme") {
- theme = value as ThemeProps;
- } else if (key === "disableThemeProvider") {
- disableThemeProvider = value as boolean;
- } else if (CHAT_PROVIDER_PROP_KEYS.has(key as keyof Omit<ChatProviderProps, "children">)) {
- chatProviderProps[key] = value;
- } else {
- innerProps[key] = value;
- }
- }
+ const {
+ storage,
+ llm,
+ artifactRenderers,
+ artifactCategories,
+ theme,
+ disableThemeProvider,
+ ...innerProps
+ } = props as ChatLayoutProps<ExtraProps>;
- const componentLibrary = innerProps["componentLibrary"] as Library | undefined;
- const customAssistantMessage = innerProps["assistantMessage"];
- const customUserMessage = innerProps["userMessage"];
+ const sharedUIProps = innerProps as SharedChatUIProps;
+ const componentLibrary = sharedUIProps.componentLibrary as Library | undefined;
+ const customAssistantMessage = sharedUIProps.assistantMessage;
+ const customUserMessage = sharedUIProps.userMessage;
const genUIAssistantMessage = useMemo(() => {
if (customAssistantMessage || !componentLibrary) return undefined;
@@ -69,19 +48,25 @@ export function withChatProvider<ExtraProps = {}>(WrappedComponent: React.Compon
return ({ message }: { message: UserMessage }) => <GenUIUserMessage message={message} />;
}, [customUserMessage, componentLibrary]);
+ const finalInnerProps: Record<string, unknown> = { ...innerProps };
if (genUIAssistantMessage && !customAssistantMessage) {
- innerProps["assistantMessage"] = genUIAssistantMessage;
+ finalInnerProps["assistantMessage"] = genUIAssistantMessage;
}
if (genUIUserMessage && !customUserMessage) {
- innerProps["userMessage"] = genUIUserMessage;
+ finalInnerProps["userMessage"] = genUIUserMessage;
}
const ThemeProviderComponent = disableThemeProvider ? DummyThemeProvider : ThemeProvider;
return (
<ThemeProviderComponent {...theme}>
- <ChatProvider {...(chatProviderProps as any)}>
- <WrappedComponent {...innerProps} />
+ <ChatProvider
+ storage={storage}
+ llm={llm}
+ artifactRenderers={artifactRenderers}
+ artifactCategories={artifactCategories}
+ >
+ <WrappedComponent {...finalInnerProps} />
</ChatProvider>
</ThemeProviderComponent>
);
diff --git a/packages/react-ui/src/components/Shell/Container.tsx b/packages/react-ui/src/components/Shell/Container.tsx
deleted file mode 100644
index bf2feb314..000000000
--- a/packages/react-ui/src/components/Shell/Container.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import clsx from "clsx";
-import { useRef } from "react";
-import { LayoutContextProvider } from "../../context/LayoutContext";
-import { useElementSize } from "../../hooks/useElementSize";
-import { ShellStoreProvider } from "../_shared/store";
-
-interface ContainerProps {
- children?: React.ReactNode;
- logoUrl: string;
- agentName: string;
- className?: string;
- showAssistantLogo?: boolean;
-}
-
-export const Container = ({
- children,
- logoUrl,
- agentName,
- className,
- showAssistantLogo = false,
-}: ContainerProps) => {
- const ref = useRef<HTMLDivElement>(null);
- const { width } = useElementSize({ ref }) || {};
- // TODO: revisit this logic
- const isMobile = width > 0 && width < 768;
- const isFullScreen = width > 768;
- const layout = isMobile ? "mobile" : isFullScreen ? "fullscreen" : "tray";
-
- return (
- <ShellStoreProvider
- logoUrl={logoUrl}
- agentName={agentName}
- showAssistantLogo={showAssistantLogo}
- >
- <LayoutContextProvider layout={layout}>
- <div
- className={clsx(
- "openui-shell-container",
- {
- "openui-shell-container--mobile": isMobile,
- },
- className,
- )}
- ref={ref}
- >
- {children}
- </div>
- </LayoutContextProvider>
- </ShellStoreProvider>
- );
-};
diff --git a/packages/react-ui/src/components/Shell/MobileHeader.tsx b/packages/react-ui/src/components/Shell/MobileHeader.tsx
deleted file mode 100644
index cb67585b5..000000000
--- a/packages/react-ui/src/components/Shell/MobileHeader.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { useThreadList } from "@openuidev/react-headless";
-import clsx from "clsx";
-import { Menu, Plus } from "lucide-react";
-import { ReactNode } from "react";
-import { IconButton } from "../IconButton";
-import { useShellStore } from "../_shared/store";
-
-interface MobileHeaderProps {
- className?: string;
- rightChildren?: ReactNode;
-}
-
-export const MobileHeader = ({ className, rightChildren }: MobileHeaderProps) => {
- const switchToNewThread = useThreadList((s) => s.switchToNewThread);
- const { logoUrl, agentName, setIsSidebarOpen } = useShellStore((state) => ({
- logoUrl: state.logoUrl,
- agentName: state.agentName,
- setIsSidebarOpen: state.setIsSidebarOpen,
- }));
-
- return (
- <div className={clsx("openui-shell-mobile-header", className)}>
- <IconButton
- size="medium"
- icon={<Menu size="1em" />}
- onClick={() => setIsSidebarOpen(true)}
- variant="secondary"
- aria-label="Open sidebar"
- />
- <div className="openui-shell-mobile-header-logo-container">
- <img className="openui-shell-mobile-header-logo" src={logoUrl} alt="Logo" />
- <span className="openui-shell-mobile-header-agent-name">{agentName}</span>
- </div>
- <div className="openui-shell-mobile-header-actions">
- {rightChildren}
- <IconButton
- size="medium"
- icon={<Plus size="1em" />}
- onClick={switchToNewThread}
- variant="secondary"
- aria-label="New chat"
- />
- </div>
- </div>
- );
-};
diff --git a/packages/react-ui/src/components/Shell/NewChatButton.tsx b/packages/react-ui/src/components/Shell/NewChatButton.tsx
deleted file mode 100644
index f06fa7d5c..000000000
--- a/packages/react-ui/src/components/Shell/NewChatButton.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { useThreadList } from "@openuidev/react-headless";
-import clsx from "clsx";
-import { SquarePen } from "lucide-react";
-import { useLayoutContext } from "../../context/LayoutContext";
-import { Button } from "../Button";
-import { IconButton } from "../IconButton";
-import { useShellStore } from "../_shared/store";
-import { useOptionalSidebarVisualState } from "./Sidebar";
-
-export const NewChatButton = ({ className }: { className?: string }) => {
- const switchToNewThread = useThreadList((s) => s.switchToNewThread);
- const { isSidebarOpen } = useShellStore((state) => ({
- isSidebarOpen: state.isSidebarOpen,
- }));
- const { layout } = useLayoutContext();
- const sidebarVisualState = useOptionalSidebarVisualState();
- const showExpandedButton = sidebarVisualState
- ? sidebarVisualState.visualState === "expanded"
- : isSidebarOpen;
- const isMobile = layout === "mobile";
-
- if (!showExpandedButton) {
- return (
- <IconButton
- icon={<SquarePen size="1em" />}
- onClick={(e) => {
- e.stopPropagation();
- switchToNewThread();
- }}
- variant="secondary"
- size={isMobile ? "medium" : "small"}
- className={clsx("openui-shell-new-chat-button_collapsed", className)}
- />
- );
- }
-
- return (
- <Button
- className={clsx("openui-shell-new-chat-button", className)}
- iconLeft={<SquarePen />}
- variant="secondary"
- size={isMobile ? "medium" : "small"}
- onClick={switchToNewThread}
- >
- New Chat
- </Button>
- );
-};
diff --git a/packages/react-ui/src/components/Shell/ResizableSeparator.tsx b/packages/react-ui/src/components/Shell/ResizableSeparator.tsx
deleted file mode 100644
index fbdf38196..000000000
--- a/packages/react-ui/src/components/Shell/ResizableSeparator.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import clsx from "clsx";
-import { useEffect, useRef } from "react";
-
-interface ResizableSeparatorProps {
- onResize: (clientX: number) => void;
- onDragStart: () => void;
- onDragEnd: () => void;
- className?: string;
-}
-
-/**
- * A draggable vertical separator for resizing panels.
- * Used between chat and artifact panels in desktop mode.
- */
-export const ResizableSeparator = ({
- onResize,
- onDragStart,
- onDragEnd,
- className,
-}: ResizableSeparatorProps) => {
- const isDraggingRef = useRef(false);
- const onResizeRef = useRef(onResize);
- const onDragStartRef = useRef(onDragStart);
- const onDragEndRef = useRef(onDragEnd);
-
- // Keep callback refs up to date without triggering effect re-runs
- useEffect(() => {
- onResizeRef.current = onResize;
- onDragStartRef.current = onDragStart;
- onDragEndRef.current = onDragEnd;
- }, [onResize, onDragStart, onDragEnd]);
-
- // Global mouse event handlers for drag behavior
- // Uses refs instead of dependencies to avoid re-creating listeners
- useEffect(() => {
- const handleMouseMove = (e: MouseEvent) => {
- if (isDraggingRef.current) {
- e.preventDefault();
- onResizeRef.current(e.clientX);
- }
- };
-
- const handleMouseUp = () => {
- if (isDraggingRef.current) {
- isDraggingRef.current = false;
- onDragEndRef.current();
- // Reset cursor styles
- document.body.style.cursor = "";
- document.body.style.userSelect = "";
- }
- };
-
- document.addEventListener("mousemove", handleMouseMove);
- document.addEventListener("mouseup", handleMouseUp);
-
- return () => {
- document.removeEventListener("mousemove", handleMouseMove);
- document.removeEventListener("mouseup", handleMouseUp);
- };
- }, []); // Empty deps - handlers use refs to access latest callbacks
-
- const handleMouseDown = () => {
- isDraggingRef.current = true;
- onDragStartRef.current();
- document.body.style.cursor = "col-resize";
- document.body.style.userSelect = "none";
- };
-
- return (
- <div
- className={clsx("openui-shell-resizable-separator", className)}
- onMouseDown={handleMouseDown}
- >
- <div className="openui-shell-resizable-separator__handle" />
- </div>
- );
-};
diff --git a/packages/react-ui/src/components/Shell/components/composer.scss b/packages/react-ui/src/components/Shell/components/composer.scss
deleted file mode 100644
index 223f46b6c..000000000
--- a/packages/react-ui/src/components/Shell/components/composer.scss
+++ /dev/null
@@ -1,73 +0,0 @@
-@use "../../../cssUtils" as cssUtils;
-
-$center-align-spacing: calc(32px + cssUtils.$space-s);
-
-.openui-shell-thread-composer {
- max-width: 880px;
- width: 100%;
- margin: 0 auto cssUtils.$space-m;
- padding: 0 $center-align-spacing;
-
- .openui-shell-container--mobile & {
- margin: 0;
- padding: cssUtils.$space-m 14px;
- }
-
- .openui-shell-thread-container--artifact-active & {
- padding-left: 0;
- padding-right: cssUtils.$space-m;
- }
-
- &__input-wrapper {
- background-color: cssUtils.$foreground;
- border: 1px solid cssUtils.$border-interactive;
- border-radius: cssUtils.$radius-3xl;
- box-shadow: cssUtils.$shadow-m;
- overflow: clip;
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-s;
- padding: cssUtils.$space-s-m;
- }
-
- &__input {
- scrollbar-width: thin;
- scrollbar-color: cssUtils.$elevated transparent;
-
- &::-webkit-scrollbar {
- width: 6px;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background-color: cssUtils.$elevated;
- border-radius: cssUtils.$radius-full;
- }
-
- padding: 0 cssUtils.$space-3xs;
- resize: none;
- max-height: 200px;
- outline: none;
- border: none;
- background: transparent;
- overflow-y: auto;
- @include cssUtils.typography(body, default);
- color: cssUtils.$text-neutral-primary;
-
- &::placeholder {
- color: cssUtils.$text-neutral-secondary;
- }
- }
-
- &__action-bar {
- display: flex;
- align-items: center;
- }
-
- &__submit-button {
- margin-left: auto;
- }
-}
diff --git a/packages/react-ui/src/components/Shell/dependencies.ts b/packages/react-ui/src/components/Shell/dependencies.ts
deleted file mode 100644
index 3028df8d3..000000000
--- a/packages/react-ui/src/components/Shell/dependencies.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import buttonDeps from "../Button/dependencies";
-import iconButtonDeps from "../IconButton/dependencies";
-
-const dependencies = ["Shell", ...iconButtonDeps, ...buttonDeps];
-export default dependencies;
diff --git a/packages/react-ui/src/components/Shell/index.ts b/packages/react-ui/src/components/Shell/index.ts
deleted file mode 100644
index 2ea9bb301..000000000
--- a/packages/react-ui/src/components/Shell/index.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export * from "../_shared/artifact";
-export * from "../_shared/store";
-export * from "./components";
-export * from "./Container";
-export * from "./ConversationStarter";
-export * from "./MobileHeader";
-export * from "./NewChatButton";
-export * from "./Sidebar";
-export * from "./Thread";
-export * from "./ThreadList";
-export * from "./WelcomeScreen";
diff --git a/packages/react-ui/src/components/Shell/mobileHeader.scss b/packages/react-ui/src/components/Shell/mobileHeader.scss
deleted file mode 100644
index 9ab8b3a95..000000000
--- a/packages/react-ui/src/components/Shell/mobileHeader.scss
+++ /dev/null
@@ -1,39 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-shell-mobile-header {
- display: none;
-
- .openui-shell-container--mobile & {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: cssUtils.$space-m-l;
- }
-}
-
-.openui-shell-mobile-header-logo-container {
- display: flex;
- align-items: center;
- gap: cssUtils.$space-m;
- @include cssUtils.typography(title, medium);
- position: absolute;
- left: 50%;
- transform: translateX(-50%);
-}
-
-.openui-shell-mobile-header-logo {
- width: 32px;
- height: 32px;
- border-radius: cssUtils.$radius-m;
-}
-
-.openui-shell-mobile-header-agent-name {
- @include cssUtils.typography(title, medium);
- color: cssUtils.$text-neutral-primary;
-}
-
-.openui-shell-mobile-header-actions {
- display: flex;
- align-items: center;
- gap: cssUtils.$space-s;
-}
diff --git a/packages/react-ui/src/components/Shell/shell.scss b/packages/react-ui/src/components/Shell/shell.scss
deleted file mode 100644
index e6f9f27a9..000000000
--- a/packages/react-ui/src/components/Shell/shell.scss
+++ /dev/null
@@ -1,43 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-@use "./sidebar.scss";
-@use "./threadlist.scss";
-@use "./thread.scss";
-@use "./mobileHeader.scss";
-@use "./resizableSeparator.scss";
-@use "./conversationStarter.scss";
-@use "./welcomeScreen.scss";
-@use "./components/desktopWelcomeComposer.scss";
-@use "./components/composer.scss";
-
-.openui-shell-container {
- display: flex;
- position: relative;
- height: 100dvh;
- width: 100dvw;
- overflow: hidden;
-
- background: cssUtils.$chat-container-bg;
- box-sizing: border-box;
- & * {
- box-sizing: border-box;
- }
-
- &.openui-shell-container--mobile {
- padding: 0;
- }
-}
-
-.openui-shell-new-chat-button {
- width: 100%;
- justify-content: flex-start;
- padding-left: cssUtils.$space-s;
- padding-right: cssUtils.$space-s;
-
- .openui-shell-sidebar-header--collapsed & {
- width: auto;
- }
-}
-
-.openui-shell-new-chat-button_collapsed {
- align-self: center;
-}
diff --git a/packages/react-ui/src/components/Shell/sidebar.scss b/packages/react-ui/src/components/Shell/sidebar.scss
deleted file mode 100644
index a5084a341..000000000
--- a/packages/react-ui/src/components/Shell/sidebar.scss
+++ /dev/null
@@ -1,216 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-$sidebar-width: 272px;
-$sidebar-padding: cssUtils.$space-m;
-$sidebar-collapsed-width: calc(
- 32px + #{cssUtils.$space-m} + #{cssUtils.$space-m} + #{cssUtils.$space-3xs} +
- #{cssUtils.$space-3xs}
-);
-$sidebar-mobile-width: 294px;
-$sidebar-mobile-padding: cssUtils.$space-m-l;
-$sidebar-fade-duration: 90ms;
-$sidebar-resize-duration: 160ms;
-$sidebar-mobile-slide-duration: 400ms;
-$sidebar-motion-ease: cubic-bezier(0.22, 1, 0.36, 1);
-
-.openui-shell-sidebar-container {
- border-right: 1px solid cssUtils.$border-default;
- height: 100%;
- background-color: cssUtils.$foreground;
- width: $sidebar-width;
- padding: $sidebar-padding;
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-m;
- z-index: 999;
- transition:
- width $sidebar-resize-duration $sidebar-motion-ease,
- height $sidebar-resize-duration $sidebar-motion-ease,
- transform $sidebar-resize-duration $sidebar-motion-ease,
- background-color $sidebar-resize-duration $sidebar-motion-ease;
-
- .openui-shell-container--mobile & {
- width: $sidebar-mobile-width;
- padding: $sidebar-mobile-padding;
- position: absolute;
- left: 0;
- top: 0;
- z-index: 1000;
- background-color: cssUtils.$foreground;
- border-radius: 0;
- transition: left $sidebar-mobile-slide-duration $sidebar-motion-ease;
- }
-
- &--collapsed {
- width: $sidebar-collapsed-width;
- transform: translateX(0);
- gap: cssUtils.$space-xs;
- cursor: e-resize;
- background-color: cssUtils.$background;
-
- .openui-shell-container--mobile & {
- width: $sidebar-mobile-width;
- height: 100%;
- left: -$sidebar-mobile-width;
- transform: none;
- cursor: default;
- }
- }
-
- &--collapsed[data-sidebar-visual-state="collapsed"]:hover {
- .openui-shell-sidebar-header__logo {
- opacity: 0;
- pointer-events: none;
- }
-
- .openui-shell-sidebar-header__toggle-button {
- opacity: 1;
- pointer-events: auto;
- }
- }
-
- &--hidden {
- display: none;
- }
-
- &[data-sidebar-visual-state="collapsing"],
- &[data-sidebar-visual-state="expanding"] {
- .openui-shell-sidebar-content,
- .openui-shell-sidebar-header > :not(.openui-shell-sidebar-header__top-row) {
- opacity: 0;
- pointer-events: none;
- }
- }
-
- &[data-sidebar-visual-state="expanding"] {
- .openui-shell-sidebar-header > :not(.openui-shell-sidebar-header__top-row) {
- opacity: 0;
- pointer-events: none;
- }
- }
-}
-
-.openui-shell-sidebar-header {
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-l;
-
- & > :not(.openui-shell-sidebar-header__top-row) {
- transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
- }
-
- &__top-row {
- display: flex;
- align-items: center;
- gap: cssUtils.$space-s;
- transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
- }
-
- &__logo {
- display: block;
- width: 32px;
- height: 32px;
- margin-left: cssUtils.$space-3xs;
- border-radius: cssUtils.$radius-m;
- transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
- }
-
- &__agent-name {
- @include cssUtils.typography(label, small);
- flex-grow: 1;
- color: cssUtils.$text-neutral-primary;
-
- .openui-shell-container--mobile & {
- @include cssUtils.typography(label, default);
- }
-
- .openui-shell-sidebar-container--collapsed & {
- display: none;
- }
- }
-
- &--collapsed {
- align-items: stretch;
-
- .openui-shell-sidebar-header__top-row {
- display: block;
- position: relative;
- min-height: 32px;
- width: 100%;
- }
-
- .openui-shell-sidebar-header__logo,
- .openui-shell-sidebar-header__toggle-button {
- position: absolute;
- top: 0;
- left: cssUtils.$space-3xs;
- margin-left: 0;
- }
-
- .openui-shell-sidebar-header__logo {
- width: 32px;
- height: 32px;
- }
-
- .openui-shell-sidebar-header__toggle-button {
- opacity: 0;
- pointer-events: none;
- transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
- }
- }
-}
-
-.openui-shell-sidebar-content {
- width: calc($sidebar-width - ($sidebar-padding * 2));
-
- .openui-shell-container--mobile & {
- width: 100%;
- }
-
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-m;
- overflow: hidden;
- opacity: 1;
- transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
-
- &--collapsed {
- width: 100%;
- align-items: center;
- gap: cssUtils.$space-s;
-
- .openui-shell-thread-list {
- display: none;
- }
- }
-}
-
-.openui-shell-sidebar-separator {
- height: 1px;
- width: 100%;
- background-color: cssUtils.$border-default;
-}
-
-.openui-shell-sidebar-header__toggle-button {
- transition: opacity $sidebar-fade-duration $sidebar-motion-ease;
-
- .openui-shell-container--mobile & {
- display: none;
- }
-}
-
-.openui-shell-sidebar-container__overlay {
- position: absolute;
- left: 0;
- top: 0;
- width: 100%;
- height: 100%;
- background-color: cssUtils.$overlay;
- transition: opacity $sidebar-resize-duration $sidebar-motion-ease;
- z-index: 99;
-
- &--collapsed {
- opacity: 0;
- pointer-events: none;
- }
-}
diff --git a/packages/react-ui/src/components/Shell/stories/Shell.mdx b/packages/react-ui/src/components/Shell/stories/Shell.mdx
deleted file mode 100644
index 15c73712f..000000000
--- a/packages/react-ui/src/components/Shell/stories/Shell.mdx
+++ /dev/null
@@ -1,397 +0,0 @@
-import { Meta } from "@storybook/blocks";
-import * as ShellStories from "./Shell.stories";
-
-<Meta of={ShellStories} />
-
-# Shell
-
-The Shell is a **full-page composable chat interface** with a sidebar for thread management. It's designed for applications where chat is the primary interface, providing a complete desktop and mobile experience.
-
-## Component Structure
-
-```
-ChatProvider
-└── Container (full-page wrapper)
- ├── SidebarContainer (collapsible sidebar)
- │ ├── SidebarHeader (logo, agent name, collapse button)
- │ └── SidebarContent
- │ ├── NewChatButton
- │ ├── SidebarSeparator
- │ └── ThreadList
- └── ThreadContainer (main chat area)
- ├── MobileHeader (mobile-only header, supports rightChildren)
- ├── ThreadHeader (desktop-only header for custom actions)
- ├── ScrollArea (scrollable message area)
- │ └── Messages
- ├── ConversationStarter (optional, shown when empty)
- └── Composer (text input)
-```
-
-## Basic Usage
-
-```tsx
-import { ChatProvider, useThreadListManager, useThreadManager } from "@openuidev/react-headless";
-import {
- Composer,
- Container,
- ConversationStarter,
- MessageLoading,
- Messages,
- MobileHeader,
- NewChatButton,
- ScrollArea,
- SidebarContainer,
- SidebarContent,
- SidebarHeader,
- SidebarSeparator,
- ThreadContainer,
- ThreadList,
-} from "@openuidev/react-ui/Shell";
-
-function MyShell() {
- const threadListManager = useThreadListManager({
- createThread: async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- isRunning: false,
- }),
- fetchThreadList: async () => [],
- deleteThread: async () => {},
- updateThread: async (t) => t,
- onSwitchToNew: () => {},
- onSelectThread: () => {},
- });
-
- const threadManager = useThreadManager({
- threadId: threadListManager.selectedThreadId,
- loadThread: async (threadId) => {
- if (!threadId) return [];
- // Load messages for thread
- return [];
- },
- onProcessMessage: async ({ message, threadManager }) => {
- threadManager.appendMessages({ ...message, id: crypto.randomUUID() });
- // Send message to your AI backend
- // Return assistant response
- return [
- {
- id: crypto.randomUUID(),
- role: "assistant",
- type: "response",
- message: [{ type: "text", text: "Response from AI" }],
- },
- ];
- },
- responseTemplates: [],
- });
-
- return (
- <ChatProvider threadListManager={threadListManager} threadManager={threadManager}>
- <Container logoUrl="/path/to/logo.png" agentName="AI Assistant">
- <SidebarContainer>
- <SidebarHeader />
- <SidebarContent>
- <NewChatButton />
- <SidebarSeparator />
- <ThreadList />
- </SidebarContent>
- </SidebarContainer>
- <ThreadContainer>
- <MobileHeader />
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter
- starters={[
- { displayText: "Help me get started", prompt: "Help me get started" },
- { displayText: "What can you do?", prompt: "What can you do?" },
- ]}
- />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- );
-}
-```
-
-## Individual Components
-
-### Container
-
-The main full-page wrapper for the Shell.
-
-```tsx
-<Container
- logoUrl="/logo.png" // Logo shown in sidebar header
- agentName="AI Assistant" // Name shown in sidebar header
- className="custom-class" // Optional custom styling
->
- {children}
-</Container>
-```
-
-### Sidebar Components
-
-The sidebar provides thread management and navigation.
-
-```tsx
-<SidebarContainer>
- <SidebarHeader /> {/* Logo, name, collapse button */}
- <SidebarContent>
- <NewChatButton /> {/* Creates new thread */}
- <SidebarSeparator /> {/* Visual separator */}
- <ThreadList /> {/* List of existing threads */}
- </SidebarContent>
-</SidebarContainer>
-```
-
-### ThreadContainer
-
-Wrapper for the main chat area with optional artifact panel support.
-
-```tsx
-<ThreadContainer
- isArtifactActive={false} // Show artifact panel (desktop: side-by-side, mobile: overlay)
- renderArtifact={() => <div />} // Artifact content
->
- {children}
-</ThreadContainer>
-```
-
-### MobileHeader
-
-Header shown only on mobile devices with sidebar toggle and optional custom actions.
-
-```tsx
-<MobileHeader
- rightChildren={
- <IconButton icon={<Share size={16} />} aria-label="Share" size="medium" variant="secondary" />
- }
-/>
-```
-
-**Props:**
-
-- `className` - Optional additional CSS class
-- `rightChildren` - Custom content rendered on the right side, before the "new chat" button
-
-### ThreadHeader
-
-Desktop-only header bar for custom actions (model selector, share button, etc.). Automatically hidden on mobile.
-
-```tsx
-import { ThreadHeader } from "@openuidev/react-ui/Shell";
-
-<ThreadContainer>
- <MobileHeader />
- <ThreadHeader>
- <Button iconLeft={<ChevronDown size={14} />} variant="secondary" size="small">
- GPT-5.5
- </Button>
- <Button iconLeft={<Share size={14} />} variant="secondary" size="small">
- Share
- </Button>
- </ThreadHeader>
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <Composer />
-</ThreadContainer>;
-```
-
-**Props:**
-
-- `children` - Content to render inside the header (uses flexbox with `justify-content: flex-end`)
-- `className` - Optional additional CSS class
-
-### ScrollArea
-
-Scrollable container for messages with smart scroll behavior.
-
-```tsx
-<ScrollArea
- scrollVariant="user-message-anchor" // Scroll behavior
- userMessageSelector=".openui-shell-thread-message-user" // CSS selector for user messages
->
- <Messages loader={<MessageLoading />} />
-</ScrollArea>
-```
-
-### ConversationStarter
-
-Full-width clickable buttons shown when the thread is empty. Automatically submits the prompt as a message when clicked.
-
-```tsx
-<ConversationStarter
- variant="short" // "short" (pill buttons) or "long" (list items)
- starters={[
- {
- displayText: "Help me get started",
- prompt: "Help me get started",
- icon: <Sparkles size={16} />,
- },
- { displayText: "What can you do?", prompt: "What can you do?" }, // Default lightbulb icon
- { displayText: "No icon example", prompt: "No icon", icon: <></> }, // No icon (use empty fragment)
- ]}
- className="custom-class" // Optional custom styling
-/>
-```
-
-**Props:**
-
-- `variant` - `"short"` (pill-style buttons) or `"long"` (list items with separators)
-- `starters` - Array of objects with:
- - `displayText` - Text shown on the button
- - `prompt` - Message sent when clicked
- - `icon` - Optional: `ReactNode` for custom icon, `undefined` for default lightbulb, `<></>` (empty fragment) for no icon
-- `className` - Optional additional CSS class
-
-**Behavior:**
-
-- Only visible when there are no messages in the thread
-- Clicking a button submits the `prompt` as a user message
-- Clicks are ignored when a response is being generated
-- Respects Shell layout (centered with max-width, mobile padding)
-
-### WelcomeScreen
-
-A centered welcome message shown when the thread is empty. On desktop, includes a built-in composer and optional conversation starters.
-
-**Props-based usage with URL:**
-
-```tsx
-{
- !hasMessages && (
- <WelcomeScreen
- title="Hi, I'm AI Assistant"
- description="I can help you with your questions."
- image={{ url: "/path/to/logo.png" }}
- starters={[
- { displayText: "Help me get started", prompt: "Help me get started" },
- { displayText: "What can you do?", prompt: "What can you do?" },
- ]}
- starterVariant="long" // "short" or "long" (default: "long")
- />
- );
-}
-```
-
-**Props-based usage with styled image:**
-
-```tsx
-{
- !hasMessages && (
- <WelcomeScreen
- title="Hi, I'm AI Assistant"
- description="I can help you with your questions."
- image={
- <img
- src="/path/to/logo.png"
- alt="AI Assistant"
- style={{ width: 64, height: 64, borderRadius: 16, objectFit: "cover" }}
- />
- }
- starters={[{ displayText: "Help me get started", prompt: "Help me get started" }]}
- />
- );
-}
-```
-
-**Custom children usage:**
-
-```tsx
-{
- !hasMessages && (
- <WelcomeScreen>
- <div style={{ textAlign: "center" }}>
- <MyCustomLogo />
- <h2>Welcome!</h2>
- <p>Custom welcome content</p>
- </div>
- </WelcomeScreen>
- );
-}
-```
-
-**Props:**
-
-- `title` - Greeting/title text (optional)
-- `description` - Description text (optional)
-- `image` - Image to display: `{ url: string }` for simple URL (renders with default 64x64 size, rounded corners), or `ReactNode` for custom styled elements (optional)
-- `starters` - Conversation starters to show below the composer (desktop only)
-- `starterVariant` - `"short"` or `"long"` for starter style (default: `"long"`)
-- `children` - Custom content (mutually exclusive with title/description/image)
-- `className` - Additional CSS class (optional)
-
-**Desktop behavior:**
-
-- Includes a built-in composer centered in the welcome screen
-- Conversation starters appear below the composer
-- The regular Composer component is hidden when WelcomeScreen is present
-
-**Note:** You must conditionally render WelcomeScreen based on `hasMessages` state.
-
-### Composer
-
-Text input for sending messages.
-
-```tsx
-<Composer className="custom-class" />
-```
-
-## Desktop vs Mobile
-
-The Shell automatically adapts to screen size:
-
-| Feature | Desktop | Mobile |
-| --------------------- | ----------------------- | ------------------------------------- |
-| Sidebar | Collapsible side panel | Hidden, accessible via hamburger menu |
-| Header | In sidebar | MobileHeader at top of thread |
-| Artifact panel | Resizable side-by-side | Full-screen overlay |
-| Conversation starters | Centered with max-width | Full-width with padding |
-
-## Artifact Panel
-
-The Shell supports a resizable artifact panel on desktop:
-
-```tsx
-<ThreadContainer
- isArtifactActive={true}
- renderArtifact={() => <div>{/* Your artifact content (code preview, document, etc.) */}</div>}
->
- {/* Chat content */}
-</ThreadContainer>
-```
-
-On desktop, the artifact panel appears to the right of the chat and can be resized by dragging the separator. On mobile, it appears as a full-screen overlay.
-
-## Comparison with Other Components
-
-| Feature | Shell | CopilotShell | BottomTray |
-| -------------- | ----------------- | ------------------ | ---------------------- |
-| Layout | Full page | Sidebar panel | Floating panel |
-| Sidebar | Yes (collapsible) | No | No |
-| Thread list | Yes | No | Yes (in header) |
-| Artifact panel | Yes (resizable) | Yes (overlay) | No |
-| Mobile | Responsive | Responsive | Fullscreen |
-| Use case | Primary chat app | Side panel copilot | Secondary/support chat |
-
-## CSS Classes
-
-All Shell components use the `openui-shell-` prefix:
-
-- `.openui-shell-container`
-- `.openui-shell-thread-container`
-- `.openui-shell-thread-scroll-area`
-- `.openui-shell-thread-messages`
-- `.openui-shell-thread-message-user`
-- `.openui-shell-thread-message-assistant`
-- `.openui-shell-thread-header`
-- `.openui-shell-thread-composer`
-- `.openui-shell-conversation-starter`
-- `.openui-shell-conversation-starter-item`
-- `.openui-shell-sidebar-container`
-- `.openui-shell-sidebar-header`
-- `.openui-shell-sidebar-content`
diff --git a/packages/react-ui/src/components/Shell/stories/Shell.stories.tsx b/packages/react-ui/src/components/Shell/stories/Shell.stories.tsx
deleted file mode 100644
index 81245d8fc..000000000
--- a/packages/react-ui/src/components/Shell/stories/Shell.stories.tsx
+++ /dev/null
@@ -1,468 +0,0 @@
-import { ChatProvider, Message, type Thread } from "@openuidev/react-headless";
-import { MessageSquare, Share, Sparkles, Zap } from "lucide-react";
-import { Button } from "../../Button";
-import { IconButton } from "../../IconButton";
-import { Container } from "../Container";
-import { ConversationStarter } from "../ConversationStarter";
-import { MobileHeader } from "../MobileHeader";
-import { NewChatButton } from "../NewChatButton";
-import { SidebarContainer, SidebarContent, SidebarHeader, SidebarSeparator } from "../Sidebar";
-import {
- Composer,
- MessageLoading,
- Messages,
- ScrollArea,
- ThreadContainer,
- ThreadHeader,
-} from "../Thread";
-import { ThreadList } from "../ThreadList";
-import { WelcomeScreen } from "../WelcomeScreen";
-import logoUrl from "./thesysdev_logo.jpeg";
-
-function mockSSEResponse(text: string, delayMs = 500): Promise<Response> {
- return new Promise((resolve) => {
- setTimeout(() => {
- const events = `data: ${JSON.stringify({ type: "TEXT_MESSAGE_CONTENT", delta: text })}\n\ndata: [DONE]\n\n`;
- const stream = new ReadableStream({
- start(controller) {
- controller.enqueue(new TextEncoder().encode(events));
- controller.close();
- },
- });
- resolve(new Response(stream));
- }, delayMs);
- });
-}
-
-function getLastUserContent(messages: Message[]): string {
- const lastUser = [...messages].reverse().find((m) => m.role === "user");
- if (!lastUser) return "";
- return typeof lastUser.content === "string" ? lastUser.content : "";
-}
-
-export default {
- title: "Components/Shell",
- tags: ["dev"],
- argTypes: {
- variant: {
- control: "select",
- options: ["short", "long"],
- description: "Conversation starter variant",
- },
- },
-};
-
-const SAMPLE_STARTERS = [
- {
- displayText: "Help me get started",
- prompt: "Help me get started",
- icon: <Sparkles size={16} />,
- },
- {
- displayText: "What can you do?",
- prompt: "What can you do?",
- },
- {
- displayText: "Tell me about your features",
- prompt: "Tell me about your features",
- icon: <MessageSquare size={16} />,
- },
- {
- displayText: "Show me some examples (no icon)",
- prompt: "Show me some examples",
- icon: <></>,
- },
-];
-
-const LONG_STARTERS = [
- {
- displayText: "Help me get started with this application and guide me through the features",
- prompt: "Help me get started with this application",
- icon: <Sparkles size={16} />,
- },
- {
- displayText: "What can you do? I'd like to know all your capabilities and how you can help me",
- prompt: "What can you do?",
- icon: <Zap size={16} />,
- },
- {
- displayText: "Tell me about your advanced features and how I can use them effectively",
- prompt: "Tell me about your features",
- },
-];
-
-export const Default = {
- args: {
- variant: "short",
- },
- render: ({ variant }: { variant: "short" | "long" }) => (
- <ChatProvider
- processMessage={async () => {
- await new Promise((r) => setTimeout(r, 100));
- return mockSSEResponse("This is a response from the AI assistant.", 1000);
- }}
- fetchThreadList={async () => {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- return {
- threads: [
- { id: "1", title: "test", createdAt: Date.now() },
- { id: "2", title: "test 2", createdAt: Date.now() },
- { id: "3", title: "test 3", createdAt: Date.now() },
- ],
- };
- }}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "test",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t: Thread) => t}
- loadThread={async (threadId) => {
- if (!threadId) return [];
- return [
- { id: crypto.randomUUID(), role: "user", content: "Hello" },
- {
- id: crypto.randomUUID(),
- role: "assistant",
- content: "Hello! How can I help you today?",
- },
- ];
- }}
- >
- <Container logoUrl={logoUrl} agentName="OpenUI">
- <SidebarContainer>
- <SidebarHeader>
- <NewChatButton />
- </SidebarHeader>
- <SidebarContent>
- <SidebarSeparator />
- <ThreadList />
- </SidebarContent>
- </SidebarContainer>
- <ThreadContainer>
- <MobileHeader
- rightChildren={
- <IconButton
- icon={<Share size={16} />}
- aria-label="Share"
- size="medium"
- variant="secondary"
- />
- }
- />
- <ThreadHeader>
- <Button iconLeft={<Share size={16} />} variant="secondary" size="small">
- Share
- </Button>
- </ThreadHeader>
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={SAMPLE_STARTERS} variant={variant} />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- ),
-};
-
-export const WithThreadHeader = {
- args: {
- variant: "short",
- },
- render: ({ variant }: { variant: "short" | "long" }) => (
- <ChatProvider
- processMessage={async ({ messages }: { messages: Message[] }) => {
- const content = getLastUserContent(messages);
- return mockSSEResponse(`You asked: "${content}"`, 1000);
- }}
- fetchThreadList={async () => ({ threads: [] })}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t: Thread) => t}
- loadThread={async () => []}
- >
- <Container logoUrl={logoUrl} agentName="OpenUI">
- <SidebarContainer>
- <SidebarHeader>
- <NewChatButton />
- </SidebarHeader>
- <SidebarContent>
- <SidebarSeparator />
- <ThreadList />
- </SidebarContent>
- </SidebarContainer>
- <ThreadContainer>
- <MobileHeader />
- <ThreadHeader>
- <select
- style={{
- padding: "4px 8px",
- borderRadius: "6px",
- border: "1px solid var(--openui-stroke-default, #ccc)",
- background: "var(--openui-bg-fill, #fff)",
- fontSize: "13px",
- }}
- >
- <option>GPT-5.5</option>
- <option>Claude 3.5 Sonnet</option>
- <option>Gemini Pro</option>
- </select>
- <Button iconLeft={<Share size={16} />} variant="secondary" size="small">
- Share
- </Button>
- </ThreadHeader>
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={SAMPLE_STARTERS} variant={variant} />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- ),
-};
-
-export const WithConversationStarter = {
- args: {
- variant: "short",
- },
- render: ({ variant }: { variant: "short" | "long" }) => (
- <ChatProvider
- processMessage={async ({ messages }: { messages: Message[] }) => {
- const content = getLastUserContent(messages);
- return mockSSEResponse(`You asked: "${content}"`, 1000);
- }}
- fetchThreadList={async () => ({ threads: [] })}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t: Thread) => t}
- loadThread={async () => []}
- >
- <Container logoUrl={logoUrl} agentName="OpenUI">
- <SidebarContainer>
- <SidebarHeader>
- <NewChatButton />
- </SidebarHeader>
- <SidebarContent>
- <SidebarSeparator />
- <ThreadList />
- </SidebarContent>
- </SidebarContainer>
- <ThreadContainer>
- <MobileHeader
- rightChildren={
- <IconButton
- icon={<Share size={16} />}
- aria-label="Share"
- size="medium"
- variant="secondary"
- />
- }
- />
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={SAMPLE_STARTERS} variant={variant} />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- ),
-};
-
-export const LongVariant = {
- args: {
- variant: "long",
- },
- render: ({ variant }: { variant: "short" | "long" }) => (
- <ChatProvider
- processMessage={async ({ messages }: { messages: Message[] }) => {
- const content = getLastUserContent(messages);
- return mockSSEResponse(`You asked: "${content}"`, 1000);
- }}
- fetchThreadList={async () => ({ threads: [] })}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t: Thread) => t}
- loadThread={async () => []}
- >
- <Container logoUrl={logoUrl} agentName="OpenUI">
- <SidebarContainer>
- <SidebarHeader>
- <NewChatButton />
- </SidebarHeader>
- <SidebarContent>
- <SidebarSeparator />
- <ThreadList />
- </SidebarContent>
- </SidebarContainer>
- <ThreadContainer>
- <MobileHeader
- rightChildren={
- <IconButton
- icon={<Share size={16} />}
- aria-label="Share"
- size="medium"
- variant="secondary"
- />
- }
- />
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={LONG_STARTERS} variant={variant} />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- ),
-};
-
-export const WithWelcomeScreen = {
- args: {
- variant: "short",
- },
- render: ({ variant }: { variant: "short" | "long" }) => (
- <ChatProvider
- processMessage={async ({ messages }: { messages: Message[] }) => {
- const content = getLastUserContent(messages);
- return mockSSEResponse(`You asked: "${content}"`, 1000);
- }}
- fetchThreadList={async () => ({ threads: [] })}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t: Thread) => t}
- loadThread={async () => []}
- >
- <Container logoUrl={logoUrl} agentName="OpenUI Assistant">
- <SidebarContainer>
- <SidebarHeader>
- <NewChatButton />
- </SidebarHeader>
- <SidebarContent>
- <SidebarSeparator />
- <ThreadList />
- </SidebarContent>
- </SidebarContainer>
- <ThreadContainer>
- <MobileHeader
- rightChildren={
- <IconButton
- icon={<Share size={16} />}
- aria-label="Share"
- size="medium"
- variant="secondary"
- />
- }
- />
- <WelcomeScreen
- title="Hi, I'm OpenUI Assistant"
- description="I can help you with questions about your account, products, and more."
- image={{ url: logoUrl }}
- starters={SAMPLE_STARTERS}
- starterVariant={variant}
- />
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={SAMPLE_STARTERS} variant={variant} />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- ),
-};
-
-export const WithCustomWelcomeScreen = {
- args: {
- variant: "short",
- },
- render: ({ variant }: { variant: "short" | "long" }) => (
- <ChatProvider
- processMessage={async ({ messages }: { messages: Message[] }) => {
- const content = getLastUserContent(messages);
- return mockSSEResponse(`You asked: "${content}"`, 1000);
- }}
- fetchThreadList={async () => ({ threads: [] })}
- createThread={async () => ({
- id: crypto.randomUUID(),
- title: "New Chat",
- createdAt: Date.now(),
- })}
- deleteThread={async () => {}}
- updateThread={async (t: Thread) => t}
- loadThread={async () => []}
- >
- <Container logoUrl={logoUrl} agentName="OpenUI Assistant">
- <SidebarContainer>
- <SidebarHeader>
- <NewChatButton />
- </SidebarHeader>
- <SidebarContent>
- <SidebarSeparator />
- <ThreadList />
- </SidebarContent>
- </SidebarContainer>
- <ThreadContainer>
- <MobileHeader
- rightChildren={
- <IconButton
- icon={<Share size={16} />}
- aria-label="Share"
- size="medium"
- variant="secondary"
- />
- }
- />
- <WelcomeScreen>
- <div style={{ textAlign: "center" }}>
- <div
- style={{
- width: 80,
- height: 80,
- borderRadius: 16,
- background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- margin: "0 auto 16px",
- }}
- >
- <Sparkles size={40} color="white" />
- </div>
- <h2 style={{ margin: "0 0 8px", fontSize: 24, fontWeight: 600 }}>
- Welcome to AI Assistant
- </h2>
- <p style={{ margin: 0, color: "rgba(0,0,0,0.5)", fontSize: 16 }}>
- Your personal AI helper for all your questions
- </p>
- </div>
- </WelcomeScreen>
- <ScrollArea>
- <Messages loader={<MessageLoading />} />
- </ScrollArea>
- <ConversationStarter starters={SAMPLE_STARTERS} variant={variant} />
- <Composer />
- </ThreadContainer>
- </Container>
- </ChatProvider>
- ),
-};
diff --git a/packages/react-ui/src/components/Shell/stories/thesysdev_logo.jpeg b/packages/react-ui/src/components/Shell/stories/thesysdev_logo.jpeg
deleted file mode 100644
index 755421486..000000000
Binary files a/packages/react-ui/src/components/Shell/stories/thesysdev_logo.jpeg and /dev/null differ
diff --git a/packages/react-ui/src/components/Shell/threadlist.scss b/packages/react-ui/src/components/Shell/threadlist.scss
deleted file mode 100644
index e90d91ee0..000000000
--- a/packages/react-ui/src/components/Shell/threadlist.scss
+++ /dev/null
@@ -1,153 +0,0 @@
-@use "../../cssUtils" as cssUtils;
-
-.openui-shell-thread-list {
- display: flex;
- flex-direction: column;
- gap: cssUtils.$space-3xs;
- overflow: auto;
- margin-top: cssUtils.$space-m;
- scrollbar-width: thin;
- scrollbar-color: cssUtils.$border-default transparent;
-
- &::-webkit-scrollbar {
- width: cssUtils.$space-xs;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background: cssUtils.$border-default;
- border-radius: calc(cssUtils.$radius-2xs + cssUtils.$space-3xs);
- }
-
- &::-webkit-scrollbar-thumb:hover {
- background: cssUtils.$text-neutral-secondary;
- }
-}
-
-.openui-shell-thread-list-group {
- display: flex;
- padding-left: cssUtils.$space-s;
- color: cssUtils.$text-neutral-tertiary;
- @include cssUtils.typography(label, small);
- margin-bottom: cssUtils.$space-2xs;
-
- .openui-shell-container--mobile & {
- @include cssUtils.typography(label, default);
- }
-
- &:not(:first-child) {
- margin-top: cssUtils.$space-m;
- }
-}
-
-.openui-shell-thread-button {
- display: flex;
- align-items: center;
- justify-content: space-between;
- width: 100%;
- border-radius: calc(cssUtils.$radius-s + 1px);
- border: 1px solid transparent;
- transition: all 0.12s ease;
-
- &--selected {
- background-color: cssUtils.$highlight;
- }
-
- &:hover {
- background-color: cssUtils.$highlight;
- }
-
- &:hover {
- .openui-shell-thread-button-dropdown-trigger {
- opacity: 1;
- }
- }
-
- &:has(.openui-shell-thread-button-dropdown-trigger[data-state="open"]) {
- background-color: cssUtils.$highlight;
-
- .openui-shell-thread-button-dropdown-trigger {
- opacity: 1;
- }
- }
-}
-
-.openui-shell-thread-button-title {
- @include cssUtils.button-reset;
- @include cssUtils.typography(body, small);
- color: cssUtils.$text-neutral-primary;
- padding: calc(cssUtils.$space-xs - 1.75px) cssUtils.$space-s;
- width: 100%;
- text-align: left;
- cursor: pointer;
- white-space: nowrap;
- text-overflow: ellipsis;
- overflow: hidden;
-
- .openui-shell-container--mobile & {
- @include cssUtils.typography(body, default);
- padding: calc(cssUtils.$space-s - 1.75px) cssUtils.$space-s;
- }
-}
-
-.openui-shell-thread-button-dropdown-trigger {
- opacity: 0;
-
- .openui-shell-container--mobile & {
- opacity: 1;
- }
-
- &:focus-visible {
- opacity: 1;
- }
-
- &[data-state="open"] {
- opacity: 1;
- background-color: cssUtils.$highlight;
- border-color: cssUtils.$border-interactive;
- }
-}
-
-.openui-shell-thread-button-dropdown-menu {
- box-sizing: border-box;
- position: relative;
- z-index: 99999;
- min-width: 160px;
- overflow: hidden;
- border: 1px solid cssUtils.$border-default;
- border-radius: cssUtils.$radius-xl;
- background-color: cssUtils.$foreground;
- box-shadow: cssUtils.$shadow-m;
- color: cssUtils.$text-neutral-primary;
- transform-origin: top center;
- animation: openui-shell-thread-menu-show 0.18s ease-out forwards;
- padding: 4px;
-}
-
-.openui-shell-thread-button-dropdown-menu-item {
- width: 100%;
- justify-content: flex-start;
- padding-left: cssUtils.$space-s;
- padding-right: cssUtils.$space-s;
-
- &:focus,
- &:focus-visible {
- outline: none;
- box-shadow: none;
- }
-}
-
-@keyframes openui-shell-thread-menu-show {
- from {
- opacity: 0;
- transform: scale(0.95);
- }
-
- to {
- opacity: 1;
- transform: scale(1);
- }
-}
diff --git a/packages/react-ui/src/components/Shell/useArtifactResize.ts b/packages/react-ui/src/components/Shell/useArtifactResize.ts
deleted file mode 100644
index b2f095134..000000000
--- a/packages/react-ui/src/components/Shell/useArtifactResize.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { useCallback, useEffect, useRef, useState } from "react";
-
-interface UseArtifactResizeProps {
- isArtifactActive: boolean;
- isMobile: boolean;
- setIsSidebarOpen: (isOpen: boolean) => void;
-}
-
-interface UseArtifactResizeReturn {
- containerRef: React.RefObject<HTMLDivElement | null>;
- chatPanelRef: React.RefObject<HTMLDivElement | null>;
- artifactPanelRef: React.RefObject<HTMLDivElement | null>;
- isDragging: boolean;
- handleResize: (clientX: number) => void;
- handleDragStart: () => void;
- handleDragEnd: () => void;
-}
-
-const INITIAL_CHAT_WIDTH = 420;
-const MIN_CHAT_WIDTH = 420;
-const MAX_CHAT_WIDTH_RATIO = 0.8;
-
-/**
- * Custom hook to manage artifact panel resizing logic (desktop only).
- * Handles:
- * - Chat panel width constraints
- * - Resize drag events
- * - Sidebar state when artifact is active/inactive
- */
-export const useArtifactResize = ({
- isArtifactActive,
- isMobile,
- setIsSidebarOpen,
-}: UseArtifactResizeProps): UseArtifactResizeReturn => {
- const [isDragging, setIsDragging] = useState(false);
- const containerRef = useRef<HTMLDivElement>(null);
- const chatPanelRef = useRef<HTMLDivElement>(null);
- const artifactPanelRef = useRef<HTMLDivElement>(null);
-
- // Handle sidebar visibility and panel widths when artifact state changes
- useEffect(() => {
- if (isMobile) return;
-
- if (isArtifactActive) {
- // Desktop artifact active: close sidebar and set chat width to 420px
- setIsSidebarOpen(false);
- if (chatPanelRef.current) {
- chatPanelRef.current.style.width = `${INITIAL_CHAT_WIDTH}px`;
- }
- } else {
- // Desktop artifact inactive: open sidebar and reset chat width
- setIsSidebarOpen(true);
- if (chatPanelRef.current) {
- chatPanelRef.current.style.width = "100%";
- }
- }
- }, [isArtifactActive, isMobile, setIsSidebarOpen]);
-
- const handleResize = useCallback((clientX: number) => {
- if (!containerRef.current || !chatPanelRef.current) return;
-
- const containerRect = containerRef.current.getBoundingClientRect();
- const newWidthPx = clientX - containerRect.left;
-
- // Constrain width between min and max
- const maxWidthPx = containerRect.width * MAX_CHAT_WIDTH_RATIO;
- const constrainedWidth = Math.min(Math.max(newWidthPx, MIN_CHAT_WIDTH), maxWidthPx);
-
- chatPanelRef.current.style.width = `${constrainedWidth}px`;
- }, []);
-
- const handleDragStart = useCallback(() => {
- setIsDragging(true);
- }, []);
-
- const handleDragEnd = useCallback(() => {
- setIsDragging(false);
- }, []);
-
- return {
- containerRef,
- chatPanelRef,
- artifactPanelRef,
- isDragging,
- handleResize,
- handleDragStart,
- handleDragEnd,
- };
-};
diff --git a/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx b/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx
index d9e54675d..b377550cf 100644
--- a/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx
+++ b/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx
@@ -7,7 +7,7 @@ import { themeToCssVars } from "./utils";
* Props for the {@link ThemeProvider} component.
*/
export type ThemeProps = {
- /** Active color scheme. @default "light" */
+ /** Active color scheme. Defaults to the parent ThemeProvider mode when nested, otherwise `"light"`. */
mode?: ThemeMode;
/** Application content rendered inside the theme context. */
children?: React.ReactNode;
@@ -148,7 +148,7 @@ function validateThemeObject(themeObj: Theme, propName: string) {
*/
export const ThemeProvider = ({
- mode = "light",
+ mode: modeProp,
children,
lightTheme,
darkTheme,
@@ -158,6 +158,7 @@ export const ThemeProvider = ({
const id = cssSafeId(useId());
const parent = useContext(InternalContext);
const isNested = parent != null;
+ const mode = modeProp ?? parent?.mode ?? "light";
const effectiveCssSelector = cssSelector || "body";
const hasExplicitSelector = effectiveCssSelector !== "body";
diff --git a/packages/react-ui/src/components/ToolCall/BehindTheScenes.tsx b/packages/react-ui/src/components/ToolCall/BehindTheScenes.tsx
index dfb0371db..6bf484561 100644
--- a/packages/react-ui/src/components/ToolCall/BehindTheScenes.tsx
+++ b/packages/react-ui/src/components/ToolCall/BehindTheScenes.tsx
@@ -1,5 +1,5 @@
import { ChevronDown, ChevronUp } from "lucide-react";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useId, useRef, useState } from "react";
export interface BehindTheScenesProps {
/** True while the overall message is still streaming */
@@ -42,9 +42,17 @@ export const BehindTheScenes = ({
setUserOverride((prev) => (prev !== null ? !prev : !isExpanded));
};
+ const panelId = useId();
+
return (
<div className="openui-behind-the-scenes">
- <button className="openui-behind-the-scenes__toggle" onClick={toggle} type="button">
+ <button
+ className="openui-behind-the-scenes__toggle"
+ onClick={toggle}
+ type="button"
+ aria-expanded={isExpanded}
+ aria-controls={panelId}
+ >
{isExpanded ? (
<ChevronUp size={14} className="openui-behind-the-scenes__toggle-icon" />
) : (
@@ -52,7 +60,11 @@ export const BehindTheScenes = ({
)}
{toolsActive ? "Working..." : "Behind the scenes"}
</button>
- {isExpanded && <div className="openui-behind-the-scenes__items">{children}</div>}
+ {isExpanded && (
+ <div className="openui-behind-the-scenes__items" id={panelId}>
+ {children}
+ </div>
+ )}
</div>
);
};
diff --git a/packages/react-ui/src/components/ToolCall/DefaultToolCard.tsx b/packages/react-ui/src/components/ToolCall/DefaultToolCard.tsx
new file mode 100644
index 000000000..166cfff24
--- /dev/null
+++ b/packages/react-ui/src/components/ToolCall/DefaultToolCard.tsx
@@ -0,0 +1,43 @@
+import type { ToolActivity } from "@openuidev/react-headless";
+import { ChevronDown } from "lucide-react";
+import { memo } from "react";
+import { ToolCall } from "./ToolCallPrimitives";
+
+/**
+ * Batteries-included default tool card — the chevron-header composition of the
+ * compound {@link ToolCall} parts. Status comes from the data, the collapsible
+ * is aria-correct, and it's memoized. Used by `<ToolCallEntry>` for flat
+ * (non-timeline) threads, sidebars, debug panels, etc.
+ *
+ * @category Components
+ */
+export const DefaultToolCard = memo(function DefaultToolCard({
+ activity,
+ isLast,
+ isRunning = true,
+}: {
+ activity: ToolActivity;
+ isLast: boolean;
+ /** Whether the owning thread is still running — gates the running spin/shimmer. */
+ isRunning?: boolean;
+}) {
+ return (
+ <ToolCall.Root
+ activity={activity}
+ isLast={isLast}
+ running={isRunning}
+ defaultOpen={activity.isError}
+ className="openui-tool-call--card"
+ >
+ <ToolCall.Trigger className="openui-tool-call__header">
+ <ToolCall.StatusIcon />
+ <ToolCall.StatusText />
+ <ChevronDown size={14} className="openui-tool-call__chevron" />
+ </ToolCall.Trigger>
+ <ToolCall.Content className="openui-tool-call__panel">
+ <ToolCall.Parameters className="openui-tool-call__request openui-tool-code-block__code" />
+ <ToolCall.Result className="openui-tool-call__response openui-tool-code-block__code" />
+ </ToolCall.Content>
+ </ToolCall.Root>
+ );
+});
diff --git a/packages/react-ui/src/components/ToolCall/SourceIcon.tsx b/packages/react-ui/src/components/ToolCall/SourceIcon.tsx
new file mode 100644
index 000000000..7901432da
--- /dev/null
+++ b/packages/react-ui/src/components/ToolCall/SourceIcon.tsx
@@ -0,0 +1,32 @@
+import { Globe } from "lucide-react";
+import { useState } from "react";
+
+/**
+ * Favicon for a web-search source, falling back to a globe glyph when the image
+ * is missing, fails to load, or resolves to a default 16×16 placeholder.
+ *
+ * @category Components
+ */
+export const SourceIcon = ({ src }: { src?: string }) => {
+ const [failed, setFailed] = useState(false);
+
+ if (!src || failed) {
+ return <Globe size={16} className="openui-tool-call__icon" />;
+ }
+
+ return (
+ <img
+ src={src}
+ alt=""
+ className="openui-tool-call__source-logo"
+ onLoad={(e) => {
+ const img = e.currentTarget;
+ // Google's default favicon is 16x16 — treat as missing.
+ if (img.naturalWidth <= 16 && img.naturalHeight <= 16) {
+ setFailed(true);
+ }
+ }}
+ onError={() => setFailed(true)}
+ />
+ );
+};
diff --git a/packages/react-ui/src/components/ToolCall/TimelineToolCard.tsx b/packages/react-ui/src/components/ToolCall/TimelineToolCard.tsx
new file mode 100644
index 000000000..1e3478f49
--- /dev/null
+++ b/packages/react-ui/src/components/ToolCall/TimelineToolCard.tsx
@@ -0,0 +1,105 @@
+import type { ToolActivity } from "@openuidev/react-headless";
+import { CircleDot } from "lucide-react";
+import { memo } from "react";
+import { Collapsible } from "../_shared/Collapsible";
+import { ToolCall } from "./ToolCallPrimitives";
+
+/**
+ * Timeline-shaped composition of the compound {@link ToolCall} parts — the
+ * molded `StatusStep` + `TimelineItem` (dot + connector). The running shimmer
+ * is `(streaming|executing) && isLast`, derived from the lifecycle status via
+ * the parts' `data-spin`, not a separate `isThinking` flag. `ToolCall.Root` is
+ * the single `.openui-tool-call` container, so we compose *inside* it.
+ *
+ * @category Components
+ */
+export const TimelineToolCard = memo(function TimelineToolCard({
+ activity,
+ isLast,
+ isRunning = true,
+}: {
+ activity: ToolActivity;
+ isLast: boolean;
+ /** Whether the owning thread is still running — gates the running shimmer/spin
+ * so a closed-args call with no result doesn't animate forever after the run ends. */
+ isRunning?: boolean;
+}) {
+ return (
+ <ToolCall.Root activity={activity} isLast={isLast} running={isRunning}>
+ <div className="openui-tool-call__title-row">
+ <ToolCall.StatusIcon
+ render={(_state, props) => (
+ <span
+ className={`openui-tool-call__icon-wrapper${
+ props["data-spin"] ? " openui-tool-call__icon--blinking" : ""
+ }`}
+ data-status={props["data-status"] as string}
+ >
+ <CircleDot size={14} className="openui-tool-call__icon" />
+ </span>
+ )}
+ />
+ <ToolCall.StatusText
+ render={(state, props) => (
+ <span
+ // Announce tool-call status transitions (Calling → Running →
+ // Called/failed) to assistive tech; only changes are spoken, so
+ // settled/historical cards stay quiet.
+ role="status"
+ aria-live="polite"
+ className={`openui-tool-call__name${
+ (state.status === "streaming" || state.status === "executing") &&
+ isLast &&
+ isRunning
+ ? " openui-tool-call__name--shimmer"
+ : ""
+ }`}
+ >
+ {props["children"] as string}
+ </span>
+ )}
+ />
+ </div>
+
+ <div
+ className={`openui-tool-call__connector${
+ isLast ? " openui-tool-call__connector--last" : ""
+ }`}
+ >
+ <div className="openui-tool-call__args-block">
+ {/* request → typed input, response → paired result, both collapsible */}
+ <Collapsible
+ label="Tool Request"
+ labelLoading={`Sending request to ${activity.toolName}...`}
+ loading={isRunning && isLast && activity.status === "streaming"}
+ >
+ <ToolCall.Parameters
+ render={(_s, p) => (
+ <pre className="openui-tool-code-block__code">{p["children"] as string}</pre>
+ )}
+ />
+ </Collapsible>
+ {/* ToolCall.Result returns null until a result/error lands, so the
+ response collapsible only appears once it does. */}
+ <ToolCall.Result
+ render={(s, p) => (
+ <Collapsible
+ label="Tool Response"
+ labelLoading={`Awaiting response from ${activity.toolName}...`}
+ loading={isRunning && isLast && activity.status === "executing"}
+ >
+ <pre
+ className={`openui-tool-code-block__code${
+ s.isError ? " openui-tool-code-block__code--error" : ""
+ }`}
+ >
+ {p["children"] as string}
+ </pre>
+ </Collapsible>
+ )}
+ />
+ </div>
+ </div>
+ </ToolCall.Root>
+ );
+});
diff --git a/packages/react-ui/src/components/ToolCall/ToolCallPrimitives.tsx b/packages/react-ui/src/components/ToolCall/ToolCallPrimitives.tsx
new file mode 100644
index 000000000..c49347f0f
--- /dev/null
+++ b/packages/react-ui/src/components/ToolCall/ToolCallPrimitives.tsx
@@ -0,0 +1,340 @@
+import type { ToolActivity, ToolCallStatus } from "@openuidev/react-headless";
+import clsx from "clsx";
+import { AlertCircle, Loader2, SquareCode } from "lucide-react";
+import { createContext, createElement, useContext, useId, useState, type ReactNode } from "react";
+
+/**
+ * Compound, reusable building blocks for rendering one tool call + its result.
+ *
+ * `ToolCall.Root` holds the typed {@link ToolActivity} and expand state in
+ * context; the thin parts read it and expose typed `data-*` / `aria` attributes
+ * plus a `render` escape hatch (Base-UI / Radix style) so a consumer can swap
+ * the element or markup per place. The batteries-included `DefaultToolCard` /
+ * `TimelineToolCard` are just two compositions of these parts — drop them into a
+ * sidebar, a compact chip, or a debug panel and reuse the typed state without
+ * re-deriving anything.
+ *
+ * @category Components
+ */
+
+// ── Context ──
+
+interface ToolCallContextValue {
+ activity: ToolActivity;
+ isLast: boolean;
+ /**
+ * Whether the owning thread is still running. The in-progress affordances
+ * (icon spin, name shimmer) require this so a tool call that closed its args
+ * but never received a result does NOT animate forever after the run ends.
+ * Defaults to `true` for standalone (thread-less) primitive use.
+ */
+ running: boolean;
+ isOpen: boolean;
+ setOpen: (value: boolean) => void;
+ panelId: string;
+ /** Stable id on the rendered Trigger button; names the Content region. */
+ triggerId: string;
+}
+
+const ToolCallContext = createContext<ToolCallContextValue | null>(null);
+
+/** Reads the nearest {@link ToolCall.Root} context. @category Hooks */
+export function useToolCall(): ToolCallContextValue {
+ const ctx = useContext(ToolCallContext);
+ if (!ctx) throw new Error("ToolCall.* parts must be used inside <ToolCall.Root>");
+ return ctx;
+}
+
+// ── render escape hatch ──
+
+type RenderProp<State, Props> = (state: State, props: Props) => ReactNode;
+
+/**
+ * Renders the consumer's `render` prop if given, else the default element with
+ * `defaultProps`, exposing the typed `state` to the render prop. Not a hook
+ * (contains no hooks) despite slotting into component bodies.
+ */
+function renderPart<State, Props extends Record<string, unknown>>(
+ render: RenderProp<State, Props> | undefined,
+ tag: string,
+ state: State,
+ defaultProps: Props,
+): ReactNode {
+ if (render) return render(state, defaultProps);
+ return createElement(tag, defaultProps);
+}
+
+const isRunning = (status: ToolCallStatus) => status === "streaming" || status === "executing";
+
+// ── Shared label / formatting helpers ──
+
+const LABELS: Record<ToolCallStatus, (name: string) => string> = {
+ streaming: (n) => `Calling the ${n} tool`,
+ executing: (n) => `Running the ${n} tool`,
+ complete: (n) => `Called the ${n} tool`,
+ error: (n) => `${n} failed`,
+};
+
+// Used when the tool name is empty/blank — avoids the doubled-word "tool tool"
+// that an interpolated `${name || "tool"}` fallback would produce.
+const NAMELESS_LABELS: Record<ToolCallStatus, string> = {
+ streaming: "Calling the tool",
+ executing: "Running the tool",
+ complete: "Called the tool",
+ error: "Tool failed",
+};
+
+/** Default human label for a status + tool name. @category Functions */
+export function defaultLabel(status: ToolCallStatus, name: string): string {
+ if (!name || !name.trim()) return NAMELESS_LABELS[status];
+ return LABELS[status](name);
+}
+
+/** Pretty-prints a JSON result string, falling back to the raw string. @category Functions */
+export function prettyResult(value?: string): string {
+ if (value == null) return "";
+ try {
+ return JSON.stringify(JSON.parse(value), null, 2);
+ } catch {
+ return value;
+ }
+}
+
+const isObject = (v: unknown): v is Record<string, unknown> =>
+ typeof v === "object" && v !== null && !Array.isArray(v);
+
+/** Pretty-prints any value (objects stringified, strings shown verbatim). */
+function prettyValue(value: unknown): string {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+/**
+ * Resolves what to show in the request panel. Honors the deprecated `_request`
+ * arg key (shows just that), and — when the parsed input is empty (unparseable
+ * / earliest streaming frame) — falls back to the raw argument string so the
+ * user sees the partial text instead of an empty `{}`.
+ */
+function resolveRequest(activity: ToolActivity): string {
+ const input = activity.input;
+ // `!= null` matches the legacy ToolCallComponent gating — a `_request: null`
+ // is treated as absent, not as the request payload.
+ if (isObject(input) && input["_request"] != null) return prettyValue(input["_request"]);
+ if (isObject(input) && Object.keys(input).length === 0) {
+ const raw = activity.toolCall.function.arguments;
+ if (raw && raw.trim()) return raw;
+ }
+ return prettyValue(input);
+}
+
+/** The deprecated `_response` arg key, if non-null (else `undefined`). */
+function resolveLegacyResponse(activity: ToolActivity): unknown {
+ const input = activity.input;
+ const value = isObject(input) ? input["_response"] : undefined;
+ return value != null ? value : undefined;
+}
+
+const STATUS_ICON: Record<ToolCallStatus, typeof SquareCode> = {
+ streaming: Loader2,
+ executing: Loader2,
+ complete: SquareCode,
+ error: AlertCircle,
+};
+
+// ── Parts ──
+
+interface PartProps<State> {
+ render?: RenderProp<State, Record<string, unknown>>;
+ className?: string;
+ children?: ReactNode;
+}
+
+function Root({
+ activity,
+ isLast = false,
+ running = true,
+ defaultOpen = false,
+ className,
+ children,
+}: {
+ activity: ToolActivity;
+ isLast?: boolean;
+ /** Whether the owning thread is still running (gates the in-progress animations). */
+ running?: boolean;
+ defaultOpen?: boolean;
+ className?: string;
+ children: ReactNode;
+}) {
+ const [isOpen, setOpen] = useState(defaultOpen);
+ const panelId = useId();
+ const triggerId = useId();
+ return (
+ <ToolCallContext.Provider
+ value={{ activity, isLast, running, isOpen, setOpen, panelId, triggerId }}
+ >
+ <div
+ className={clsx("openui-tool-call", `openui-tool-call--${activity.status}`, className)}
+ data-status={activity.status}
+ >
+ {children}
+ </div>
+ </ToolCallContext.Provider>
+ );
+}
+
+const StatusIcon = ({ render, className }: PartProps<{ status: ToolCallStatus }>) => {
+ const { activity, isLast, running } = useToolCall();
+ const spin = isRunning(activity.status) && isLast && running;
+ const Icon = STATUS_ICON[activity.status];
+ return renderPart(
+ render,
+ "span",
+ { status: activity.status },
+ {
+ className: clsx(
+ "openui-tool-call__icon-wrapper",
+ { "openui-tool-call__icon--blinking": spin },
+ className,
+ ),
+ "data-status": activity.status,
+ "data-spin": spin,
+ children: <Icon size={14} className="openui-tool-call__icon" />,
+ },
+ );
+};
+
+const ToolName = ({ render, className }: PartProps<{ toolName: string }>) => {
+ const { activity } = useToolCall();
+ return renderPart(
+ render,
+ "span",
+ { toolName: activity.toolName },
+ {
+ className,
+ children: activity.toolName,
+ },
+ );
+};
+
+const StatusText = ({
+ render,
+ className,
+}: PartProps<{ status: ToolCallStatus; label: string }>) => {
+ const { activity, isLast, running } = useToolCall();
+ const label = activity.statusMessage ?? defaultLabel(activity.status, activity.toolName);
+ const shimmer = isRunning(activity.status) && isLast && running;
+ return renderPart(
+ render,
+ "span",
+ { status: activity.status, label },
+ {
+ // Live region so status transitions (Calling → Running → Called/failed)
+ // are announced; only changes are spoken, so settled cards stay quiet.
+ role: "status",
+ "aria-live": "polite",
+ className: clsx(
+ "openui-tool-call__name",
+ { "openui-tool-call__name--shimmer": shimmer },
+ className,
+ ),
+ children: label,
+ },
+ );
+};
+
+const Parameters = ({ render, className }: PartProps<{ input: unknown; inputString: string }>) => {
+ const { activity } = useToolCall();
+ // Honors the legacy `_request` key + falls back to raw args when unparseable.
+ const inputString = resolveRequest(activity);
+ return renderPart(
+ render,
+ "pre",
+ { input: activity.input, inputString },
+ {
+ className,
+ children: inputString,
+ },
+ );
+};
+
+const Result = ({
+ render,
+ className,
+}: PartProps<{ result?: string; isError: boolean; errorText?: string }>) => {
+ const { activity } = useToolCall();
+ // Legacy tools packed the result into a `_response` arg key (no tool message).
+ const legacyResponse = resolveLegacyResponse(activity);
+ // Enabled when there's a paired result, an error, or a legacy `_response`.
+ if (activity.result == null && !activity.isError && legacyResponse === undefined) return null;
+ const text = activity.isError
+ ? (activity.errorText ?? activity.result ?? "")
+ : legacyResponse !== undefined
+ ? prettyValue(legacyResponse)
+ : prettyResult(activity.result);
+ return renderPart(
+ render,
+ "div",
+ { result: activity.result, isError: activity.isError, errorText: activity.errorText },
+ {
+ className: clsx({ "openui-tool-call__result--error": activity.isError }, className),
+ children: text,
+ },
+ );
+};
+
+const Trigger = ({ render, className, children }: PartProps<{ state: "open" | "closed" }>) => {
+ const { isOpen, setOpen, panelId, triggerId } = useToolCall();
+ return renderPart(
+ render,
+ "button",
+ { state: isOpen ? "open" : "closed" },
+ {
+ type: "button",
+ id: triggerId,
+ className,
+ "aria-expanded": isOpen,
+ "aria-controls": panelId,
+ onClick: () => setOpen(!isOpen),
+ children,
+ },
+ );
+};
+
+const Content = ({ render, className, children }: PartProps<{ isOpen: boolean }>) => {
+ const { isOpen, panelId, triggerId } = useToolCall();
+ if (!isOpen) return null;
+ return renderPart(
+ render,
+ "div",
+ { isOpen },
+ {
+ id: panelId,
+ role: "region",
+ "aria-labelledby": triggerId,
+ "data-state": "open",
+ className,
+ children,
+ },
+ );
+};
+
+/**
+ * The compound tool-call primitive set. Compose `Root` + parts to render a tool
+ * call however a given surface needs.
+ *
+ * @category Components
+ */
+export const ToolCall = {
+ Root,
+ Trigger,
+ Content,
+ StatusIcon,
+ StatusText,
+ ToolName,
+ Parameters,
+ Result,
+};
diff --git a/packages/react-ui/src/components/ToolCall/ToolCallTimeline.tsx b/packages/react-ui/src/components/ToolCall/ToolCallTimeline.tsx
new file mode 100644
index 000000000..dc58df620
--- /dev/null
+++ b/packages/react-ui/src/components/ToolCall/ToolCallTimeline.tsx
@@ -0,0 +1,173 @@
+import { useThread, type ToolActivity } from "@openuidev/react-headless";
+import { ChevronDown, ChevronUp } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { TimelineEntry } from "../_shared/tool-renderer/TimelineEntry";
+import type { ToolDetailedViewPanel } from "../_shared/tool-renderer/ToolActivityRenderer";
+import { defaultLabel } from "./ToolCallPrimitives";
+
+const REVEAL_INTERVAL = 600;
+
+/** Visually hidden but available to screen readers; inline so we don't depend on
+ * scss (a sibling agent owns the stylesheet). */
+const VISUALLY_HIDDEN = {
+ position: "absolute",
+ width: 1,
+ height: 1,
+ overflow: "hidden",
+ clipPath: "inset(50%)",
+ whiteSpace: "nowrap",
+ border: 0,
+ padding: 0,
+ margin: -1,
+} as const;
+
+const isRunning = (a: ToolActivity) => a.status === "streaming" || a.status === "executing";
+
+/**
+ * The "Working… / Behind the scenes" timeline wrapper, driven by
+ * {@link ToolActivity}[] from `useToolActivities` instead of the branch's
+ * `ThinkItem[]`. Keeps the staggered reveal + toggle; "running" is read from the
+ * activity status (not an `isThinking` prop), and "current item ready" asks the
+ * status union instead of peeking at magic `_request`/`_response` keys.
+ *
+ * (The compact reveal uses a CSS fade — framer-motion is intentionally not a
+ * dependency of this package.)
+ *
+ * @category Components
+ */
+export function ToolCallTimeline({
+ activities,
+ isLast = false,
+ detailedViewPanel,
+ forceDefault = false,
+}: {
+ activities: ToolActivity[];
+ isLast?: boolean;
+ detailedViewPanel?: ToolDetailedViewPanel;
+ /** Render every row as the raw default card (e.g. so matched tools' raw
+ * request/response stay inspectable here while their rich preview renders elsewhere). */
+ forceDefault?: boolean;
+}) {
+ // The timeline is "thinking" while its own last activity is still running, it's
+ // the live message, AND the thread is actually running — so a closed-args call
+ // that never received a result stops showing "Working..." once the run ends.
+ const isThreadRunning = useThread((s) => s.isRunning);
+ const thinking =
+ isThreadRunning &&
+ isLast &&
+ activities.length > 0 &&
+ isRunning(activities[activities.length - 1]!);
+
+ const [expanded, setExpanded] = useState(false);
+ // Live message → reveal one-by-one from the first; historical (not live) →
+ // everything already revealed so it never animates "Working…" on mount.
+ const [revealedCount, setRevealedCount] = useState(() =>
+ isLast ? 1 : Math.max(activities.length, 1),
+ );
+ const prevThinking = useRef(thinking);
+
+ useEffect(() => {
+ if (!prevThinking.current && thinking) {
+ setRevealedCount(1);
+ setExpanded(false);
+ }
+ if (prevThinking.current && !thinking) {
+ setExpanded(false);
+ setRevealedCount(activities.length);
+ }
+ prevThinking.current = thinking;
+ }, [thinking, activities.length]);
+
+ // Advance only when the current activity has left "streaming" (args closed) —
+ // replaces the branch's `!!toolRequest || !!toolResponse` peek with the union.
+ const currentReady = (() => {
+ const a = activities[revealedCount - 1];
+ return a ? a.status !== "streaming" : true;
+ })();
+
+ useEffect(() => {
+ // Only the live message reveals incrementally; historical messages show all.
+ if (isLast && revealedCount < activities.length && currentReady) {
+ const t = setTimeout(() => setRevealedCount((c) => c + 1), REVEAL_INTERVAL);
+ return () => clearTimeout(t);
+ }
+ return undefined;
+ }, [isLast, activities.length, revealedCount, currentReady]);
+
+ if (activities.length === 0) return null;
+
+ const revealing = revealedCount < activities.length;
+ const showCompact = (thinking || revealing) && !expanded;
+ const current = activities[Math.min(revealedCount - 1, activities.length - 1)]!;
+
+ // Persistent live announcement reflecting the current step's status — driven by
+ // the same fallback the primitives use so SRs hear status changes as content
+ // updates (the keyed reveal wrapper remounts and never announces on its own).
+ const liveLabel = current.statusMessage ?? defaultLabel(current.status, current.toolName);
+
+ // Once settled, surface a failure count on the toggle so errors aren't hidden
+ // behind a collapsed "Behind the scenes".
+ const settled = !thinking && !revealing;
+ const failedCount = settled ? activities.filter((a) => a.status === "error").length : 0;
+ const toggleLabel =
+ thinking || revealing
+ ? "Working..."
+ : failedCount > 0
+ ? `Behind the scenes · ${failedCount} failed`
+ : "Behind the scenes";
+
+ return (
+ <div className="openui-behind-the-scenes">
+ <div role="status" aria-live="polite" style={VISUALLY_HIDDEN}>
+ {liveLabel}
+ </div>
+
+ <button
+ className="openui-behind-the-scenes__toggle"
+ type="button"
+ aria-expanded={expanded}
+ onClick={() => setExpanded((v) => !v)}
+ >
+ {expanded ? (
+ <ChevronUp size={14} className="openui-behind-the-scenes__toggle-icon" />
+ ) : (
+ <ChevronDown size={14} className="openui-behind-the-scenes__toggle-icon" />
+ )}
+ {toggleLabel}
+ </button>
+
+ {showCompact && (
+ <div className="openui-behind-the-scenes__items">
+ {/* key changes per reveal → remounts → re-triggers the CSS fade-in */}
+ <div
+ key={revealedCount}
+ className="openui-behind-the-scenes__reveal-item"
+ style={{ width: "100%" }}
+ >
+ <TimelineEntry
+ activity={current}
+ isLast
+ detailedViewPanel={detailedViewPanel}
+ forceDefault={forceDefault}
+ />
+ </div>
+ </div>
+ )}
+
+ {expanded && (
+ <div className="openui-behind-the-scenes__items">
+ {activities.map((a, idx) => (
+ <div key={a.id} style={{ width: "100%" }}>
+ <TimelineEntry
+ activity={a}
+ isLast={isLast && idx === activities.length - 1}
+ detailedViewPanel={detailedViewPanel}
+ forceDefault={forceDefault}
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/react-ui/src/components/ToolCall/index.ts b/packages/react-ui/src/components/ToolCall/index.ts
index b2758bcbe..75c6f44f0 100644
--- a/packages/react-ui/src/components/ToolCall/index.ts
+++ b/packages/react-ui/src/components/ToolCall/index.ts
@@ -1,2 +1,10 @@
+// Legacy (deprecated) — kept so external imports don't break.
export { BehindTheScenes, type BehindTheScenesProps } from "./BehindTheScenes";
export { ToolCallComponent, type ToolCallProps } from "./ToolCall";
+
+// Compound primitive set + batteries-included compositions.
+export { DefaultToolCard } from "./DefaultToolCard";
+export { SourceIcon } from "./SourceIcon";
+export { TimelineToolCard } from "./TimelineToolCard";
+export { ToolCall, defaultLabel, prettyResult, useToolCall } from "./ToolCallPrimitives";
+export { ToolCallTimeline } from "./ToolCallTimeline";
diff --git a/packages/react-ui/src/components/ToolCall/toolCall.scss b/packages/react-ui/src/components/ToolCall/toolCall.scss
index 96d60ae60..e9fe85047 100644
--- a/packages/react-ui/src/components/ToolCall/toolCall.scss
+++ b/packages/react-ui/src/components/ToolCall/toolCall.scss
@@ -28,6 +28,12 @@
&:not(:disabled):active {
background-color: cssUtils.$sunk;
}
+
+ // button-reset strips chrome, so restore a visible keyboard focus ring.
+ &:focus-visible {
+ outline: 2px solid cssUtils.$border-interactive-emphasis;
+ outline-offset: cssUtils.$space-3xs;
+ }
}
&__toggle-icon {
@@ -42,6 +48,22 @@
align-items: flex-start;
width: 100%;
}
+
+ // Compact staggered reveal (CSS fade-in; remounted per step via React key).
+ &__reveal-item {
+ animation: openui-behind-the-scenes-reveal 0.2s ease;
+ }
+}
+
+@keyframes openui-behind-the-scenes-reveal {
+ from {
+ opacity: 0;
+ transform: translateY(8px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
}
// ── Timeline item (each tool call) ──
@@ -50,13 +72,15 @@
display: flex;
flex-direction: column;
width: 100%;
- padding-left: cssUtils.$space-l;
+ padding-inline-start: cssUtils.$space-l;
&__title-row {
display: flex;
align-items: center;
gap: cssUtils.$space-m;
color: cssUtils.$text-neutral-secondary;
+ // Allow the name to shrink/ellipsize instead of overflowing the row.
+ min-width: 0;
}
&__icon-wrapper {
@@ -82,6 +106,9 @@
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
+ // Shrink + ellipsize so a long tool name never pushes the chevron offscreen.
+ flex: 1 1 auto;
+ min-width: 0;
}
&__name--shimmer {
@@ -108,16 +135,17 @@
display: flex;
gap: cssUtils.$space-m;
padding: cssUtils.$space-s-m cssUtils.$space-s;
- padding-right: 0;
+ padding-inline-end: 0;
min-height: 20px;
+ width: calc(100% - 6px);
// 6px offset = half of 14px icon - half of 1px border
- margin-left: 6px;
- border-left: 1px solid cssUtils.$border-interactive;
+ margin-inline-start: 6px;
+ border-inline-start: 1px solid cssUtils.$border-interactive;
}
&__connector--last {
- border-left-color: transparent;
+ border-inline-start-color: transparent;
}
&__args-block {
@@ -127,6 +155,164 @@
padding-left: cssUtils.$space-m;
width: 100%;
}
+
+ // ── Web-search presentation (reasoning line + sources list) ──
+
+ &__reasoning {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-secondary;
+ font-style: italic;
+ margin: 0;
+ }
+
+ &__sources {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ border: 1px solid cssUtils.$border-default;
+ border-radius: cssUtils.$radius-l;
+ background-color: cssUtils.$foreground;
+ padding: cssUtils.$space-2xs;
+ }
+
+ &__source {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: cssUtils.$space-2xs cssUtils.$space-s;
+ padding-left: cssUtils.$space-2xs;
+ border-radius: cssUtils.$radius-m;
+ cursor: pointer;
+ text-decoration: none;
+ color: inherit;
+ transition: background-color 0.15s ease;
+
+ &:hover {
+ background-color: cssUtils.$sunk;
+ }
+
+ &:focus-visible {
+ outline: 2px solid cssUtils.$border-interactive-emphasis;
+ outline-offset: cssUtils.$space-3xs;
+ }
+ }
+
+ &__source-left {
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-s;
+ min-width: 0;
+ }
+
+ &__source-logo {
+ width: 24px;
+ height: 24px;
+ border-radius: cssUtils.$radius-xs;
+ flex-shrink: 0;
+ }
+
+ &__source-title {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-primary;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ &__source-desc {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-secondary;
+ // Let the description shrink + truncate so it never squeezes the title.
+ min-width: 0;
+ flex-shrink: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ // ── Chevron "card" composition (DefaultToolCard) ──
+
+ &--card {
+ padding-left: 0;
+ }
+
+ &__header {
+ @include cssUtils.button-reset;
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-m;
+ width: 100%;
+ padding: cssUtils.$space-2xs cssUtils.$space-s;
+ border-radius: cssUtils.$radius-m;
+ cursor: pointer;
+ background-color: transparent;
+ color: cssUtils.$text-neutral-secondary;
+
+ &:not(:disabled):hover {
+ background-color: cssUtils.$sunk;
+ }
+
+ // button-reset strips chrome, so restore a visible keyboard focus ring.
+ &:focus-visible {
+ outline: 2px solid cssUtils.$border-interactive-emphasis;
+ outline-offset: cssUtils.$space-3xs;
+ }
+ }
+
+ &__chevron {
+ flex-shrink: 0;
+ margin-inline-start: auto;
+ color: cssUtils.$text-neutral-secondary;
+ transition: transform 0.2s ease;
+ }
+
+ &__panel {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-xs;
+ padding: cssUtils.$space-s cssUtils.$space-m;
+ width: 100%;
+ }
+
+ &__request,
+ &__response {
+ @include cssUtils.typography(code, small);
+ color: cssUtils.$text-neutral-secondary;
+ margin: 0;
+ white-space: pre-wrap;
+ // Wrap at spaces; only hard-break tokens too long to fit.
+ overflow-wrap: anywhere;
+ // Clamp a huge result in the chevron card (parity with the timeline path).
+ max-height: 250px;
+ overflow: auto;
+ }
+
+ &__result--error {
+ color: cssUtils.$text-danger-primary;
+ }
+
+ // ── Status tints (subtle; driven by the Root `--{status}` modifier) ──
+ // Complete vs running look near-identical otherwise — tint the glyph only.
+ &--complete {
+ .openui-tool-call__icon {
+ color: cssUtils.$text-success-primary;
+ }
+ }
+
+ // A failed call should read as failed at a glance: tint the glyph + name and
+ // give the card a restrained danger left-border + faint background.
+ &--error {
+ border-inline-start: 2px solid cssUtils.$text-danger-primary;
+ background-color: cssUtils.$danger-background;
+ border-radius: cssUtils.$radius-m;
+
+ .openui-tool-call__icon {
+ color: cssUtils.$text-danger-primary;
+ }
+
+ .openui-tool-call__name {
+ color: cssUtils.$text-danger-primary;
+ }
+ }
}
// ── Expandable code block (request / response) ──
@@ -148,16 +334,27 @@
display: flex;
align-items: center;
justify-content: space-between;
+ gap: cssUtils.$space-s;
width: 100%;
padding: cssUtils.$space-s;
cursor: pointer;
background-color: transparent;
+
+ // button-reset strips chrome, so restore a visible keyboard focus ring.
+ &:focus-visible {
+ outline: 2px solid cssUtils.$border-interactive-emphasis;
+ outline-offset: cssUtils.$space-3xs;
+ }
}
&__label {
@include cssUtils.typography(label, small);
color: cssUtils.$text-neutral-secondary;
-webkit-text-fill-color: currentColor;
+ // Truncate a grown/loading label instead of shoving the chevron offscreen.
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
}
&__label--loading {
@@ -204,7 +401,41 @@
color: cssUtils.$text-neutral-secondary;
margin: 0;
white-space: pre-wrap;
- word-break: break-all;
+ // Wrap at spaces; only hard-break tokens too long to fit.
+ overflow-wrap: anywhere;
+ }
+
+ &__code--error {
+ color: cssUtils.$text-danger-primary;
+ }
+}
+
+// ── Web-search detailed view (renderer `actual`) ──
+
+.openui-web-search__detailed {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$space-m;
+ list-style: none;
+ margin: 0;
+ padding: cssUtils.$space-m;
+
+ a {
+ display: inline-flex;
+ align-items: center;
+ gap: cssUtils.$space-s;
+ color: cssUtils.$text-neutral-primary;
+ text-decoration: none;
+
+ &:hover {
+ text-decoration: underline;
+ }
+ }
+
+ p {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-secondary;
+ margin: cssUtils.$space-2xs 0 0;
}
}
@@ -226,3 +457,34 @@
background-position: 0% center;
}
}
+
+// ── Reduced motion ──
+// Honor `prefers-reduced-motion: reduce`: stop the infinite icon blink + text
+// shimmer (the shimmer also paints text via a clipped gradient, so reset it to a
+// solid fill or it would freeze half-transparent), drop the staggered reveal
+// fade, and disable the decorative chevron/hover transitions.
+@media (prefers-reduced-motion: reduce) {
+ .openui-behind-the-scenes__reveal-item,
+ .openui-tool-call__icon--blinking {
+ animation: none;
+ }
+
+ .openui-tool-call__name--shimmer,
+ .openui-tool-code-block__label--loading {
+ animation: none;
+ background-image: none;
+ -webkit-text-fill-color: currentColor;
+ }
+
+ .openui-tool-code-block__label--loading {
+ color: cssUtils.$text-neutral-secondary;
+ }
+
+ .openui-behind-the-scenes__toggle-icon,
+ .openui-tool-call__chevron,
+ .openui-tool-call__source,
+ .openui-tool-code-block,
+ .openui-tool-code-block__chevron {
+ transition: none;
+ }
+}
diff --git a/packages/react-ui/src/components/_shared/Collapsible.tsx b/packages/react-ui/src/components/_shared/Collapsible.tsx
new file mode 100644
index 000000000..97db0a2d2
--- /dev/null
+++ b/packages/react-ui/src/components/_shared/Collapsible.tsx
@@ -0,0 +1,67 @@
+import clsx from "clsx";
+import { ChevronDown } from "lucide-react";
+import { useId, useState, type ReactNode } from "react";
+
+/**
+ * Content-agnostic, aria-correct collapsible — the extracted version of the old
+ * `ToolCodeBlock` (chevron + `aria-expanded`/`aria-controls`, the `--loading`
+ * label state) so request/response (and anything else) can slot into it.
+ *
+ * @category Components
+ */
+export function Collapsible({
+ label,
+ labelLoading,
+ loading = false,
+ defaultOpen = false,
+ children,
+}: {
+ label: string;
+ /** Shimmering label shown while `loading` is `true` (falls back to `label`). */
+ labelLoading?: string;
+ loading?: boolean;
+ defaultOpen?: boolean;
+ children: ReactNode;
+}) {
+ const [isExpanded, setIsExpanded] = useState(defaultOpen);
+ const panelId = useId();
+ const labelId = useId();
+ const shownLabel = loading && labelLoading ? labelLoading : label;
+
+ return (
+ <div className="openui-tool-code-block">
+ <button
+ className="openui-tool-code-block__header"
+ type="button"
+ aria-expanded={isExpanded}
+ aria-controls={panelId}
+ onClick={() => setIsExpanded((v) => !v)}
+ >
+ <span
+ id={labelId}
+ className={clsx("openui-tool-code-block__label", {
+ "openui-tool-code-block__label--loading": loading,
+ })}
+ >
+ {shownLabel}
+ </span>
+ <ChevronDown
+ size={14}
+ className={clsx("openui-tool-code-block__chevron", {
+ "openui-tool-code-block__chevron--expanded": isExpanded,
+ })}
+ />
+ </button>
+ {isExpanded && (
+ <div
+ className="openui-tool-code-block__content"
+ id={panelId}
+ role="region"
+ aria-labelledby={labelId}
+ >
+ {children}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/react-ui/src/components/_shared/artifact/ArtifactPanel.tsx b/packages/react-ui/src/components/_shared/artifact/ArtifactPanel.tsx
deleted file mode 100644
index 07dac2b5c..000000000
--- a/packages/react-ui/src/components/_shared/artifact/ArtifactPanel.tsx
+++ /dev/null
@@ -1,134 +0,0 @@
-import { useArtifact, useArtifactPortalTarget } from "@openuidev/react-headless";
-import clsx from "clsx";
-import { X } from "lucide-react";
-import { Component, forwardRef, useEffect, type ReactNode } from "react";
-import { createPortal } from "react-dom";
-import { useTheme } from "../../ThemeProvider/ThemeProvider";
-
-/** @internal */
-type ArtifactErrorBoundaryProps = {
- children: ReactNode;
- fallback?: ReactNode;
-};
-
-type ArtifactErrorBoundaryState = {
- hasError: boolean;
-};
-
-/** @internal */
-class ArtifactErrorBoundary extends Component<
- ArtifactErrorBoundaryProps,
- ArtifactErrorBoundaryState
-> {
- constructor(props: ArtifactErrorBoundaryProps) {
- super(props);
- this.state = { hasError: false };
- }
-
- static getDerivedStateFromError(): ArtifactErrorBoundaryState {
- return { hasError: true };
- }
-
- override render() {
- if (this.state.hasError) {
- return this.props.fallback ?? null;
- }
- return this.props.children;
- }
-}
-
-/**
- * Props for {@link ArtifactPanel}.
- *
- * @category Components
- */
-export type ArtifactPanelProps = {
- /** Artifact ID this panel renders content for. Must match the ID passed to `useArtifact(id)`. */
- artifactId: string;
- /** Content rendered inside the panel when this artifact is active. */
- children: ReactNode;
- /** Display title for the panel header and aria-label. Defaults to `"Artifact"`. */
- title?: string;
- /** Additional CSS class name(s) applied to the panel container. */
- className?: string;
- /** Fallback UI rendered if children throw during rendering. Defaults to `null`. */
- errorFallback?: ReactNode;
- /**
- * Controls the panel header.
- * - `true` (default): built-in header with title + close button
- * - `false`: no header, raw children only
- * - `ReactNode`: custom header replacing the built-in one
- */
- header?: boolean | ReactNode;
-};
-
-/** @internal */
-const DefaultHeader = ({ title, onClose }: { title: string; onClose: () => void }) => (
- <div className="openui-artifact-panel__header">
- <span className="openui-artifact-panel__title">{title}</span>
- <button
- className="openui-artifact-panel__close"
- onClick={onClose}
- aria-label="Close artifact panel"
- >
- <X size={16} />
- </button>
- </div>
-);
-
-/**
- * Portals artifact content into the nearest {@link ArtifactPortalTarget}.
- *
- * Renders nothing when the artifact is inactive or no portal target is mounted.
- * Wraps children in an error boundary and applies theme-scoped class names.
- *
- * Requires `<ArtifactPortalTarget />` to be mounted in the layout.
- *
- * @category Components
- */
-export const ArtifactPanel = forwardRef<HTMLDivElement, ArtifactPanelProps>(
- ({ artifactId, children, title, className, errorFallback, header = true }, ref) => {
- const { isActive, close } = useArtifact(artifactId);
- const { node: panelNode } = useArtifactPortalTarget();
- const { portalThemeClassName } = useTheme();
-
- useEffect(() => {
- if (!isActive || panelNode) return;
-
- const timer = setTimeout(() => {
- console.warn(
- "[OpenUI] ArtifactPanel: artifact is active but no render target is mounted. " +
- "Ensure <ArtifactPortalTarget /> is rendered in your layout.",
- );
- }, 100);
- return () => clearTimeout(timer);
- }, [isActive, panelNode]);
-
- if (!isActive || !panelNode) return null;
-
- const handleClose = () => close();
-
- let headerContent: ReactNode = null;
- if (header === true) {
- headerContent = <DefaultHeader title={title ?? "Artifact"} onClose={handleClose} />;
- } else if (header !== false) {
- headerContent = header;
- }
-
- return createPortal(
- <div
- ref={ref}
- id={`openui-artifact-panel-${artifactId}`}
- className={clsx("openui-artifact-panel", portalThemeClassName, className)}
- role="region"
- aria-label={title ?? "Artifact panel"}
- >
- {headerContent}
- <ArtifactErrorBoundary fallback={errorFallback}>{children}</ArtifactErrorBoundary>
- </div>,
- panelNode,
- );
- },
-);
-
-ArtifactPanel.displayName = "ArtifactPanel";
diff --git a/packages/react-ui/src/components/_shared/artifact/artifactPanel.scss b/packages/react-ui/src/components/_shared/artifact/artifactPanel.scss
deleted file mode 100644
index 634ce066d..000000000
--- a/packages/react-ui/src/components/_shared/artifact/artifactPanel.scss
+++ /dev/null
@@ -1,46 +0,0 @@
-@use "../../../cssUtils" as cssUtils;
-
-.openui-artifact-panel__header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: cssUtils.$space-s;
- padding: cssUtils.$space-s cssUtils.$space-m;
- border-bottom: 1px solid cssUtils.$border-default;
- background-color: cssUtils.$foreground;
- position: sticky;
- top: 0;
- z-index: 1;
-}
-
-.openui-artifact-panel__title {
- @include cssUtils.typography(body, default);
- color: cssUtils.$text-neutral-primary;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- min-width: 0;
-}
-
-.openui-artifact-panel__close {
- display: flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- width: 28px;
- height: 28px;
- padding: 0;
- border: none;
- border-radius: cssUtils.$radius-s;
- background: transparent;
- color: cssUtils.$text-neutral-secondary;
- cursor: pointer;
- transition:
- background-color 0.15s ease,
- color 0.15s ease;
-
- &:hover {
- background: cssUtils.$highlight;
- color: cssUtils.$text-neutral-primary;
- }
-}
diff --git a/packages/react-ui/src/components/_shared/artifact/index.ts b/packages/react-ui/src/components/_shared/artifact/index.ts
deleted file mode 100644
index 010430867..000000000
--- a/packages/react-ui/src/components/_shared/artifact/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export * from "./ArtifactOverlay";
-export * from "./ArtifactPanel";
-export * from "./ArtifactPortalTarget";
diff --git a/packages/react-ui/src/components/_shared/index.ts b/packages/react-ui/src/components/_shared/index.ts
index 60d968b92..187e7f6d0 100644
--- a/packages/react-ui/src/components/_shared/index.ts
+++ b/packages/react-ui/src/components/_shared/index.ts
@@ -1,4 +1,4 @@
-export * from "./artifact";
export * from "./store";
+export * from "./tool-renderer";
export * from "./types";
export * from "./utils";
diff --git a/packages/react-ui/src/components/_shared/shared.scss b/packages/react-ui/src/components/_shared/shared.scss
index 1e4098651..e69de29bb 100644
--- a/packages/react-ui/src/components/_shared/shared.scss
+++ b/packages/react-ui/src/components/_shared/shared.scss
@@ -1,2 +0,0 @@
-@forward "./artifact/artifactOverlay.scss";
-@forward "./artifact/artifactPanel.scss";
diff --git a/packages/react-ui/src/components/_shared/store/store.tsx b/packages/react-ui/src/components/_shared/store/store.tsx
index daf47436a..2b5067f73 100644
--- a/packages/react-ui/src/components/_shared/store/store.tsx
+++ b/packages/react-ui/src/components/_shared/store/store.tsx
@@ -4,10 +4,12 @@ import { useShallow } from "zustand/react/shallow";
interface ShellState {
isSidebarOpen: boolean;
+ isWorkspaceOpen: boolean;
agentName: string;
logoUrl: string;
showAssistantLogo: boolean;
setIsSidebarOpen: (isOpen: boolean) => void;
+ setIsWorkspaceOpen: (isOpen: boolean) => void;
setAgentName: (name: string) => void;
setLogoUrl: (url: string) => void;
setShowAssistantLogo: (show: boolean) => void;
@@ -24,10 +26,12 @@ export const createShellStore = ({
}) =>
create<ShellState>((set) => ({
isSidebarOpen: true,
+ isWorkspaceOpen: true,
agentName: agentName,
logoUrl: logoUrl,
showAssistantLogo,
setIsSidebarOpen: (isOpen: boolean) => set({ isSidebarOpen: isOpen }),
+ setIsWorkspaceOpen: (isOpen: boolean) => set({ isWorkspaceOpen: isOpen }),
setAgentName: (name: string) => set({ agentName: name }),
setLogoUrl: (url: string) => set({ logoUrl: url }),
setShowAssistantLogo: (show: boolean) => set({ showAssistantLogo: show }),
@@ -38,9 +42,8 @@ export const ShellStoreContext = createContext<ReturnType<typeof createShellStor
export const useShellStore = <T,>(selector: (state: ShellState) => T): T => {
const store = useContext(ShellStoreContext);
if (!store) {
- throw new Error("useShellStore must be used within ShellStoreProvider");
+ throw new Error("useShellStore must be used within a ShellStoreProvider");
}
-
return store(useShallow(selector));
};
diff --git a/packages/react-ui/src/components/_shared/tool-renderer/TimelineEntry.tsx b/packages/react-ui/src/components/_shared/tool-renderer/TimelineEntry.tsx
new file mode 100644
index 000000000..95b81a8b8
--- /dev/null
+++ b/packages/react-ui/src/components/_shared/tool-renderer/TimelineEntry.tsx
@@ -0,0 +1,68 @@
+import { useArtifactRenderer, useThread, type ToolActivity } from "@openuidev/react-headless";
+import { memo } from "react";
+import { TimelineToolCard } from "../../ToolCall/TimelineToolCard";
+import { ToolActivityRenderer, type ToolDetailedViewPanel } from "./ToolActivityRenderer";
+
+export interface TimelineEntryProps {
+ activity: ToolActivity;
+ /** Whether this entry belongs to the live (last assistant) message — drives the running shimmer. */
+ isLast?: boolean;
+ /** Optional detailed-view panel for matched renderers (defaults to the shared one). */
+ detailedViewPanel?: ToolDetailedViewPanel;
+ /** Always render the raw default card, even when a renderer matches (used for the "Behind the scenes" raw view). */
+ forceDefault?: boolean;
+ /**
+ * When a matched renderer's parser returns null, fall back to the raw default
+ * card (default `true`). Set `false` when a separate raw card already covers
+ * this call (e.g. OpenUIChat shows the raw card in its forceDefault timeline),
+ * to avoid rendering the raw card twice.
+ */
+ fallbackToDefault?: boolean;
+}
+
+const propsEqual = (a: TimelineEntryProps, b: TimelineEntryProps) =>
+ a.activity.status === b.activity.status &&
+ a.activity.toolCall.function.arguments === b.activity.toolCall.function.arguments &&
+ a.activity.result === b.activity.result &&
+ a.activity.isError === b.activity.isError &&
+ a.isLast === b.isLast &&
+ a.forceDefault === b.forceDefault &&
+ a.fallbackToDefault === b.fallbackToDefault &&
+ a.detailedViewPanel === b.detailedViewPanel;
+
+/**
+ * Timeline-flavoured sibling of {@link ToolCallEntry}: the same matched-renderer
+ * **xor** default dispatch, but the default is the timeline-shaped
+ * {@link TimelineToolCard} (dot + connector + StatusStep) instead of the chevron
+ * card. Used both inside `<ToolCallTimeline>` and directly by flat threads that
+ * want the always-visible timeline rows.
+ *
+ * @category Components
+ */
+export const TimelineEntry = memo(function TimelineEntry({
+ activity,
+ isLast = false,
+ detailedViewPanel,
+ forceDefault = false,
+ fallbackToDefault = true,
+}: TimelineEntryProps) {
+ const renderer = useArtifactRenderer(activity.toolName); // exact → RegExp → "*"
+ // Run-gate the in-progress animation: a closed-args call with no result must
+ // not shimmer forever after the run ends (the status stays streaming/executing).
+ const isRunning = useThread((s) => s.isRunning);
+ const defaultCard = (
+ <TimelineToolCard activity={activity} isLast={isLast} isRunning={isRunning} />
+ );
+ if (forceDefault || !renderer) return defaultCard;
+ // Matched renderer; if its parser returns null (skips), fall back to the raw
+ // card so a tool call is never invisible mid-stream — unless a separate raw
+ // card already covers it (fallbackToDefault=false).
+ return (
+ <ToolActivityRenderer
+ renderer={renderer}
+ activity={activity}
+ detailedViewPanel={detailedViewPanel}
+ fallback={fallbackToDefault ? defaultCard : null}
+ />
+ );
+}, propsEqual);
diff --git a/packages/react-ui/src/components/_shared/tool-renderer/ToolActivityRenderer.tsx b/packages/react-ui/src/components/_shared/tool-renderer/ToolActivityRenderer.tsx
new file mode 100644
index 000000000..20a74aea1
--- /dev/null
+++ b/packages/react-ui/src/components/_shared/tool-renderer/ToolActivityRenderer.tsx
@@ -0,0 +1,166 @@
+import {
+ useDetailedView,
+ useDetailedViewStore,
+ useThreadContextStore,
+ type ArtifactRendererConfig,
+ type ArtifactRendererControls,
+ type ParsedArtifact,
+ type ToolActivity,
+} from "@openuidev/react-headless";
+import { useEffect, useId, useMemo, useRef, type ComponentType, type ReactNode } from "react";
+import { DetailedViewPanel as DefaultDetailedViewPanel } from "../../AgentInterface/_shared/detailed-view";
+import { ToolCallErrorFallback } from "./ToolCallErrorFallback";
+
+/**
+ * The subset of `DetailedViewPanel` props the renderer needs. Lets a thread
+ * family inject its own panel (the AgentInterface panel differs from the shared
+ * one only in its close button) so one renderer module serves all of them.
+ *
+ * @category Types
+ */
+export type ToolDetailedViewPanel = ComponentType<{
+ viewId: string;
+ title?: string;
+ children: ReactNode;
+}>;
+
+/**
+ * Runs a matched renderer for one tool activity via the `parser` contract:
+ * reconstruct the raw envelope from the typed activity (`args` = the raw JSON
+ * string, `response` = the result or null) so parsers see exactly today's input.
+ */
+function runRenderer<Props>(
+ renderer: ArtifactRendererConfig<Props>,
+ activity: ToolActivity,
+): ParsedArtifact<Props> | null {
+ return renderer.parser(
+ { args: activity.toolCall.function.arguments, response: activity.result ?? null },
+ { isStreaming: activity.status === "streaming" || activity.status === "executing" },
+ );
+}
+
+/**
+ * Renders a matched artifact renderer for a single {@link ToolActivity}.
+ *
+ * Lifecycle mirrors the previous `RendererInstance`: run the renderer, register
+ * the entry in ThreadContext when `meta` is non-null, and render
+ * `preview(props, controls)` inline + `<DetailedViewPanel>` for the side panel.
+ * The renderer is wrapped in try/catch — a throw renders an inline fallback
+ * instead of blanking the thread.
+ *
+ * @internal
+ */
+export function ToolActivityRenderer<Props>({
+ renderer,
+ activity,
+ detailedViewPanel: DetailedViewPanel = DefaultDetailedViewPanel,
+ fallback = null,
+}: {
+ renderer: ArtifactRendererConfig<Props>;
+ activity: ToolActivity;
+ detailedViewPanel?: ToolDetailedViewPanel;
+ /** Rendered when the matched renderer's parse/parser returns `null` (skips) —
+ * lets the caller show a default card instead of nothing. */
+ fallback?: ReactNode;
+}) {
+ const fallbackId = useId();
+ const tcStore = useThreadContextStore();
+ const dvStore = useDetailedViewStore();
+
+ const isStreaming = activity.status === "streaming" || activity.status === "executing";
+
+ const { parsed, error } = useMemo(() => {
+ try {
+ return { parsed: runRenderer(renderer, activity), error: null as string | null };
+ } catch (e) {
+ return { parsed: null as ParsedArtifact<Props> | null, error: String(e) };
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ renderer,
+ activity.id,
+ activity.status,
+ activity.toolCall.function.arguments,
+ activity.result,
+ activity.isError,
+ ]);
+
+ const meta = parsed?.meta ?? null;
+
+ // viewId derives from meta when present, otherwise from React's useId so
+ // `controls.open` still works for an inline-only renderer.
+ const viewId = meta ? `${meta.id}:${meta.version}` : fallbackId;
+
+ // Register entry on mount; unregister on unmount or when (id, version) changes.
+ useEffect(() => {
+ if (!meta) return;
+ // Prefer the artifact's REAL kind from the parser (meta.type) so a report
+ // lists as "Report" and a deck as "Slides" — even though a single
+ // tool-owning renderer (e.g. Presentation) matched the generate/edit tool
+ // names and would otherwise stamp its own static type on both. Fall back to
+ // the matched renderer's type for parsers that don't set meta.type.
+ tcStore.getState().registerArtifact({
+ ...meta,
+ type: meta.type ?? renderer.type,
+ updatedAt: Date.now(),
+ });
+ return () => tcStore.getState().unregisterArtifact(meta.id, meta.version);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [tcStore, renderer.type, meta?.id, meta?.version, meta?.heading, meta?.type]);
+
+ // Keep an OPEN side panel alive when this instance's viewId changes for the
+ // same logical artifact (streamed artifact resolves its real id, or version
+ // bumps on edit).
+ const prevViewIdRef = useRef(viewId);
+ useEffect(() => {
+ const prev = prevViewIdRef.current;
+ if (prev === viewId) return;
+ prevViewIdRef.current = viewId;
+ const dv = dvStore.getState();
+ if (dv.activeDetailedViewId === prev) dv.setActiveDetailedView(viewId);
+ }, [viewId, dvStore]);
+
+ // Follow an edit across instances: when a NEWER version of the artifact that's
+ // currently open registers, re-point the active view to it.
+ useEffect(() => {
+ if (!meta) return;
+ const dv = dvStore.getState();
+ const active = dv.activeDetailedViewId;
+ if (!active || active === viewId || !active.startsWith(`${meta.id}:`)) return;
+ const activeVersion = Number(active.slice(meta.id.length + 1));
+ if (!Number.isFinite(activeVersion) || meta.version > activeVersion) {
+ dv.setActiveDetailedView(viewId);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dvStore, viewId, meta?.id, meta?.version]);
+
+ const { isActive, open, close, toggle } = useDetailedView(viewId);
+
+ if (error) {
+ return <ToolCallErrorFallback error={error} toolName={activity.toolName} />;
+ }
+ // A failed tool call has no real artifact. The c1 parser still produces a
+ // preview from the streamed args (artifact_content), independent of the error
+ // result, so `parsed` is non-null — but that preview is never registered and
+ // vanishes on refresh. Suppress it on error and show the raw tool card
+ // (fallback) instead, so the UI only shows artifacts that actually succeeded
+ // — consistent live and after reload.
+ if (activity.isError || parsed === null) return <>{fallback}</>;
+
+ const controls: ArtifactRendererControls = {
+ isActive,
+ isStreaming,
+ open,
+ close,
+ toggle,
+ };
+
+ return (
+ <>
+ {renderer.preview(parsed.props, controls)}
+ <DetailedViewPanel viewId={viewId} title={meta?.heading ?? "Detailed view"}>
+ {renderer.actual(parsed.props, controls)}
+ </DetailedViewPanel>
+ </>
+ );
+}
diff --git a/packages/react-ui/src/components/_shared/tool-renderer/ToolCallEntry.tsx b/packages/react-ui/src/components/_shared/tool-renderer/ToolCallEntry.tsx
new file mode 100644
index 000000000..56fcd8501
--- /dev/null
+++ b/packages/react-ui/src/components/_shared/tool-renderer/ToolCallEntry.tsx
@@ -0,0 +1,50 @@
+import { useArtifactRenderer, useThread, type ToolActivity } from "@openuidev/react-headless";
+import { memo } from "react";
+import { DefaultToolCard } from "../../ToolCall/DefaultToolCard";
+import { ToolActivityRenderer, type ToolDetailedViewPanel } from "./ToolActivityRenderer";
+
+export interface ToolCallEntryProps {
+ activity: ToolActivity;
+ /** Whether this entry belongs to the live (last assistant) message — drives the running shimmer. */
+ isLast?: boolean;
+ /** Optional detailed-view panel for matched renderers (defaults to the shared one). */
+ detailedViewPanel?: ToolDetailedViewPanel;
+}
+
+const propsEqual = (a: ToolCallEntryProps, b: ToolCallEntryProps) =>
+ a.activity.status === b.activity.status &&
+ a.activity.toolCall.function.arguments === b.activity.toolCall.function.arguments &&
+ a.activity.result === b.activity.result &&
+ a.activity.isError === b.activity.isError &&
+ a.isLast === b.isLast &&
+ a.detailedViewPanel === b.detailedViewPanel;
+
+/**
+ * Renders one tool call: a matched artifact renderer (exact → RegExp → `"*"`)
+ * **xor** the batteries-included {@link DefaultToolCard} — never both. The
+ * single render path that replaces the copy-pasted call-card + result-renderer
+ * blocks across the thread components. Memoized so it only re-renders when the
+ * activity actually changes.
+ *
+ * @category Components
+ */
+export const ToolCallEntry = memo(function ToolCallEntry({
+ activity,
+ isLast = false,
+ detailedViewPanel,
+}: ToolCallEntryProps) {
+ const renderer = useArtifactRenderer(activity.toolName);
+ // Run-gate the in-progress animation (see TimelineEntry).
+ const isRunning = useThread((s) => s.isRunning);
+ const defaultCard = <DefaultToolCard activity={activity} isLast={isLast} isRunning={isRunning} />;
+ if (!renderer) return defaultCard;
+ // Matched renderer; fall back to the default card if its parser returns null.
+ return (
+ <ToolActivityRenderer
+ renderer={renderer}
+ activity={activity}
+ detailedViewPanel={detailedViewPanel}
+ fallback={defaultCard}
+ />
+ );
+}, propsEqual);
diff --git a/packages/react-ui/src/components/_shared/tool-renderer/ToolCallErrorFallback.tsx b/packages/react-ui/src/components/_shared/tool-renderer/ToolCallErrorFallback.tsx
new file mode 100644
index 000000000..3eb87a7ba
--- /dev/null
+++ b/packages/react-ui/src/components/_shared/tool-renderer/ToolCallErrorFallback.tsx
@@ -0,0 +1,27 @@
+import { AlertCircle } from "lucide-react";
+
+/**
+ * Inline fallback shown when a matched renderer's `parse`/`parser` throws.
+ * Keeps one bad renderer from blanking the whole thread.
+ *
+ * @internal
+ */
+export function ToolCallErrorFallback({ error, toolName }: { error: string; toolName: string }) {
+ return (
+ <div className="openui-tool-call openui-tool-call--error" data-status="error">
+ <div className="openui-tool-call__title-row">
+ <span className="openui-tool-call__icon-wrapper">
+ <AlertCircle size={14} className="openui-tool-call__icon" />
+ </span>
+ <span className="openui-tool-call__name">Couldn’t render the {toolName} tool</span>
+ </div>
+ <div className="openui-tool-call__connector openui-tool-call__connector--last">
+ <div className="openui-tool-call__args-block">
+ <pre className="openui-tool-code-block__code openui-tool-code-block__code--error">
+ {error}
+ </pre>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/react-ui/src/components/_shared/tool-renderer/ToolMessageRenderer.tsx b/packages/react-ui/src/components/_shared/tool-renderer/ToolMessageRenderer.tsx
new file mode 100644
index 000000000..15df56385
--- /dev/null
+++ b/packages/react-ui/src/components/_shared/tool-renderer/ToolMessageRenderer.tsx
@@ -0,0 +1,66 @@
+import {
+ pairToolActivity,
+ useArtifactRenderer,
+ type AssistantMessage,
+ type ToolCall,
+ type ToolMessage,
+} from "@openuidev/react-headless";
+import type { ReactNode } from "react";
+import { ToolActivityRenderer, type ToolDetailedViewPanel } from "./ToolActivityRenderer";
+
+/**
+ * Props for {@link ToolMessageRenderer}.
+ *
+ * @category Components
+ */
+export type ToolMessageRendererProps = {
+ /**
+ * The tool message containing the response payload, or `null` while the tool
+ * call is still streaming. The matched renderer sees `controls.isStreaming = true`.
+ */
+ toolMessage: ToolMessage | null;
+ /** The matching tool call from the parent assistant message. */
+ toolCall: ToolCall;
+ /** Rendered when no renderer matches `toolCall.function.name`. */
+ fallback: ReactNode;
+ /** Optional detailed-view panel (defaults to the shared one). */
+ detailedViewPanel?: ToolDetailedViewPanel;
+};
+
+/**
+ * Dispatches a tool call to a matching renderer, else renders `fallback`.
+ *
+ * @deprecated Prefer `useToolActivities` + `<ToolCallEntry>` / `<ToolCallTimeline>`,
+ * which pair calls↔results by id, carry real status, and render the matched
+ * renderer xor the default card. This wrapper now builds a single
+ * {@link ToolActivity} from `toolCall`/`toolMessage` and delegates to
+ * {@link ToolActivityRenderer}, so existing imports keep working.
+ *
+ * @category Components
+ */
+export const ToolMessageRenderer = ({
+ toolMessage,
+ toolCall,
+ fallback,
+ detailedViewPanel,
+}: ToolMessageRendererProps) => {
+ const renderer = useArtifactRenderer(toolCall.function.name);
+ if (!renderer) return <>{fallback}</>;
+
+ const syntheticAssistant: AssistantMessage = {
+ id: `__tool_message_renderer__${toolCall.id}`,
+ role: "assistant",
+ content: "",
+ toolCalls: [toolCall],
+ };
+ const [activity] = pairToolActivity(syntheticAssistant, toolMessage ? [toolMessage] : []);
+ if (!activity) return <>{fallback}</>;
+
+ return (
+ <ToolActivityRenderer
+ renderer={renderer}
+ activity={activity}
+ detailedViewPanel={detailedViewPanel}
+ />
+ );
+};
diff --git a/packages/react-ui/src/components/_shared/tool-renderer/index.ts b/packages/react-ui/src/components/_shared/tool-renderer/index.ts
new file mode 100644
index 000000000..5ad8bf957
--- /dev/null
+++ b/packages/react-ui/src/components/_shared/tool-renderer/index.ts
@@ -0,0 +1,5 @@
+export { TimelineEntry, type TimelineEntryProps } from "./TimelineEntry";
+export { ToolActivityRenderer, type ToolDetailedViewPanel } from "./ToolActivityRenderer";
+export { ToolCallEntry, type ToolCallEntryProps } from "./ToolCallEntry";
+export { ToolCallErrorFallback } from "./ToolCallErrorFallback";
+export { ToolMessageRenderer, type ToolMessageRendererProps } from "./ToolMessageRenderer";
diff --git a/packages/react-ui/src/components/index.scss b/packages/react-ui/src/components/index.scss
index 84471fec1..b66fcb0fa 100644
--- a/packages/react-ui/src/components/index.scss
+++ b/packages/react-ui/src/components/index.scss
@@ -6,7 +6,6 @@
@use "../openui-defaults.scss";
@forward "./Accordion/accordion.scss";
-@forward "./BottomTray/bottomTray.scss";
@forward "./Button/button.scss";
@forward "./Buttons/buttons.scss";
@forward "./Calendar/calendar.scss";
@@ -18,7 +17,6 @@
@forward "./CheckBoxGroup/checkBoxGroup.scss";
@forward "./CheckBoxItem/checkBoxItem.scss";
@forward "./CodeBlock/codeBlock.scss";
-@forward "./CopilotShell/copilotShell.scss";
@forward "./DatePicker/datePicker.scss";
@forward "./FollowUpBlock/followUpBlock.scss";
@forward "./FollowUpItem/followUpItem.scss";
@@ -40,7 +38,7 @@
@forward "./SectionBlock/sectionBlock.scss";
@forward "./Select/select.scss";
@forward "./Separator/separator.scss";
-@forward "./Shell/shell.scss";
+@forward "./AgentInterface/agentInterface.scss";
@forward "./Skeleton/skeleton.scss";
@forward "./Slider/slider.scss";
@forward "./Steps/steps.scss";
diff --git a/packages/react-ui/src/hooks/useScrollToBottom.ts b/packages/react-ui/src/hooks/useScrollToBottom.ts
index e6dd25359..7c6a192bb 100644
--- a/packages/react-ui/src/hooks/useScrollToBottom.ts
+++ b/packages/react-ui/src/hooks/useScrollToBottom.ts
@@ -10,6 +10,7 @@ export const useScrollToBottom = <T extends HTMLElement | null, L extends { id:
userMessageSelector = ".openui-shell-thread-message-user",
isRunning,
isLoadingMessages,
+ scrollOnLoad = true,
}: {
ref: RefObject<T>;
// scroll to bottom when this value changes
@@ -19,6 +20,9 @@ export const useScrollToBottom = <T extends HTMLElement | null, L extends { id:
// if true, scroll to bottom logic will work
isRunning?: boolean;
isLoadingMessages?: boolean;
+ // when false, do NOT auto-scroll on initial load / conversation switch;
+ // auto-scroll then only happens while a response is generating (isRunning)
+ scrollOnLoad?: boolean;
}) => {
const previousLastMessage = useRef<L | null>(null);
const lastUserMessage = useRef<HTMLElement | null>(null);
@@ -131,7 +135,7 @@ export const useScrollToBottom = <T extends HTMLElement | null, L extends { id:
useEffect(() => {
if (
(isRunning && !hasUserScrolledWhenIsRunning.current) || // scroll to bottom if user hasn't scrolled when isRunning is true
- (!wasScrolledToBottomAfterLoading.current && !isLoadingMessages) // scroll to bottom once when messages are loaded
+ (scrollOnLoad && !wasScrolledToBottomAfterLoading.current && !isLoadingMessages) // scroll to bottom once when messages are loaded (skipped when scrollOnLoad is false)
) {
scrollToBottom();
wasScrolledToBottomAfterLoading.current = true;
@@ -140,5 +144,5 @@ export const useScrollToBottom = <T extends HTMLElement | null, L extends { id:
if (isLoadingMessages) {
wasScrolledToBottomAfterLoading.current = false;
}
- }, [scrollToBottom, isRunning, isLoadingMessages]);
+ }, [scrollToBottom, isRunning, isLoadingMessages, scrollOnLoad]);
};
diff --git a/packages/react-ui/src/index.ts b/packages/react-ui/src/index.ts
index 0d01180fa..39865721f 100644
--- a/packages/react-ui/src/index.ts
+++ b/packages/react-ui/src/index.ts
@@ -1,23 +1,61 @@
"use client";
export * from "./components/Accordion";
+export * from "./components/AgentInterface";
-// Artifact() factory — generates a ComponentRenderer with artifact wiring
-export { Artifact } from "./artifact";
-export type { ArtifactConfig, ArtifactControls } from "./artifact";
-
-// Artifact exports (ArtifactPanel/ArtifactPortalTarget also available as Shell.*)
-export { useActiveArtifact, useArtifact } from "@openuidev/react-headless";
+// Adapter factories + types — paired with AgentInterface's `storage` / `llm` props,
+// re-exported so consumers can build adapters without reaching into react-headless.
export {
- ArtifactOverlay,
- ArtifactPanel,
- ArtifactPortalTarget,
-} from "./components/_shared/artifact";
+ defineArtifactRenderer,
+ fetchLLM,
+ pairToolActivity,
+ partialJSONParse,
+ restStorage,
+ useToolActivities,
+} from "@openuidev/react-headless";
export type {
- ArtifactOverlayProps,
- ArtifactPanelProps,
- ArtifactPortalTargetProps,
-} from "./components/_shared/artifact";
+ Artifact,
+ ArtifactCategory,
+ ArtifactListParams,
+ ArtifactRendererConfig,
+ ArtifactRendererControls,
+ ArtifactStorage,
+ ArtifactSummary,
+ ChatLLM,
+ ChatStorage,
+ FetchLLMOptions,
+ RestStorageOptions,
+ ThreadStorage,
+ ToolActivity,
+ ToolCallStatus,
+} from "@openuidev/react-headless";
+
+// Re-export the full headless surface so apps import everything (adapters,
+// formats, hooks, storage, message types) from @openuidev/react-ui.
+export * from "@openuidev/react-headless";
+// `ToolCall` exists in both packages (a message type in react-headless, the
+// component here). Pin the component so the two star re-exports don't collide.
+export { ToolCall } from "./components/ToolCall";
+
+// Tool-call rendering: the typed-activity dispatchers (matched renderer xor
+// default) + the legacy ToolMessageRenderer wrapper.
+export {
+ TimelineEntry,
+ ToolActivityRenderer,
+ ToolCallEntry,
+ ToolCallErrorFallback,
+ ToolMessageRenderer,
+ type TimelineEntryProps,
+ type ToolCallEntryProps,
+ type ToolDetailedViewPanel,
+ type ToolMessageRendererProps,
+} from "./components/_shared/tool-renderer";
+
+// Shared Collapsible primitive + built-in web-search renderer.
+export { Collapsible } from "./components/_shared/Collapsible";
+
+// Detailed-view exports (DetailedViewPanel/DetailedViewPortalTarget)
+export { useActiveDetailedView, useDetailedView } from "@openuidev/react-headless";
export * from "./components/Button";
export * from "./components/Buttons";
@@ -31,7 +69,6 @@ export type { ExportChartData } from "./components/Charts/Charts";
export * from "./components/CheckBoxGroup";
export * from "./components/CheckBoxItem";
export * from "./components/CodeBlock";
-export * as CopilotShell from "./components/CopilotShell";
export * from "./components/DatePicker";
export * from "./components/FollowUpBlock";
export * from "./components/FollowUpItem";
@@ -52,7 +89,6 @@ export * from "./components/RadioItem";
export * from "./components/SectionBlock";
export * from "./components/Select";
export * from "./components/Separator";
-export * as Shell from "./components/Shell";
export * from "./components/Skeleton";
export * from "./components/Slider";
export * from "./components/Steps";
@@ -90,7 +126,7 @@ export * from "./context/LayoutContext";
export * from "./context/PrintContext";
// Types Export
-export type { ConversationStarterVariant } from "./components/BottomTray/ConversationStarter";
+export type { ConversationStarterVariant } from "./components/AgentInterface/ConversationStarter";
export type {
ConversationStarterIcon,
ConversationStarterProps,
diff --git a/packages/react-ui/src/utils/contentParser.ts b/packages/react-ui/src/utils/contentParser.ts
deleted file mode 100644
index 31361e41e..000000000
--- a/packages/react-ui/src/utils/contentParser.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-const openTag = (tag: string) => `<${tag}>`;
-const closeTag = (tag: string) => `</${tag}>`;
-
-export function wrapContent(text: string): string {
- return `${openTag("content")}${text}${closeTag("content")}`;
-}
-
-export function wrapContext(json: string): string {
- return `${openTag("context")}${json}${closeTag("context")}`;
-}
-
-/**
- * Separate openui-lang code from <context> tag in a message.
- * Returns { content: the message/code, contextString: raw JSON or null }
- */
-export function separateContentAndContext(raw: string): {
- content: string;
- contextString: string | null;
-} {
- const contextMatch = raw.match(/<context>([\s\S]*)<\/context>\s*$/);
- let content = raw;
- let contextString: string | null = null;
-
- if (contextMatch) {
- contextString = contextMatch[1] ?? null;
- content = raw.slice(0, contextMatch.index!).trimEnd();
- }
-
- const contentMatch = content.match(/^<content[^>]*>([\s\S]*)<\/content>\s*$/);
- if (contentMatch) {
- content = contentMatch[1] ?? content;
- }
-
- return { content, contextString };
-}
diff --git a/packages/react-ui/src/utils/sentinelParser.ts b/packages/react-ui/src/utils/sentinelParser.ts
new file mode 100644
index 000000000..45edd3529
--- /dev/null
+++ b/packages/react-ui/src/utils/sentinelParser.ts
@@ -0,0 +1,225 @@
+const OPENUI_INLINE_SENTINEL = "]]>openui:";
+const CONTENT_MARKER = `${OPENUI_INLINE_SENTINEL}content`;
+const CONTEXT_MARKER = `${OPENUI_INLINE_SENTINEL}context`;
+const END_MARKER = `${OPENUI_INLINE_SENTINEL}end`;
+
+// Tokens whose partial prefix can sit at the tail of a still-streaming chunk.
+// Trimming keeps a half-arrived marker from flashing as raw text; the next
+// delta re-parses the full message, so any false positive is transient.
+const STREAM_PARTIAL_TOKENS = [CONTENT_MARKER, CONTEXT_MARKER, END_MARKER];
+
+export interface ParsedMessageContent {
+ content: string;
+ contextString: string | null;
+ contentHeader?: string;
+ /**
+ * True when the bare `]]>openui:end` liveness marker was present — the
+ * stream reached its terminal chunk. Absent on a PERSISTED message ⇒ the
+ * stream died mid-write. HOW a response ended is structural (output item
+ * `status` + the Responses terminal event), never in-band bytes.
+ */
+ end?: boolean;
+}
+
+export function wrapContent(text: string): string {
+ return `${CONTENT_MARKER}\n${text}`;
+}
+
+// Round-trip the original header verbatim so its attrs (libraryVersion, etc.)
+// survive form-state persistence.
+export function wrapContentWithHeader(text: string, contentHeader?: string): string {
+ return contentHeader ? `${contentHeader}\n${text}` : wrapContent(text);
+}
+
+export function wrapContext(json: string): string {
+ return `\n${CONTEXT_MARKER}\n${json}`;
+}
+
+// Separate openui-lang code from inline context in a message, stripping
+// display-only noise: the bare end marker and partial streaming tails. The
+// raw message bytes in the store stay untouched.
+export function separateContentAndContext(raw: string): ParsedMessageContent {
+ const { text, end } = extractEndMarker(raw);
+ const sections = splitSections(text);
+ const content = stripStreamingTail(sections.content);
+ return { ...sections, content, ...(end ? { end: true } : {}) };
+}
+
+// The ordered section walk over the inline-sentinel format.
+function splitSections(raw: string): {
+ content: string;
+ contextString: string | null;
+ contentHeader?: string;
+} {
+ const lastContentIdx = raw.lastIndexOf(CONTENT_MARKER);
+ const lastContextIdx = raw.lastIndexOf(CONTEXT_MARKER);
+
+ // No inline markers: fall back to the deprecated XML envelope so messages
+ // persisted by older app versions still round-trip on reload.
+ if (lastContentIdx === -1 && lastContextIdx === -1) {
+ return parseLegacyXml(raw);
+ }
+
+ // Only context section
+ if (lastContentIdx === -1) {
+ return {
+ content: stripSectionSeparator(raw.slice(0, lastContextIdx)),
+ contextString: raw.slice(bodyStartIndex(raw, lastContextIdx)),
+ };
+ }
+
+ // Content-only response
+ if (lastContextIdx === -1 || lastContentIdx > lastContextIdx) {
+ return {
+ content: raw.slice(bodyStartIndex(raw, lastContentIdx)),
+ contextString: null,
+ contentHeader: contentHeader(raw, lastContentIdx),
+ };
+ }
+
+ // Content section followed by context section
+ return {
+ content: stripSectionSeparator(raw.slice(bodyStartIndex(raw, lastContentIdx), lastContextIdx)),
+ contextString: raw.slice(bodyStartIndex(raw, lastContextIdx)),
+ contentHeader: contentHeader(raw, lastContentIdx),
+ };
+}
+
+// Strip every `]]>openui:end` marker LINE and report presence. Mirrors the
+// backend's inline-format 'end' case: the separator newline before the marker
+// is removed, header attrs on the marker line are ignored (a future
+// `?status=…` form must not break display), and defensive trailing text after
+// the line stays with the section it interrupted.
+function extractEndMarker(raw: string): { text: string; end: boolean } {
+ let text = raw;
+ let end = false;
+ for (let idx = text.indexOf(END_MARKER); idx !== -1; idx = text.indexOf(END_MARKER)) {
+ end = true;
+ const lineEnd = text.indexOf("\n", idx);
+ const before = stripSectionSeparator(text.slice(0, idx));
+ const after = lineEnd === -1 ? "" : text.slice(lineEnd + 1);
+ text = after === "" ? before : `${before}\n${after}`;
+ }
+ return { text, end };
+}
+
+// Trim a PROPER prefix of a marker token sitting at the very end of the
+// content. Full tokens are handled upstream (the section walk); this only
+// suppresses the one-frame flash while a chunk boundary splits a token.
+function stripStreamingTail(content: string): string {
+ let trim = 0;
+ for (const token of STREAM_PARTIAL_TOKENS) {
+ const max = Math.min(token.length - 1, content.length);
+ for (let k = max; k > trim; k--) {
+ if (content.endsWith(token.slice(0, k))) {
+ trim = k;
+ break;
+ }
+ }
+ }
+ return trim > 0 ? stripSectionSeparator(content.slice(0, content.length - trim)) : content;
+}
+
+function contentHeader(raw: string, markerIdx: number): string {
+ const headerEndIdx = raw.indexOf("\n", markerIdx);
+ return headerEndIdx === -1 ? raw.slice(markerIdx) : raw.slice(markerIdx, headerEndIdx);
+}
+
+function bodyStartIndex(raw: string, markerIdx: number): number {
+ const headerEndIdx = raw.indexOf("\n", markerIdx);
+ return headerEndIdx === -1 ? raw.length : headerEndIdx + 1;
+}
+
+function stripSectionSeparator(value: string): string {
+ if (value.endsWith("\r\n")) {
+ return value.slice(0, -2);
+ }
+ if (value.endsWith("\n")) {
+ return value.slice(0, -1);
+ }
+ return value;
+}
+
+/**
+ * @deprecated Legacy `<content>`/`<context>` XML envelope. Retained only to
+ * parse messages persisted before the inline sentinel format; new messages are
+ * always wrapped with {@link wrapContent}/{@link wrapContext}.
+ */
+function parseLegacyXml(raw: string): { content: string; contextString: string | null } {
+ let content = raw;
+ let contextString: string | null = null;
+
+ const contextMatch = raw.match(/<context>([\s\S]*)<\/context>\s*$/);
+ if (contextMatch) {
+ contextString = contextMatch[1] ?? null;
+ content = raw.slice(0, contextMatch.index!).trimEnd();
+ }
+
+ const contentMatch = content.match(/^<content[^>]*>([\s\S]*)<\/content>\s*$/);
+ if (contentMatch) {
+ content = contentMatch[1] ?? content;
+ }
+
+ return { content, contextString };
+}
+
+// ---------------------------------------------------------------------------
+// Artifact sentinel — the `]]>openui:artifact` member of the inline-sentinel
+// family. Unlike content/context (assistant-message channel), this rides the
+// tool-result channel (function_call_output + response.artifact_call.delta).
+// Carrier: `]]>openui:artifact <header-json>\n<program>` (header-only on a
+// stripped reload). Byte-mirrors the example renderer's parseArtifact.ts and
+// the backend builder (muse artifact-shared.ts buildArtifactSentinel).
+// ---------------------------------------------------------------------------
+const ARTIFACT_MARKER = `${OPENUI_INLINE_SENTINEL}artifact`;
+
+export type ArtifactKind = "slides" | "report";
+
+export interface ArtifactSentinelHeader {
+ artifact_id: string;
+ type: ArtifactKind;
+ name?: string;
+ version?: string;
+}
+
+const ARTIFACT_KIND_BY_TYPE: Record<string, ArtifactKind> = {
+ slides: "slides",
+ presentation: "slides",
+ report: "report",
+};
+
+/**
+ * Parse the artifact carrier `]]>openui:artifact <header-json>\n<program>` into
+ * the validated header + raw program (program is "" on a stripped reload).
+ * Returns null when `raw` is not an artifact sentinel.
+ */
+export function parseArtifactSentinel(
+ raw: unknown,
+): { header: ArtifactSentinelHeader; program: string } | null {
+ if (typeof raw !== "string") return null;
+ const prefix = `${ARTIFACT_MARKER} `;
+ if (!raw.startsWith(prefix)) return null;
+ const nl = raw.indexOf("\n");
+ const headerStr = nl === -1 ? raw.slice(prefix.length) : raw.slice(prefix.length, nl);
+ const program = nl === -1 ? "" : raw.slice(nl + 1);
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(headerStr);
+ } catch {
+ return null;
+ }
+ if (typeof parsed !== "object" || parsed === null) return null;
+ const h = parsed as Record<string, unknown>;
+ if (typeof h["artifact_id"] !== "string" || h["artifact_id"] === "") return null;
+ const kind = typeof h["type"] === "string" ? ARTIFACT_KIND_BY_TYPE[h["type"]] : undefined;
+ if (kind === undefined) return null;
+ return {
+ header: {
+ artifact_id: h["artifact_id"],
+ type: kind,
+ ...(typeof h["name"] === "string" && h["name"] !== "" ? { name: h["name"] } : {}),
+ ...(typeof h["version"] === "string" && h["version"] !== "" ? { version: h["version"] } : {}),
+ },
+ program,
+ };
+}
diff --git a/packages/react-ui/tsconfig.json b/packages/react-ui/tsconfig.json
index 2f0f71078..b5d5611df 100644
--- a/packages/react-ui/tsconfig.json
+++ b/packages/react-ui/tsconfig.json
@@ -8,5 +8,6 @@
"outDir": "./dist",
"rootDir": "./src",
"types": ["./src/types.d.ts", "node"]
- }
+ },
+ "exclude": ["vitest.config.ts", "src/**/__tests__", "dist", "node_modules"]
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4d6b2568f..704311233 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -224,14 +224,14 @@ importers:
examples/fastapi-backend/frontend:
dependencies:
'@openuidev/react-headless':
- specifier: latest
+ specifier: workspace:*
+ version: link:../../../packages/react-headless
'@openuidev/react-lang':
- specifier: latest
+ specifier: workspace:*
+ version: link:../../../packages/react-lang
'@openuidev/react-ui':
- specifier: latest
+ specifier: workspace:*
+ version: link:../../../packages/react-ui
react:
specifier: ^19.0.0
version: 19.2.4
@@ -528,7 +528,7 @@ importers:
devDependencies:
'@langchain/langgraph-cli':
specifier: ^1.2.5
- version: 1.3.0(rkbxzf4lbb37fnypru5cw45rfm)
+ version: 1.3.0(ad8de7214a48057c647fd68b44767328)
'@openuidev/cli':
specifier: workspace:*
version: link:../../packages/openui-cli
@@ -564,7 +564,7 @@ importers:
version: 0.0.53
'@ag-ui/mastra':
specifier: ^1.0.1
- version: 1.0.2(hjtxoyfvlz4rpqmlqd5xziyo4m)
+ version: 1.0.2(480e24a4fb499f3218e7d020b1a73a0c)
'@mastra/core':
specifier: 1.15.0
@@ -749,7 +749,7 @@ importers:
specifier: ^5
version: 5.9.3
- examples/openui-artifact-demo:
+ examples/openui-chat:
dependencies:
'@openuidev/react-headless':
specifier: workspace:*
@@ -775,9 +775,6 @@ importers:
react-dom:
specifier: 19.2.3
version: 19.2.3([email protected])
- react-syntax-highlighter:
- specifier: ^16.1.1
- version: 16.1.1([email protected])
zod:
specifier: ^4.0.0
version: 4.3.6
@@ -797,9 +794,6 @@ importers:
'@types/react-dom':
specifier: ^19
version: 19.2.3(@types/[email protected])
- '@types/react-syntax-highlighter':
- specifier: ^15.5.13
- version: 15.5.13
eslint:
specifier: ^9
version: 9.29.0([email protected])
@@ -808,13 +802,22 @@ importers:
tailwindcss:
specifier: ^4
- version: 4.2.2
+ version: 4.2.1
typescript:
specifier: ^5
version: 5.9.3
- examples/openui-chat:
+ examples/openui-dashboard:
dependencies:
+ '@modelcontextprotocol/sdk':
+ specifier: ^1.27.1
+ version: 1.29.0(@cfworker/[email protected])([email protected])
+ '@openuidev/cli':
+ specifier: workspace:*
+ version: link:../../packages/openui-cli
+ '@openuidev/lang-core':
+ specifier: workspace:*
+ version: link:../../packages/lang-core
'@openuidev/react-headless':
specifier: workspace:*
version: link:../../packages/react-headless
@@ -843,9 +846,146 @@ importers:
specifier: ^4.0.0
version: 4.3.6
devDependencies:
+ '@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
+ tailwindcss:
+ specifier: ^4
+ version: 4.2.2
+ typescript:
+ specifier: ^5
+ version: 5.9.3
+
+ examples/openui-react-native: {}
+
+ examples/openui-react-native/backend:
+ dependencies:
+ next:
+ specifier: ^15.2.3
+ openai:
+ specifier: ^4.90.0
+ react:
+ specifier: ^19.0.0
+ version: 19.2.4
+ react-dom:
+ specifier: ^19.0.0
+ version: 19.2.4([email protected])
+ devDependencies:
+ '@openuidev/react-lang':
+ specifier: ^0.1.3
+ version: 0.1.3([email protected])
+ '@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])
+ typescript:
+ specifier: ^5
+ version: 5.9.3
+ zod:
+ specifier: 4.4.3
+ version: 4.4.3
+
+ examples/openui-react-native/chat-app:
+ dependencies:
+ '@openuidev/react-lang':
+ specifier: ^0.1.3
+ version: 0.1.3([email protected])
+ expo:
+ specifier: ~54.0.6
+ expo-status-bar:
+ specifier: ~55.0.4
+ openai:
+ specifier: ^4.90.0
+ react:
+ specifier: 19.2.0
+ version: 19.2.0
+ react-native:
+ specifier: 0.83.2
+ version: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native-safe-area-context:
+ specifier: ^5.7.0
+ react-native-svg:
+ specifier: 15.12.1
+ react-native-web:
+ specifier: ^0.21.0
+ zod:
+ specifier: ^4.3.6
+ version: 4.3.6
+ devDependencies:
+ '@types/react':
+ specifier: ~19.2.2
+ version: 19.2.14
+ typescript:
+ specifier: ~5.9.2
+ version: 5.9.3
+
+ examples/react-email:
+ dependencies:
'@openuidev/cli':
specifier: workspace:*
version: link:../../packages/openui-cli
+ '@openuidev/react-email':
+ specifier: 0.2.4
+ '@openuidev/react-headless':
+ specifier: 0.8.2
+ '@openuidev/react-lang':
+ specifier: 0.2.6
+ '@react-email/components':
+ specifier: ^0.0.41
+ '@react-email/render':
+ specifier: ^1.0.6
+ lucide-react:
+ specifier: ^0.562.0
+ version: 0.562.0([email protected])
+ next:
+ specifier: 16.2.6
+ openai:
+ specifier: ^6.22.0
+ react:
+ specifier: 19.2.3
+ version: 19.2.3
+ react-dom:
+ specifier: 19.2.3
+ version: 19.2.3([email protected])
+ zod:
+ specifier: ^4.0.0
+ version: 4.3.6
+ devDependencies:
'@tailwindcss/postcss':
specifier: ^4
version: 4.2.1
@@ -867,21 +1007,15 @@ importers:
tailwindcss:
specifier: ^4
version: 4.2.1
+ tsx:
+ specifier: ^4.19.2
+ version: 4.20.3
typescript:
specifier: ^5
version: 5.9.3
- examples/openui-dashboard:
+ examples/shadcn-chat:
dependencies:
- '@modelcontextprotocol/sdk':
- specifier: ^1.27.1
- version: 1.29.0(@cfworker/[email protected])([email protected])
- '@openuidev/cli':
- specifier: workspace:*
- version: link:../../packages/openui-cli
- '@openuidev/lang-core':
- specifier: workspace:*
- version: link:../../packages/lang-core
'@openuidev/react-headless':
specifier: workspace:*
version: link:../../packages/react-headless
@@ -891,6 +1025,84 @@ importers:
'@openuidev/react-ui':
specifier: workspace:*
version: link:../../packages/react-ui
+ '@radix-ui/react-accordion':
+ specifier: ^1.2.3
+ '@radix-ui/react-alert-dialog':
+ specifier: ^1.1.15
+ '@radix-ui/react-aspect-ratio':
+ specifier: ^1.1.1
+ '@radix-ui/react-avatar':
+ specifier: ^1.1.3
+ '@radix-ui/react-checkbox':
+ specifier: ^1.1.4
+ '@radix-ui/react-collapsible':
+ specifier: ^1.1.3
+ '@radix-ui/react-dialog':
+ specifier: ^1.1.15
+ '@radix-ui/react-hover-card':
+ specifier: ^1.1.15
+ '@radix-ui/react-label':
+ specifier: ^2.1.2
+ '@radix-ui/react-popover':
+ specifier: ^1.1.6
+ '@radix-ui/react-progress':
+ specifier: ^1.1.2
+ '@radix-ui/react-radio-group':
+ specifier: ^1.2.3
+ '@radix-ui/react-select':
+ specifier: ^2.1.6
+ '@radix-ui/react-separator':
+ specifier: ^1.1.2
+ '@radix-ui/react-slider':
+ specifier: ^1.2.3
+ '@radix-ui/react-switch':
+ specifier: ^1.1.3
+ '@radix-ui/react-tabs':
+ specifier: ^1.1.3
+ '@radix-ui/react-toggle':
+ specifier: ^1.1.2
+ '@radix-ui/react-toggle-group':
+ specifier: ^1.1.2
+ '@radix-ui/react-tooltip':
+ specifier: ^1.2.7
+ '@tanstack/react-table':
+ specifier: ^8.21.3
+ class-variance-authority:
+ specifier: ^0.7.1
+ version: 0.7.1
+ clsx:
+ specifier: ^2.1.1
+ version: 2.1.1
+ date-fns:
+ specifier: ^4.1.0
+ version: 4.1.0
+ embla-carousel-react:
+ specifier: ^8.6.0
+ version: 8.6.0([email protected])
+ input-otp:
+ specifier: ^1.4.2
lucide-react:
specifier: ^0.575.0
version: 0.575.0([email protected])
@@ -900,312 +1112,36 @@ importers:
openai:
specifier: ^6.22.0
+ radix-ui:
+ specifier: ^1.4.3
react:
specifier: 19.2.3
version: 19.2.3
+ react-day-picker:
+ specifier: ^9.14.0
+ version: 9.14.0([email protected])
react-dom:
specifier: 19.2.3
version: 19.2.3([email protected])
- zod:
- specifier: ^4.0.0
- version: 4.3.6
- devDependencies:
- '@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
- tailwindcss:
- specifier: ^4
- version: 4.2.2
- typescript:
- specifier: ^5
- version: 5.9.3
-
- examples/openui-react-native: {}
-
- examples/openui-react-native/backend:
- dependencies:
- next:
- specifier: ^15.2.3
- openai:
- specifier: ^4.90.0
- react:
- specifier: ^19.0.0
- version: 19.2.4
- react-dom:
- specifier: ^19.0.0
- version: 19.2.4([email protected])
- devDependencies:
- '@openuidev/react-lang':
- specifier: ^0.1.3
- version: 0.1.3([email protected])
- '@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])
- typescript:
- specifier: ^5
- version: 5.9.3
- zod:
- specifier: 4.4.3
- version: 4.4.3
-
- examples/openui-react-native/chat-app:
- dependencies:
- '@openuidev/react-lang':
- specifier: ^0.1.3
- version: 0.1.3([email protected])
- expo:
- specifier: ~54.0.6
- expo-status-bar:
- specifier: ~55.0.4
- openai:
- specifier: ^4.90.0
- react:
- specifier: 19.2.0
- version: 19.2.0
- react-native:
- specifier: 0.83.2
- version: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
- react-native-safe-area-context:
- specifier: ^5.7.0
- react-native-svg:
- specifier: 15.12.1
- react-native-web:
- specifier: ^0.21.0
- zod:
- specifier: ^4.3.6
- version: 4.3.6
- devDependencies:
- '@types/react':
- specifier: ~19.2.2
- version: 19.2.14
- typescript:
- specifier: ~5.9.2
- version: 5.9.3
-
- examples/react-email:
- dependencies:
- '@openuidev/cli':
- specifier: workspace:*
- version: link:../../packages/openui-cli
- '@openuidev/react-email':
- specifier: workspace:*
- version: link:../../packages/react-email
- '@openuidev/react-headless':
- specifier: workspace:*
- version: link:../../packages/react-headless
- '@openuidev/react-lang':
- specifier: workspace:*
- version: link:../../packages/react-lang
- '@react-email/components':
- specifier: ^0.0.41
- '@react-email/render':
- specifier: ^1.0.6
- lucide-react:
- specifier: ^0.562.0
- version: 0.562.0([email protected])
- next:
- specifier: 16.2.6
- openai:
- specifier: ^6.22.0
- react:
- specifier: 19.2.3
- version: 19.2.3
- react-dom:
- specifier: 19.2.3
- version: 19.2.3([email protected])
- zod:
- specifier: ^4.0.0
- version: 4.3.6
- devDependencies:
- '@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
- tailwindcss:
- specifier: ^4
- version: 4.2.1
- tsx:
- specifier: ^4.19.2
- version: 4.20.3
- typescript:
- specifier: ^5
- version: 5.9.3
-
- examples/shadcn-chat:
- 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
- '@radix-ui/react-accordion':
- specifier: ^1.2.3
- '@radix-ui/react-alert-dialog':
- specifier: ^1.1.15
- '@radix-ui/react-aspect-ratio':
- specifier: ^1.1.1
- '@radix-ui/react-avatar':
- specifier: ^1.1.3
- '@radix-ui/react-checkbox':
- specifier: ^1.1.4
- '@radix-ui/react-collapsible':
- specifier: ^1.1.3
- '@radix-ui/react-dialog':
- specifier: ^1.1.15
- '@radix-ui/react-hover-card':
- specifier: ^1.1.15
- '@radix-ui/react-label':
- specifier: ^2.1.2
- '@radix-ui/react-popover':
- specifier: ^1.1.6
- '@radix-ui/react-progress':
- specifier: ^1.1.2
- '@radix-ui/react-radio-group':
- specifier: ^1.2.3
- '@radix-ui/react-select':
- specifier: ^2.1.6
- '@radix-ui/react-separator':
- specifier: ^1.1.2
- '@radix-ui/react-slider':
- specifier: ^1.2.3
- '@radix-ui/react-switch':
- specifier: ^1.1.3
- '@radix-ui/react-tabs':
- specifier: ^1.1.3
- '@radix-ui/react-toggle':
- specifier: ^1.1.2
- '@radix-ui/react-toggle-group':
- specifier: ^1.1.2
- '@radix-ui/react-tooltip':
- specifier: ^1.2.7
- '@tanstack/react-table':
- specifier: ^8.21.3
- class-variance-authority:
- specifier: ^0.7.1
- version: 0.7.1
- clsx:
- specifier: ^2.1.1
- version: 2.1.1
- date-fns:
- specifier: ^4.1.0
- version: 4.1.0
- embla-carousel-react:
- specifier: ^8.6.0
- version: 8.6.0([email protected])
- input-otp:
- specifier: ^1.4.2
- lucide-react:
- specifier: ^0.575.0
- version: 0.575.0([email protected])
- next:
- specifier: 16.2.6
- openai:
- specifier: ^6.22.0
- radix-ui:
- specifier: ^1.4.3
- react:
- specifier: 19.2.3
- version: 19.2.3
- react-day-picker:
- specifier: ^9.14.0
- version: 9.14.0([email protected])
- react-dom:
- specifier: 19.2.3
- version: 19.2.3([email protected])
- react-markdown:
- specifier: ^10.1.0
- version: 10.1.0(@types/[email protected])([email protected])
- recharts:
- specifier: ^2.15.4
- remark-gfm:
- specifier: ^4.0.1
- version: 4.0.1
- sonner:
- specifier: ^2.0.7
- tailwind-merge:
- specifier: ^3.3.0
- version: 3.5.0
- vaul:
- specifier: ^1.1.2
+ react-markdown:
+ specifier: ^10.1.0
+ version: 10.1.0(@types/[email protected])([email protected])
+ recharts:
+ specifier: ^2.15.4
+ remark-gfm:
+ specifier: ^4.0.1
+ version: 4.0.1
+ sonner:
+ specifier: ^2.0.7
+ tailwind-merge:
+ specifier: ^3.3.0
+ version: 3.5.0
+ vaul:
+ specifier: ^1.1.2
zod:
specifier: ^4.0.0
version: 4.3.6
@@ -1423,13 +1359,13 @@ importers:
devDependencies:
'@tailwindcss/vite':
specifier: ^4
jiti:
specifier: ^2.0.0
version: 2.6.1
nuxt:
specifier: ^3.17.0
tailwindcss:
specifier: ^4
version: 4.2.1
@@ -1528,8 +1464,8 @@ importers:
packages/react-headless:
dependencies:
'@ag-ui/core':
- specifier: ^0.0.45
- version: 0.0.45
+ specifier: ^0.0.53
+ version: 0.0.53
react:
specifier: 'catalog:'
version: 19.2.4
@@ -3967,89 +3903,105 @@ packages:
resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==}
cpu: [arm]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==}
@@ -4442,30 +4394,35 @@ packages:
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@mariozechner/[email protected]':
resolution: {integrity: sha512-AGuJdgKsmJdm4Pych7kv3sqe591ERRaAHW3xjLooiFzn8J+PxUyof++7YZrB5Y5tpnTO+K18Og3taj2NpluCRQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@mariozechner/[email protected]':
resolution: {integrity: sha512-DXBEAiuMpk7dhS1a9NzNxVAFi1vaKoPu7rQNgY8LIDLGrK3lnIp3nT10DUum+PKVJoJppIP+NAA8IZe4DMNDPw==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@mariozechner/[email protected]':
resolution: {integrity: sha512-WORrMLd6EpElEME7JRKfSaY34nW1P5LbdgK5YNCS1ncG2LqmITsSMEJ8nh2mpvxb3TxqbOOKgY7k9eMJYlW9Mw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@mariozechner/[email protected]':
resolution: {integrity: sha512-/DHn+1DrfL6oRaPPWXaOKvonFFrni666fxd+zFqiQEfvBH0tsHVWjq9iqBk0oDp0qaPA72lIMy5BptxISBEhZQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@mariozechner/[email protected]':
resolution: {integrity: sha512-O5FHD3ErkMwMhNzAfu3ggy0ug4z7btZuoQgwwxlzPrwV2bxlD6WDpqBY4NCgICAgZdDKdp+loUEKVAVt8aYnhQ==}
@@ -4755,96 +4712,112 @@ packages:
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-OJYkCd5pj/QloBvoEcJ2XiMnlJkRv9idWA/j0ugSuA34gMT6f5b7vOiCQHVRpvStoZUknhl6/UxOXL4OwtdaBw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-RPOvqlYBbcQjkz9VQQDZ2T2bARIjXZV1KFlt+V2Mr6SW/e4I9fcKsaA0hdyf2FHoTlsV2xnBd5Y912rP/1Ce6w==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-Re6PZtjBDd0aMU+VcZcC/PrIvj4WhrjDYtMhhCVQamWN4L90EVP0pcEOBQD25prSlw7OzNw5QpHLWMilRLsRNw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-glaCczEWIrHsokFZ3pP08U4BpKxwIdnT+txdOM32OBgpL9Yw4aqx8NejmgtZQZOdstQ5f0L3CasIZudzCuD+nw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-S4J2v+8tT3NIO9u2q+S0G5KdvNDjXfAv06OhfOzNDaBn5rw84DGXWndOEB7d5/x852A20sW1M56vhC/tRVbccQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-URUTu1+dMkxJsPFgm+OeEvq9wf5sujw0EvgYy80TDGHTSLTnIHeqb0Eu8A3sC95IRgjejQL+kC4mw+4yPxiAXA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-qyogG9QtBzWxgJfeGBvOEHI3851gTfCF3wLZ5RDLTBJGAmE9p1qDwKCOdrBrvBzRvYDT+gUDp72pzlSEfAXgNA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-oUfg2EgJmU3R0OCOWiokGFUTvZiPfXtriXiuF3YNxRoROCdgvTedHIzYoeKH34gsZxS/V7mHbfq2hpAHwhH1/A==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-2eEBDkFlMMNQnkTyPBhQOAyn2qMxyG2eE7GPH2WIDGEpEILcBPI/jdSv4t6xupSP+ot/jkfrCShLAa7+ZUPcJQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-DOj182mPV8G3UkrayLoREM5YEYI+Dk5wv7Ox9xl1fFibAELEsFD0lDPfHIeILlutMMfdyhlzYPELG3peuKaurw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-Vhe4ZDuBpmMogrGi5D4R2Kq4JAQlj6+wvgaFYy31zfES0zPmt6TLA+cuYpM/OLrPZjo2MYQTHVqNUSCR6+fDZQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-JLxSP3KTd9iu/bvUMQxH7RJo9xKSHf55/6RPE4a6FTSZygGn7uvZbCej0AHXydwkggQGSD9UddSjwv6Xz5ESfA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-oicJwRlyOoZXVlxmIMaTq7f8pN9QNbdes0q2FXfRsPhfCi8n8JmOZJm5oo1pwDaFbnnD421rVU409M3evFbIqg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-HKQ5SP/V/ub73UvF7n/zeJlxk2kLmtL7Wzrg4WfmkjmNos5onJ2tKu7yZOPdL18A6Svfn3max29ym+ry7NkK4g==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-srvian89JahFLw1YLBEuhvPJ0DO5lpUeJQMXy4xYo7g628ZlNgXdNkqoxSAv9OYrBfByh6vxISMwW/mRbzCY+g==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-ir1v7enP52K2HNz3tQQvwF+x7VNxBk1ciiZ18WBPvxf4C59IqdfmHPJYK3vH7rSxpuCVw/8C712wTXNAtEp+NA==}
@@ -5170,8 +5143,8 @@ packages:
resolution: {integrity: sha512-/UhIkaZgPutTFmQ7RnIJGgDXZmtEJ7Dvi86xNTFWcnRxVRNk/aotsqDJYeEvDP+FSMB2SdW+pQzNMcWP0rwuNA==}
engines: {node: '>=14'}
- '@openuidev/[email protected]':
- resolution: {integrity: sha512-cL01txOXWeDdOJY83F8R0QR7F1FPEsuUFft/8uRYiaN8LozKySNonc1g5nhreYKjcQ2YvvyvwHZn/AQZCaFtDQ==}
+ '@openuidev/[email protected]':
+ resolution: {integrity: sha512-a/WkffvnclxSYBGhJxho8mvaVDYCBNw9GBMP5J2tl17mK6ukA6YmSQvwSmlC0UNi3FiLdj6Wk6qJIjESZ8EOUg==}
peerDependencies:
'@modelcontextprotocol/sdk': '>=1.0.0'
zod: ^3.25.0 || ^4.0.0
@@ -5179,6 +5152,14 @@ packages:
'@modelcontextprotocol/sdk':
optional: true
+ '@openuidev/[email protected]':
+ resolution: {integrity: sha512-n8z4Zv3Df/cXksMwQo9RNL1aeC/M0REQclvp44TGfhiMiCi1mvWlYZ3uX5qzrerIwHBS+m7NUdI6LugCpFeiaQ==}
+ peerDependencies:
+ '@openuidev/react-lang': 0.2.6
+ react: ^18.3.1 || ^19.0.0
+ react-dom: ^18.0.0 || ^19.0.0
+ zod: ^3.25.0 || ^4.0.0
+
'@openuidev/[email protected]':
resolution: {integrity: sha512-o70dZnwVli25JWYFFZBEtXpCVrdJAkQRoW1/La58C6jVvga/Q2KTnz+rXCLUHX/e9iZpHQ9doZZht+GZ9vRfjA==}
peerDependencies:
@@ -5200,16 +5181,6 @@ packages:
'@modelcontextprotocol/sdk':
optional: true
- '@openuidev/[email protected]':
- resolution: {integrity: sha512-UQlqjycpppAl8oCO50dffLMq60N23xZx5HD6P6lHzSYJgeEjh/p0T0g3EpN6fb5M3ZjpfVPQw8EgCtVMDo0HfA==}
- peerDependencies:
- '@openuidev/react-headless': ^0.8.2
- '@openuidev/react-lang': ^0.2.6
- react: ^18.3.1 || ^19.0.0
- react-dom: ^18.0.0 || ^19.0.0
- zod: ^3.25.0 || ^4.0.0
- zustand: ^4.5.5
-
resolution: {integrity: sha512-a61ljmRVVyG5MC/698C8/FfFDw5a8LOIvyOLW5fztgUXqUpc1jOfQzOitSCbge657OgXXThmY3Tk8fpiDb4UcA==}
engines: {node: '>= 20.0.0'}
@@ -5261,48 +5232,56 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@oxc-minify/[email protected]':
resolution: {integrity: sha512-HGzqTov5sAzXyaNfRkQEpl0fRs+PrMYjT8b5jZAw8foQ/qnW+VMWgAr80Q+2j79T5nhXfboSF5SUgB8mcisgHw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@oxc-minify/[email protected]':
resolution: {integrity: sha512-zpUZ4pmbDBqaZmRYacxeLHUBxA3fs5K7hi1WSXRVMXC4OjWuVcLsNxeavenKF9i0YtP7Q5n2z12Rz7eEnNWoDA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@oxc-minify/[email protected]':
resolution: {integrity: sha512-CYrC4tpW1wolbw/Fox+T0hxW92s1aG/WLi+htkk02JMiCHOWqGQKxUnm37lLiODKR/OwTYht3LB4xNrsS0RtCg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@oxc-minify/[email protected]':
resolution: {integrity: sha512-ZQNur0zujUjNYgjFF4mcNaeEKWuerY9XkaALYtBsHqNetkj55w0ZwCKYfYKLH2JAdyNF2LuS0s7VGgjXP9EvWA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
'@oxc-minify/[email protected]':
resolution: {integrity: sha512-tR8oiFSNpcS1mfGY1N3/Hy6TxP2wr5X9FFdn/y8GarN8ST/JMLY5SUiwPiU35NKiC69CDaAsLHXoIKUxK/r8Pw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@oxc-minify/[email protected]':
resolution: {integrity: sha512-KodzbW12zmT/C/w4bGv2aWN7Q5+KVJKbNoAv5hooYeSujj8xSPGWl8pnyj7dJ9nd8j0CVjubEvHQ86rtzV99OA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@oxc-minify/[email protected]':
resolution: {integrity: sha512-CNG3/hPE6MxdLikfLq5l0aZMvJ3W5AP1aoVjzQ1Itokv5sbfBcW0fp6Srn8mB86CyAqO9e7dbffZVOWBDVkhgw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@oxc-minify/[email protected]':
resolution: {integrity: sha512-UyfimTwMLitJ0+5i5fL9M9U4E+DcIQJpGZWbVxxD3Mp9f7CTyQBIHnS68VEGZe+KQL/Y3IIb3AJ7cZB+ICgTVQ==}
@@ -5380,48 +5359,56 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-vtPiwmfVTAXzaxDKsOXG+LwgRAA7WEnaeHzhS5z0GE89gAK18KSXnly7Z6saXXq6L3dVMyK44uoTI03zKxrpmw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-8AW8L7w5cGHSdZPcyZX2yR0+GUODsT15rbRjfdD54rv6DMbtuEB19ysLOpKJlRGfH6UNYNpCHaU1uJWgTWf1/w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-vvpjkjEOUsPcsYf8evE4MO3aGx9+3wodXEBOicGNnOwTuAik8eBONNkgSdhkGsAblQmfVHJyanRnpxglddTXIA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-AqmcNC3fClXX+fxQ6VGEN1667xVFiRBkY0CZmDMSiaeFUsv1+UkBPYYi48IUKcA9/ivvoKNRzQl2I4//kT9F/w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-7d3jOMKy7RSQCcDLIci+ySll2FgsOMl/GiRux4q2JNv0zg4EdhFISa9idvrdN/HEUIQQJNg6dmveUeJl2YErGA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-JHK/h95qVqVQ+ITER837kcTdwBDFpFaNnOTYGCP0zdUSX/mLKC7tXOoyrTb6vG7iRPwGlcgBil3v2IjYw1FqJA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-b2BO82O8azXAyf7EUgOPKu145nWypbNyk07HbU09fkzhm9lEA5oPvaN/M8Nlo7tOErVTa2WOgS4QbOnxAPXdDQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-GHO9glZaX7LkX/OGfluEPf1yjg+ehiFbUdowbX6uNWOQhmwKWU4m4+nZ9FJkrHNKuxyI1KKertMdGjVKCApKWA==}
@@ -5508,48 +5495,56 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@oxc-transform/[email protected]':
resolution: {integrity: sha512-cW0Ab1s0sxfiyP1+gdd94f0vUjwGzJF4F3DepF3VnR9nFTGMmFLugwtrBS3DYjTnbugiUH3Fp+16yys1FhNzIA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@oxc-transform/[email protected]':
resolution: {integrity: sha512-wunAU/lzE1nPGKL47uI0g+4Nsv/12xveOXNu4M70xe85kNBm7mQdMpZIeoVYCxtXew0iHxFKJDT6qK5mYFSA3w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@oxc-transform/[email protected]':
resolution: {integrity: sha512-r4sMt4OB4TryDcVWW9KnsXOf/ea7tIGX2QASNrpetzPocsBZqhHIFDbZ8EkBDjmlmWGHg6BgjVx6lLcMXX4Dcw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@oxc-transform/[email protected]':
resolution: {integrity: sha512-/rLVLItsBjKrnZFLiGrwRB3fs0dAjXZLqY7F42omvacFJjZsceQ3481oQX1bBs3RwoDDyDy/9ZkIN7kYIkv5Gw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
'@oxc-transform/[email protected]':
resolution: {integrity: sha512-fUprJgJauI1A7e7cDgY/Z3mwLVtE3aswB4lvS96KpRNDHrwOh8bnCJOWf+0CYveDQzghDVFiZWVDo56pO4Wr9Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@oxc-transform/[email protected]':
resolution: {integrity: sha512-XdbvDT1GPNxrTLXSRt4RU2uCH112q3nINTT05DZqTYYcAxaCPImnMoZe2TlBv5j2376Gk+2pcVnJs6xut47aSw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@oxc-transform/[email protected]':
resolution: {integrity: sha512-Du2CxlBfC98EV3hOAmLVSUgP0JgqM9F47lRv9v43T4sGPcQVOjs9wffUybGUUraG9unmBZ4dgpMAqlCq0k3dGw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@oxc-transform/[email protected]':
resolution: {integrity: sha512-wTj2FkOgNhgdisnA0a15QQksyj6AH2snmpgYgAtj098i477x5LpHHdqfuk60jsA/QHSjmUc6dm4P88yI5GY4xA==}
@@ -5633,72 +5628,84 @@ packages:
engines: {node: '>= 10.0.0'}
cpu: [arm]
os: [linux]
+ libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-9JiYfB6h6BgV50CCfasfLf/uvOcJskMSwcdH1PHH9rvS1IrNy8zad6IUVPVUfmXr+u+Km9IxcfMLzgdOudz9EQ==}
engines: {node: '>= 10.0.0'}
cpu: [arm]
os: [linux]
+ libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q==}
engines: {node: '>= 10.0.0'}
cpu: [arm]
os: [linux]
+ libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg==}
engines: {node: '>= 10.0.0'}
cpu: [arm]
os: [linux]
+ libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w==}
engines: {node: '>= 10.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA==}
engines: {node: '>= 10.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg==}
engines: {node: '>= 10.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA==}
engines: {node: '>= 10.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-GcESn8NZySmfwlTsIur+49yDqSny2IhPeZfXunQi48DMugKeZ7uy1FX83pO0X22sHntJ4Ub+9k34XQCX+oHt2A==}
engines: {node: '>= 10.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ==}
engines: {node: '>= 10.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-n0E2EQbatQ3bXhcH2D1XIAANAcTZkQICBPVaxMeaCVBtOpBZpWJuf7LwyWPSBDITb7In8mqQgJ7gH8CILCURXg==}
engines: {node: '>= 10.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg==}
engines: {node: '>= 10.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-byAiBZ1t3tXQvc8dMD/eoyE7lTXYorhn+6uVW5AC+JGI1KtJC/LvDche5cfUE+qiefH+Ybq0bUCJU0aB1cSHUA==}
@@ -7735,72 +7742,84 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-gBSUVO0eaWgw1JMjK3gB8BMlX2Mk148s2lTiVT3e9vjVxbl7UDfMWWY8CfIaaqiXuM9fVTMxIpUz6CAo/B6Vlw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-b/CgbwAJpmrRLp02RPfhbudf5tZnN9nsPWK82znefso832etkem8H7FSZwxrOI9djcdTP7U6YfNhbRnh7djErg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-LjQP/iZLBu8o8PjIfk4x3At0/mT6h282pvz8Z5LAyhGbu/kDezyO7ea62rF5uoqmgnIYqbN/MqJ3Si3Aymi7xQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-4EII1iNGRUN5WwGbF/kOh/EIkoDN9HsupgLQoXfY+D1oyJm7/F4t5PYU5n8SWZgG0FEwakyM8pGgwcBYruGTlA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-X/7bVLWelEsbyWDUSXt7zVsTniLLPIY2n1rH58qr78l9i7MNbbxBWD8gI2vRfBWf4NUXJCUuQnfZDsp32LqsfQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-AH8oq3XqQo4IibpVXvPeLDI5pzkpYn0WiZAfT05kFzoJ6tQNzwRdDYQ45M8I/gslbodRZwW8uxLhbSBbkv96rA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-gb6dYKW/1KDorGXyy48glEBJs/sxVSC5pcVrox/pFGV4mvwSFeg2sK5L2tRkVsVlh7kueqOgg4GEcuipJcGuKg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-cLnjV3xfo7KslbU41Z7z8BH/E1y5mzUYzAqih1d1MDaIGZRCMqTijqLv76/P7fyHuvUcfGsIpqCdddbxLLK9rA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-JY4w85pU3iAiJVMh5nuk4/Mh9GjMsupe8MrIN53rwxAZW64GKrWeJBuN6SxQg9QTU5uB1cxyhDzW8jqRn1EABw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0phclDw1spsL7dUB37sIARuis2tAgomCJXAHZlpt8PXZ4Ba0dRP1e+66lsRqrfhISeN9bEGNjQs+T/Fbd7oYGw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-xvpA7o5KCYLB0Rwscmuylb1/zHHSUx4g4xilm4prC5jP76pEUlzBmMbgpbh7bVDbId4NcfT96gN5i6mE6UDaiw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0ag/hEgXOwgw4t8QyQvUCxvEg+V0KBcA6YuOx9g0r02MprutRF5dyljgm3EmR02O292UX7UeS6HzWHAl6KgyhA==}
@@ -7963,66 +7982,79 @@ packages:
resolution: {integrity: sha512-EIPRXTVQpHyF8WOo219AD2yEltPehLTcTMz2fn6JsatLYSzQf00hj3rulF+yauOlF9/FtM2WpkT/hJh/KJFGhA==}
cpu: [arm]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-J3Yh9PzzF1Ovah2At+lHiGQdsYgArxBbXv/zHfSyaiFQEqvNv7DcW98pCrmdjCZBrqBiKrKKe2V+aaSGWuBe/w==}
cpu: [arm]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-BFDEZMYfUvLn37ONE1yMBojPxnMlTFsdyNoqncT0qFq1mAfllL+ATMMJd8TeuVMiX84s1KbcxcZbXInmcO2mRg==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-pc9EYOSlOgdQ2uPl1o9PF6/kLSgaUosia7gOuS8mB69IxJvlclko1MECXysjs5ryez1/5zjYqx3+xYU0TU6R1A==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-NxnomyxYerDh5n4iLrNa+sH+Z+U4BMEE46V2PgQ/hoB909i8gV1M5wPojWg9fk1jWpO3IQnOs20K4wyZuFLEFQ==}
cpu: [loong64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-nbJnQ8a3z1mtmrwImCYhc6BGpThAyYVRQxw9uKSKG4wR6aAYno9sVjJ0zaZcW9BPJX1GbrDPf+SvdWjgTuDmnw==}
cpu: [loong64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-2EU6acNrQLd8tYvo/LXW535wupT3m6fo7HKo6lr7ktQoItxTyOL1ZCR/GfGCuXl2vR+zmfI6eRXkSemafv+iVg==}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-WeBtoMuaMxiiIrO2IYP3xs6GMWkJP2C0EoT8beTLkUPmzV1i/UcOSVw1d5r9KBODtHKilG5yFxsGRnBbK3wJ4A==}
cpu: [ppc64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-FJHFfqpKUI3A10WrWKiFbBZ7yVbGT4q4B5o1qKFFojqpaYoh9LrQgqWCmmcxQzVSXYtyB5bzkXrYzlHTs21MYA==}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-mcEl6CUT5IAUmQf1m9FYSmVqCJlpQ8r8eyftFUHG8i9OhY7BkBXSUdnLH5DOf0wCOjcP9v/QO93zpmF1SptCCw==}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-ynt3JxVd2w2buzoKDWIyiV1pJW93xlQic1THVLXilz429oijRpSHivZAgp65KBu+cMcgf1eVVjdnTLvPxgCuoQ==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-Boiz5+MsaROEWDf+GGEwF8VMHGhlUoQMtIPjOgA5fv4osupqTVnJteQNKJwUcnUog2G55jYXH7KZFFiJe0TEzQ==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-+qfSY27qIrFfI/Hom04KYFw3GKZSGU4lXus51wsb5EuySfFlWRwjkKWoE9emgRw/ukoT4Udsj4W/+xxG8VbPKg==}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-VpTfOPHgVXEBeeR8hZ2O0F3aSso+JDWqTWmTmzcQKted54IAdUVbxE+j/MVxUsKa8L20HJhv3vUezVPoquqWjA==}
@@ -8594,48 +8626,56 @@ packages:
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-4og1V+ftEPXGttOO7eCmW7VICmzzJWgMx+QXAJRAhjrSjumCwWqMfkDrNu1LXEQzNAwz28NCUpucgQPrR4S2yw==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-WZA0CHRL/SP1TRbA5mp9htsppSEkWuQ4KsSUumYQnyl8ZdT39ntwqmz4IUHGN6p4XdSlYfJwM4rRzZLShHsGAQ==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-oCfG/mS+/+XRlwNjnsNLVwnMWYH7tn/kYPsNPh+JSOMlnt93mYNCKHYzylRhI51X+TbR+ufNhhKKzm6QkqX8ag==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-qMFzxI2YlBOLW5PhblzuSWlWfwLHaneBE0xHzLrBgNtqN6mWfs+qYbhryGSXQjFYB1Dzf5w+LN5qbUTPhW7Y5g==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-rTAGAkDgqbXHNp/xW0iugLVmX62wOp2PoE39BTCGKjv3Iocf6AFbRP/wZT/kuCxC9QBh9Pu8XPkv/zCZB2mcMg==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-5r1X2FKnCMUPlXTWRYpHdPYUY6a1Ar/t7P24OuiEdEOmms5lyqjDRvVY1yy9Rmioh+AunQ0rWiOTPE8F9A3v5g==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-XW3t3qwbIwiSyRCggeO2zxe3KWaEbM0/kW9e8+0XpBgyKU4ATYzcVSMKteZJ1iukJ3HgHBjbg9P5YPRCVUxlnQ==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-MGFB5cVPvshR85MTJkEvqDUnuNoysrsRxd6vnk1Lf2tbiqNlXpHYZqkqOQalydienEWOHHFyyuTSYRsLfxFJ2Q==}
@@ -8718,24 +8758,28 @@ packages:
engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@takumi-rs/[email protected]':
resolution: {integrity: sha512-4CiEF518wDnujF0fjql2XN6uO+OXl0svy0WgAF2656dCx2gJtWscaHytT2rsQ0ZmoFWE0dyWcDW1g/FBVPvuvA==}
engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@takumi-rs/[email protected]':
resolution: {integrity: sha512-jm8lTe2E6Tfq2b97GJC31TWK1JAEv+MsVbvL9DCLlYcafgYFlMXDUnOkZFMjlrmh0HcFAYDaBkniNDgIQfXqzg==}
engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@takumi-rs/[email protected]':
resolution: {integrity: sha512-nbdzQgC4ywzltDDV1fer1cKswwGE+xXZHdDiacdd7RM5XBng209Bmo3j1iv9dsX+4xXhByzCCGbxdWhhHqVXmw==}
engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@takumi-rs/[email protected]':
resolution: {integrity: sha512-kE4F0LRmuhSwiNkFG7dTY9ID8+B7zb97QedyN/IO2fBJmRQDkqCGcip2gloh8YPPhCuKGjCqqqh2L+Tg9PKW7w==}
@@ -9278,51 +9322,61 @@ packages:
resolution: {integrity: sha512-zJc0H99FEPoFfSrNpa91HYfxzfAJCr502oxNK1cfdC9hlaFI43RT+JFCann9JUgZmLzzntChHyn13Sgn9ljHNg==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-KQ3Lki6l+Pz1k/eBipN41ES+YUK30beLGb9YqcB1O542cyLCNE6GaxrfcY3T6EezmGGk84wb5XyO9loTM9tkcA==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-3SJGEh1DborhG6pyxvhPzCT4bbSIVihsvgJc13P1bHG7KLdNDaF9T3gsTwFc7Jw/5Y5/iWOjkEx7Zy0NvCGX3Q==}
cpu: [loong64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-jiuG/Obbel7uw1PwHNFfrkiKhLAF6mnyZ6aWlOAVN9WqKm8v0OFGnciJIHu8+CMvXLQ8AD51LPzAoUfT21D5Ew==}
cpu: [loong64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-q7xRvVpmcfeL+LlZg8Pbbo6QaTZwDU5BaGZbwfhkEsXJn3Was8xYfE0RBH266xZt0rM6B7i8xAYIvjthuUIWHg==}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-0CVdx6lcnT3Q9inOH8tsMIOJ6ImndllMjqJHg8RLVdB7Vq4SfkEXl9mCSsVNuNA4MCYycRicCUxPCabVHJRr6A==}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-iOwlRo9vnp6R6ohHQS11n0NnfdXx/omhkocmIfaPRpQhKZ+3BDMkkdRVh53qjkFkpPddf+FETA28NwGN7l5l+w==}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-HYJtLfXq94q8iZNFT1lknx258wlkkWhZeUXJRqzKBBUJ00CvZ+N33zgbCqimLjsyw5Va6uUxhVa12mI+kaveEw==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-mPsUhunKKDih5O96Y6enDQyHc1SqBPlY1E/SfMWDM3EdJ95Z9CArPeCVwCCqbP45ljvivdEk8Fxn+SIb1rDAJQ==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-azrt6+5ydLd8Vt210AAFis/lZevSfPw93EJRIJG+xPu4WCJ8K0kppCTpMyLPcKT7H15M4Jnt2tMp5bOvCkRC6A==}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-YZ9hP4O0X9PQb8eO980qmLNGH4zT3I9+SZTdt0Pr0YyuGQhYKoOZkV02VzrzyOZJ5xIJ3UFIenKkUkGg8GjgWQ==}
@@ -13360,48 +13414,56 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-mVZ7Pg2zIbe3XlNbZJdjs86YViQFoJSpc41CbVmKBPiGmC4YrfeOyz65ms2qpAobVd7WQsbW4PdsSJEMymyIMg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-xGlFWRMl+0KvUhgySdIaReQdB4FNudfUTARn7q0hh/V67PVGCs3ADFjw+6++kG1RNd0zdGRlEKa+T13/tQjPMA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-eowF8PrKHw9LpoZii5tdZwnBcYDxRw2rRCyvAXLi34iyeYfqCQNA9rmUM0ce62NlPhCvof1+9ivRaTY6pSKDaA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-aJReEbSEQzx1uBlQizAOBSjcmr9dCdL3XuC/6HLXAxmtErsj2ICo5yYggg1qOODQMtnjNQv2UHb9NpOuFtYe4w==}
@@ -17823,12 +17885,12 @@ snapshots:
- react-dom
- ws
- '@ag-ui/[email protected](hjtxoyfvlz4rpqmlqd5xziyo4m)':
+ '@ag-ui/[email protected](480e24a4fb499f3218e7d020b1a73a0c)':
dependencies:
'@ag-ui/client': 0.0.49
'@ag-ui/core': 0.0.53
'@ai-sdk/ui-utils': 1.2.11([email protected])
rxjs: 7.8.1
@@ -18410,19 +18472,6 @@ snapshots:
lru-cache: 5.1.1
semver: 6.3.1
- dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-annotate-as-pure': 7.27.3
- '@babel/helper-member-expression-to-functions': 7.28.5
- '@babel/helper-optimise-call-expression': 7.27.1
- '@babel/helper-replace-supers': 7.28.6(@babel/[email protected])
- '@babel/helper-skip-transparent-expression-wrappers': 7.27.1
- '@babel/traverse': 7.29.7
- semver: 6.3.1
- transitivePeerDependencies:
- - supports-color
-
dependencies:
'@babel/core': 7.29.7
@@ -18436,16 +18485,16 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-annotate-as-pure': 7.27.3
regexpu-core: 6.4.0
semver: 6.3.1
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-compilation-targets': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
debug: 4.4.3
@@ -18488,15 +18537,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-module-imports': 7.29.7
- '@babel/helper-validator-identifier': 7.29.7
- '@babel/traverse': 7.29.7
- transitivePeerDependencies:
- - supports-color
-
dependencies:
'@babel/core': 7.29.7
@@ -18512,24 +18552,15 @@ snapshots:
'@babel/[email protected]': {}
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-annotate-as-pure': 7.27.3
'@babel/helper-wrap-function': 7.28.6
'@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
- dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-member-expression-to-functions': 7.28.5
- '@babel/helper-optimise-call-expression': 7.27.1
- '@babel/traverse': 7.29.7
- transitivePeerDependencies:
- - supports-color
-
dependencies:
'@babel/core': 7.29.7
@@ -18611,78 +18642,73 @@ snapshots:
dependencies:
'@babel/types': 8.0.0-rc.6
dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])
'@babel/helper-plugin-utils': 7.28.6
- '@babel/plugin-syntax-decorators': 7.28.6(@babel/[email protected])
+ '@babel/plugin-syntax-decorators': 7.28.6(@babel/[email protected])
transitivePeerDependencies:
- supports-color
- dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-plugin-utils': 7.28.6
-
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
@@ -18690,49 +18716,44 @@ snapshots:
'@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
- dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-plugin-utils': 7.28.6
-
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
@@ -18740,278 +18761,257 @@ snapshots:
'@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
- '@babel/helper-remap-async-to-generator': 7.27.1(@babel/[email protected])
+ '@babel/helper-remap-async-to-generator': 7.27.1(@babel/[email protected])
'@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-module-imports': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
- '@babel/helper-remap-async-to-generator': 7.27.1(@babel/[email protected])
+ '@babel/helper-remap-async-to-generator': 7.27.1(@babel/[email protected])
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])
'@babel/helper-plugin-utils': 7.28.6
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])
'@babel/helper-plugin-utils': 7.28.6
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-annotate-as-pure': 7.27.3
'@babel/helper-compilation-targets': 7.29.7
'@babel/helper-globals': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
- '@babel/helper-replace-supers': 7.28.6(@babel/[email protected])
+ '@babel/helper-replace-supers': 7.28.6(@babel/[email protected])
'@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
'@babel/template': 7.29.7
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
'@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
- '@babel/plugin-syntax-flow': 7.28.6(@babel/[email protected])
+ '@babel/plugin-syntax-flow': 7.28.6(@babel/[email protected])
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
'@babel/helper-skip-transparent-expression-wrappers': 7.27.1
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-compilation-targets': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
'@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-module-transforms': 7.29.7(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/helper-module-transforms': 7.29.7(@babel/[email protected])
'@babel/helper-plugin-utils': 7.28.6
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-compilation-targets': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
- '@babel/plugin-transform-destructuring': 7.28.5(@babel/[email protected])
- '@babel/plugin-transform-parameters': 7.27.7(@babel/[email protected])
+ '@babel/plugin-transform-destructuring': 7.28.5(@babel/[email protected])
+ '@babel/plugin-transform-parameters': 7.27.7(@babel/[email protected])
'@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
'@babel/helper-skip-transparent-expression-wrappers': 7.27.1
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])
'@babel/helper-plugin-utils': 7.28.6
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-annotate-as-pure': 7.27.3
- '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])
+ '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])
'@babel/helper-plugin-utils': 7.28.6
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
- '@babel/plugin-transform-react-jsx': 7.28.6(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/plugin-transform-react-jsx': 7.28.6(@babel/[email protected])
transitivePeerDependencies:
- supports-color
- dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-plugin-utils': 7.28.6
-
dependencies:
'@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
- dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-plugin-utils': 7.28.6
-
dependencies:
'@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-annotate-as-pure': 7.27.3
'@babel/helper-module-imports': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
- '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
+ '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
'@babel/types': 7.29.7
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-annotate-as-pure': 7.27.3
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-module-imports': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
- babel-plugin-polyfill-corejs2: 0.4.16(@babel/[email protected])
- babel-plugin-polyfill-corejs3: 0.13.0(@babel/[email protected])
- babel-plugin-polyfill-regenerator: 0.6.7(@babel/[email protected])
+ babel-plugin-polyfill-corejs2: 0.4.16(@babel/[email protected])
+ babel-plugin-polyfill-corejs3: 0.13.0(@babel/[email protected])
+ babel-plugin-polyfill-regenerator: 0.6.7(@babel/[email protected])
semver: 6.3.1
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
'@babel/helper-skip-transparent-expression-wrappers': 7.27.1
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-plugin-utils': 7.28.6
-
- dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-annotate-as-pure': 7.27.3
- '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
- '@babel/helper-skip-transparent-expression-wrappers': 7.27.1
- '@babel/plugin-syntax-typescript': 7.28.6(@babel/[email protected])
- transitivePeerDependencies:
- - supports-color
dependencies:
@@ -19024,32 +19024,32 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])
'@babel/helper-plugin-utils': 7.28.6
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
'@babel/helper-validator-option': 7.29.7
- '@babel/plugin-transform-react-display-name': 7.28.0(@babel/[email protected])
- '@babel/plugin-transform-react-jsx': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-react-jsx-development': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-react-pure-annotations': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-react-display-name': 7.28.0(@babel/[email protected])
+ '@babel/plugin-transform-react-jsx': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-react-jsx-development': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-react-pure-annotations': 7.27.1(@babel/[email protected])
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.28.6
'@babel/helper-validator-option': 7.29.7
- '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-typescript': 7.28.6(@babel/[email protected])
+ '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-typescript': 7.28.6(@babel/[email protected])
transitivePeerDependencies:
- supports-color
@@ -19183,7 +19183,7 @@ snapshots:
dependencies:
commander: 13.1.0
: dependencies:
'@ag-ui/client': 0.0.46
'@ag-ui/core': 0.0.46
@@ -19192,10 +19192,10 @@ snapshots:
'@ai-sdk/openai': 2.0.106([email protected])
'@copilotkit/shared': 0.0.0-mme-ag-ui-0-0-46-20260227141603(@ag-ui/[email protected])
'@copilotkitnext/agent': 0.0.0-mme-ag-ui-0-0-46-20260227141603(@cfworker/[email protected])
- '@copilotkitnext/runtime': 0.0.0-mme-ag-ui-0-0-46-20260227141603(@ag-ui/[email protected])(@ag-ui/[email protected])(@ag-ui/[email protected])(@copilotkitnext/[email protected])
+ '@copilotkitnext/runtime': 0.0.0-mme-ag-ui-0-0-46-20260227141603(@ag-ui/[email protected])(@ag-ui/[email protected])(@ag-ui/[email protected])(@copilotkitnext/[email protected])
'@graphql-yoga/plugin-defer-stream': 3.21.0([email protected]([email protected]))([email protected])
'@hono/node-server': 1.19.14([email protected])
- '@langchain/core': 0.3.80(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
'@scarf/scarf': 1.4.0
ai: 5.0.192([email protected])
class-transformer: 0.5.1
@@ -19212,8 +19212,8 @@ snapshots:
zod: 3.25.76
optionalDependencies:
transitivePeerDependencies:
- '@ag-ui/encoder'
@@ -19254,11 +19254,11 @@ snapshots:
- '@cfworker/json-schema'
- supports-color
- '@copilotkitnext/[email protected](@ag-ui/[email protected])(@ag-ui/[email protected])(@ag-ui/[email protected])(@copilotkitnext/[email protected])':
+ '@copilotkitnext/[email protected](@ag-ui/[email protected])(@ag-ui/[email protected])(@ag-ui/[email protected])(@copilotkitnext/[email protected])':
dependencies:
'@ag-ui/client': 0.0.46
'@ag-ui/core': 0.0.46
- '@ag-ui/encoder': 0.0.49
+ '@ag-ui/encoder': 0.0.46
'@copilotkitnext/shared': 0.0.0-mme-ag-ui-0-0-46-20260227141603
cors: 2.8.6
express: 4.22.2
@@ -19838,7 +19838,7 @@ snapshots:
'@exodus/[email protected]':
optional: true
dependencies:
'@0no-co/graphql.web': 1.2.0([email protected])
'@expo/code-signing-certificates': 0.0.6
@@ -19849,11 +19849,11 @@ snapshots:
'@expo/image-utils': 0.8.12
'@expo/json-file': 10.0.12
'@expo/metro': 54.2.0
'@expo/osascript': 2.4.2
'@expo/package-manager': 1.10.3
'@expo/plist': 0.4.8
'@expo/schema-utils': 0.1.8
'@expo/spawn-async': 1.7.2
'@expo/ws-tunnel': 1.0.6
@@ -19872,7 +19872,7 @@ snapshots:
connect: 3.7.0
debug: 4.4.3
env-editor: 0.4.2
expo-server: 1.0.6
freeport-async: 2.0.0
getenv: 2.0.0
@@ -19905,7 +19905,7 @@ snapshots:
wrap-ansi: 7.0.0
ws: 8.21.0
optionalDependencies:
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
transitivePeerDependencies:
- bufferutil
- graphql
@@ -19962,12 +19962,12 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
chalk: 4.1.2
optionalDependencies:
react: 19.2.0
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
dependencies:
@@ -20010,7 +20010,7 @@ snapshots:
'@babel/code-frame': 7.29.7
json5: 2.2.3
dependencies:
'@babel/code-frame': 7.29.7
'@babel/core': 7.29.7
@@ -20034,7 +20034,7 @@ snapshots:
postcss: 8.5.15
resolve-from: 5.0.0
optionalDependencies:
transitivePeerDependencies:
- bufferutil
- supports-color
@@ -20080,7 +20080,7 @@ snapshots:
base64-js: 1.5.1
xmlbuilder: 15.1.1
dependencies:
'@expo/config': 12.0.13
'@expo/config-plugins': 54.0.4
@@ -20089,7 +20089,7 @@ snapshots:
'@expo/json-file': 10.0.12
'@react-native/normalize-colors': 0.81.5
debug: 4.4.3
resolve-from: 5.0.0
semver: 7.8.1
xml2js: 0.6.0
@@ -20106,11 +20106,11 @@ snapshots:
'@expo/[email protected]': {}
dependencies:
react: 19.2.0
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
'@expo/[email protected]': {}
@@ -20714,6 +20714,22 @@ snapshots:
- openai
- ws
+ dependencies:
+ '@cfworker/json-schema': 4.1.1
+ '@standard-schema/spec': 1.1.0
+ js-tiktoken: 1.0.21
+ mustache: 4.2.0
+ p-queue: 6.6.2
+ zod: 4.4.3
+ transitivePeerDependencies:
+ - '@opentelemetry/api'
+ - '@opentelemetry/exporter-trace-otlp-proto'
+ - '@opentelemetry/sdk-trace-base'
+ - openai
+ - ws
+
dependencies:
'@cfworker/json-schema': 4.1.1
@@ -20730,7 +20746,7 @@ snapshots:
- openai
- ws
- '@langchain/[email protected](rkbxzf4lbb37fnypru5cw45rfm)':
+ '@langchain/[email protected](ad8de7214a48057c647fd68b44767328)':
dependencies:
'@babel/code-frame': 7.29.7
'@hono/node-server': 1.19.14([email protected])
@@ -20776,11 +20792,11 @@ snapshots:
'@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
uuid: 14.0.0
- '@langchain/[email protected](rkbxzf4lbb37fnypru5cw45rfm)':
+ '@langchain/[email protected](ad8de7214a48057c647fd68b44767328)':
dependencies:
'@babel/code-frame': 7.29.7
'@commander-js/extra-typings': 13.1.0([email protected])
- '@langchain/langgraph-api': 1.3.0(rkbxzf4lbb37fnypru5cw45rfm)
+ '@langchain/langgraph-api': 1.3.0(ad8de7214a48057c647fd68b44767328)
chokidar: 4.0.3
commander: 13.1.0
create-langgraph: 1.1.5([email protected])
@@ -20825,9 +20841,9 @@ snapshots:
react: 19.2.3
react-dom: 19.2.3([email protected])
dependencies:
- '@langchain/core': 0.3.80(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
'@langchain/protocol': 0.0.16
'@types/json-schema': 7.0.15
p-queue: 9.3.0
@@ -20879,9 +20895,9 @@ snapshots:
- svelte
- vue
dependencies:
- '@langchain/core': 0.3.80(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
js-tiktoken: 1.0.21
zod: 4.4.3
@@ -21540,7 +21556,7 @@ snapshots:
'@nuxt/[email protected]': {}
dependencies:
'@nuxt/kit': 4.4.2([email protected])
execa: 8.0.1
@@ -21559,9 +21575,9 @@ snapshots:
pkg-types: 2.3.1
semver: 7.8.1
dependencies:
'@nuxt/devtools-wizard': 3.2.4
'@nuxt/kit': 4.4.2([email protected])
'@vue/devtools-core': 8.1.1([email protected]([email protected]))
@@ -21590,8 +21606,8 @@ snapshots:
structured-clone-es: 2.0.0
tinyglobby: 0.2.16
which: 6.0.1
ws: 8.21.0
transitivePeerDependencies:
@@ -21651,7 +21667,7 @@ snapshots:
transitivePeerDependencies:
- magicast
dependencies:
'@nuxt/devalue': 2.0.2
'@nuxt/kit': 3.21.6([email protected])
@@ -21669,7 +21685,7 @@ snapshots:
klona: 2.0.6
mocked-exports: 0.1.1
ohash: 2.0.11
pathe: 2.0.3
pkg-types: 2.3.1
@@ -21736,12 +21752,12 @@ snapshots:
rc9: 3.0.1
std-env: 4.1.0
dependencies:
'@nuxt/kit': 3.21.6([email protected])
'@rollup/plugin-replace': 6.0.3([email protected])
autoprefixer: 10.5.0([email protected])
consola: 3.4.2
cssnano: 7.1.9([email protected])
@@ -21755,7 +21771,7 @@ snapshots:
magic-string: 0.30.21
mlly: 1.8.2
mocked-exports: 0.1.1
nypm: 0.6.6
ohash: 2.0.11
pathe: 2.0.3
@@ -21766,9 +21782,9 @@ snapshots:
std-env: 4.1.0
ufo: 1.6.4
unenv: 2.0.0-rc.24
vue: 3.5.34([email protected])
vue-bundle-renderer: 2.2.0
optionalDependencies:
@@ -22027,17 +22043,25 @@ snapshots:
'@opentelemetry/[email protected]': {}
dependencies:
- zod: 4.4.3
+ zod: 4.3.6
optionalDependencies:
- '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
+ '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
+ dependencies:
+ '@openuidev/react-lang': 0.2.6(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
+ '@react-email/components': 0.0.41([email protected]([email protected]))([email protected])
+ react: 19.2.3
+ react-dom: 19.2.3([email protected])
+ zod: 4.3.6
+
dependencies:
'@ag-ui/core': 0.0.45
- react: 19.2.4
- zustand: 4.5.7(@types/[email protected])([email protected])
+ react: 19.2.3
+ zustand: 4.5.7(@types/[email protected])([email protected])
dependencies:
@@ -22049,55 +22073,13 @@ snapshots:
react: 19.2.4
zod: 4.4.3
dependencies:
- '@openuidev/lang-core': 0.2.5(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])
- react: 19.2.4
- zod: 4.4.3
+ '@openuidev/lang-core': 0.2.6(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])
+ react: 19.2.3
+ zod: 4.3.6
optionalDependencies:
- '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
-
- dependencies:
- '@floating-ui/react-dom': 2.1.3([email protected]([email protected]))([email protected])
- '@openuidev/react-headless': 0.8.2([email protected])([email protected](@types/[email protected])([email protected]))
- '@openuidev/react-lang': 0.2.6(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
- '@radix-ui/react-aspect-ratio': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- '@radix-ui/react-dropdown-menu': 2.1.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- '@radix-ui/react-toggle-group': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- clsx: 2.1.1
- date-fns: 4.1.0
- lodash-es: 4.18.1
- lucide-react: 0.562.0([email protected])
- react: 19.2.4
- react-day-picker: 9.14.0([email protected])
- react-dom: 19.2.4([email protected])
- react-markdown: 10.1.0(@types/[email protected])([email protected])
- react-syntax-highlighter: 16.1.1([email protected])
- rehype-katex: 7.0.1
- remark-breaks: 4.0.0
- remark-emoji: 5.0.1
- remark-gfm: 4.0.1
- remark-math: 6.0.0
- tiny-invariant: 1.3.3
- zod: 4.4.3
- zustand: 4.5.7(@types/[email protected])([email protected])
- transitivePeerDependencies:
- - '@types/react'
- - '@types/react-dom'
- - supports-color
+ '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
'@orama/[email protected]': {}
@@ -22679,22 +22661,6 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
- dependencies:
- '@radix-ui/primitive': 1.1.3
- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
- '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])
- react: 19.2.4
- react-dom: 19.2.4([email protected])
- optionalDependencies:
- '@types/react': 19.2.14
- '@types/react-dom': 19.2.3(@types/[email protected])
-
dependencies:
'@radix-ui/primitive': 1.1.2
@@ -22949,21 +22915,6 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
- dependencies:
- '@radix-ui/primitive': 1.1.3
- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
- react: 19.2.4
- react-dom: 19.2.4([email protected])
- optionalDependencies:
- '@types/react': 19.2.14
- '@types/react-dom': 19.2.3(@types/[email protected])
-
dependencies:
react: 19.2.3
@@ -23125,32 +23076,6 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
- dependencies:
- '@radix-ui/primitive': 1.1.3
- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- '@radix-ui/react-focus-guards': 1.1.3(@types/[email protected])([email protected])
- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
- aria-hidden: 1.2.6
- react: 19.2.4
- react-dom: 19.2.4([email protected])
- react-remove-scroll: 2.7.2(@types/[email protected])([email protected])
- optionalDependencies:
- '@types/react': 19.2.14
- '@types/react-dom': 19.2.3(@types/[email protected])
-
dependencies:
'@radix-ui/primitive': 1.1.3
@@ -23528,24 +23453,6 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
- dependencies:
- '@radix-ui/primitive': 1.1.3
- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
- '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])
- react: 19.2.4
- react-dom: 19.2.4([email protected])
- optionalDependencies:
- '@types/react': 19.2.14
- '@types/react-dom': 19.2.3(@types/[email protected])
-
dependencies:
'@radix-ui/primitive': 1.1.2
@@ -23735,35 +23642,6 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
- dependencies:
- '@radix-ui/number': 1.1.1
- '@radix-ui/primitive': 1.1.3
- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- '@radix-ui/react-focus-guards': 1.1.3(@types/[email protected])([email protected])
- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-visually-hidden': 1.2.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- aria-hidden: 1.2.6
- react: 19.2.4
- react-dom: 19.2.4([email protected])
- react-remove-scroll: 2.7.2(@types/[email protected])([email protected])
- optionalDependencies:
- '@types/react': 19.2.14
- '@types/react-dom': 19.2.3(@types/[email protected])
-
dependencies:
@@ -23839,25 +23717,6 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
- dependencies:
- '@radix-ui/number': 1.1.1
- '@radix-ui/primitive': 1.1.3
- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])
- react: 19.2.4
- react-dom: 19.2.4([email protected])
- optionalDependencies:
- '@types/react': 19.2.14
- '@types/react-dom': 19.2.3(@types/[email protected])
-
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
@@ -23931,21 +23790,6 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
- dependencies:
- '@radix-ui/primitive': 1.1.3
- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
- '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])
- react: 19.2.4
- react-dom: 19.2.4([email protected])
- optionalDependencies:
- '@types/react': 19.2.14
- '@types/react-dom': 19.2.3(@types/[email protected])
-
dependencies:
'@radix-ui/primitive': 1.1.2
@@ -24059,21 +23903,6 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
- dependencies:
- '@radix-ui/primitive': 1.1.3
- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
- react: 19.2.4
- react-dom: 19.2.4([email protected])
- optionalDependencies:
- '@types/react': 19.2.14
- '@types/react-dom': 19.2.3(@types/[email protected])
-
dependencies:
'@radix-ui/primitive': 1.1.3
@@ -24085,17 +23914,6 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
- dependencies:
- '@radix-ui/primitive': 1.1.3
- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
- react: 19.2.4
- react-dom: 19.2.4([email protected])
- optionalDependencies:
- '@types/react': 19.2.14
- '@types/react-dom': 19.2.3(@types/[email protected])
-
dependencies:
'@radix-ui/primitive': 1.1.2
@@ -24173,26 +23991,6 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
- dependencies:
- '@radix-ui/primitive': 1.1.3
- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
- '@radix-ui/react-visually-hidden': 1.2.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- react: 19.2.4
- react-dom: 19.2.4([email protected])
- optionalDependencies:
- '@types/react': 19.2.14
- '@types/react-dom': 19.2.3(@types/[email protected])
-
dependencies:
react: 19.2.3
@@ -25197,67 +24995,67 @@ snapshots:
'@react-native/[email protected]': {}
- '@react-native/[email protected](@babel/[email protected])':
+ '@react-native/[email protected](@babel/[email protected])':
dependencies:
'@babel/traverse': 7.29.7
- '@react-native/codegen': 0.81.5(@babel/[email protected])
+ '@react-native/codegen': 0.81.5(@babel/[email protected])
transitivePeerDependencies:
- '@babel/core'
- supports-color
- '@react-native/[email protected](@babel/[email protected])':
+ '@react-native/[email protected](@babel/[email protected])':
dependencies:
- '@babel/core': 7.29.0
- '@babel/plugin-proposal-export-default-from': 7.27.1(@babel/[email protected])
- '@babel/plugin-syntax-dynamic-import': 7.8.3(@babel/[email protected])
- '@babel/plugin-syntax-export-default-from': 7.28.6(@babel/[email protected])
- '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/[email protected])
- '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/[email protected])
- '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-async-generator-functions': 7.29.0(@babel/[email protected])
- '@babel/plugin-transform-async-to-generator': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-block-scoping': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-class-properties': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-classes': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-computed-properties': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-destructuring': 7.28.5(@babel/[email protected])
- '@babel/plugin-transform-flow-strip-types': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-for-of': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-function-name': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-literals': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-logical-assignment-operators': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-named-capturing-groups-regex': 7.29.0(@babel/[email protected])
- '@babel/plugin-transform-nullish-coalescing-operator': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-numeric-separator': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-optional-catch-binding': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-parameters': 7.27.7(@babel/[email protected])
- '@babel/plugin-transform-private-methods': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-private-property-in-object': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-react-display-name': 7.28.0(@babel/[email protected])
- '@babel/plugin-transform-react-jsx': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-regenerator': 7.29.0(@babel/[email protected])
- '@babel/plugin-transform-runtime': 7.29.0(@babel/[email protected])
- '@babel/plugin-transform-shorthand-properties': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-spread': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-sticky-regex': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-typescript': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-unicode-regex': 7.27.1(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/plugin-proposal-export-default-from': 7.27.1(@babel/[email protected])
+ '@babel/plugin-syntax-dynamic-import': 7.8.3(@babel/[email protected])
+ '@babel/plugin-syntax-export-default-from': 7.28.6(@babel/[email protected])
+ '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/[email protected])
+ '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/[email protected])
+ '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-async-generator-functions': 7.29.0(@babel/[email protected])
+ '@babel/plugin-transform-async-to-generator': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-block-scoping': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-class-properties': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-classes': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-computed-properties': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-destructuring': 7.28.5(@babel/[email protected])
+ '@babel/plugin-transform-flow-strip-types': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-for-of': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-function-name': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-literals': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-logical-assignment-operators': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-named-capturing-groups-regex': 7.29.0(@babel/[email protected])
+ '@babel/plugin-transform-nullish-coalescing-operator': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-numeric-separator': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-optional-catch-binding': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-parameters': 7.27.7(@babel/[email protected])
+ '@babel/plugin-transform-private-methods': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-private-property-in-object': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-react-display-name': 7.28.0(@babel/[email protected])
+ '@babel/plugin-transform-react-jsx': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-regenerator': 7.29.0(@babel/[email protected])
+ '@babel/plugin-transform-runtime': 7.29.0(@babel/[email protected])
+ '@babel/plugin-transform-shorthand-properties': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-spread': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-sticky-regex': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-typescript': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-unicode-regex': 7.27.1(@babel/[email protected])
'@babel/template': 7.29.7
- '@react-native/babel-plugin-codegen': 0.81.5(@babel/[email protected])
+ '@react-native/babel-plugin-codegen': 0.81.5(@babel/[email protected])
babel-plugin-syntax-hermes-parser: 0.29.1
- babel-plugin-transform-flow-enums: 0.0.2(@babel/[email protected])
+ babel-plugin-transform-flow-enums: 0.0.2(@babel/[email protected])
react-refresh: 0.14.2
transitivePeerDependencies:
- supports-color
- '@react-native/[email protected](@babel/[email protected])':
+ '@react-native/[email protected](@babel/[email protected])':
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/parser': 7.29.7
glob: 7.2.3
hermes-parser: 0.29.1
@@ -25265,9 +25063,9 @@ snapshots:
nullthrows: 1.1.1
yargs: 17.7.2
- '@react-native/[email protected](@babel/[email protected])':
+ '@react-native/[email protected](@babel/[email protected])':
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@babel/parser': 7.29.0
glob: 7.2.3
hermes-parser: 0.32.0
@@ -25345,12 +25143,12 @@ snapshots:
'@react-native/[email protected]': {}
dependencies:
invariant: 2.2.4
nullthrows: 1.1.1
react: 19.2.0
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
optionalDependencies:
'@types/react': 19.2.14
@@ -26753,7 +26551,7 @@ snapshots:
tailwindcss: 4.2.2
dependencies:
'@tailwindcss/node': 4.2.2
'@tailwindcss/oxide': 4.2.2
@@ -27486,7 +27284,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@babel/core': 7.29.7
'@babel/plugin-syntax-typescript': 7.28.6(@babel/[email protected])
@@ -27504,7 +27302,7 @@ snapshots:
vue: 3.5.31([email protected])
dependencies:
'@rolldown/pluginutils': 1.0.1
@@ -28252,13 +28050,13 @@ snapshots:
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
'@jest/transform': 29.7.0
'@types/babel__core': 7.20.5
babel-plugin-istanbul: 6.1.1
- babel-preset-jest: 29.6.3(@babel/[email protected])
+ babel-preset-jest: 29.6.3(@babel/[email protected])
chalk: 4.1.2
graceful-fs: 4.2.11
slash: 3.0.0
@@ -28288,27 +28086,27 @@ snapshots:
cosmiconfig: 7.1.0
resolve: 1.22.11
dependencies:
'@babel/compat-data': 7.29.7
- '@babel/core': 7.29.0
- '@babel/helper-define-polyfill-provider': 0.6.7(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/helper-define-polyfill-provider': 0.6.7(@babel/[email protected])
semver: 6.3.1
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-define-polyfill-provider': 0.6.7(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/helper-define-polyfill-provider': 0.6.7(@babel/[email protected])
core-js-compat: 3.48.0
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/core': 7.29.0
- '@babel/helper-define-polyfill-provider': 0.6.7(@babel/[email protected])
+ '@babel/core': 7.29.7
+ '@babel/helper-define-polyfill-provider': 0.6.7(@babel/[email protected])
transitivePeerDependencies:
- supports-color
@@ -28326,68 +28124,68 @@ snapshots:
dependencies:
hermes-parser: 0.32.0
dependencies:
- '@babel/plugin-syntax-flow': 7.28.6(@babel/[email protected])
+ '@babel/plugin-syntax-flow': 7.28.6(@babel/[email protected])
transitivePeerDependencies:
- '@babel/core'
dependencies:
- '@babel/core': 7.29.0
- '@babel/plugin-syntax-async-generators': 7.8.4(@babel/[email protected])
- '@babel/plugin-syntax-bigint': 7.8.3(@babel/[email protected])
- '@babel/plugin-syntax-class-properties': 7.12.13(@babel/[email protected])
- '@babel/plugin-syntax-class-static-block': 7.14.5(@babel/[email protected])
- '@babel/plugin-syntax-import-attributes': 7.28.6(@babel/[email protected])
- '@babel/plugin-syntax-import-meta': 7.10.4(@babel/[email protected])
- '@babel/plugin-syntax-json-strings': 7.8.3(@babel/[email protected])
- '@babel/plugin-syntax-logical-assignment-operators': 7.10.4(@babel/[email protected])
- '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/[email protected])
- '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/[email protected])
- '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/[email protected])
- '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/[email protected])
- '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/[email protected])
- '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/[email protected])
- '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/[email protected])
-
+ '@babel/core': 7.29.7
+ '@babel/plugin-syntax-async-generators': 7.8.4(@babel/[email protected])
+ '@babel/plugin-syntax-bigint': 7.8.3(@babel/[email protected])
+ '@babel/plugin-syntax-class-properties': 7.12.13(@babel/[email protected])
+ '@babel/plugin-syntax-class-static-block': 7.14.5(@babel/[email protected])
+ '@babel/plugin-syntax-import-attributes': 7.28.6(@babel/[email protected])
+ '@babel/plugin-syntax-import-meta': 7.10.4(@babel/[email protected])
+ '@babel/plugin-syntax-json-strings': 7.8.3(@babel/[email protected])
+ '@babel/plugin-syntax-logical-assignment-operators': 7.10.4(@babel/[email protected])
+ '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/[email protected])
+ '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/[email protected])
+ '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/[email protected])
+ '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/[email protected])
+ '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/[email protected])
+ '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/[email protected])
+ '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/[email protected])
+
dependencies:
'@babel/helper-module-imports': 7.29.7
- '@babel/plugin-proposal-decorators': 7.29.0(@babel/[email protected])
- '@babel/plugin-proposal-export-default-from': 7.27.1(@babel/[email protected])
- '@babel/plugin-syntax-export-default-from': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-class-static-block': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-flow-strip-types': 7.27.1(@babel/[email protected])
- '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-parameters': 7.27.7(@babel/[email protected])
- '@babel/plugin-transform-private-methods': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-private-property-in-object': 7.28.6(@babel/[email protected])
- '@babel/plugin-transform-runtime': 7.29.0(@babel/[email protected])
- '@babel/preset-react': 7.28.5(@babel/[email protected])
- '@babel/preset-typescript': 7.28.5(@babel/[email protected])
- '@react-native/babel-preset': 0.81.5(@babel/[email protected])
+ '@babel/plugin-proposal-decorators': 7.29.0(@babel/[email protected])
+ '@babel/plugin-proposal-export-default-from': 7.27.1(@babel/[email protected])
+ '@babel/plugin-syntax-export-default-from': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-class-static-block': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-flow-strip-types': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-parameters': 7.27.7(@babel/[email protected])
+ '@babel/plugin-transform-private-methods': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-private-property-in-object': 7.28.6(@babel/[email protected])
+ '@babel/plugin-transform-runtime': 7.29.0(@babel/[email protected])
+ '@babel/preset-react': 7.28.5(@babel/[email protected])
+ '@babel/preset-typescript': 7.28.5(@babel/[email protected])
+ '@react-native/babel-preset': 0.81.5(@babel/[email protected])
babel-plugin-react-compiler: 1.0.0
babel-plugin-react-native-web: 0.21.2
babel-plugin-syntax-hermes-parser: 0.29.1
- babel-plugin-transform-flow-enums: 0.0.2(@babel/[email protected])
+ babel-plugin-transform-flow-enums: 0.0.2(@babel/[email protected])
debug: 4.4.3
react-refresh: 0.14.2
resolve-from: 5.0.0
optionalDependencies:
'@babel/runtime': 7.29.7
transitivePeerDependencies:
- '@babel/core'
- supports-color
dependencies:
- '@babel/core': 7.29.0
+ '@babel/core': 7.29.7
babel-plugin-jest-hoist: 29.6.3
- babel-preset-current-node-syntax: 1.2.0(@babel/[email protected])
+ babel-preset-current-node-syntax: 1.2.0(@babel/[email protected])
@@ -29918,7 +29716,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
@@ -29940,7 +29738,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.29.0([email protected])
eslint-import-resolver-node: 0.3.10
hasown: 2.0.3
is-core-module: 2.16.2
is-glob: 4.0.3
@@ -30284,40 +30082,40 @@ snapshots:
dependencies:
'@expo/image-utils': 0.8.12
react: 19.2.0
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
'@expo/config': 12.0.13
'@expo/env': 2.0.11
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
dependencies:
fontfaceobserver: 2.3.0
react: 19.2.0
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
dependencies:
react: 19.2.0
@@ -30328,43 +30126,43 @@ snapshots:
require-from-string: 2.0.2
resolve-from: 5.0.0
dependencies:
invariant: 2.2.4
react: 19.2.0
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
dependencies:
react: 19.2.0
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
- react-native-is-edge-to-edge: 1.3.1([email protected](@babel/[email protected])(@types/[email protected])([email protected]))([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native-is-edge-to-edge: 1.3.1([email protected](@babel/[email protected])(@types/[email protected])([email protected]))([email protected])
dependencies:
'@babel/runtime': 7.29.7
'@expo/config': 12.0.13
'@expo/config-plugins': 54.0.4
'@expo/fingerprint': 0.15.5
'@expo/metro': 54.2.0
'@ungap/structured-clone': 1.3.1
expo-modules-autolinking: 3.0.25
pretty-format: 29.7.0
react: 19.2.0
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
react-refresh: 0.14.2
whatwg-url-without-unicode: 8.0.0-3
transitivePeerDependencies:
@@ -33781,16 +33579,16 @@ snapshots:
dependencies:
bignumber.js: 9.3.1
dependencies:
'@dxup/nuxt': 0.4.1([email protected])([email protected])
'@nuxt/kit': 3.21.6([email protected])
'@nuxt/schema': 3.21.6
'@nuxt/telemetry': 2.8.0(@nuxt/[email protected]([email protected]))
'@unhead/vue': 2.1.15([email protected]([email protected]))
'@vue/shared': 3.5.34
c12: 3.3.4([email protected])
@@ -35025,14 +34823,6 @@ snapshots:
date-fns-jalali: 4.1.0-0
react: 19.2.3
- dependencies:
- '@date-fns/tz': 1.4.1
- '@tabby_ai/hijri-converter': 1.0.5
- date-fns: 4.1.0
- date-fns-jalali: 4.1.0-0
- react: 19.2.4
-
dependencies:
'@date-fns/tz': 1.2.0
@@ -35126,22 +34916,22 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
react: 19.2.0
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
dependencies:
react: 19.2.0
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
dependencies:
css-select: 5.2.2
css-tree: 1.1.3
react: 19.2.0
- react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
+ react-native: 0.83.2(@babel/[email protected])(@types/[email protected])([email protected])
warn-once: 0.1.1
@@ -35159,20 +34949,20 @@ snapshots:
transitivePeerDependencies:
- encoding
dependencies:
'@jest/create-cache-key-function': 29.7.0
'@react-native/assets-registry': 0.83.2
- '@react-native/codegen': 0.83.2(@babel/[email protected])
+ '@react-native/codegen': 0.83.2(@babel/[email protected])
'@react-native/community-cli-plugin': 0.83.2
'@react-native/gradle-plugin': 0.83.2
'@react-native/js-polyfills': 0.83.2
'@react-native/normalize-colors': 0.83.2
- '@react-native/virtualized-lists': 0.83.2(@types/[email protected])([email protected](@babel/[email protected])(@types/[email protected])([email protected]))([email protected])
+ '@react-native/virtualized-lists': 0.83.2(@types/[email protected])([email protected](@babel/[email protected])(@types/[email protected])([email protected]))([email protected])
abort-controller: 3.0.0
anser: 1.4.10
ansi-regex: 5.0.1
- babel-jest: 29.7.0(@babel/[email protected])
+ babel-jest: 29.7.0(@babel/[email protected])
babel-plugin-syntax-hermes-parser: 0.32.0
base64-js: 1.5.1
commander: 12.1.0
@@ -35337,16 +35127,6 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.14
- dependencies:
- '@babel/runtime': 7.29.7
- highlight.js: 10.7.3
- highlightjs-vue: 1.0.0
- lowlight: 1.20.0
- prismjs: 1.30.0
- react: 19.2.3
- refractor: 5.0.0
-
dependencies:
'@babel/runtime': 7.29.7
@@ -37309,13 +37089,13 @@ snapshots:
d3-time: 3.1.0
d3-timer: 3.0.1
dependencies:
birpc: 2.9.0
dependencies:
@@ -37339,7 +37119,7 @@ snapshots:
- tsx
- yaml
dependencies:
'@babel/code-frame': 7.29.7
chokidar: 4.0.3
@@ -37357,7 +37137,7 @@ snapshots:
typescript: 5.9.3
vue-tsc: 2.2.12([email protected])
dependencies:
ansis: 4.2.0
debug: 4.4.3
@@ -37368,13 +37148,13 @@ snapshots:
sirv: 3.0.2
unplugin-utils: 0.3.1
optionalDependencies:
'@nuxt/kit': 4.4.2([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
estree-walker: 3.0.3
exsolve: 1.0.8
@@ -38029,6 +37809,13 @@ snapshots:
+ dependencies:
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.14
+ react: 19.2.3
+
dependencies:
use-sync-external-store: 1.6.0([email protected])
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 29ecd1f54..e4e7cefb0 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -3,6 +3,7 @@ packages:
- "examples/**/*"
- "docs/"
- "!**/src/templates/**"
+ - "!examples/openui-cloud"
# Centralized dependency versions shared across packages.
# Reference these from a package.json with the "catalog:" protocol.
diff --git a/skills/openui/SKILL.md b/skills/openui/SKILL.md
index 382a39fce..09138d33a 100644
--- a/skills/openui/SKILL.md
+++ b/skills/openui/SKILL.md
@@ -78,7 +78,7 @@ When you need detail on a specific topic, fetch the relevant page from the allow
| --------------------------- | ----------------------------------------------------------------------- | ------------------------- |
| `@openuidev/react-lang` | Core: defineComponent, createLibrary, Renderer, parser | Every OpenUI project |
| `@openuidev/react-headless` | Chat state: ChatProvider, hooks, streaming adapters (OpenAI, AG-UI) | Custom chat UI |
-| `@openuidev/react-ui` | Prebuilt layouts (Copilot, FullScreen, BottomTray) + built-in libraries | Fast path to working chat |
+| `@openuidev/react-ui` | Prebuilt AgentInterface chat surface + built-in libraries | Fast path to working chat |
## Scaffolding