React and Helpers Packages
Overview
packages/react publishes headless React 19 primitives under @shadcn/react. Its package export map in packages/…/package.json exposes two client UI entry points: @shadcn/react/message-scroller from packages/…/index.ts and @shadcn/react/questionnaire from packages/…/index.ts. packages/…/index.ts is not exported as a package entry; it is the local polymorphic-render helper used by those primitives. packages/…/tsup.config.ts builds only the two public entries and then prepends "use client" on the published React entry files. If a new React client entry is added but not listed in CLIENT_UI_ENTRIES, importing that entry from an RSC app can fail because the built module will not be marked as a client boundary.
The message scroller public surface is assembled in packages/…/index.ts as a MessageScroller namespace with Provider, Root, Viewport, Content, Item, and Button, plus the flat hooks useMessageScroller, useMessageScrollerScrollable, and useMessageScrollerVisibility. The implementation in packages/…/components.tsx renders plain div/button elements and stores all behavior in React context created by MessageScroller.Provider. MessageScroller.Viewport is the scrollable element; it marks wheel, touch, and keyboard scroll keys as user intent, syncs state on native scroll, and installs a ResizeObserver for viewport resizes. MessageScroller.Content defaults to role="log" and aria-relevant="additions", registers the message list element, watches child mutations, observes content resize, and appends an internal hidden tail spacer used when anchoring streamed turns. MessageScroller.Item registers a stable messageId and data-scroll-anchor row; MessageScroller.Button uses useRender so consumers can replace the rendered button while preserving click behavior and data-active/data-direction state attributes.
Most scroller policy lives in packages/…/use-message-scroller-controller.ts. It creates external stores from packages/…/stores.ts for useSyncExternalStore subscribers, coalesces scrollability and visibility updates with requestAnimationFrame, and tracks scroll modes (following-bottom, free-scrolling, anchored-to-message, settling-jump) in refs from packages/…/use-message-scroller-refs.ts. The controller applies defaultScrollPosition once on the first non-empty render, preserves the first visible row across prepends, auto-follows the bottom when autoScroll remains armed, scrolls newly appended scrollAnchor rows to the reading line, and lazily starts visibility tracking only when useMessageScrollerVisibility has subscribers. Geometry and edge detection are factored into packages/…/geometry.ts; it computes scrollability, visible ids, current anchor id, element-aligned scroll positions, padding, flex gap, and spacer height using live DOM rects. Imperative commands are in packages/…/use-message-scroller-commands.ts, where scrollToStart, scrollToEnd, and scrollToMessage clear or reserve the tail spacer, queue missing-message jumps, set data-autoscrolling, and return false when the viewport or target is unavailable.
The questionnaire public surface is assembled in packages/…/index.ts as a Questionnaire namespace with Root, Progress, Item, Title, Description, Choices, Choice, ChoiceInput, ChoiceLabel, ChoiceShortcut, Input, Error, Previous, Skip, Next, and Submit. Questionnaire.Root in packages/…/components.tsx renders a native form by default and delegates state to packages/…/use-questionnaire-root.ts; answers are meant to be read from FormData at submit time. The root supports uncontrolled defaultItem, controlled item/onItemChange, optional items definitions for SSR and deterministic collection ordering, optional letter/number shortcuts, native validation when noValidate={false}, and keyboard navigation (Meta/Ctrl+Enter, arrows, Enter, and answer shortcuts). packages/…/collection.ts turns Root.items into enabled-item and choice maps and emits development warnings when definitions diverge from rendered Questionnaire.Item and Questionnaire.Choice nodes.
Questionnaire.Item is a fieldset-like step managed by packages/…/use-questionnaire-item.ts. It registers itself with the root, orders answer controls by DOM position, derives status (unanswered, answered, skipped), tracks validation attempts, collects description and error ids for aria-describedby, and exposes focus, reset, skip, validate, shortcut lookup, and answer-focus movement to the root. Questionnaire.Choice/ChoiceInput use packages/…/use-questionnaire-choice.ts to create radio or checkbox inputs depending on the item multiple flag, support controlled and uncontrolled checked state, clear the name when an item is skipped, and assign shortcut labels from either Root.items choice order or rendered answer order. Questionnaire.Input uses packages/…/use-questionnaire-input.ts as a freeform answer: it only contributes the item name when filled and selected, uses form="" while unselected so inactive values do not submit, and tracks controlled or uncontrolled filled state. packages/…/utils.ts owns shortcut keys, input-filled checks, text-entry detection, and DOM-order comparison.
packages/…/index.ts gives React primitives a shared render prop contract. With no render, it creates the default tag; with a render function, it passes merged props and state; with a React element, it clones the element after merging primitive props with user props. mergeProps concatenates className, shallow-merges style, composes refs, and composes event handlers so the user handler runs first and the primitive handler runs only if the event was not prevented. State becomes data-* attributes by default, with per-component overrides such as questionnaire data-active and message scroller button data-active="true|false".
packages/helpers publishes @shadcn/helpers for scripted AI/chat fixtures. Its export map in packages/…/package.json exposes @shadcn/helpers/ai-sdk from packages/…/index.ts and @shadcn/helpers/tanstack-ai from packages/…/index.ts; packages/…/tsup.config.ts builds only those two ESM entries. The shared core in packages/…/index.ts is package-internal to those adapters but is the behavioral center: packages/…/chat.ts implements createChatRuntime, packages/…/writer.ts implements the fluent assistant writer DSL, packages/…/lower.ts lowers event logs to neutral stream chunks, packages/…/stream.ts plays chunks through a ReadableStream, and packages/…/types.ts defines the framework-neutral chat event, part payload, tool, metadata, and adapter contracts.
createChatRuntime in packages/…/chat.ts is adapter-driven: callers provide a ChatFormat with methods to materialize parts, parse parts back to events, create/read messages, summarize tool calls, and build the framework transport. The returned chat chains .user(), .assistant(), .error(), and .sleep(), then reads deterministic snapshots with .get(), proposes the next configured user message with .next(messages), or streams assistant responses through .transport(). It uses packages/…/ids.ts for deterministic msg-*, call-*, source-*, and approval-* sequences and packages/…/payloads.ts for stable default file/source/custom payloads and fixed-clock metadata (2026-01-01T00:00:00.000Z unless overridden). Messages and explicit parts are cloned through structuredClone in packages/…/utils.ts so consumers cannot mutate scripted state after reading it.
The writer in packages/…/writer.ts appends ordered ChatEvents. writer.text() and writer.reasoning() create streamable text/reasoning parts; writer.sleep() inserts after-start delays; writer.data() creates typed data-* events; writer.sourceUrl(), sourceDocument(), file(), reasoningFile(), and custom() use default payload factories; writer.tool() writes a tool input and returns a handle for latency, output, error, or denial. A tool with needsApproval writes a tool-approval-request instead of resolving immediately; its scripted output or errorText is held server-side until a continuation turn sees an approval response in the live transcript. packages/…/lower.ts converts the event log to a neutral stream with leading before-start sleeps before the start chunk, word-plus-whitespace deltas by default, instant mode for static parts, direct chunks for data/tools/files/sources/custom events, and an early close for error events. packages/…/stream.ts encodes those neutral chunks into framework chunks, honors abort signals, and emits an abort chunk only if the stream had already started.
Human-in-the-loop behavior is resolved in packages/…/chat.ts. An assistant callback scripted after a paused assistant turn becomes a continuation rather than an eagerly materialized message. At transport time, materializeDeferredTurn reads pending tool inputs from the previous assistant events, asks the adapter's getToolCalls to inspect the live transcript, inserts a step-start, applies approved/denied approval outcomes, and invokes the callback with toolCall, toolCalls, messages, and a writer. get() deliberately stops before unresolved continuation turns because they require a live transcript, while .transport({ fallback }) can synthesize a response when the transcript has consumed every configured assistant turn.
The AI SDK adapter in packages/…/chat.ts exports createChat, AiSdkChat, and CreateChatOptions; the source file also exports yieldMessageParts and streamMessageParts, but these helpers are not re-exported from packages/…/index.ts. createChat wraps createChatRuntime with createAiSdkFormat from packages/…/format.ts, preserving the generic UIMessage metadata, data-parts, and tools types. packages/…/parts.ts maps neutral events to AI SDK UI message parts: text/reasoning become done parts, data parts reconcile by type + id unless transient, typed tools become tool-<name>, dynamic tools become dynamic-tool, approval/output/error/denial update the matching tool part, and source/file/custom/step parts are preserved. The AI SDK transport's sendMessages resolves the next configured assistant turn, uses messageId only for regenerate triggers, returns a ChatTransport stream of AI SDK chunks, and throws No assistant response found for this transcript. when no turn or fallback exists.
The TanStack AI adapter in packages/…/chat.ts exports createChat, CreateChatOptions, TanStackChat, and TanStack-specific writer/tool metadata types. It wraps createChatRuntime with createTanStackFormat from packages/…/format.ts and returns a ConnectConnectionAdapter for useChat({ connection }). packages/…/types.ts narrows the writer to operations AG-UI can represent end-to-end: text, reasoning, sleep, error, and declared tools; it intentionally omits data, source, file, custom, approval, and title/provider-metadata features from the public TanStack writer type. packages/…/parts.ts maps neutral text to TanStack text, reasoning to thinking, tools to tool-call plus tool-result, file payloads to image/audio/video/document URL parts, and skips neutral data/source/custom/step/approval events because TanStack message parts do not preserve them. createRunEncoder in packages/…/format.ts streams neutral chunks as AG-UI events using threadId and runId from runContext when present; unsupported chunks encode to null, and streamToAsyncIterable wraps the ReadableStream with a reader because Safari may not support native stream async iteration.
Testing is split by package and environment. packages/…/vitest.config.ts runs jsdom/unit tests while excluding *.browser.test.*; packages/…/vitest.browser.config.ts runs Chromium Playwright browser tests with setup from packages/…/vitest.browser.setup.ts. The scroller has extensive DOM-geometry stubbing in packages/…/message-scroller.test.tsx, pure geometry coverage in packages/…/geometry.test.ts, and browser/performance coverage in packages/…/message-scroller.browser.test.tsx and packages/…/message-scroller.perf.browser.test.tsx for behavior jsdom cannot model, such as native scroll anchoring. Questionnaire behavior is covered in jsdom by packages/…/questionnaire.test.tsx, browser interaction by packages/…/questionnaire.browser.test.tsx, and server rendering by packages/…/questionnaire-ssr.test.tsx. packages/…/vitest.config.ts runs node tests; shared chat behavior is exercised through packages/…/chat-contract.ts, core units such as packages/…/chat.test.ts, writer.test.ts, lower.test.ts, stream.test.ts, payloads.test.ts, and adapter tests under packages/…/*.test.ts and packages/…/*.test.ts.
Coupling
- If packages/…/package.json adds a new exported React primitive, also update packages/…/tsup.config.ts entry points and the
CLIENT_UI_ENTRIESlist; the build only emits declared entries, and only listed dist files receive the"use client"directive. - If packages/…/types.ts changes
data-message-id,data-scroll-anchor, default thresholds, or scroll mode semantics, verify packages/…/geometry.ts, use-message-scroller-controller.ts, and use-message-scroller-commands.ts together; controller policy depends on geometry helpers reading those exact dataset attributes and threshold constants. - If
MessageScroller.Itemregistration in packages/…/components.tsx changes, verifyscrollToMessagequeuing in packages/…/use-message-scroller-commands.ts and lazy visibility setup in packages/…/use-message-scroller-controller.ts; both use the sharedmessageElementsRefpopulated by item registration. - If questionnaire
Root.itemsshape in packages/…/types.ts changes, also update packages/…/collection.ts and shortcut assignment in packages/…/use-questionnaire-item.ts; SSR ordering, development warnings, and choice shortcut maps all read the collection definitions rather than the rendered children alone. - If packages/…/index.ts changes event, ref, or prop merge ordering, verify both React primitive modules; packages/…/components.tsx and packages/…/components.tsx rely on user handlers being able to prevent primitive behavior and on state-to-
data-*attributes for styling. - If packages/…/types.ts adds or changes a
ChatEventorNeutralChunk, update packages/…/writer.ts, packages/…/lower.ts, packages/…/format.ts, packages/…/parts.ts, packages/…/format.ts, and packages/…/parts.ts; the core event vocabulary must be representable in final message snapshots and, where supported, in streamed adapter chunks. - If AI SDK tool-part states or approval part shapes change upstream, update packages/…/parts.ts and continuation resolution in packages/…/chat.ts; human-in-the-loop continuations depend on
getToolCallsreturningapproval.approved, inputs, outputs, and terminal states using the framework-neutral summary shape. - If TanStack AG-UI event names or
MessagePartshapes change, update both packages/…/format.ts and packages/…/parts.ts; the transport stream and staticchat.get()snapshots are separate mappings and can drift silently.
Risks
- packages/…/use-message-scroller-controller.ts, packages/…/use-message-scroller-commands.ts, and packages/…/geometry.ts are tightly coupled to browser scroll geometry and rAF timing. If spacer draining or anchored-turn placement is changed, streamed chat rows can jump, leave dead space, or strobe the scroll button; the comments around
drainReleasedSpacer,reanchorToAnchoredMessage, and ResizeObserver rAF coalescing document specific browser-loop and native-scroll-anchoring failure modes. - packages/…/use-questionnaire-input.ts prevents unselected freeform inputs from submitting by setting
form=""and omittingnameuntil selected. If that logic changes, stale freeform values can appear inFormDataeven when a choice answer is selected or an item is skipped. - packages/…/chat.ts materializes continuation turns by replaying callback logic against the live transcript. If continuation callbacks are not pure or if adapter
getToolCallsmisses a pending call, regenerated or automatic follow-up streams can diverge from the scripted transcript and produce duplicate or empty tool-call context. - packages/…/format.ts intentionally drops neutral chunks that AG-UI cannot represent, including approval requests, file/source chunks, denied tool outputs, and step starts. If callers script those operations through the core and then use the TanStack adapter, the streamed transport will omit them even though
materializePartsmay preserve some final message state.