The Open Standard for Generative UI
react-headless: cleanup and modernize (#273)
Ankit Das31cfaaa4446b
diff --git a/.gitignore b/.gitignoreindex 83468ded9..82e85c083 100644--- a/.gitignore+++ b/.gitignore@@ -21,6 +21,11 @@.cursor/plans.cursor/agents+# Claude+Claude.md+.claude/+CLAUDE.local.md+# Dependenciesnode_modules.pnpm-store/diff --git a/eslint.config.cjs b/eslint.config.cjsindex 22c907096..e30cb5abd 100644--- a/eslint.config.cjs+++ b/eslint.config.cjs@@ -71,18 +71,6 @@ module.exports = [allow: ["error", "warn", "info"],},],- "no-restricted-imports": [- "error",- {- paths: [- {- name: "react",- importNames: ["useId"],- message: "import of useId is allowed only using polyfills",- },- ],- },- ],...eslintPluginPrettier.configs.recommended.rules,"react-hooks/exhaustive-deps": "warn",},diff --git a/packages/lang-react/eslint.config.cjs b/packages/lang-react/eslint.config.cjsindex bc6f579ff..0df857619 100644--- a/packages/lang-react/eslint.config.cjs+++ b/packages/lang-react/eslint.config.cjs@@ -51,18 +51,6 @@ module.exports = [allow: ["error", "warn", "info"],},],- "no-restricted-imports": [- "error",- {- paths: [- {- name: "react",- importNames: ["useId"],- message: "import of useId is allowed only using polyfills",- },- ],- },- ],...eslintPluginPrettier.configs.recommended.rules,},},diff --git a/packages/lang-react/package.json b/packages/lang-react/package.jsonindex 1b9093d83..58aa85029 100644--- a/packages/lang-react/package.json+++ b/packages/lang-react/package.json@@ -30,7 +30,7 @@"zod": "^4.0.0"},"peerDependencies": {- "react": ">=18.0.0"+ "react": ">=19.0.0"},"devDependencies": {"@types/react": "^19.0.0"diff --git a/packages/react-headless/AGENTS.md b/packages/react-headless/AGENTS.mdindex 1c38496ca..d6c861313 100644--- a/packages/react-headless/AGENTS.md+++ b/packages/react-headless/AGENTS.md@@ -1,48 +1,48 @@-# react-core — Agent Guide+# react-headless — Agent Guide## Build / Test / Lint```bash-# From js/ workspace root:-pnpm --filter @openuidev/react-core run build # tsc → dist/-pnpm --filter @openuidev/react-core run test # vitest-pnpm --filter @openuidev/react-core run ci # lint:check + format:check+# From monorepo root:+pnpm --filter @openuidev/react-headless run build # tsc → dist/+pnpm --filter @openuidev/react-headless run test # vitest+pnpm --filter @openuidev/react-headless run ci # lint:check + format:check# Or from this directory:pnpm build && pnpm test```-Build order: `stream` → **`react-core`** → `react-ui`. This package has no upstream JS workspace deps (only `@ag-ui/core` from npm), so it can always build independently.+Build order: **`react-headless`** → `lang-react` → `react-ui`. This package has no upstream workspace deps (only `@ag-ui/core` from npm), so it can always build independently.## File Map| Path | Purpose || ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- || `src/index.ts` | Public API surface — every export consumers see. Check here first when adding/removing exports. |-| `src/v2/createChatStore.ts` | Zustand store factory. All state + actions live here. This is the most critical file. |-| `src/v2/ChatProvider.tsx` | React provider — thin wrapper that creates the store once via `useState`. |-| `src/v2/ChatContext.ts` | React context + `useChatStore()` internal hook. |-| `src/v2/hooks.ts` | `useThread()` / `useThreadList()` — selector hooks over the store. |-| `src/v2/types.ts` | All v2 types: `ChatStore`, `ChatProviderProps`, `Thread`, state/action slices. |-| `src/v2/__tests__/createChatStore.test.ts` | Comprehensive test suite for the store (thread CRUD, message CRUD, streaming, cancellation, URL-based defaults, messageFormat round-trips). |+| `src/store/createChatStore.ts` | Zustand store factory. All state + actions live here. This is the most critical file. |+| `src/store/ChatProvider.tsx` | React provider — thin wrapper that creates the store once via `useState`. |+| `src/store/ChatContext.ts` | React context + `useChatStore()` internal hook. |+| `src/store/hooks.ts` | `useThread()` / `useThreadList()` — selector hooks over the store. |+| `src/store/types.ts` | All store types: `ChatStore`, `ChatProviderProps`, `Thread`, state/action slices. |+| `src/store/__tests__/createChatStore.test.ts` | Comprehensive test suite for the store (thread CRUD, message CRUD, streaming, cancellation, URL-based defaults, messageFormat round-trips). || `src/stream/processStreamedMessage.ts` | Consumes `AsyncIterable<AGUIEvent>` and drives message create/update/delete callbacks. || `src/stream/adapters/ag-ui.ts` | Default SSE adapter — parses `data: {json}\n` lines. || `src/stream/adapters/openai-completions.ts` | Adapter for OpenAI Chat Completions streaming (`ChatCompletionChunk`). || `src/stream/adapters/openai-responses.ts` | Adapter for OpenAI Responses API streaming (`ResponseStreamEvent`). |+| `src/stream/adapters/openai-readable-stream.ts` | Adapter for OpenAI SDK's `Stream.toReadableStream()` — parses NDJSON (no SSE prefix) `ChatCompletionChunk` objects. || `src/stream/adapters/openai-message-format.ts` | `MessageFormat` for OpenAI Completions (`ChatCompletionMessageParam[]` ↔ AG-UI). || `src/stream/adapters/openai-conversation-message-format.ts` | `MessageFormat` for OpenAI Responses/Conversations API (`ResponseInputItem[]` ↔ AG-UI). |-| `src/types/` | Shared types: `message.ts` (re-exports from `@ag-ui/core`), `messageFormat.ts`, `stream.ts`, `chatManager.ts` (legacy v1 types). |+| `src/types/` | Shared types: `message.ts` (re-exports from `@ag-ui/core`), `messageFormat.ts`, `stream.ts`. || `src/hooks/useMessage.tsx` | `MessageContext` / `MessageProvider` / `useMessage` — per-message React context used by `react-ui`. |-| `src/polyfills/react-17.ts` | `useId` polyfill for React 17 compatibility. |## Key Patterns### Adding a new store action-1. Add the type to the appropriate slice in `src/v2/types.ts` (`ThreadActions` or `ThreadListActions`).+1. Add the type to the appropriate slice in `src/store/types.ts` (`ThreadActions` or `ThreadListActions`).2. Implement it in `createChatStore.ts` inside the `createStore<ChatStore>(...)` call.-3. Add it to the selector in `src/v2/hooks.ts` (`threadSelector` or `threadListSelector`).-4. Add tests in `src/v2/__tests__/createChatStore.test.ts`.+3. Add it to the selector in `src/store/hooks.ts` (`threadSelector` or `threadListSelector`).+4. Add tests in `src/store/__tests__/createChatStore.test.ts`.5. If it should be public, export the type from `src/index.ts`.### Adding a new stream adapterdiff --git a/packages/react-headless/README.md b/packages/react-headless/README.mdindex 749a699a4..b43a6c2e5 100644--- a/packages/react-headless/README.md+++ b/packages/react-headless/README.md@@ -2,6 +2,507 @@Headless React primitives, streaming adapters, and state management for OpenUI.+<<<<<<< nit/react-headless+## Table of Contents++- [@openuidev/react-headless](#openuidevreact-headless)+ - [Table of Contents](#table-of-contents)+ - [Architecture Overview](#architecture-overview)+ - [Installation](#installation)+ - [Peer dependencies](#peer-dependencies)+ - [Quick Start](#quick-start)+ - [Minimal setup (URL-based)](#minimal-setup-url-based)+ - [Custom backend functions](#custom-backend-functions)+ - [Core Concepts](#core-concepts)+ - [ChatProvider](#chatprovider)+ - [Hooks](#hooks)+ - [Streaming](#streaming)+ - [Message Formats](#message-formats)+ - [Stream Protocol Adapters](#stream-protocol-adapters)+ - [Module Breakdown](#module-breakdown)+ - [`v2/` — Zustand Store \& Provider](#v2--zustand-store--provider)+ - [Store Internals](#store-internals)+ - [`stream/` — Streaming Engine](#stream--streaming-engine)+ - [`types/` — Type Definitions](#types--type-definitions)+ - [`hooks/` — Message Context](#hooks--message-context)+ - [API Reference](#api-reference)+ - [ChatProviderProps](#chatproviderprops)+ - [Thread API (choose one):](#thread-api-choose-one)+ - [Chat API (choose one):](#chat-api-choose-one)+ - [Optional:](#optional)+ - [useThread](#usethread)+ - [useThreadList](#usethreadlist)+ - [useMessage](#usemessage)+ - [processStreamedMessage](#processstreamedmessage)+ - [Stream Adapters](#stream-adapters)+ - [Message Format Converters](#message-format-converters)+ - [Type Reference](#type-reference)+ - [Message Types (from `@ag-ui/core`)](#message-types-from-ag-uicore)+ - [Store Types](#store-types)+ - [Adapter Types](#adapter-types)+ - [How It All Fits Together](#how-it-all-fits-together)++---++## Architecture Overview++```+┌──────────────────────────────────────────────────────────────┐+│ <ChatProvider> │+│ │+│ ┌────────────────────────────────────────────────────────┐ │+│ │ Zustand Store (ChatStore) │ │+│ │ │ │+│ │ ┌─────────────────┐ ┌───────────────────────────┐ │ │+│ │ │ ThreadListSlice │ │ ThreadSlice │ │ │+│ │ │ │ │ │ │ │+│ │ │ • threads[] │ │ • messages[] │ │ │+│ │ │ • selectedId │ │ • isRunning │ │ │+│ │ │ • loadThreads() │ │ • processMessage() │ │ │+│ │ │ • createThread()│ │ • cancelMessage() │ │ │+│ │ │ • deleteThread()│ │ • appendMessages() │ │ │+│ │ │ • selectThread()│ │ • updateMessage() │ │ │+│ │ │ • ... │ │ • ... │ │ │+│ │ └─────────────────┘ └───────────┬───────────────┘ │ │+│ │ │ │ │+│ └─────────────────────────────────────┼──────────────────┘ │+│ │ │+│ processMessage() calls: │+│ │ │+│ ┌─────────────────────────────────────▼──────────────────┐ │+│ │ Streaming Pipeline │ │+│ │ │ │+│ │ fetch(apiUrl) ──► StreamProtocolAdapter.parse() │ │+│ │ │ │ │+│ │ AG-UI Events (SSE) │ │+│ │ │ │ │+│ │ processStreamedMessage() │ │+│ │ │ │ │ │ │+│ │ createMsg updateMsg deleteMsg │ │+│ │ └─────────┴─────────┘ │ │+│ │ │ │ │+│ │ Zustand set(messages) │ │+│ └────────────────────────────────────────────────────────┘ │+│ │+│ Hooks: useThread() · useThreadList() · useMessage() │+└──────────────────────────────────────────────────────────────┘+```++---++## Installation++```bash+pnpm add @openuidev/react-headless+```++### Peer dependencies++```bash+pnpm add react react-dom zustand eventsource-parser tiny-invariant+```++---++## Quick Start++### Minimal setup (URL-based)++```tsx+import { ChatProvider, useThread, useThreadList } from "@openuidev/react-headless";++function App() {+ return (+ <ChatProvider apiUrl="/api/chat" threadApiUrl="/api/threads">+ <ChatUI />+ </ChatProvider>+ );+}++function ChatUI() {+ const { messages, processMessage, isRunning } = useThread();+ const { threads, selectThread, loadThreads } = useThreadList();++ // ... render your chat UI+}+```++### Custom backend functions++```tsx+<ChatProvider+ processMessage={async ({ threadId, messages, abortController }) => {+ return fetch("/my/custom/endpoint", {+ method: "POST",+ body: JSON.stringify({ threadId, messages }),+ signal: abortController.signal,+ });+ }}+ fetchThreadList={async () => {+ const res = await fetch("/my/threads");+ return res.json(); // { threads: Thread[], nextCursor?: any }+ }}+ createThread={async (firstMessage) => {+ const res = await fetch("/my/threads", {+ method: "POST",+ body: JSON.stringify({ message: firstMessage }),+ });+ return res.json(); // Thread+ }}+>+ <ChatUI />+</ChatProvider>+```++---++## Core Concepts++### ChatProvider++The `<ChatProvider>` is the top-level React component that creates and owns the Zustand store. It accepts configuration for how to communicate with your backend (either URL strings for convention-based REST endpoints, or custom async functions) and makes the store available to all descendant components via React context.++The store is created once on mount via `useState(() => createChatStore(config))`, so config changes after mount are not picked up.++### Hooks++The package exposes two primary hooks that select specific slices from the unified store:++- **`useThread()`** — Returns the current thread's messages, loading/running state, and actions to send/edit/delete messages.+- **`useThreadList()`** — Returns the list of threads, selection state, and actions to create/select/delete/update threads.++Both hooks use Zustand's `useShallow` for automatic shallow-equality memoization, preventing unnecessary re-renders. They also support an optional selector function for fine-grained subscriptions:++```tsx+// Only re-renders when messages change+const messages = useThread((s) => s.messages);++// Only re-renders when thread count changes+const count = useThreadList((s) => s.threads.length);+```++### Streaming++When `processMessage()` is called, the following pipeline executes:++1. An **optimistic user message** is appended to the store immediately.+2. If no thread is selected, one is created automatically (via `createThread` or `threadApiUrl`), or an `"ephemeral"` ID is used.+3. The message is sent to the backend via `fetch(apiUrl, ...)` or the custom `processMessage` function.+4. The response is piped through a **StreamProtocolAdapter** (default: AG-UI SSE format) which yields `AGUIEvent` objects.+5. **`processStreamedMessage()`** consumes these events and translates them into `createMessage`, `updateMessage`, and `deleteMessage` calls that update the Zustand store in real-time.++Supported event types:++- `TEXT_MESSAGE_START` — New assistant message begins+- `TEXT_MESSAGE_CONTENT` — Text delta appended to the current message+- `TEXT_MESSAGE_END` — Message streaming complete+- `TOOL_CALL_START` — A tool/function call begins+- `TOOL_CALL_ARGS` — Argument delta for a tool call+- `TOOL_CALL_END` — Tool call streaming complete+- `RUN_ERROR` — Error during the stream++### Message Formats++A `MessageFormat` is a bidirectional converter between the internal AG-UI message format and whatever format your backend expects. It has two methods:++- `toApi(messages)` — Converts outgoing messages (sent to your backend)+- `fromApi(data)` — Converts incoming messages (loaded from your backend/storage)++Built-in formats:+| Format | Use Case |+|--------|----------|+| `identityMessageFormat` | No conversion (default). Backend uses AG-UI format directly. |+| `openAIMessageFormat` | OpenAI Chat Completions API (`ChatCompletionMessageParam[]`) |+| `openAIConversationMessageFormat` | OpenAI Responses/Conversations API (`ResponseInputItem[]`) |++### Stream Protocol Adapters++A `StreamProtocolAdapter` parses a `Response` body into an `AsyncIterable<AGUIEvent>`. This decouples the streaming protocol from the business logic.++Built-in adapters:+| Adapter | Protocol |+|---------|----------|+| `agUIAdapter()` | AG-UI SSE format (default). Lines are `data: {JSON}\n` with `[DONE]` sentinel. |+| `openAIAdapter()` | OpenAI Chat Completions streaming format (`ChatCompletionChunk`). |+| `openAIResponsesAdapter()` | OpenAI Responses API streaming format (`ResponseStreamEvent`). |+| `openAIReadableStreamAdapter()` | OpenAI SDK's `Stream.toReadableStream()` NDJSON format (no SSE prefix). |++---++## Module Breakdown++### `v2/` — Zustand Store & Provider++This is the heart of the package. The "v2" designation indicates it's the current API, replacing an earlier hook-based approach.++| File | Purpose |+| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `createChatStore.ts` | Factory function that creates the unified Zustand store. Accepts config (URLs or custom functions) and returns a fully wired store with all thread list and thread actions. Contains default implementations for REST operations when `threadApiUrl` is provided. |+| `ChatProvider.tsx` | React component that wraps `createChatStore` in a context provider. Creates the store once on mount. |+| `ChatContext.ts` | React context definition + `useChatStore()` hook that retrieves the raw Zustand `StoreApi`. Throws if used outside `<ChatProvider>`. |+| `hooks.ts` | `useThread()` and `useThreadList()` — typed selector hooks that project the unified store into focused slices. Uses `useShallow` for memoization. |+| `types.ts` | All TypeScript types for the v2 API: `Thread`, `ThreadState`, `ThreadActions`, `ThreadListState`, `ThreadListActions`, `ChatStore`, `ChatProviderProps`. Also defines the discriminated union config types (`ThreadApiConfig`, `ChatApiConfig`). |++#### Store Internals++The store is a single flat Zustand store combining two logical slices:++**ThreadListSlice** manages the sidebar/thread list:++- `threads: Thread[]` — sorted by `createdAt` descending+- `isLoadingThreads` / `threadListError` / `hasMoreThreads` — loading state+- `selectedThreadId` — the active thread+- `_nextCursor` — internal pagination cursor+- Actions: `loadThreads`, `loadMoreThreads`, `switchToNewThread`, `createThread`, `selectThread`, `updateThread`, `deleteThread`++**ThreadSlice** manages the active conversation:++- `messages: Message[]` — the current thread's messages+- `isRunning` — whether a stream is in progress+- `isLoadingMessages` / `threadError` — loading state+- `_abortController` — internal abort controller for cancellation+- Actions: `processMessage`, `appendMessages`, `updateMessage`, `setMessages`, `deleteMessage`, `cancelMessage`++Key behaviors:++- **Optimistic updates**: `processMessage` appends the user message instantly before the network call.+- **Auto thread creation**: If no thread is selected when sending a message, the store auto-creates one (or uses `"ephemeral"` if no create function is configured).+- **Abort on switch**: `selectThread` and `switchToNewThread` cancel any in-flight stream via `AbortController`.+- **Deduplication**: `mergeThreadList` uses a `Map` keyed by `threadId` to merge paginated results without duplicates.+- **Pending state**: `deleteThread` and `updateThread` set `isPending: true` on the thread while the operation is in flight.++### `stream/` — Streaming Engine++| File | Purpose |+| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `processStreamedMessage.ts` | Core function that consumes an `AsyncIterable<AGUIEvent>` (from an adapter) and translates events into message CRUD operations. Manages a running `currentMessage` that accumulates text deltas and tool calls. |+| `adapters/ag-ui.ts` | Default adapter. Parses SSE lines (`data: {...}\n`) from a `Response` body and yields `AGUIEvent` objects. |+| `adapters/openai-completions.ts` | Parses OpenAI Chat Completions streaming chunks (`ChatCompletionChunk`) and translates them to AG-UI events. Handles content deltas, tool call start/args/end, and finish reasons. |+| `adapters/openai-responses.ts` | Parses OpenAI Responses API streaming events (`ResponseStreamEvent`) and translates them to AG-UI events. Handles output items, text deltas, function call arguments, and error events. |+| `adapters/openai-message-format.ts` | `MessageFormat` implementation for OpenAI Chat Completions. Bidirectional conversion between AG-UI `Message[]` and `ChatCompletionMessageParam[]`. Handles user (including multipart/image), assistant (including tool calls), tool, system, and developer messages. |+| `adapters/openai-conversation-message-format.ts` | `MessageFormat` implementation for OpenAI Responses/Conversations API. Converts AG-UI messages to `ResponseInputItem[]` (flattening assistant tool calls into sibling items) and converts `ConversationItem[]` back to AG-UI messages (grouping adjacent function_calls into assistant messages). |++### `types/` — Type Definitions++| File | Purpose |+| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `message.ts` | Re-exports all message types from `@ag-ui/core`: `Message`, `UserMessage`, `AssistantMessage`, `ToolMessage`, `SystemMessage`, `DeveloperMessage`, `ReasoningMessage`, `ActivityMessage`, `ToolCall`, `FunctionCall`, `InputContent`, `TextInputContent`, `BinaryInputContent`. Also defines `CreateMessage = Omit<UserMessage, "id">`. |+| `messageFormat.ts` | Defines the `MessageFormat` interface (`toApi`/`fromApi`) and the default `identityMessageFormat` (pass-through). |+| `stream.ts` | Defines the `StreamProtocolAdapter` interface (a `parse(response) → AsyncIterable<AGUIEvent>` contract). Re-exports `EventType` enum and `AGUIEvent` type from `@ag-ui/core`. |++### `hooks/` — Message Context++| File | Purpose |+| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `useMessage.tsx` | `MessageContext`, `MessageProvider`, and `useMessage` hook. Provides a React context for passing the current `Message` down to child components (used by `react-ui` when rendering individual messages). Uses `useShallow` for stable context values. |++---++## API Reference++### ChatProviderProps++The provider accepts a **discriminated union** config — you provide either URL strings or custom functions, but not both:++#### Thread API (choose one):++| Prop | Type | Description |+| ----------------- | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |+| `threadApiUrl` | `string` | Base URL for convention-based REST endpoints (`/get`, `/create`, `/delete/:id`, `/update/:id`, `/get/:id`) |+| **— or —** | | |+| `fetchThreadList` | `(cursor?) => Promise<{ threads, nextCursor? }>` | Custom function to load threads with pagination |+| `createThread` | `(firstMessage) => Promise<Thread>` | Custom function to create a thread |+| `deleteThread` | `(id) => Promise<void>` | Custom function to delete a thread |+| `updateThread` | `(thread) => Promise<Thread>` | Custom function to update a thread |+| `loadThread` | `(threadId) => Promise<Message[]>` | Custom function to load a thread's messages |++#### Chat API (choose one):++| Prop | Type | Description |+| ---------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |+| `apiUrl` | `string` | URL to POST messages to. Sends `{ threadId, messages }` and expects an SSE stream response. |+| **— or —** | | |+| `processMessage` | `({ threadId, messages, abortController }) => Promise<Response>` | Custom function to send messages. Must return a `Response` with a readable stream body. |++#### Optional:++| Prop | Type | Default | Description |+| ---------------- | ----------------------- | ----------------------- | ----------------------------------------------------- |+| `streamProtocol` | `StreamProtocolAdapter` | `agUIAdapter()` | How to parse the streaming response |+| `messageFormat` | `MessageFormat` | `identityMessageFormat` | How to convert messages to/from your backend's format |++### useThread++```tsx+function useThread(): ThreadState & ThreadActions;+function useThread<T>(selector: (state: ThreadState & ThreadActions) => T): T;+```++**State:**+| Field | Type | Description |+|-------|------|-------------|+| `messages` | `Message[]` | Messages in the current thread |+| `isRunning` | `boolean` | Whether a message is being streamed |+| `isLoadingMessages` | `boolean` | Whether messages are being loaded from the backend |+| `threadError` | `Error \| null` | Error from the last operation |++**Actions:**+| Method | Signature | Description |+|--------|-----------|-------------|+| `processMessage` | `(msg: CreateMessage) => Promise<void>` | Send a user message and stream the response |+| `appendMessages` | `(...msgs: Message[]) => void` | Append messages to the thread |+| `updateMessage` | `(msg: Message) => void` | Replace a message by ID |+| `setMessages` | `(msgs: Message[]) => void` | Replace all messages |+| `deleteMessage` | `(id: string) => void` | Remove a message by ID |+| `cancelMessage` | `() => void` | Abort the in-flight stream |++### useThreadList++```tsx+function useThreadList(): ThreadListState & ThreadListActions;+function useThreadList<T>(selector: (state: ThreadListState & ThreadListActions) => T): T;+```++**State:**+| Field | Type | Description |+|-------|------|-------------|+| `threads` | `Thread[]` | All loaded threads, sorted by `createdAt` desc |+| `isLoadingThreads` | `boolean` | Whether the thread list is loading |+| `threadListError` | `Error \| null` | Error from thread list operations |+| `selectedThreadId` | `string \| null` | Currently active thread ID |+| `hasMoreThreads` | `boolean` | Whether more pages are available |++**Actions:**+| Method | Signature | Description |+|--------|-----------|-------------|+| `loadThreads` | `() => void` | Fetch the first page of threads |+| `loadMoreThreads` | `() => void` | Fetch the next page (uses cursor) |+| `switchToNewThread` | `() => void` | Deselect current thread, clear messages |+| `createThread` | `(firstMessage: UserMessage) => Promise<Thread>` | Create a new thread |+| `selectThread` | `(threadId: string) => void` | Select a thread and load its messages |+| `updateThread` | `(thread: Thread) => void` | Update thread metadata (e.g., title) |+| `deleteThread` | `(threadId: string) => void` | Delete a thread |++### useMessage++```tsx+function useMessage(): { message: Message };+```++Returns the current message from `MessageContext`. Must be used inside a `<MessageProvider>`. This is primarily used by `@openuidev/react-ui` when rendering individual message components.++### processStreamedMessage++```tsx+function processStreamedMessage(params: {+ response: Response;+ createMessage: (msg: AssistantMessage) => void;+ updateMessage: (msg: AssistantMessage) => void;+ deleteMessage: (id: string) => void;+ adapter?: StreamProtocolAdapter;+}): Promise<AssistantMessage | void>;+```++Low-level utility that consumes an SSE response via the given adapter and calls the provided callbacks as the message is built up incrementally. Used internally by the store's `processMessage` action, but exported for advanced use cases.++### Stream Adapters++```tsx+import {+ agUIAdapter,+ openAIAdapter,+ openAIReadableStreamAdapter,+ openAIResponsesAdapter,+} from "@openuidev/react-headless";++// Use with ChatProvider+<ChatProvider streamProtocol={openAIAdapter()} apiUrl="/api/chat">+ ...+</ChatProvider>;+```++### Message Format Converters++```tsx+import {+ openAIMessageFormat,+ openAIConversationMessageFormat,+ identityMessageFormat,+} from "@openuidev/react-headless";++// For OpenAI Chat Completions backends+<ChatProvider messageFormat={openAIMessageFormat} streamProtocol={openAIAdapter()} apiUrl="/api/chat">+ ...+</ChatProvider>++// For OpenAI Responses API backends+<ChatProvider+ messageFormat={openAIConversationMessageFormat}+ streamProtocol={openAIResponsesAdapter()}+ apiUrl="/api/chat"+>+ ...+</ChatProvider>+```++---++## Type Reference++### Message Types (from `@ag-ui/core`)++| Type | Description |+| ------------------ | ---------------------------------------------------------- |+| `Message` | Union of all message types |+| `UserMessage` | User-sent message (text or multipart content with images) |+| `AssistantMessage` | LLM response (text content + optional tool calls) |+| `ToolMessage` | Tool/function result message |+| `SystemMessage` | System prompt message |+| `DeveloperMessage` | Developer instruction message |+| `ReasoningMessage` | Chain-of-thought reasoning |+| `ActivityMessage` | Status/activity indicator |+| `ToolCall` | A tool call within an assistant message |+| `FunctionCall` | The function name + arguments within a ToolCall |+| `CreateMessage` | `Omit<UserMessage, "id">` — used when sending new messages |++### Store Types++| Type | Description |+| ------------------- | ------------------------------------------------------------------------------------------------------------- |+| `Thread` | `{ threadId, title, createdAt, isPending? }` |+| `ThreadState` | `{ messages, isRunning, isLoadingMessages, threadError }` |+| `ThreadActions` | `{ processMessage, appendMessages, updateMessage, setMessages, deleteMessage, cancelMessage }` |+| `ThreadListState` | `{ threads, isLoadingThreads, threadListError, selectedThreadId, hasMoreThreads }` |+| `ThreadListActions` | `{ loadThreads, loadMoreThreads, switchToNewThread, createThread, selectThread, updateThread, deleteThread }` |+| `ChatStore` | `ThreadListState & ThreadListActions & ThreadState & ThreadActions` (plus internal fields) |+| `ChatProviderProps` | Configuration for `<ChatProvider>` |++### Adapter Types++| Type | Description |+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |+| `StreamProtocolAdapter` | `{ parse(response: Response): AsyncIterable<AGUIEvent> }` |+| `MessageFormat` | `{ toApi(msgs: Message[]): unknown; fromApi(data: unknown): Message[] }` |+| `AGUIEvent` | Event emitted by stream adapters (from `@ag-ui/core`) |+| `EventType` | Enum: `TEXT_MESSAGE_START`, `TEXT_MESSAGE_CONTENT`, `TEXT_MESSAGE_END`, `TOOL_CALL_START`, `TOOL_CALL_ARGS`, `TOOL_CALL_END`, `RUN_ERROR`, etc. |++---++## How It All Fits Together++1. **You wrap your app** in `<ChatProvider>` with your backend config.+2. **The provider creates a Zustand store** with all thread and message management baked in.+3. **Your UI components** call `useThread()` and `useThreadList()` to read state and dispatch actions.+4. **When a user sends a message**, `processMessage()`:+ - Appends an optimistic user message+ - Auto-creates a thread if needed+ - Sends the request to your backend+ - Streams the response through the adapter pipeline+ - Updates the store in real-time as tokens arrive+5. **The `MessageFormat` layer** handles serialization differences between AG-UI's internal format and your backend (OpenAI Completions, Responses API, or custom).+6. **The `StreamProtocolAdapter` layer** handles parsing differences between SSE protocols.+7. **Everything is cancellable** via `AbortController` — switching threads or calling `cancelMessage()` cleanly aborts in-flight streams.+=======## Install```bash@@ -9,5 +510,6 @@ pnpm add @openuidev/react-headless```## Docs+>>>>>>> mainDetailed documentation is available at [openui.com](https://openui.com).diff --git a/packages/react-headless/package.json b/packages/react-headless/package.jsonindex b91f95703..3a65c63e1 100644--- a/packages/react-headless/package.json+++ b/packages/react-headless/package.json@@ -20,14 +20,12 @@"ci": "pnpm run lint:check && pnpm run format:check"},"peerDependencies": {- "eventsource-parser": "^3.0.0",- "react": ">=17.0.0",- "react-dom": ">=17.0.0",- "tiny-invariant": "^1.3.3",+ "react": ">=19.0.0",+ "react-dom": ">=19.0.0","zustand": "^4.5.5"},"devDependencies": {- "@types/react": ">=17.0.0",+ "@types/react": ">=19.0.0","openai": "^6.22.0","vitest": "^4.0.18"},@@ -47,7 +45,6 @@"directory": "js/packages/react-headless"},"dependencies": {- "@ag-ui/core": "^0.0.45",- "zod": "^3.24.1"+ "@ag-ui/core": "^0.0.45"}}diff --git a/packages/react-headless/src/v2/hooks.ts b/packages/react-headless/src/hooks/useThread.tssimilarity index 96%rename from packages/react-headless/src/v2/hooks.tsrename to packages/react-headless/src/hooks/useThread.tsindex 4a4893bda..68dfc6b59 100644--- a/packages/react-headless/src/v2/hooks.ts+++ b/packages/react-headless/src/hooks/useThread.ts@@ -1,13 +1,13 @@import { useStore } from "zustand";import { useShallow } from "zustand/react/shallow";-import { useChatStore } from "./ChatContext";+import { useChatStore } from "../store/ChatContext";import type {ChatStore,ThreadActions,ThreadListActions,ThreadListState,ThreadState,-} from "./types";+} from "../store/types";type ThreadSlice = ThreadState & ThreadActions;type ThreadListSlice = ThreadListState & ThreadListActions;diff --git a/packages/react-headless/src/index.ts b/packages/react-headless/src/index.tsindex 7d815f924..ddacb1ba4 100644--- a/packages/react-headless/src/index.ts+++ b/packages/react-headless/src/index.ts@@ -1,15 +1,14 @@-export { ChatProvider } from "./v2/ChatProvider";-export { useThread, useThreadList } from "./v2/hooks";-export { MessageContext, MessageProvider, useMessage } from "./hooks/useMessage";+export { useThread, useThreadList } from "./hooks/useThread";++export { ChatProvider } from "./store/ChatProvider";export {agUIAdapter,openAIAdapter,- openAIConversationMessageFormat,- openAIMessageFormat,openAIReadableStreamAdapter,openAIResponsesAdapter,} from "./stream/adapters";+export { openAIConversationMessageFormat, openAIMessageFormat } from "./stream/formats";export { processStreamedMessage } from "./stream/processStreamedMessage";export type {@@ -21,7 +20,7 @@ export type {ThreadListActions,ThreadListState,ThreadState,-} from "./v2/types";+} from "./store/types";export type {ActivityMessage,diff --git a/packages/react-headless/src/polyfills/index.ts b/packages/react-headless/src/polyfills/index.tsdeleted file mode 100644index 36e941af1..000000000--- a/packages/react-headless/src/polyfills/index.ts+++ /dev/null@@ -1,2 +0,0 @@-// Export polyfills for React 17 compatibility-export { useId } from "./react-17";diff --git a/packages/react-headless/src/polyfills/react-17.ts b/packages/react-headless/src/polyfills/react-17.tsdeleted file mode 100644index a5338cd61..000000000--- a/packages/react-headless/src/polyfills/react-17.ts+++ /dev/null@@ -1,15 +0,0 @@-import { useRef } from "react";--// Polyfill for useId (React 18+)-let globalIdCounter = 0;--export function useId(): string {- const idRef = useRef<string>(null);- if (!idRef.current) {- idRef.current = `uid-${++globalIdCounter}`;- }- return idRef.current;-}--// Type compatibility-export type { ReactElement, ReactNode } from "react";diff --git a/packages/react-headless/src/v2/ChatContext.ts b/packages/react-headless/src/store/ChatContext.tssimilarity index 100%rename from packages/react-headless/src/v2/ChatContext.tsrename to packages/react-headless/src/store/ChatContext.tsdiff --git a/packages/react-headless/src/v2/ChatProvider.tsx b/packages/react-headless/src/store/ChatProvider.tsxsimilarity index 100%rename from packages/react-headless/src/v2/ChatProvider.tsxrename to packages/react-headless/src/store/ChatProvider.tsxdiff --git a/packages/react-headless/src/v2/__tests__/createChatStore.test.ts b/packages/react-headless/src/store/__tests__/createChatStore.test.tssimilarity index 100%rename from packages/react-headless/src/v2/__tests__/createChatStore.test.tsrename to packages/react-headless/src/store/__tests__/createChatStore.test.tsdiff --git a/packages/react-headless/src/v2/createChatStore.ts b/packages/react-headless/src/store/createChatStore.tssimilarity index 100%rename from packages/react-headless/src/v2/createChatStore.tsrename to packages/react-headless/src/store/createChatStore.tsdiff --git a/packages/react-headless/src/v2/types.ts b/packages/react-headless/src/store/types.tssimilarity index 100%rename from packages/react-headless/src/v2/types.tsrename to packages/react-headless/src/store/types.tsdiff --git a/packages/react-headless/src/stream/adapters/index.ts b/packages/react-headless/src/stream/adapters/index.tsindex 0c5934197..a3e2e4d74 100644--- a/packages/react-headless/src/stream/adapters/index.ts+++ b/packages/react-headless/src/stream/adapters/index.ts@@ -1,6 +1,4 @@export * from "./ag-ui";export * from "./openai-completions";-export * from "./openai-conversation-message-format";-export * from "./openai-message-format";export * from "./openai-readable-stream";export * from "./openai-responses";diff --git a/packages/react-headless/src/stream/formats/index.ts b/packages/react-headless/src/stream/formats/index.tsnew file mode 100644index 000000000..ed4cdd377--- /dev/null+++ b/packages/react-headless/src/stream/formats/index.ts@@ -0,0 +1,2 @@+export * from "./openai-conversation-message-format";+export * from "./openai-message-format";diff --git a/packages/react-headless/src/stream/adapters/openai-conversation-message-format.ts b/packages/react-headless/src/stream/formats/openai-conversation-message-format.tssimilarity index 100%rename from packages/react-headless/src/stream/adapters/openai-conversation-message-format.tsrename to packages/react-headless/src/stream/formats/openai-conversation-message-format.tsdiff --git a/packages/react-headless/src/stream/adapters/openai-message-format.ts b/packages/react-headless/src/stream/formats/openai-message-format.tssimilarity index 100%rename from packages/react-headless/src/stream/adapters/openai-message-format.tsrename to packages/react-headless/src/stream/formats/openai-message-format.tsdiff --git a/packages/react-headless/src/types/chatManager.ts b/packages/react-headless/src/types/chatManager.tsdeleted file mode 100644index a6fa71950..000000000--- a/packages/react-headless/src/types/chatManager.ts+++ /dev/null@@ -1,118 +0,0 @@-import { CreateMessage, Message, UserMessage } from "./message";--/**- * Represents a chat thread- *- * @category Types- */-export type Thread = {- /** Unique identifier for the thread */- id: string;- /** Title of the thread */- title: string;- /** Creation timestamp */- createdAt: string | number;- /** Indicates if the thread is currently processing */- isRunning?: boolean;-};--/**- * Actions available for managing the state of a thread- *- * @category Types- */-export type ThreadActions = {- /** Calls the `processMessage` method of the `ThreadManager` to process a new user message and request a response from the agent. If- * the `useThreadManager` hook was used to create a `ThreadManager`, this method is the same one as the `processMessage` method provided to the hook.- */- processMessage: (message: CreateMessage) => Promise<void>;- /** Appends a new message to the thread */- appendMessages: (...messages: Message[]) => void;- /** Updates a message in the thread */- updateMessage: (message: Message, shouldTriggerCallback?: boolean) => void;- /** Cancels the current message processing */- onCancel: () => void;- /** Sets the messages in the thread */- setMessages: (messages: Message[]) => void;- /** Deletes a message from the thread */- deleteMessage: (messageId: string) => void;-};--/**- * Represents the state of a thread- *- * @category Types- */-export type ThreadState = {- /** Indicates if the thread is currently processing and controls should be disabled */- isRunning?: boolean | undefined;- /** Indicates if the messages are currently loading */- isLoadingMessages: boolean | undefined;- /** The messages in the thread */- messages: Message[];- /** The error that occurred during the last message processing */- error: Error | null | undefined;- /** Indicates if the thread manager is initialized and the thread can show threadList or welcome screen */- isInitialized: boolean;-};--/**- * @category Types- */-export type ThreadManager = ThreadState & ThreadActions;--/**- * Represents the state of the thread list- *- * @category Types- */-export type ThreadListState = {- /** The list of threads */- threads: Thread[];- /** Indicates if the thread list is currently loading */- isLoading: boolean;- /** The error that occurred while fetching the thread list */- error: Error | null | undefined;- /** The id of the selected / active thread */- selectedThreadId: string | null;- /** Indicates if the thread state should be reset when the selected thread changes. This helps clear and update the list of messages on the screen when switching- * between threads. */- shouldResetThreadState: boolean;-};--/**- * Actions available for managing the state of a thread list- *- * @category Types- */-export type ThreadListActions = {- /** Loads the thread list */- load: () => void;- /** Clears the thread state so that the user can start a new thread */- switchToNewThread: () => void;- /** Creates a new thread with given `firstMessage` as the user message */- createThread: (firstMessage: UserMessage) => Promise<Thread>;- /** Selects a thread */- selectThread: (threadId: string, shouldResetThreadState?: boolean) => void;- /** Updates a thread */- updateThread: (thread: Thread) => void;- /** Deletes a thread */- deleteThread: (threadId: string) => void;-};--/**- * @category Types- */-export type ThreadListManager = ThreadListState & ThreadListActions;--/**- * Main chat manager combining thread and thread list management- *- * @category Types- */-export type ChatManager = {- /** The thread list manager, a combination of thread list state and actions */- threadListManager: ThreadListManager;- /** The thread manager, a combination of thread state and actions */- threadManager: ThreadManager;-};diff --git a/packages/react-headless/src/types/index.ts b/packages/react-headless/src/types/index.tsindex 8e2bf1cd2..8743c0bd8 100644--- a/packages/react-headless/src/types/index.ts+++ b/packages/react-headless/src/types/index.ts@@ -1,4 +1,3 @@-export * from "./chatManager";export * from "./message";export * from "./messageFormat";export * from "./stream";diff --git a/packages/react-headless/src/types/message.ts b/packages/react-headless/src/types/message.tsindex 692681a55..2458172cf 100644--- a/packages/react-headless/src/types/message.ts+++ b/packages/react-headless/src/types/message.ts@@ -13,6 +13,3 @@ export type {ToolMessage,UserMessage,} from "@ag-ui/core";--import type { UserMessage } from "@ag-ui/core";-export type CreateMessage = Omit<UserMessage, "id">;diff --git a/packages/react-headless/src/v2/index.ts b/packages/react-headless/src/v2/index.tsdeleted file mode 100644index cc2bb9fd0..000000000--- a/packages/react-headless/src/v2/index.ts+++ /dev/null@@ -1,14 +0,0 @@-export { ChatProvider } from "./ChatProvider";-export { useThread, useThreadList } from "./hooks";-export type {- ChatProviderProps,- ChatStore,- CreateMessage,- Message,- Thread,- ThreadActions,- ThreadListActions,- ThreadListState,- ThreadState,- UserMessage,-} from "./types";diff --git a/packages/react-ui/package.json b/packages/react-ui/package.jsonindex 86e76a0a7..69f2e91d5 100644--- a/packages/react-ui/package.json+++ b/packages/react-ui/package.json@@ -61,8 +61,8 @@"peerDependencies": {"@openuidev/lang-react": "workspace:^","@openuidev/react-headless": "workspace:^",- "react": ">=18.0.0",- "react-dom": ">=18.0.0",+ "react": ">=19.0.0",+ "react-dom": ">=19.0.0","zustand": "^4.5.5"},"dependencies": {diff --git a/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsx b/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsxindex cf50d08a0..d93e92fbb 100644--- a/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsx+++ b/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsx@@ -1,8 +1,7 @@import clsx from "clsx";-import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";import { Area, AreaChart as RechartsAreaChart, XAxis, YAxis } from "recharts";import { usePrintContext } from "../../../context/PrintContext";-import { useId } from "../../../polyfills";import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";import {diff --git a/packages/react-ui/src/components/Charts/AreaChartCondensed/AreaChartCondensed.tsx b/packages/react-ui/src/components/Charts/AreaChartCondensed/AreaChartCondensed.tsxindex 8f68390ab..ea3f13eda 100644--- a/packages/react-ui/src/components/Charts/AreaChartCondensed/AreaChartCondensed.tsx+++ b/packages/react-ui/src/components/Charts/AreaChartCondensed/AreaChartCondensed.tsx@@ -1,8 +1,7 @@import clsx from "clsx";-import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";import { Area, AreaChart as RechartsAreaChart, XAxis, YAxis } from "recharts";import { usePrintContext } from "../../../context/PrintContext";-import { useId } from "../../../polyfills";import { AreaChartData, AreaChartVariant } from "../AreaChart/types";import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";import { DEFAULT_X_AXIS_HEIGHT, X_AXIS_PADDING } from "../constants";diff --git a/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx b/packages/react-ui/src/components/Charts/BarChart/BarChart.tsxindex 923bbc8a5..cd6225040 100644--- a/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx+++ b/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx@@ -1,8 +1,7 @@import clsx from "clsx";-import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";import { Bar, BarChart as RechartsBarChart, XAxis, YAxis } from "recharts";import { usePrintContext } from "../../../context/PrintContext";-import { useId } from "../../../polyfills";import { useTheme } from "../../ThemeProvider";import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";diff --git a/packages/react-ui/src/components/Charts/BarChartCondensed/BarChartCondensed.tsx b/packages/react-ui/src/components/Charts/BarChartCondensed/BarChartCondensed.tsxindex b75fd0ff9..4f5089cba 100644--- a/packages/react-ui/src/components/Charts/BarChartCondensed/BarChartCondensed.tsx+++ b/packages/react-ui/src/components/Charts/BarChartCondensed/BarChartCondensed.tsx@@ -1,8 +1,7 @@import clsx from "clsx";-import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";import { Bar, BarChart as RechartsBarChart, XAxis, YAxis } from "recharts";import { usePrintContext } from "../../../context/PrintContext";-import { useId } from "../../../polyfills";import { useTheme } from "../../ThemeProvider";import { BarChartData, BarChartVariant } from "../BarChart/types";import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";diff --git a/packages/react-ui/src/components/Charts/Charts.tsx b/packages/react-ui/src/components/Charts/Charts.tsxindex 13b71d304..fcba12f0b 100644--- a/packages/react-ui/src/components/Charts/Charts.tsx+++ b/packages/react-ui/src/components/Charts/Charts.tsx@@ -1,8 +1,7 @@import clsx from "clsx";import { uniqueId } from "lodash-es";-import { ComponentProps, createContext, forwardRef, useContext, useMemo } from "react";+import { ComponentProps, createContext, forwardRef, useContext, useId, useMemo } from "react";import * as RechartsPrimitive from "recharts";-import { useId } from "../../polyfills";import { useTheme } from "../ThemeProvider";/**diff --git a/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx b/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsxindex 9e8c46814..568279e19 100644--- a/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx+++ b/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx@@ -1,8 +1,7 @@import clsx from "clsx";-import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";import { Bar, BarChart as RechartsBarChart, XAxis, YAxis } from "recharts";import { usePrintContext } from "../../../context/PrintContext";-import { useId } from "../../../polyfills";import { useTheme } from "../../ThemeProvider";import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";diff --git a/packages/react-ui/src/components/Charts/LineChart/LineChart.tsx b/packages/react-ui/src/components/Charts/LineChart/LineChart.tsxindex f3c536209..292dc584c 100644--- a/packages/react-ui/src/components/Charts/LineChart/LineChart.tsx+++ b/packages/react-ui/src/components/Charts/LineChart/LineChart.tsx@@ -1,8 +1,7 @@import clsx from "clsx";-import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";import { Line, LineChart as RechartsLineChart, XAxis, YAxis } from "recharts";import { usePrintContext } from "../../../context/PrintContext";-import { useId } from "../../../polyfills";import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";import {diff --git a/packages/react-ui/src/components/Charts/LineChartCondensed/LineChartCondensed.tsx b/packages/react-ui/src/components/Charts/LineChartCondensed/LineChartCondensed.tsxindex 4df6d5b39..33fdbfb8e 100644--- a/packages/react-ui/src/components/Charts/LineChartCondensed/LineChartCondensed.tsx+++ b/packages/react-ui/src/components/Charts/LineChartCondensed/LineChartCondensed.tsx@@ -1,8 +1,7 @@import clsx from "clsx";-import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";import { Line, LineChart as RechartsLineChart, XAxis, YAxis } from "recharts";import { usePrintContext } from "../../../context/PrintContext";-import { useId } from "../../../polyfills";import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";import { DEFAULT_X_AXIS_HEIGHT, X_AXIS_PADDING } from "../constants";import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";diff --git a/packages/react-ui/src/components/Charts/MiniAreaChart/MiniAreaChart.tsx b/packages/react-ui/src/components/Charts/MiniAreaChart/MiniAreaChart.tsxindex ca00e2f55..7168615ec 100644--- a/packages/react-ui/src/components/Charts/MiniAreaChart/MiniAreaChart.tsx+++ b/packages/react-ui/src/components/Charts/MiniAreaChart/MiniAreaChart.tsx@@ -1,8 +1,7 @@import clsx from "clsx";-import { useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useId, useMemo, useRef, useState } from "react";import { Area, AreaChart as RechartsAreaChart, XAxis } from "recharts";import { usePrintContext } from "../../../context/PrintContext";-import { useId } from "../../../polyfills";import { AreaChartVariant } from "../AreaChart/types";import { ChartConfig, ChartContainer } from "../Charts";import {diff --git a/packages/react-ui/src/components/Charts/ScatterChart/ScatterChart.tsx b/packages/react-ui/src/components/Charts/ScatterChart/ScatterChart.tsxindex d3cddf34c..45906506b 100644--- a/packages/react-ui/src/components/Charts/ScatterChart/ScatterChart.tsx+++ b/packages/react-ui/src/components/Charts/ScatterChart/ScatterChart.tsx@@ -1,8 +1,7 @@import clsx from "clsx";-import React, { useEffect, useMemo, useRef, useState } from "react";+import React, { useEffect, useId, useMemo, useRef, useState } from "react";import { Cell, ScatterChart as RechartsScatterChart, Scatter, XAxis, YAxis } from "recharts";import { usePrintContext } from "../../../context/PrintContext";-import { useId } from "../../../polyfills";import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";import { useExportChartData, useYAxisLabelWidth } from "../hooks";diff --git a/packages/react-ui/src/components/CheckBoxItem/CheckBoxItem.tsx b/packages/react-ui/src/components/CheckBoxItem/CheckBoxItem.tsxindex 931fc50a8..1ad24b644 100644--- a/packages/react-ui/src/components/CheckBoxItem/CheckBoxItem.tsx+++ b/packages/react-ui/src/components/CheckBoxItem/CheckBoxItem.tsx@@ -1,7 +1,6 @@import * as Checkbox from "@radix-ui/react-checkbox";import clsx from "clsx";-import { CSSProperties, forwardRef, ReactNode } from "react";-import { useId } from "../../polyfills";+import { CSSProperties, forwardRef, ReactNode, useId } from "react";export interface CheckBoxItemProps {label?: ReactNode;diff --git a/packages/react-ui/src/components/RadioItem/RadioItem.tsx b/packages/react-ui/src/components/RadioItem/RadioItem.tsxindex 3ffc183ba..366dee142 100644--- a/packages/react-ui/src/components/RadioItem/RadioItem.tsx+++ b/packages/react-ui/src/components/RadioItem/RadioItem.tsx@@ -1,7 +1,6 @@import * as Radio from "@radix-ui/react-radio-group";import clsx from "clsx";-import { CSSProperties, forwardRef, ReactNode } from "react";-import { useId } from "../../polyfills";+import { CSSProperties, forwardRef, ReactNode, useId } from "react";export interface RadioItemProps {label?: ReactNode;diff --git a/packages/react-ui/src/components/SwitchItem/SwitchItem.tsx b/packages/react-ui/src/components/SwitchItem/SwitchItem.tsxindex 553536b6e..d14cd4793 100644--- a/packages/react-ui/src/components/SwitchItem/SwitchItem.tsx+++ b/packages/react-ui/src/components/SwitchItem/SwitchItem.tsx@@ -1,7 +1,6 @@import * as Switch from "@radix-ui/react-switch";import clsx from "clsx";-import { CSSProperties, forwardRef, ReactNode } from "react";-import { useId } from "../../polyfills";+import { CSSProperties, forwardRef, ReactNode, useId } from "react";interface SwitchItemProps {label?: ReactNode;diff --git a/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx b/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsxindex f8588beb3..1949046ce 100644--- a/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx+++ b/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx@@ -1,4 +1,4 @@-import React, { createContext, useContext, useId, useInsertionEffect, useMemo } from "react"; // eslint-disable-line no-restricted-imports+import React, { createContext, useContext, useId, useInsertionEffect, useMemo } from "react";import { defaultDarkTheme, defaultLightTheme } from "./defaultTheme";import { Theme, ThemeMode } from "./types";import { themeToCssVars } from "./utils";diff --git a/packages/react-ui/src/polyfills/index.ts b/packages/react-ui/src/polyfills/index.tsdeleted file mode 100644index 36e941af1..000000000--- a/packages/react-ui/src/polyfills/index.ts+++ /dev/null@@ -1,2 +0,0 @@-// Export polyfills for React 17 compatibility-export { useId } from "./react-17";diff --git a/packages/react-ui/src/polyfills/react-17.ts b/packages/react-ui/src/polyfills/react-17.tsdeleted file mode 100644index da60cf5d7..000000000--- a/packages/react-ui/src/polyfills/react-17.ts+++ /dev/null@@ -1,12 +0,0 @@-import { useRef } from "react";--// Polyfill for useId (React 18+)-let globalIdCounter = 0;--export function useId(): string {- const idRef = useRef<string>(null);- if (!idRef.current) {- idRef.current = `uid-${++globalIdCounter}`;- }- return idRef.current;-}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 242576e15..88e73c820 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -198,7 +198,7 @@ importers:packages/lang-react:dependencies:react:- specifier: '>=18.0.0'+ specifier: '>=19.0.0'version: 19.2.4zod:specifier: ^4.0.0@@ -213,31 +213,22 @@ importers:'@ag-ui/core':specifier: ^0.0.45version: 0.0.45- eventsource-parser:- specifier: ^3.0.0- version: 3.0.2react:- specifier: '>=17.0.0'+ specifier: '>=19.0.0'version: 19.2.4react-dom:- specifier: '>=17.0.0'+ specifier: '>=19.0.0'version: 19.2.4([email protected])- tiny-invariant:- specifier: ^1.3.3- version: 1.3.3- zod:- specifier: ^3.24.1- version: 3.25.67zustand:specifier: ^4.5.5version: 4.5.7(@types/[email protected])([email protected])devDependencies:'@types/react':- specifier: '>=17.0.0'+ specifier: '>=19.0.0'version: 19.2.14openai:specifier: ^6.22.0- version: 6.22.0([email protected])([email protected])+ version: 6.22.0([email protected])([email protected])vitest:specifier: ^4.0.18version: 4.0.18(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -305,13 +296,13 @@ importers:specifier: ^0.562.0version: 0.562.0([email protected])react:- specifier: '>=18.0.0'+ specifier: '>=19.0.0'version: 19.2.4react-day-picker:specifier: ^9.5.1version: 9.7.0([email protected])react-dom:- specifier: '>=18.0.0'+ specifier: '>=19.0.0'version: 19.2.4([email protected])react-markdown:specifier: ^10.1.0@@ -4201,10 +4192,6 @@ packages:resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}engines: {node: '>=0.8.x'}- resolution: {integrity: sha512-6RxOBZ/cYgd8usLwsEl+EC09Au/9BcmCKYF2/xbml6DNczf7nv0MQb+7BA2F+li6//I+28VNlQR37XfQtcAJuA==}- engines: {node: '>=18.0.0'}-resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}engines: {node: '>=12.0.0'}@@ -10686,8 +10673,6 @@ snapshots:- [email protected]: {}-@@ -12240,11 +12225,6 @@ snapshots:is-docker: 2.2.1is-wsl: 2.2.0- optionalDependencies:- ws: 8.18.2- zod: 3.25.67-optionalDependencies:ws: 8.18.2