Skip to content

Latest commit

 

History

History
597 lines (458 loc) · 29.7 KB

cms-ui-react.md

File metadata and controls

597 lines (458 loc) · 29.7 KB
title @tanstack/cms-ui-react
id api-cms-ui-react
order 6
description API reference for @tanstack/cms-ui-react: block rendering, layout shells, MarkdownEditor, MediaImg, auth bindings and mock auth, admin i18n, the UI primitives, experimental on-page editing, the virtual route set, the Vite plugin, and styles.
keywords
tanstack cms
api reference
@tanstack/cms-ui-react
BlocksView
MarkdownEditor
useCan
createMockAuth
createRoutes
CmsRouteKey
tanstackCms vite plugin
admin i18n
ui primitives

@tanstack/cms-ui-react is the React UI for TanStack CMS on TanStack Start: the public pages, the admin, the API route files, and the components and hooks they are built from. Data comes from @tanstack/cms-api/start server functions, in-process.

pnpm add @tanstack/cms-ui-react @tanstack/cms-api @tanstack/cms-core

Peer dependencies: react and react-dom 19, @tanstack/react-router, @tanstack/router-core, @tanstack/react-start, and tailwindcss 4. Optional peers:

  • @tanstack/ai for AI features, and @tanstack/ai-mcp for /api/mcp. These are passed through to @tanstack/cms-api.
  • @modelcontextprotocol/sdk and @mcp-b/transports for the WebMCP badge, which stays hidden without them.
Import Contents
@tanstack/cms-ui-react Auth bindings, AdminShell, MarkdownEditor, MediaImg, admin i18n, WebMcpBadge.
@tanstack/cms-ui-react/primitives The admin's UI primitives (field editors, pickers, list, diff and review panels) for bespoke and generated admin screens.
@tanstack/cms-ui-react/site Public-site building blocks: SiteShell, DocsLayout, BlocksView/BlockView, and the stable on-page editor.
@tanstack/cms-ui-react/virtual-routes createRoutes() and the route key types.
@tanstack/cms-ui-react/vite tanstackCms() Vite plugin.
@tanstack/cms-ui-react/styles.css Tailwind entry with the theme token fallbacks.
@tanstack/cms-ui-react/routes/* The route files createRoutes() mounts. Not meant to be imported directly.

Block rendering

BlocksView

function BlocksView(props: BlocksViewProps): JSX.Element

interface BlocksViewProps {
  blocks: ReadonlyArray<Block>
  className?: string // default 'space-y-8'
  onSelectBlockField?: (blockIndex: number, fieldName: string) => void
  renderers?: CmsRenderers
}

Renders an ordered array of blocks. Each block's renderer is renderers.blocks[_type] from the prop, then from the renderers module bound through createRoutes(definition, { renderers }), then a built-in renderer, then a generic view of its fields. See Blocks & Rendering.

BlockView

function BlockView(props: BlockViewProps): JSX.Element

interface BlockViewProps {
  block: Block
  onSelectField?: (fieldName: string) => void
  renderers?: CmsRenderers
}

Renders a single block.

defineRenderers(renderers)

function defineRenderers(renderers: CmsRenderers): CmsRenderers

interface CmsRenderers {
  blocks?: { readonly [type: string]: ComponentType<BlockRendererProps> }
  inputs?: { readonly [name: string]: ComponentType<FieldInputProps> } // a field's `input: '<name>'`
  fieldTypes?: { readonly [type: string]: FieldTypeRenderers } // custom types only
}

interface FieldTypeRenderers {
  input?: ComponentType<FieldInputProps>
  cell?: ComponentType<FieldCellProps>
}

interface BlockRendererProps {
  block: Block
  onSelectField?: (fieldName: string) => void
}

Declares the app's React renderers: block renderers keyed by _type, named field inputs, and custom field types' inputs and list cells. Exported from the package root, /site, and /primitives. It checks the shape and returns the object. Export the result as renderers from a module (e.g. src/cms.renderers.tsx), name that module's path in createRoutes(definition, { renderers }) for the CMS's own routes, and pass the object as the renderers prop in your own (BlocksView, BlockView, InteractiveDocument, FieldInput, CollectionSection, and columnFields(collection, session, renderers)). Block types, fields, and field types stay data only: a block component, a field input component, or a field type input / cell throws when the config loads. See Custom block renderers and Custom inputs and cells.

import { BlocksView } from '@tanstack/cms-ui-react/site'
import type { Block } from '@tanstack/cms-core'

export function PageBody({ blocks }: { blocks: Array<Block> }) {
  return <BlocksView blocks={blocks} className="mx-auto max-w-3xl space-y-12" />
}

Layout

SiteShell

function SiteShell(props: { nav?: Array<NavItem>; children: ReactNode }): JSX.Element

interface NavItem {
  id: string // page slug or id; links to /p/$id
  label: string
}

The public site frame: header with the theme name and navigation, the auth header control, and the content column, styled from the theme tokens.

AdminShell

function AdminShell(props: {
  children: ReactNode
  paletteSearch?: PaletteDocSearch
}): JSX.Element

The admin frame: navigation (Content, Content agent, Review queue, Settings, shown by permission), the auth header control, the ⌘K command palette, and an access screen for sessions without a CMS role. Use it for custom admin pages so they match the built-in ones. paletteSearch replaces the palette's document search, which by default queries every readable collection.

DocsLayout

function DocsLayout(props: { pages: Array<DocPage>; currentId?: string; children: ReactNode }): JSX.Element

interface DocPage {
  id: string
  title: string
  slug: string
  sidebarLabel: string
  sidebarOrder: number
  published: boolean
}

The docs theme variant's layout: a sidebar tree built from pages (grouped by the first slug segment, ordered by sidebarOrder, labeled by sidebarLabel or the title) next to the article column.


MarkdownEditor

function MarkdownEditor(props: MarkdownEditorProps): JSX.Element

type MarkdownEditorMode = 'write' | 'split' | 'preview'

interface MarkdownEditorProps {
  value: string
  onChange: (next: string) => void
  label?: string
  fieldName?: string // used for AI field edits
  contextTitle?: string // document title passed to AI as context
  rows?: number
  placeholder?: string
  defaultMode?: MarkdownEditorMode
  onSave?: (finalValue: string) => void // shows Save / Cancel controls
  onCancel?: () => void
  saving?: boolean
  changed?: boolean
  autoFocus?: boolean
  initialShowAi?: boolean
}

The Markdown editor used for markdown fields: a toolbar, Write / Split / Preview modes, keyboard shortcuts, image upload, and an "ask AI" bar (when a text adapter is configured and the session has agent.use).

import { useState } from 'react'
import { MarkdownEditor } from '@tanstack/cms-ui-react'

export function NotesField() {
  const [value, setValue] = useState('# Notes\n')
  return <MarkdownEditor label="Notes" fieldName="notes" value={value} onChange={setValue} defaultMode="split" />
}

MediaImg

function MediaImg(props: {
  src: string
  className?: string
  alt?: string
  style?: CSSProperties
  width?: number // display width in CSS px; caps the srcSet
  sizes?: string
  priority?: boolean // eager loading, high fetch priority
}): JSX.Element

Renders a stored image. For /api/media/<id> URLs it adds a responsive srcSet of resized, format=auto variants (served when sharp is installed); other URLs render as a plain <img>.

import { MediaImg } from '@tanstack/cms-ui-react'

export function Hero({ src, alt }: { src: string; alt: string }) {
  return <MediaImg src={src} alt={alt} width={1200} sizes="100vw" priority className="w-full rounded-xl" />
}

Auth bindings

The package root route resolves the session with getAuthSession() and wraps the app in CmsAuthProvider; custom root routes should do the same. These hooks gate UI only; the server enforces the same rules.

CmsAuthProvider

function CmsAuthProvider(props: { initialSession: CmsSession; children: ReactNode }): JSX.Element

useCmsAuth()

function useCmsAuth(): CmsSession & { setSession: (next: CmsSession | CmsSessionInput) => void }

The current session (isAuthenticated, isAdmin, user, role, permissions, …) and a setter for optimistic updates after sign-in or sign-out.

useCan(permission | action, collection?)

function useCan(what: Permission | CollectionAction, collection?: string): boolean

Whether the session holds a permission (useCan('content.write')) or may perform a collection action, including the collection's access rules (useCan('publish', 'post')).

useCmsAi()

function useCmsAi(): CmsAiCapabilities // { text: boolean; image: boolean }

Which AI features are configured, for hiding AI controls.

AuthHeaderSlot

Renders the configured auth.HeaderControl (a sign-in / account control) with the current session. SiteShell and AdminShell include it.

import { adminPath } from '@tanstack/cms-core'
import { useCan, useCmsAuth } from '@tanstack/cms-ui-react'

export function EditLink({ collection, id }: { collection: string; id: string }) {
  const { user } = useCmsAuth()
  const canEdit = useCan('update', collection)
  if (!canEdit) return null
  return <a href={adminPath(`/edit/${collection}/${id}`)}>Edit as {user?.name ?? 'editor'}</a>
}

Mock auth

function createMockAuth(options?: CreateMockAuthOptions): CmsAuthConfig

interface CreateMockAuthOptions {
  defaultRole?: MockRoleKey // default 'admin'
  cookieName?: string // default 'cms_mock_role'
  personas?: Array<MockPersona> // default DEFAULT_MOCK_PERSONAS
  allowInProduction?: boolean // default false
}

type MockRoleKey = 'unauthenticated' | 'customer' | 'viewer' | 'author' | 'editor' | 'admin'

interface MockPersona {
  key: MockRoleKey
  label: string
  badge: string
  description: string
  session: CmsSessionInput
}

A demo auth config: a header control that switches between personas (stored in a cookie) so you can try every role. Because anyone can pick any persona, it signs nobody in when NODE_ENV is production unless allowInProduction is set (for public demos).

import { createMockAuth } from '@tanstack/cms-ui-react'

export const auth = createMockAuth({ defaultRole: 'editor' })
// defineCms({ auth, ... })

Re-exports

From @tanstack/cms-core: normalizeSession, DEFAULT_UNCONFIGURED_SESSION, UNAUTHENTICATED_SESSION, and the types CmsUser, CmsSession, CmsAiCapabilities, CmsAuthConfig, and Permission. See Authentication contract.


Admin i18n

Every user-visible admin string (shell, content list, editor, review queue, content agent, settings, media library, and Markdown editor) is a message id with an English default. Translate them with defineCms({ admin: { locale, messages } }); missing ids fall back to English.

function adminT(id: AdminMessageId, vars?: Record<string, string | number>): string
function adminRich(id: AdminMessageId, nodes: Record<string, ReactNode>): ReactNode
const defaultAdminMessages: Record<AdminMessageId, string>
type AdminMessageId = keyof typeof defaultAdminMessages

adminT returns the configured message (or the default) with {name} placeholders filled from vars. adminRich does the same with React nodes, for sentences that contain a link or <code>, so a translation can move the placeholder anywhere in the sentence. Use them in custom admin pages so they follow the same translations.

import { adminT, defaultAdminMessages } from '@tanstack/cms-ui-react'

export const messages: Partial<Record<keyof typeof defaultAdminMessages, string>> = {
  'nav.content': 'Inhalte',
  'nav.review': 'Prüfung',
  'content.new': '+ Neu: {label}',
}

export const heading = adminT('content.pageOf', { page: 2, count: 5 })

Browse defaultAdminMessages for the full list of ids.


On-page editing and experimental exports

The on-page editor components are exported from @tanstack/cms-ui-react/site (with unstable_* aliases for backwards compatibility), and unstable_WebMcpBadge from the package root.

Export Description
InteractiveDocument (unstable_InteractiveDocument) ({ id, doc, collection }). Dispatches to InteractivePageContent when the collection defines a blocks field (blocksField, or its first blocks field) or to InteractivePostContent otherwise, and disables inline editing for read-only collections.
InteractivePageContent (unstable_InteractivePageContent) ({ id, doc, collection? = 'page' }). Renders a page's blocks with on-page editing for sessions with content.write: hold Ctrl or Option and click a title or block to edit inline, reorder, add, or remove blocks, or ask AI to edit the selection or the whole page. Reads and writes the collection's blocks field (blocksField, or its first blocks field).
InteractivePostContent (unstable_InteractivePostContent) ({ id, doc, collection? = 'post' }). The same for flat documents. It edits the collection's roles: title (titleField), byline (bylineField), summary (summaryField), featured image (imageField, or the first image field), and body (bodyField, or the first markdown or richtext field). An undeclared byline or summary isn't shown.
SelectedPageObject (unstable_SelectedPageObject) { kind: 'title' } | { kind: 'block'; index; focusField? } | null
SelectedPostObject (unstable_SelectedPostObject) { kind: 'field'; field: string } | null
unstable_WebMcpBadge Exposes the agent tools to in-browser agents through WebMCP (MCP-B), for sessions with agent.use. Tool calls go to POST /api/cms and their writes are staged for review. The package root route renders it.

Visitors without edit rights see the plain rendered content.


@tanstack/cms-ui-react/primitives

Every UI primitive the built-in admin routes use, exported so bespoke domain apps and generated admin screens compose the same pieces. The admin routes import only from this entry point.

Export Use
AdminShell, CommandPalette The admin frame and the ⌘K palette.
DocForm, useDocForm, docPatch The schema-driven document form on TanStack Form (see DocForm).
FieldInput, RelationPicker, ImageField, MediaInsert, MarkdownEditor, LocaleControls Field editors. FieldInputComponentProps is the FieldInput props type.
CollectionSection, columnFields, defaultSort The content list for one collection and its column and sort defaults.
Diff, CommentsPanel, AssigneePanel Review: a proposed edit's diff, the comment thread, the assignee.
AgentChat, InterfaceRenderer, InterfaceView, InterfaceBuilder The content agent and persistent interfaces.

Two rules hold across the set:

  • collection is always the collection's name, as in the read and op APIs ({ collection: 'post', … }). Primitives look the definition up in the registered config, so pass collection="post", not the Collection object: columnFields('post', session), <Diff collection="post" … />, <CommentsPanel collection="post" id={id} />.
  • Pickers take their search backend as a prop, not from a React context. Each defaults to the built-in listDocumentSummaries search. Custom inputs and list cells come in the same way (see below).
type RelationSearch = (
  collection: string,
  query: string,
  limit: number,
) => Promise<{ items: Array<RelationOption>; total: number }>

<FieldInput field={field} value={value} changed={false} onChange={set} relationSearch={search} />
<RelationPicker field={field} value={value} titles={titles} onChange={set} labelId={id} ring="" search={search} />
<CommandPalette open={open} onClose={close} search={paletteSearch} />
<AdminShell paletteSearch={paletteSearch}>{children}</AdminShell>

FieldInput passes relationSearch on to relation fields nested in group, array, and blocks fields.

Custom inputs and list cells are props too: FieldInput (and its nested fields), CollectionSection, and columnFields(collection, session, renderers) take renderers from defineRenderers({ inputs, fieldTypes }), which /primitives also exports. Without the prop they use the module bound through createRoutes(definition, { renderers }).

DocForm

A <form> for one document of a collection, generated from its schema. It keeps the draft in a TanStack Form instance, renders a control per top-level field in schema order, and calls onSubmit with a patch of the fields that changed. It doesn't save anything itself: the submit handler decides where the patch goes.

import { DocForm } from '@tanstack/cms-ui-react/primitives'
import type { Doc } from '@tanstack/cms-core'

export function PostForm({ post, save }: { post: Doc; save: (patch: Doc) => Promise<void> }) {
  return (
    <DocForm collection="post" defaultValue={post} onSubmit={(patch) => save(patch)}>
      {({ dirty, submitting }) => (
        <button type="submit" disabled={!dirty || submitting}>
          Save
        </button>
      )}
    </DocForm>
  )
}
Prop Type Description
collection string The collection's name. An unknown name throws, as for the other primitives.
onSubmit (patch: Doc, context: { doc, baseline, meta }) => unknown Receives the top-level fields whose values differ from the baseline, compared as JSON, plus the whole document, the baseline, and the meta given to submit(meta). If it throws or rejects, the submit fails: the error is kept and the baseline doesn't move. Otherwise the submitted document becomes the baseline.
value / onChange Doc / (doc: Doc) => void Controlled use. onChange gets the whole document after every change. When value changes to something other than the form's values, the form adopts it without calling onChange.
defaultValue Doc The initial document when the form owns its state.
baseline Doc The stored document that the patch and dirty compare against. Defaults to the initial document. Set it when the parent tracks what is saved; the form then never moves it itself.
fieldRenderers { [fieldType]: ComponentType<FieldInputComponentProps> } Per-form renderers for top-level fields, keyed by field type, built-in types (text, markdown) included. Each replaces FieldInput for that type and gets FieldInput's props, so it can wrap FieldInput. Fields nested in group, array, and blocks still render with FieldInput.
renderers CmsRenderers The app-wide renderers module from defineRenderers({ inputs, fieldTypes }), passed to every FieldInput, nested fields included. Without it, FieldInput uses the module bound through createRoutes(definition, { renderers }). useDocForm takes it too.
access { session, doc } Field-level access: fields the session can't read are left out, and fields it can't write are read-only. doc is the stored document, or null for the draft. Without access, every field is editable; the server still enforces field rules.
disabled boolean Renders every field read-only.
errors Record<string, string> Messages by field name, shown under each control (for example the fieldErrors of a failed save).
changedFields Array<string> Field names to highlight, as FieldInput's changed does (for example the fields an agent's proposal changes).
store, relationSearch Passed to FieldInput: relation titles by collection and id, and the relation search backend.
id, className, aria-label Set on the <form>. aria-label defaults to the collection's label.
children ReactNode | (state) => ReactNode Rendered after the fields. The function form gets { values, patch, dirty, submitting, error, submit, reset, setValue }.

renderers and fieldRenderers work at different levels. renderers is the app's module, keyed by input name (a field's input) and by custom field type. fieldRenderers is an override for one form, keyed by field type. For each top-level field, DocForm uses fieldRenderers[field.type] if there is one. Otherwise it renders FieldInput, which resolves as usual: the field's named input, then its custom type's input (each from renderers, then the bound module), then the built-in control. A renderers.fieldTypes input replaces only the control under FieldInput's label and error message, and it can't target built-in types. A fieldRenderers entry replaces the whole field, for any type.

Fields hidden by showWhen aren't rendered, and their stored values stay in the document. There is no client-side validation yet: put a save's field errors in errors.

To keep the form's state in the parent (for example to put the buttons in a header), call useDocForm with the same options and pass the result to DocForm as form:

import { DocForm, useDocForm } from '@tanstack/cms-ui-react/primitives'
import type { Doc } from '@tanstack/cms-core'

export function PostEditor({ post, save }: { post: Doc; save: (patch: Doc, publish: boolean) => Promise<void> }) {
  const editor = useDocForm<{ publish: boolean }>({
    collection: 'post',
    defaultValue: post,
    onSubmit: (patch, { meta }) => save(patch, meta?.publish ?? false),
  })
  return (
    <>
      <header>
        <button type="button" disabled={!editor.dirty} onClick={() => editor.reset()}>
          Revert
        </button>
        <button type="button" onClick={() => void editor.submit({ publish: true })}>
          Publish
        </button>
      </header>
      <DocForm form={editor} />
    </>
  )
}

useDocForm returns { form, collection, values, baseline, patch, dirty, submitting, error, submit, reset, setValue }. form is the TanStack Form instance, for form.Field and form.Subscribe. submit(meta?) resolves true when onSubmit succeeded. reset() goes back to the baseline, and reset(doc) loads doc and makes it the baseline. docPatch(baseline, doc) is the patch computation on its own.


@tanstack/cms-ui-react/virtual-routes

function createRoutes(
  definition: CmsDefinition, // from defineCmsDefinition()
  spec?: CreateRoutesSpec,
): VirtualRootRoute

interface CreateRoutesSpec {
  public?: CmsRouteSurfaceSpec<'public'>
  admin?: CmsRouteSurfaceSpec<'admin'>
  api?: CmsRouteSurfaceSpec<'api'>
  // catch-alls at {publicPrefix}/$; default true unless public is false
  collections?:
    | boolean
    | ReadonlyArray<string>
    | { [collection: string]: boolean | string }
  custom?: ReadonlyArray<VirtualRouteNode>
  rootFile?: string
  renderers?: string // the app's renderers module, relative to the routes directory
}

// true: every route; false: none; a key list: only those;
// an object: drop (false) or replace (a file path) single keys
type CmsRouteSurfaceSpec<S extends CmsRouteSurface> =
  | boolean
  | ReadonlyArray<CmsSurfaceRouteKey<S>>
  | { [K in CmsSurfaceRouteKey<S>]?: boolean | string }

// Re-exported from @tanstack/cms-core/definition (CMS_ROUTE_KEYS)
type CmsRouteSurface = 'public' | 'admin' | 'api'
type CmsRouteKey =
  | 'index' | 'page' | 'post' | 'preview' | 'sitemap' | 'robots' | 'notFound'
  | 'content' | 'edit' | 'agent' | 'review' | 'settings'
  | 'apiWebMcp' | 'apiV1' | 'apiMcp' | 'apiMedia' | 'apiMediaFile'
type CmsSurfaceRouteKey<S extends CmsRouteSurface> // the keys of one surface

The virtual route tree for the TanStack Router plugin: the public pages, the admin, and the API routes, a catch-all per collection with a publicPrefix, plus your own custom routes. The admin base path and plugin routes come from the definition. A surface you leave out is mounted, so createRoutes(definition) mounts everything. renderers is the path of a module that exports renderers = defineRenderers({ … }); the CMS routes render blocks with it. It is a path rather than an import so vite.config.ts never loads React, and it must exist when the config loads. Route keys are stable public API: renaming or removing one is a breaking change. Keys, paths, and options are listed in the route table; overriding and adding routes is covered in Building Pages.


@tanstack/cms-ui-react/vite

function tanstackCms(options?: {
  packages?: Array<string>
  routesDirectory?: string // default <cwd>/src/routes
  generatedDirectory?: string // where prefixed admin route copies are written
}): CmsVitePlugin

interface CmsVitePlugin {
  name: string // 'tanstack-cms'
  enforce: 'pre'
  config: () => {
    ssr: { noExternal: Array<string | RegExp> }
    optimizeDeps: { exclude: Array<string> }
    // set once createRoutes() has run: the route segments under each
    // collection's publicPrefix that its locators can't use
    define?: { __TANSTACK_CMS_SHADOWED_LOCATORS__: string }
  }
  resolveId: (
    id: string,
    importer: string | undefined,
    options?: { ssr?: boolean },
  ) => string | undefined
  load: (id: string) => string | undefined
}

The CMS packages ship TanStack Start server functions and route files that your app's Start compiler must transform. The plugin keeps @tanstack/cms-core, @tanstack/cms-api, @tanstack/cms-ui-react, and @tanstack/cms-client (plus any packages you add) out of Vite's SSR externals and dependency pre-bundling, and bundles @tanstack/ai* into SSR alongside them. In SSR, resolveId and load serve use-sync-external-store as ESM on React's own useSyncExternalStore, so a production server bundle under pnpm loads one React. routesDirectory and generatedDirectory are read by createRoutes(), which resolves route files when the config loads. In return, the plugin passes the build the route segments that shadow a collection's locators, so writes can reject them. When createRoutes(definition, { renderers }) names a renderers module, the plugin's load hook serves the package's app-renderers module (which every CMS page route imports) as code that binds it. Add it before tanstackStart().

import { defineConfig } from 'vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes'
import { tanstackCms } from '@tanstack/cms-ui-react/vite'
import { definition } from './src/cms.definition'

export default defineConfig({
  plugins: [tanstackCms(), tanstackStart({ router: { virtualRouteConfig: createRoutes(definition) } })],
})

@tanstack/cms-ui-react/styles.css

The stylesheet for the CMS routes: Tailwind CSS 4 (@import 'tailwindcss'), an @source so Tailwind scans the package's own files under node_modules, and :root fallbacks for the --cms-* theme tokens. The package root route links it and injects themeCss(getTheme()) to apply your theme.tokens. A custom rootFile should do both:

import appCss from '@tanstack/cms-ui-react/styles.css?url'
import { getTheme, themeCss } from '@tanstack/cms-core'

// head: () => ({ links: [{ rel: 'stylesheet', href: appCss }] })
// <style dangerouslySetInnerHTML={{ __html: themeCss(getTheme()) }} />

See Theming & Variants.

Persistent interface components

  • InterfaceBuilder() lists saved pages/reports and lets unscoped admins create, revise, preview, and submit them for review. It uses the configured text model when available, with collection templates and a definition editor otherwise. Snapshot report controls expose reviewed schedules, status, pause/resume, and refresh of the approved snapshot.
  • InterfaceView({ id, kind }), where kind is page or report, loads an authorized published interface. Live views refresh on state changes, manually, and through collection event subscriptions. Only affected components rerun; reconnects, interface revisions, and a 30-second fallback trigger full reads. Snapshot views update when a new approved snapshot revision is published.
  • InterfaceRenderer({ result, disabled?, onStateChange?, onAction? }) renders an InterfaceResult with controlled state and action callbacks. Code executes on the server, not in the browser. Tables sort and paginate their returned rows.

These components use interfaces.collection and the existing auth provider. Mount them in your app's routes; Base exposes them at /interfaces, /p/$page, and /r/$report. See persistent pages and reports.

Customer chat component

AgentChat({ suggestions?, renderToolResult? }) is the shared conversation used by the default agent route and TanStack Base. It renders Markdown replies, actual query results, proposed records, and explicit human approval using pending-version receipts. It requires a text adapter and agent.use; approval additionally requires review.decide. Session changes clear the view and ignore old in-flight responses.

Use renderToolResult(tool, controls) to render app-specific proposal cards; return undefined to use the shared renderer. controls.appendMessage(content) adds a status message after a human action. Base uses this for validated collection schemas, publishing them through its existing administrator operation. Tool receipts use the exported client-safe CmsToolResult type from CMS core.

Conversation state lives in the mounted component. Query results contain only records authorized by the server. Rendering a receipt never approves a change.