Files
ui/LLM.md

84 KiB
Raw Permalink Blame History

@hanzo/ui — LLM context

What this is. The React component library for AI applications: 161+ components, 24+ blocks, two themes, and a single typed import surface, all on ONE substrate (@hanzo/gui) so the same import runs on web, native and desktop. Published as @hanzo/ui (v8) on npm. Docs at https://ui.hanzo.ai. Dev port: 3003.

Canonical role. This is the canonical impl repo for Hanzo's web UI kit — frontend components, not an SDK. It sits alongside the two SDK lines (full cloud SDK generated from OpenAPI in hanzo-<lang>/sdk + wrapper in hanzoai/<lang>-sdk; AI/agents lib hanzo in hanzoai/python-sdk flagship, @hanzo/ai in hanzo-js/ai). @hanzo/event (telemetry, POST /v1/event) lives here in pkg/event. DRY: one impl, one place — link out, never duplicate.

Brand rules (hard).

  • Never call Hanzo an "LLM gateway" or position it against LiteLLM — it is a full AI SDK / AI cloud, not a proxy. Purge that framing on sight.
  • Paths are /v1/… only — never an /api/ prefix.
  • Zen models are our own family — never name upstream models.
  • Voice: "Hanzo — the Open AI Cloud." Developer-first, crisp, no emoji-spam.

Install / run.

pnpm add @hanzo/ui         # consume
# dev:
pnpm install && pnpm --filter @hanzo/ui... build

Key entry points. pkg/ui/ (core lib + v8 subpaths: /product /data /canvas /dashboard /usage /gitops) · pkg/* (the auto-published @hanzo/* family) · apps/cd (the @hanzo/cd demo). Publish = bump a package version + merge to main (.hanzo/workflows/publish.yml).

What is NOT here. Everything shadcn-lineage lives in hanzoai/shadcn: the shadcn CLI, the component registry (app/registry/**, apps/v4/registry/**), both docs sites, the templates/* scaffolds, and the docs-site e2e suite. ui.hanzo.ai is built and deployed from there. This repo is @hanzo/ui@8 on @hanzo/gui plus the @hanzo/* family, and nothing else — no Tailwind, no Radix, no registry.

Spec / more context. Canonical SDK + docs model: ~/work/hanzo/SDK-ARCHITECTURE.md. Detailed engineering notes (build order, import surface, telemetry, upstream sync, gotchas) follow below.


v8 — the canonical @hanzo/ui (pkg/ui)

@hanzo/ui@8 (pkg/ui) is THE Hanzo component library, and there is ONE substrate: every component renders through @hanzo/gui primitives on the @hanzo/tokens scale, so one import works on web, native (expo) and desktop (Tauri). The Radix + Tailwind surface it used to ship alongside is gone — it lives on as its own package, @hanzo/shadcn, and @hanzo/ui no longer depends on it, on any @radix-ui/* package, on cva, cmdk or sonner.

@hanzo/ui-shadcn (pkgs/ui, v5.x) is the legacy standalone package — superseded, being retired.

Layout

pkg/ui/src/
  core/            design core: cn.ts (clsx+tailwind-merge),
                   tokens.ts (re-export of @hanzo/tokens), fonts.ts (Zen vars)
  root.tsx         <Hanzo> — the root. Carries the gui config AND the stylesheet.
  gallery.tsx      EVERY component, once, in every variant. The one list.
  theme.css        SELF-CONTAINED token CSS vars + Zen / Zen Mono — the identity
  backends/gui/    THE component surface on @hanzo/gui. index.ts is its manifest.
  product/         the product/app layer (charts, PageHeader, ComboBox, …)
  models/          ModelPicker (the one model picker: grouped, searchable,
                   virtualised, a sheet on phones; the trigger alone until it
                   is pointed at, focused or opened, when ModelPickerMenu —
                   popover/sheet, search, list — loads in its own chunk;
                   RESEARCH lives in research.ts so naming Zen 7 does not load
                   the catalog) + the catalog read from
                   GET /v1/models fields alone (class, family, inputs,
                   outputs, supports_*, pricing). RESEARCH is the models nobody
                   can call yet; the picker appends them, disabled. A row sold
                   against another (`compare_at`, or Kai against Jev) says
                   `savingOf` from the two list prices; a router
                   (`variable: true`) says `formatCeiling` — "Up to $X / 1M ·
                   billed at the model that serves it" — and is compared with
                   nothing. Pricing reads `input_per_million`, else `prompt`.
                   `@hanzo/ui/models/catalog` is the pure half, which bare
                   Node and a server can load; `./models` pulls in gui
  primitives/      GENERATED per-member entrypoints (scripts/gen-primitives.mjs)
  index.ts         root barrel = the component surface + cn

Out of the box — the package carries its own config and its own CSS

import { Hanzo, Button } from '@hanzo/ui'
<Hanzo><Button>Ship</Button></Hanzo>

That is the entire setup. No gui.config.ts, no CSS import, no generator script. Three things used to be each app's job:

  1. The stylesheet. gui compiles a style prop to an atomic class the first time something RENDERS it, so the sheet does not exist until a render has happened — which is why every app ran a gen-gui-css.mjs of its own. hanzo.app never did: it shipped 103 _bg- classes and 26 _dsp- classes against a stylesheet containing ZERO of either, every gui-styled element unstyled in production, green build throughout. The render happens at OUR publish time now (scripts/gen-css.mjs renders src/gallery.tsx in both themes and writes dist/styles.css — 362 KB, 71 KB gzipped, 611 atomic selectors, plus react-native-web's own sheet, which is 13 KB of that and is not gui's to generate), and <Hanzo> imports it. Styles gui generates at RUNTIME for props we could not know at publish time still reach the document through insertStyleRules; the shipped sheet is what makes the FIRST paint and every SSR/static render correct.

  2. The config. <Hanzo> passes config from gui-config.ts to GuiProvider — as a VALUE, never a bare import './gui-config'. Vite 8 (rolldown) ignores package.json sideEffects ARRAYS outright: with any array the registration is dropped and the first render dies on "Missing hanzogui config"; only sideEffects: true keeps it, and that costs +63% bundle (404 KB → 661 KB measured). Correctness does not live in bundler metadata.

  3. The theme. gui throws Missing theme. for any component with no root theme context, so a root is structurally required — there is no version of this with no root at all. Forgetting <Hanzo> is therefore a hard crash on first paint, never a silently unstyled page.

theme.css is dark-first at :root (it used to claim dark-first while shipping LIGHT at :root, so an app that mounted the dark default and read --background got white). .light retunes, and both answer to gui's own .t_light/.t_dark that <Hanzo> stamps on the body — one theme, named the same by the CSS custom properties and the component tokens.

Three tests, one list of components

src/gallery.tsx is the specification of "what this package has to style", and all three layers render THAT — a second copy of the list is how a component gets styled by one and missed by another.

Layer Command What it catches
src/styles.test.tsx pnpm test:unit every class the gallery renders — gui's _… AND react-native-web's r-…/css-… — vs every class dist/styles.css defines a rule for. Not "the intersection is large" — TOTAL. Catches a stale sheet.
src/backends/gui/render.test.tsx pnpm test:unit the surface mounts under the real provider; a component that throws on first paint fails.
test/consumer.spec.ts pnpm test:consumer packs the tarball, installs it into a temp app OUTSIDE the repo (never a workspace link — that hides files/exports/workspace:* defects), builds, serves, and asserts COMPUTED styles + screenshots at 390 and 1280 in both themes.
test/stress.tsx pnpm test:contain every shell given LESS room than its content: what escapes, what is merely clipped, and what actually scrolls. Mounts in a browser, and checks the stylesheets arrived before it believes a box.

The consumer spec also fails on a solid-white border (the @hanzo/design border-card: var(--white…) defect — borders are low-alpha hairlines) and on any element that has a text child and a zero-height box.

Boxes a test compares are read in ONE frame (frame(page, {a: sel, b: sel})). The gallery holds its modal surfaces open, and on load their focus scopes pass focus down the page and the browser smooth-scrolls after it for a second or more past networkidle. getBoundingClientRect is viewport-relative, so two boxes read in two round trips straddle the scroll: 8.27.20's CI read Home's mark 151–491px off its own line and the rail's brand 586px under the search it sits above, on a layout that was right (both 0 off read together — the published tarball, measured). It passed locally because a fast machine measured after the scroll ended. A size alone (w, h) is scroll-invariant; a position is only comparable to another read in the same frame.

House rules for a component

  • Style through gui props and theme tokens ($background, $color12, $borderColor) — never a utility class string, never a hard-coded font.
  • Touch targets meet the 44px floor via hitSlop, never via padding.
  • Behaviour (focus, portalling, keyboard, a11y) comes from the matching @hanzogui/* primitive; nothing reimplements it.
  • Free-form text children go through ink(); data-slot markers through slot(). One helper each, one place.
  • Module scope stays side-effect free — forwardRef/createContext calls carry /* @__PURE__ */ and nothing assigns displayName, so importing one symbol never drags a neighbour in. A one-symbol import bundles ~4.7KB against ~29KB for the whole barrel.
  • Utility classes carry hz-, and as of 8.3.0 that is the only spelling. This sheet claimed twelve bare names at the document level — collapse, drag, fade, fade-up, menu-in, mono, paper, row, row-in, skeleton, slide, tnum — in a package an app imports once at its root; an app with its own .row got no warning, it got whichever rule the cascade preferred. Each was a second selector on a rule the hz- form already carried, so removing them changed 21 selectors and no declarations. Nothing here emitted them — styles.test.tsx scans every className= literal in src/ and fails on an unprefixed one, which is why this was a promise to outside callers rather than a migration of our own. Two earlier releases named themselves as the one that would do it and shipped carrying them anyway; a removal scheduled in prose is not scheduled. glass/elevation-N are the one family still bare: they are an API VALUE (glass(3).className), not a typed literal, so they move on their own change.
  • A prop must actually arrive. gui is not the DOM, and two measured cases prove it in both directions: name is gui's OWN prop (it names a styled component and a theme) and is consumed before it reaches the element, so a name on a field type-checks and renders nothing; and gui drops secureTextEntry on web, which is why masking needs BOTH spellings via masked() in backends/gui/mask.ts and why <Input type="password"> rendered passwords in PLAIN TEXT until 8.0.61 (the wrapper destructured type out and never forwarded it, next to an eye offering to reveal what was already visible). Render it and read the markup before you believe a prop works.

TWO stylesheets, and only one of them was being shipped

Components here render through gui, and gui renders through react-native-web, so the markup carries classes from both: gui's atomic _… classes, and rnw's r-… (one declaration each) and css-… (a component's base rule). Both are written by the running app — rnw appends its <style> on import, gui inserts a rule the first time a prop renders — and scripts/gen-css.mjs collected only gui's.

So dist/styles.css shipped 20 rnw classes with no rule anywhere, including the overflow-y: auto that makes every ScrollView scroll. A browser hid it: rnw appends that sheet itself, so a client-rendered app was always fine and only server-rendered markup was bare. dist/gallery.html is server-rendered — so the gallery drew those components as unstyled block-level HTML, and responsive.mjs measured that page.

styles.test.tsx claimed a TOTAL match of classes-to-rules and stayed green throughout, because it read only tokens starting _. It reads r- and css- too now, which is the guard that closes this rather than the fix that patched it.

A harness renders the way an app renders. scripts/contain.mjs mounts test/stress.tsx in a real browser through vite, and refuses to report a number until it has confirmed both base rules arrived (display:flex, min-height:0). That check is not decoration. A document with no styles fails every containment question AND fails the negative control, which reads exactly like a good run — an earlier server-rendering version of this harness reported the sidebar and the drawer as broken shells on that basis, and both are fine.

The shell contract, measured

A shell is something pinned top, something pinned bottom, and a middle that takes what is left and scrolls. Screen and Fill (backends/gui/screen.tsx) are that shape; ScrollView is the other way to get it, and it is the one that also works off the web. scripts/contain.mjs over-fills all of them and asks three questions: does visible content escape the frame, is clipped content reachable, and what actually scrolls.

Measured at 24 rows in a 320px column and 90 rows in a 900px drawer: nothing escapes, and the scroller in each case is real — the sidebar's middle holds 804px of rows in 193px and the user chip stays pinned inside the frame; the drawer's body holds 2884px in 844px.

On web, the half of the folklore that does the work is declaring the overflow. minHeight: 0 is already zero before anyone writes it — rnw's View base and gui's own stack base both set min-height: 0 and min-width: 0, measured on the rendered element, not read off a source file. The gate keeps one frame of each as a control: only-overflow (overflow, no minH) contains and scrolls; only-minh (minH, no overflow) escapes by 310px and is REQUIRED to fail, since a gate nobody has watched fail is not known to run.

Nothing here says what happens on native. This harness is a browser and cannot answer it, so no claim is recorded.

Subpaths

Subpath What
@hanzo/ui the component API: Button, Badge, Card*, Checkbox, Dialog*, DropdownMenu*, Input, Toaster, Avatar*, Tabs*, Select*, Tooltip*, Popover*, Command*, Collapsible*, Resizable*, ScrollArea, Slider, Switch, Progress, Separator, Label, Textarea, AspectRatio — + cn (the product layer is kept off root, at /product)
@hanzo/ui/components alias of the root surface, for hosts that shim the package through a declare module
@hanzo/ui/product the product/app layer: charts, metrics, PageHeader, StatusTag, EmptyState, ComboBox, SlideOver, Toast, Reorder, Field
@hanzo/ui/models ModelPicker + parseModels/fetchModelCatalog + catalog helpers + defaultModel
@hanzo/ui/core · /tokens cn, Zen font vars, the @hanzo/tokens color/theme/radii/spacing scale
@hanzo/ui/theme.css the design tokens alone (custom properties + Zen + touch/elevation)
@hanzo/ui/styles.css the COMPLETE sheet — tokens + motion + the generated gui atomic/theme CSS. <Hanzo> imports it, so an app never has to
@hanzo/ui/gallery every component, once — what the generator, the unit test and the consumer test all render
@hanzo/ui/primitives/<Member> per-member entrypoints (for hosts that modularize @hanzo/ui imports)
@hanzo/ui/data @hanzo/data: RecordsView, DataTable, typed field editors
@hanzo/ui/{canvas,dashboard,usage,gitops} the optional-peer kits (each re-exports its home package)
@hanzo/ui/settings a settings page (Settings) and the parts every section is drawn from (Heading, Group, Card, Row, Field, Soft, Note, Once)
@hanzo/ui/catalog a catalogue page (Shelf) and its cards (Tiles, Tile, Featured, Add) — web-only, on @hanzo/ui/grid
@hanzo/ui/product/* · /primitives/* deep imports — one module without its barrel
@hanzo/ui/product/pure the product layer's RULES with none of the layer (below)
@hanzo/ui/product/theme-toggle-next the @hanzogui/next-theme binding, off the barrel on purpose (below)
@hanzo/ui/grid Grid + Cell — a real CSS grid, so web-only and off the barrel (below)
@hanzo/ui/css substitute() — resolve a var() chain, for tests jsdom cannot answer (below)

Everything ships COMPILED from dist — every exports target is a real file in the tarball, including theme.css and all 90 primitives/* entrypoints. src/dist.test.ts asserts that against the built output, wildcards included; a subpath pointing at a file tsc never emitted is invisible from source.

Three entry points that exist because the barrel is not one

@hanzo/ui/product mounts the whole gui runtime to give you one component, and for three kinds of caller that is not a cost — it is a wall.

@hanzo/ui/product/pure — the rules, without the layer. pages(), masked(), displayName(), tone(), orgScope, filterOptions, resolveBrand and the wordmark geometry. Every module it re-exports imports NOTHING (src/dist.test.ts asserts the closure is empty) and is on postbuild.mjs's DATA list, so none is stamped 'use client' — a stamped module is a client REFERENCE on React's server layer, and calling pages() through one in a server component throws instead of paging. It loads under a bare require() with no transform and no DOM; the test proves it in a child node process rather than under vitest, which has vite's transform already installed and would prove nothing.

The components import these same modules, so there is one definition and not a testable copy of a shipped one.

@hanzo/ui/product/theme-toggle-next — Next, quarantined. @hanzogui/next-theme's provider imports next/script, so the product barrel's one export { ThemeToggleNext } line put Next in the graph of every Vite, Express and Tauri host — the hosts this layer promises to run on. A barrel re-export is a static edge no bundler can split. It is off the barrel; <ThemeToggle /> with no props still reaches it by dynamic import and degrades when next-theme is absent, and dist.test.ts asserts BOTH — no static edge, and the dynamic one still there, because a test that only asserted the absence would pass on a deleted feature. next is now an OPTIONAL peer here: next-theme requires it and nothing in this package admitted that.

@hanzo/ui/css — substitute(value, vars?). jsdom does not resolve var(); it hands a test the text verbatim. The theme rungs are var(--border, rgb(255 255 255 / .10)) on purpose (follow the live cascade where design's sheet is mounted, keep the audited literal where it is not), so every consumer trying to assert a border's contrast compared a colour to a function call. With no vars map the answer is exact rather than approximate: jsdom mounts no design sheet, so the fallback IS what a browser computes. It is NOT part of @hanzo/ui/core — that subpath is ESM-only because @hanzo/design publishes no require condition, and a jest consumer is the caller that needs this. Importing nothing is what lets it ship both formats.

Grid is off the barrel — 8.2.0

It renders a div and sets display: grid, and neither exists on React Native, so it ships at @hanzo/ui/grid beside @hanzo/ui/dots rather than on the surface that promises to run everywhere. That is a statement about the file, not a claim about anyone's bundle.

One prop carries the tracks. columns takes a count, a list, a written track list, or {min, max} — the responsive repeat(auto-fill, minmax(…)) form, which is why there are no breakpoint props. rows is the same down the page, and Cell takes col/row, where a number spans and a string places. min/cols/max are gone with no alias; the seven trust/site call sites moved in the same change.

Two formulas in tracks() look like verbosity and are each one tidy-up away from the ragged row this component exists to prevent, so grid.test.ts asserts both against the shorter spelling they must NOT produce. A count is minmax(0, 1fr), never a bare 1fr, because 1fr means minmax(auto, 1fr) and auto floors the track at its content. A fit floor is min(Npx, 100%), never a bare Npx, because minmax(240px, 1fr) forces a 240px track into a 390px phone: measured at 390, the 900px-min grid lays out one 342px track and the document does not scroll sideways.

The min-width floor grid children need is [data-slot='grid'] > * in styles/motion.css, declared once. Cell does not restate it inline — a grid-column only applies to a direct child of the grid, so a Cell is always in range of that selector, and the computed floor is 0px on every cell at both 390 and 1280.

One DropdownMenu

There is one DropdownMenu, with one API. It is the compound surface (Trigger, Content, Item, CheckboxItem, RadioItem, Label, Separator, Shortcut, Group, Portal, Sub*, RadioGroup) AND it accepts the declarative trigger + items spec, which it renders through those very same parts. @hanzo/ui and @hanzo/ui/product export the same component; there is no second shape.

Generative UI — the model drives the interface (@hanzo/ui/chat)

Three tools the model calls to move the interface, and no second protocol beside tool use. A caller passes TOOLS to messages.stream, folds the events through stage, and hands the pieces to three components:

const s = frames.reduce(stage, EMPTY)          // Frame[] from content_block_*
<Persona scenes={scenes} emotion={s.emotion} /> // feel  → the clip switches
<Parts parts={s.parts} />                       // show  → an inert Preview
<Aside><Inspector summary={s.report?.summary} …/></Aside>   // report → the panel

feel({emotion}) · show({title, kind, markup}) · report({summary, inputs, outputs}). ONE WORD EACH, AND NO DOTS — a tool name is [a-zA-Z0-9_-]{1,64}, so persona.set is rejected by the API before the model ever sees the request, and the rejection names the request rather than the name.

The persona moves whether or not the model calls anything. stage reads the raw stream — a thinking block or delta reads as thinking, the first text as speaking, message_stop as rest — so a turn with no directives still animates. A feel directive then OUTRANKS that reading and is held (Stage.held) until the model changes it; it survives message_stop, so a turn that ended happy rests happy, and only message_start clears it. Resetting at the end of the turn would flatten every deliberate ending.

Preview renders model-authored markup under sandbox="". An empty allow-list is the strictest setting the attribute has, not a lax one: no scripts, no same-origin, no forms, no navigation. The document lays out and paints and can do nothing else — which is the whole shape of a mockup, so nothing is lost. This is why Parts now draws an artifact carrying markup and still refuses a uiResource: a uiResource is a URL, and loading one pulls a third-party origin into the page over the network. Preview.test.tsx reads the ATTRIBUTE, because jsdom does not reflect sandbox as a DOMTokenList (iframe.sandbox is undefined there and every question asked of it answers undefined), and it asserts toEqual([]) rather than "no allow-scripts" — a MISSING attribute is a fully trusted frame and would satisfy the weaker form.

Nothing imports @hanzo/ai. Frame is open and insists only on type, the way words's Part is open, and content_block/delta are unknown on purpose: a narrower spelling makes half the event union unassignable (a delta typed with all-optional fields trips weak-type detection against message_delta), and this is a boundary where reading defensively is correct anyway. Tool is a type alias and not an interface for the same class of reason — only a type literal gets an implicit index signature, and an interface compiles here and fails at every call site against AnthropicTool's [key: string]: unknown. directive.test.ts restates both @hanzo/ai types verbatim and assigns across them; those assignments are checked by tsc, not by vitest.

Inspector is the CONTENTS of the right rail; Aside is the column. A section carries facts (name to value) or parts, and MessagePart already covers every shape a run produces — steps and artifacts for a chat turn, files and console output for a coding run, citation for a research run's sources — so one panel serves all three. An empty section does not render at all: a heading over blank space reads as "produced nothing" when the truth is "not reported".

The builder workspace (@hanzo/ui/agents)

Ported from build-v2's editor (hanzoai/build-v2, MIT, itself from OSW Studio and DeepSite — attribution in NOTICE). v2 was one app that owned its project, pages, frames and fetches; the port keeps the SCREEN and hands every one of those back to the host, so the builder, a console page and a desktop shell can compose the same frame over their own transport.

Piece What it is
Workspace the frame: bar (start · middle · end), chat column, the view as children, dock. collapsed (wide) and pane (phone) are controlled — the host persists them.
Views + VIEWS/CHAT/DEVICES the segmented control, a WAI-ARIA tablist; CHAT is drawn only below md, which is how a phone switches between the chat and the work with the same control.
ProjectChip · PageSelect · ModeSelect the bar's project trigger, the page field, the composer's Build/Plan chip. The two selects are one Choice over the one DropdownMenu.
PreviewFrame frames an ADDRESS (http/https only, web()), sandboxed; allow-same-origin only for a foreign origin. ref → reload()/post().
FileTree files (flat) or load(dir) (one level per call, like /v1/git/repos/:name/tree); tree roles and keys from tree.ts.
FileTabs open files as tabs over CodeEditor; Delete closes; no onChange = read-only. Distinct from CodeTabs (a snippet in several languages).
Console the dock: one dimension, height (> HEAD is open), grip drag/keys/click all resolve through log.ts; optional onRun, extra tabs.
Suggestions · Attachments · Feedback the chat column's chips, the "this turn is about" row, and the copy/thumbs row for Message actions.

Everything a run or a repo supplies is TEXT — file contents, paths, log lines, picked-element HTML. Nothing in the module renders markup it was given.

The preview bridge is opt-in and origin-pinned (bridge.ts). A deployed page on its own origin is not ours to inject into, so a page that wants element picking and console forwarding ships script(parentOrigin); it posts only to that origin and obeys only its parent from there, and accept() on this side believes only the frame's own window at the frame's own origin. v2's live style/text edits are NOT in the protocol: a change made inside the frame is gone on reload, and the builder's edits are runs that commit.

ref is a plain prop on PreviewFrame and ProjectChip (React 19), not forwardRef: the wrapper's Omit<Props, 'ref'> collapses every prop to any against gui's index signature, which the docs app's typecheck caught.

test/axe.ts does not descend into frames (iframes: false): a framed page is another document, and axe's frame messaging throws in jsdom besides.

The sessions surface — SessionRail, RailBar, Home, EmptyPrompt, Composer one-line, ChipSelect

A coding surface's shell is these pieces, each in the home its kind already had. hanzo.build's look is the default: an app that mounts them gets it.

Piece Home What it is
Composer inline · head · foot @hanzo/ui/chat inline puts field and send in ONE row inside the frame (↵ idle, Stop busy); head is drawn ABOVE the frame (the context chips), foot UNDER it (attach, voice, mode … model). With neither, the frame is the root exactly as before — no wrapper — so existing callers' trees are unchanged. ComposerTool is one quiet 24px control for those rows.
Home @hanzo/ui/chat a fresh pane: mark + question ($8, centred, role=heading) and the composer as children, grouped in the middle of the pane in one column (default 768).
EmptyPrompt @hanzo/ui/chat the smaller question at the TOP of the column, for a pane whose composer stays at the foot. The mark is a slot; no brand is picked here.
SessionRail @hanzo/ui/chat head (brand wordmark — press = onBrand ?? onNew — over a bordered Search box when onSearch) · New · links · a More disclosure · Recents (status dots, sort control) · notice · account row (name over sub) with its menu · collapse. Built on Sidebar/SidebarIconButton. The sidebar canon: collapse is collapsed in / onCollapse out (the host persists), collapsed is a 56px icon rail whose top row expands (then a search icon), and below md the column is display:none and the same contents open as a left Sheet (open/onOpenChange); EVERY press in the drawer that leads somewhere closes it — New, a recent, a link, a More link, the brand, search, an account-menu row.
RailBar @hanzo/ui/chat the phone's header, below md only: menu (opens the drawer) · brand · search. In flow at the top of the pane.
RailNotice @hanzo/ui/chat the card for SessionRail notice: icon, title, one action (aria-describedby the title), dismiss.

One way each: search is the head's box (an icon on the collapsed rail), and settings/usage/help/sign-out are rows of the ACCOUNT MENU — the foot has only the account row and the collapse control. The account menu is the same body UserMenu draws (product/account.tsx, off the product barrel), in a package Popover anchored to the account row itself: top-start on the open rail, right-end on the collapsed one. No anchor numbers.

A choice inside a menu is group + menuitemradio. MenuRow, UserMenu's body and OrgSwitcher used a radiogroup of radio rows inside role="menu", and axe fails that outright (aria-required-children: "children which are not allowed: [role=radiogroup]") — a menu owns menu items, groups and separators. gui's role union is React Native's and lacks menuitemradio, so MenuRow casts once, and on native (no such role) the row is radio.

Every account sheet works from the keyboard. A MenuRow is press(onPress) (focusable, Enter/Space) with the ring; the popover's focus scope then lands on the first row when the sheet opens and loops Tab inside it; menuKeyDown (product/menu/roving.ts, now over menuitem/menuitemradio/menuitemcheckbox, and leaving a field's own Home/End alone) moves on the arrows with wrap. Escape is the popover's — and the RETURN of focus to the trigger is ours: gui's popover returns it through a trigger ref that an asChild child never fills, so focus fell to <body>. UserMenu, OrgSwitcher and the rail's menu each hold a ref to their trigger and focus it in onCloseAutoFocus. The drawer does the same for RailBar's menu button: a dialog returns focus to its own trigger and the drawer has none, so SessionRail remembers what had focus when it opened and hands it back on close (after the closing event, so an overlay tap's mousedown cannot blur it again). It reads the opener in RENDER, on the render where open turns true: gui's Dialog is a native <dialog>, Chromium moves focus into it as it opens, and then the focus scope's onOpenAutoFocus never fires (focus is already inside) — the first cut read it there, passed on jsdom (whose <dialog> moves nothing) and left focus on <body> in every browser. So the consumer suite measures it: ?page=phone renders Phone from @hanzo/ui/gallery (a bar and a drawer on a page with nothing else open — the gallery's open modals would take focus back). The drawer tells the host onOpenChange(false) once per gesture: a choice and the dialog's own dismissal can both fire in the turn it unmounts, so a latch collapses them and lets go after the turn. Mutation-checked in SessionRail.test.tsx / product/menu.test.tsx.

A stack that should scroll is a ScrollView (overflowY="auto", as Thread), never a stack given overflow="scroll" — that scrolls nothing on native. Home and Settings are; Shelf is web-only with its grid. Add is ONE button through add, busy and added (aria-disabled, still focusable), so focus does not fall to the page when the add lands. A settings Note's role=status is always mounted, empty when silent — a live region that mounts with its text is often unread.

press(run) (backends/gui/press.ts) is the one spelling of a stack-drawn button — role=button, tabIndex 0, onPress, and Enter/Space — and RING beside it is the one focus ring (five files each declared their own copy). | ChipSelect · RepoSelect · BranchSelect | @hanzo/ui/product | a chip that opens an UPWARD (flipping) searchable list: chosen row pinned first with ✓, footer, cta, the search at the BOTTOM. Data is load(q, after) → {items, next} (debounced, paged on reaching the end, stale answers dropped by generation) or a whole items list searched in place. quiet is the plain look for a choice in a row of words. Repo/Branch are thin wrappers over the host's loader and link; no git host is baked in. |

Rules these carry, each learned by building them:

  • gui does not activate role="button" on Enter. Measured: a keydown Enter on an XStack with onPress fires nothing; a click fires once. So every control here handles Enter/Space itself — and that cannot double-fire, for the same reason.
  • A listbox option may not contain a control (axe aria-required-children / nested-interactive). A row's second action ("Add to project") is therefore a DECLARED action {label, onPress, when}: drawn on the active row for the pointer, run by Ctrl/⌘+Enter for the keyboard, announced through aria-describedby.
  • A loader is read through a ref, never a dependency. Hosts pass inline functions; keying the fetch on the loader's identity refetches on every render.
  • The cursor lands after the first page. A loader answers after the panel opens; until the cursor is set on that first row, Enter chooses nothing.
  • followable(href) gates every link out of the panel: a same-origin path or http(s). javascript:, data: and protocol-relative //host are not drawn.
  • Focus: the search field takes focus on open (not the first focusable, which is a footer link), the field owns the cursor through aria-activedescendant, and closing returns focus to the chip.

Every mounted suite runs audit() (pkg/ui/test/axe.ts: axe-core, WCAG 2.2 A/AA, contrast left to the browser) and asserts zero violations.

Plan usage limits — useLimits, UsageMeter, LimitedBanner (@hanzo/ui/product)

product/limits.ts is the GET /v1/ai/limits contract (also on /product/pure): limitsOf checks the body, servedOf reads a served call's X-Hanzo-Usage, -Usage-Class, -Paid-By, -Fallback, -Usage-Reason, and refusalOf reads the billing_error envelope of a 402/429 — and the 429 rate_limit_error the gateway sends for free_plan_cap and usage_cap_exceeded (ai limitReached: caps that lift by themselves are typed as rate limits), and no other rate limit. classOf(id) sorts a model into premium (third-party), ours (zen/enso/kai/jev) or free. noticeOf words a pause ("Premium models are paused until Oct 31. You're chatting on Zen Free.") or the server's message; nearOf is the one-line near note. Shares only — no copy here ever states an amount, a count or a cap, and limits.test.ts asserts it.

useLimits(read, key, name) holds the limits: the host passes its own authenticated read (base URL, bearer, org stay the host's), and calls observe(response) in its fetch for every AI call; a served header or refusal that disagrees with the last read triggers a re-read. UsageMeter draws one row per class (bar in $good/$yellow10/$bad, "Resets ", a slim session bar for a short window); LimitedBanner is the message plus the server's actions. ModelPicker takes limits: a model whose class is limited, or that a paused entry names (exact id or * glob), says "Paused" and still picks. PlanUsage is the page block: plan name, period, UsageMeter, the plan's terms in plain words (PLAN_TERMS/FREE_TERMS) and the actions, led by the banner when paused. The server's actions arrive in its order and LimitActions draws them so — the first filled (primary), the rest quiet. upgrade/topup are pages and open on their own; credits (the org's PUT /v1/ai/limits {creditsAfterAllowance}) and switch (a model for the picker) are drawn only when the host passes onAction. A class pays from plan|credits|free|none. PlanUsage shows the continue-with- credits switch only when the limits carry creditsAfterAllowance and the host passes onCredits. A model_cap names the one capped model from limits.paused and leaves its class open. A fallback reply carries X-Hanzo-Fallback (it may name only the lane, free) and X-Hanzo-Served (the model that answered); servedOf takes the served one. After the re-read a plan_allowance_used fallback counts only while the limits say limited; a paid_plan_required or model_cap fallback, like a refusal, stands until an answer comes back without one — a free plan's limits have no class to say it in. Placement: bars (UsageMeter, PlanUsage) render on a usage settings page only, never in a chat surface. A chat draws LimitedBanner only when the reader was turned away — notice.fallback or notice.refused — with onUsage opening its usage settings ("See usage"); it never draws a near note.

Settings and catalogue pages — @hanzo/ui/settings, @hanzo/ui/catalog

Lifted from hanzo.build's Settings and Customize so every surface draws them the same way.

  • Settings — entries {id,label,group}, groups? (default: the entries' own, first-seen), active, onPick, children (the open section). From md up a 220px grouped nav (role=navigation, each group a list labelled by its name, aria-current="page" on the open entry); below md a chip row carrying the same entries; the section in a 760px column. The section parts: Heading (level 2), Group (level 3), Card (a bordered box — NOT a list, since sections put form lines and Soft in it), Row (first draws no rule; mono sets $mono), Field, Soft (action?), Note (role=status, nothing when empty), Once (value in $mono + CopyButton).
  • Shelf — title, detail, tabs (View[], the kinds, an underlined WAI-ARIA tablist: one tab stop, arrows/Home/End), view/views (Yours/Discover by default, drawn by agents' Views — the package's one segmented control), search/query/onQuery, add/onAdd, children. Tiles (a named list on @hanzo/ui/grid { min: 280 } — the grid there is the one grid, so there is no second Grid), Tile (press and action are two controls side by side), Featured, Add (+ button / role=img check). catalog is its own subpath rather than part of /product because it is web-only (a CSS grid div), and the product layer promises web + native.
  • A titled dialog and a confirm are DialogTemplate / ConfirmDelete (/product) — not lifted again.

The docs (apps/ui.hanzo.ai, published by hanzo.yml's site: ui — not from hanzoai/shadcn, whatever the header above says) have chat, agents, settings and catalog groups beside ui/product/blocks; an example file is named EXACTLY after its module (examples/product/ChipSelect.tsx), because the page looks it up by module name. A new group is a GROUPS entry in catalog.ts, app/<group>/{index,[name]}.tsx, its lines in app/routes.d.ts, and a header and footer link. Its code — fences in data/docs, each example's source, each module's types — is highlighted at build by code.ts: shiki in codeTheme (@hanzo/ui/core), every token and the block's ground written as light-dark(), so the scheme on <html> picks Dracula or GitHub Light and no stylesheet carries a palette. No highlighter ships to the browser.

Code — CodeEditor is CodeMirror 6, JsonTree is gui, checkJson is the one verdict

CodeEditor was a plain TextArea with a gutter — no colouring, fixed height, no resize. It is CodeMirror 6 now, in the same gui frame and under the same import, so FileTabs and every caller kept working. It is the package's one code editor; do not add a second.

  • Height. No height → the editor follows its text from minHeight to maxHeight, then scrolls. The footer is a role="separator" that drags (or ArrowUp/ArrowDown) to a height of the reader's own, past the cap; a double-click hands it back to the text. height="100%" fills a sized frame (the body flexes only then). CodeMirror's base .cm-scroller { height: 100% } resolves against an auto-height editor as its MIN-height and pins a growing editor at its floor — the theme sets flex: 1 1 auto; height: auto; min-height: 0 instead. Measured, not guessed.
  • JSON. language="json" adds @codemirror/lang-json and a verdict field: a broken document tints its line (.cm-fault), underlines the byte (.cm-fault-at) and names line, column and reason in the footer. allowText lets prose pass and still holds {/[ to JSON. Format (Shift-Alt-F) re-indents. One grammar ships; other languages edit as plain text, and the doc comment says so.
  • checkJson (backends/gui/json.ts) decides, everywhere. JSON.parse is the arbiter; a broken document is walked again by an RFC 8259 scanner for a position and a reason that read the same on every engine (V8 names a position, Firefox a line, Safari nothing). A host sending what the editor shows calls the same function (@hanzo/ui/primitives/checkJson is import-free, node-safe).
  • Colour is a theme rung, never a design text token. --ink, --soft, --dim, --edge, --panel, --raised, --bad — gui emits each on the theme class, and they read design (--foreground, --border, --state-error). --text-primary is NOT safe: a host that mounts design's sheet without its light selector (the console) keeps the dark theme's white on a light page — measured, the syntax vanished.
  • Syntax is the code theme (src/code-theme.ts, 8.27.83): codeTheme is shiki's names (dracula dark, github-light light) and syntax the eight colours (key, string, number, boolean, null, punctuation, comment, keyword). gui-config publishes each as a theme key ($codeKey, var(--codeKey) …), so it follows the nearest theme. Shiki paints number, boolean and null alike (and GitHub Light paints a key the same), so those take other colours from the same theme. It was monochrome on purpose before: keys, numbers, booleans and null were all --ink, strings --soft. Server code (a shiki block in an RSC) imports it from @hanzo/ui/core; the root barrel is a client boundary.
  • The scanner is a loop over an explicit stack, not a call per nesting level: '['.repeat(20000) exhausted the call stack and handed the editor a NaN position. Under allowText, [ only means JSON when a JSON value follows it, so a log line ([INFO] …) is text.
  • A controlled value the editor reported is an echo, however late it comes back (sent holds every text given to onChange and not yet seen as value); writing a parent's one-keystroke-stale value back in dropped the key and moved the caret.
  • Grip is the one resizer (backends/gui/grip.tsx, exported; moved from @hanzo/build, which hanzo.ai's sidebar and asides use). side is the edge the box is pinned to: left grows right (a sidebar, a split's first pane), right grows left (an aside), top grows down (CodeEditor's and JsonTree's height). It sits absolutely on the free edge, measures its parent as drawn on every drag and key, steps 8px (32 with Shift), Home/End to the bounds, onShut for a snap past the floor, reset or onReset on a double-click, and draws its line only on hover, drag or keyboard focus (no outline). useSpan(store, initial, floor, ceil) (moved from @hanzo/rooms) keeps a width in localStorage and draws it through --span. build and rooms still carry their own copies until they move onto these.
  • Folding. JSON gets a fold gutter on every multi-line object and array. The fold runs from { through } (lang-json folds inside the brackets) so the placeholder can draw {…} 3 keys / […] 2 items; the count is read off the syntax tree.
  • Wrapped lines hang under their own text (a per-line padding + negative text-indent of the line's indentation plus two), so a long string in nested JSON still reads as its key's.
  • JsonTree draws any JSON value as a disclosure tree (rows are buttons with aria-expanded), first depth levels open, Expand all / Collapse all / Copy. A long value wraps anywhere — a hash otherwise sets the tree's min-content width and pushes a phone's page sideways. Built from gui only. The header's filter (search, default on; not filter, which is gui's CSS prop) keeps rows whose key, dotted path or value contains the text, plus their ancestors, opened (sift); a matching branch keeps its whole subtree, and clearing restores the open set from before. maxHeight scrolls, resizable adds the grip, defaultHeight/onResize let a host remember the height.
  • ResizableHandle: arrows move it, a double-click restores defaultLayout, and it states aria-valuenow (the share before it); autoSaveId persists to localStorage. It stretches across the group (self="stretch"), not 100% of it: in a group as tall as its content a percentage resolves to nothing and the handle drew no line.
  • JsonTree's header is one row (title, filter, three icon actions); the filter and the actions wrap as one group under the title on a narrow pane. The filter has no adornment: Input's adornment wrapper holds the field at its intrinsic width.
  • A View does not shrink. RNW Views are flex-shrink: 0, so a toolbar's button group held its width at 390px; the groups carry shrink={1} minW={0} + flexWrap.

modularizeImports support

scripts/gen-primitives.mjs reads the gui backend barrel and emits one src/primitives/<Member>.tsx per exported value (re-export from the backend). This makes @hanzo/ui/primitives/Button etc. resolve, so a host whose next.config rewrites @hanzo/ui → @hanzo/ui/primitives/{{member}} works unchanged. Re-run pnpm gen:primitives after changing the surface.

Build — plain tsc, one file in, one file out

There is no bundler. pnpm build is two tsc passes, scripts/postbuild.mjs, then scripts/gen-css.mjs (which renders the gallery through vite's SSR pipeline to harvest config.getCSS() into dist/styles.css — the slow step, ~2 min):

Pass Config Emits
ESM + types tsconfig.build.json dist/**/*.js, .d.ts, .js.map, .d.ts.map
CJS tsconfig.cjs.json (--noCheck) dist-cjs/**/*.js, folded into dist/**/*.cjs

postbuild.mjs does the only two things tsc will not: it resolves every relative specifier to a fully-specified path (./button → ./button.js, ./x → ./x/index.js; .cjs on the CJS half) so Node ESM and strict bundlers resolve, and it prepends 'use client' to every emitted module — the whole library is client-side @hanzo/gui UI and Next's flight-client loader wants the directive first. It is prepended without a newline so source-map lines hold.

@hanzo/data runs this same script, with its package root and its own data modules as arguments (node ../ui/scripts/postbuild.mjs . theme,table/logic,…). It has the same two formats and the same two problems, and a second copy of the file would be a second place to get the barrel rule wrong. That package used to point its exports at src/index.ts and ship raw TSX — every consumer had to transpile it, and require('@hanzo/data') could not load at all, which is one of the two edges that broke require('@hanzo/ui'). It emits dist/ now, both formats, from 1.2.2.

The output is UNBUNDLED and mirrors src/ one-for-one, so a consumer importing one symbol pulls one module. A bundler here would be actively harmful: tsup's code splitting emitted 11 shared chunk-*.js, and importing Button alone dragged in chunk-RCMDRI6V.js (48K of source). Measured with esbuild, import { Button } from '@hanzo/ui' costs 4717 bytes bundled from tsup output vs 2021 from tsc output. Dropping rollup-plugin-dts (tsup's dts worker) is also what makes the package build on TypeScript 7, which it cannot do otherwise.

Every package here emits declarations the same way, and none of them use tsup's dts. That worker loads rollup-plugin-dts, which reads ts.sys at import time; TypeScript 7 moved the compiler API behind ./unstable/*, so it throws Cannot read properties of undefined (reading 'useCaseSensitiveFileNames') before writing anything and takes the whole build down. A tsup package therefore builds tsup && tsc --emitDeclarationOnly --declaration --outDir dist && node ../../scripts/dts.mjs — one spelling, everywhere.

scripts/dts.mjs is the last step because tsc will not write the same declaration under two extensions, and a dual-format package promises .d.cts beside .d.ts. It reads the package's OWN exports, copies each missing alias from the .d.ts tsc emitted, and exits non-zero if a promised declaration has no source. That check is the point: a subpath with no types resolves to any for every consumer without erroring anywhere, which is how @hanzo/react came to publish four subpaths — ./hooks, ./components, ./tools, ./mcp — that resolved to nothing at all, two of them with no source directory in the repo. They are gone; the root barrel already exported everything they named.

Three things TypeScript 7 requires that 5 did not, each of which failed as "cannot find" rather than as a config error:

  • types is now the whole list. TS7 stops sweeping every installed @types package into scope, so a project naming any of them must name all of them — pkg/ui said ["react"] and lost node:fs in its own suites. Add it to the CHECK config only; tsconfig.build.json overrides back to ["react"] so node's globals stay out of a browser library's declarations.
  • A relative specifier is resolved strictly. declare module '*.css' no longer covers import './styles.css', and that file is GENERATED into dist after tsc runs. allowArbitraryExtensions plus src/styles.d.css.ts is the form the compiler asks for, and it beats a placeholder stylesheet in src that would shadow the real one.
  • moduleResolution: node10 is removed (TS5108), and the TS5095 rule that bundler needs an ES module target went with it. Every CJS config here used to state node to escape TS5095; they inherit bundler now.

pkg/annotate is the one package still on TypeScript 5, and it stays there: it consumes the compiler API (ts.ScriptKind, ts.Node), which TS7 does not publish from its main export.

@hanzo/canvas ships compiled, from 0.2.3. Its exports pointed at ./src/index.ts and ./src/pure.ts, so every consumer had to transpile it — the same defect @hanzo/data carried until 1.2.2 — and it also put this package's source inside a CONSUMER's program: @hanzo/cd then spanned two packages, its common root became the repo, and tsc refused to emit anything for it (TS5011). gui.config.ts and gui.d.ts moved into src/ in the same change so nothing lands outside dist.

Everything under src/ is emitted, so every exports subpath resolves by construction — no hand-maintained entry list to drift.

NOTE: pkg/ui publishes through .github/workflows/publish.yml like every other package here — the workflow globs pkg/*/package.json, one root. Measured — bumping this package's version and pushing main put 8.0.115 on npm with no further step. Read the glob, not this paragraph.

Install from the REPO ROOT, not from pkg/ui. This package depends on siblings by workspace:* (@hanzo/cd among them), so pnpm install --ignore-workspace here cannot resolve them and stops at ERR_PNPM_WORKSPACE_PKG_NOT_FOUND — the standalone recipe this paragraph used to give. One root pnpm install links every sibling and this package with it:

pnpm install                        # from the repo root
pnpm --filter @hanzo/ui gen:primitives   # refresh the per-member entrypoints
pnpm --filter @hanzo/ui exec tsc --noEmit

The reason given for going standalone was that the optional-peer kits are not on the public registry. They are: @hanzo/canvas, @hanzo/dashboard, @hanzo/gitops and @hanzo/usage all resolve on npmjs.

The kits = canvas, wallet, network, billing, dashboard, usage, gitops, data. Add one by mirroring src/gitops.ts (a one-line export *) + a ./name export

  • an optional peer/devDep. pkg/* is a pnpm workspace member (for workspace:* dev links), and pkg/ui publishes on a version bump like the rest — see PUBLISH_GUIDE.md. The shared shell lives here too: AppHeader + BrandMark (@hanzo/logo) + OrgSwitcher + orgScope (the console org-scope contract, hoisted per #36). Lux surfaces use @luxfi/web3 for wallet/login; @hanzo/ui/wallet+/network are the Hanzo-branded equivalents.

Appearance, end to end

One chain, one writer per step:

@hanzo/tokens  src/theme.ts — the colour system (dark :root, .light)
  -> dist/colors.css, copied by @hanzo/design's gen on every build
@hanzo/design  tokens/*.css — ramps that read the knobs:
               --type-scale --type-ratio --density --radius-scale,
               the --primary / --accent family
               vars(pref) — a preference as those properties
@hanzo/appearance
               apply(pref) — properties inline on <html>, the theme as
               classes (light/dark + gui's t_light/t_dark), kept under
               hanzo.appearance.painted; bootScript() replays it pre-paint
               useAppearance() — resolve install < org < person, sync IAM
               useScheme() — light|dark as the document shows it
@hanzo/ui      gui-config: every theme key that names a colour reads the
               design var (accentBackground -> --accent, accentColor ->
               --accent-foreground, accentHover -> --accent-hover, edge ->
               --border …); radii x --radius-scale, space x --density,
               type -> --text-*; <Hanzo> mounts useAppearance + useScheme

The workspace rooms that consume all of this ship as @hanzo/rooms (github.com/hanzoai/rooms), beside this repo rather than in it, the way @hanzo/build does.

What a host does: bootScript() in <head>, <Hanzo appearance={…}> (or useAppearance() + defaultTheme={useScheme()} beside its own gui provider), and nothing else — no next-themes, no class mirror, no theme toggle of its own.

An accent is a family. vars({ accent }) writes the fill, the ink that reads on it (design's #0a0a0a or #fafafa, whichever contrasts more) and a hover (color-mix toward that ink) on both --primary-* and --accent-*. A colour it cannot read (named colours, wide-gamut spaces) is not an accent.

Measured on live hanzo.ai and hanzo.team before 0.2.6: a stored accent reached no page on load (the boot script skipped it and nothing applied it until the panel opened); theme lived in three places (next-themes, IAM useUserTheme, none in appearance), all per origin; --radius-scale was read by gui and written by nothing; the primary Button's hover and PrimaryButton ignored the person's accent; design hand-edited a colours file generated from tokens.

Repository Structure

ui/
  pkg/                   every package, and the reason this repo exists
    ui/                  @hanzo/ui@8 — the core library (npm)
    appearance/          @hanzo/appearance     composer/ @hanzo/composer
    data/                @hanzo/data           hanzo/    the CLI
    event/               telemetry client — POST /v1/event
    observe/             capture engine        og/       OG image generation
    commerce/  checkout/  shop/  products/     canvas/   cd/   dashboard/
    agent-ui/  annotate/  react/  replay/      sentinel/ tokens/  desk/
    events/    next/      vite/   source/      observe-native/  observe-svelte/
    voice/               @hanzo/voice — dictation, read-aloud, talk mode, live transcript
  apps/
    cd/                  demo app for @hanzo/cd

One root: .github/workflows/publish.yml globs pkg/*/package.json. A package there ships on a version bump.

Build Order

@hanzo/ui depends on siblings that type themselves through their own "types": "dist/index.d.ts", so they must be built first. The ... suffix does that, in topological order — never build @hanzo/ui alone.

pnpm --filter @hanzo/ui... build

Commands

pnpm --filter @hanzo/ui... build   # the library and its workspace deps
pnpm --filter @hanzo/ui test:unit  # styles + render surface
pnpm lint                          # lint all workspaces
pnpm typecheck                     # type checking
pnpm test                          # unit tests

How this ships

One way, and it runs on our own stack:

push  ->  git.hanzo.ai/hanzoai/ui           CANONICAL
          .hanzo/workflows/cicd.yml         the whole pipeline, from hanzo.yml
          .github/workflows/publish.yml     publishes pkg/*
          .hanzo/workflows/snapshots.yml    refreshes the visual baselines
  ->  npmjs                                 @hanzo/ui and the @hanzo/* family
    github.com/hanzoai/ui                   a mirror, pushed alongside;
                                            it runs nothing

No image and no deploy lane. This repo emits packages. ui.hanzo.ai is built from hanzoai/shadcn, which owns the docs site and the registry it serves.

git.hanzo.ai is canonical; GitHub is a mirror. There is no .github/workflows/ — every build, check, publish and deploy is a workflow under .hanzo/workflows/, which the forge reads. .hanzo/workflows uses GitHub Actions syntax, so a workflow moves between the two by changing directory and nothing else, and github.com has no runner registered for the hanzo-build-* labels these ask for. Keeping the mirror current means pushing both remotes; nothing carries refs for you.

cicd.yml names only the triggers: every decision — what to test, what to build, where it rolls — is read from the root hanzo.yml. No Vercel, no preview deploys.

Publishing

One way: bump a package's version in its package.json and merge to main. .hanzo/workflows/publish.yml detects the changed @hanzo/* package and publishes it to npm (needs NPM_TOKEN as a forge secret). No changesets, no version-PR bot — the semver bump is the trigger.

It is the SOLE publisher of every non-private @hanzo/* in pkg/*, and it mirrors the same tarball to api.hanzo.ai/v1/packages/hanzo/npm when HANZO_REGISTRY_TOKEN is present. That mirror is best-effort by construction: no token means a notice, not a failure, and npmjs stays authoritative either way.

The gate

hanzo.yml's test: block, which cicd.yml runs through hanzoai/ci: ui-unit builds @hanzo/ui with its workspace deps and runs test:unit, and ui-consumer installs chromium and runs test:consumer under both bundlers — Vite and webpack disagree about css url() asset resolution, and a Vite-only gate is how 8.0.46 shipped a stylesheet pointing at a font the package does not pack. No coverage upload runs here.

test:consumer is red on published 8.1.0 and later, and it is not a split defect. @hanzo/ui → @hanzogui/lucide-icons-2 → [email protected] imports AssetRegistry, which [email protected] does not export, so the consumer app fails to build. The fix is a version pin on that chain, which is its own decision — do not paper over it here.

Telemetry — @hanzo/event is the ONE client (pkg/event)

@hanzo/event is the single canonical telemetry client for every Hanzo surface. ONE API surface over TWO planes — the client never sends the org; the server resolves the tenant.

  1. Event stream — pageview/event/identify/group (and an error breadcrumb), batched to POST {host}/v1/event with { batch: [Event, …] } -> { accepted, dropped }. Tenant from the session or a publishable pk_ key.

  2. Error plane — every captured exception is ALSO framed as a real Sentry envelope and POSTed to POST {dsn.base}/envelope/?sentry_key=…, i.e. the SAME /v1/event address the stream uses: /v1/event/{projectId}/envelope/. This is the ONLY thing that reaches the error dashboard.

    ONE address, from 0.3.29. Both planes are /v1/event — the error plane used to be spelled /v1/sentry/{projectId}/envelope/, a second public address for the same wire. And it was written THREE times: dsnForProduct minted it, parseDsn threw the DSN's path away and rebuilt it as a literal, and buildEnvelope restated it again in the envelope header. Dsn.base is that address now, DERIVED from the DSN in parseDsn, so dsnForProduct is the one place it is spelled. Do not re-introduce a second spelling, and do not hardcode a path anywhere downstream of the DSN.

There is NO server-side fan-out from /v1/event into Sentry. Versions ≤ 0.3.1 claimed there was ("lensed server-side into … error tracking"). There is not: cloud's handler folds the exception into properties.$exception, writes one row to the event warehouse (readable via GET /v1/errors), and stops. Because every property believed that claim, the whole fleet reported zero errors to Sentry until 0.3.2 added the envelope. Do not re-collapse these planes.

Configure the error plane with dsn (or NEXT_PUBLIC_HANZO_EVENT_DSN), minted per property via POST /v1/sentry/projects. The DSN key is publishable and write-only — safe in a bundle, same trust class as pk_. No DSN => the error plane is inert (fail-safe: nothing sent, nothing thrown, event stream unaffected); assert client.errorPlaneEnabled if you need to know.

There is NO third plane. Web analytics used to be one — analytics.hanzo.ai/hz.js posting a bare JSON array of {site, ts, type, …} to a second collector behind an identical path spelling — and 0.3.7 deleted both.

This package no longer ships a script tag at all. 0.3.33 deleted hz.js: the hosted tag is CLOUD'S, served at GET https://api.hanzo.ai/v1/event/tag.js from hanzoai/cloud (apps/event/tag.go, which splices this package's src/anon.js ahead of it so both distributions resolve ONE anonymous id). It versions with the address it posts to, which is what keeps a tag from drifting off its own wire. data-key is the attribute, pk-… the value, and no key means the tag installs nothing — a keyless beacon lands in a tenant its owner cannot read, so silence is the honest failure.

/v1/event.js was that tag's address until the ingest endpoint took the app's name. .js is part of a segment rather than a child of one, so the tag became a CHILD of /v1/event; the old sibling 404s and there is no alias behind it. Its config endpoint moved the same way: /v1/projects/tags, never /v1/tags.

So this package is the client for a surface that BUILDS, and the hosted tag is the client for one that does not. A page runs exactly one of them — both post pageviews to the same endpoint, so a page carrying both counts every one twice.

Entries: . (framework-agnostic: createAnalytics, EVENTS, GOALS, attribution + DSN/scrub helpers) and ./react (AnalyticsProvider, useAnalytics, usePageview, ErrorBoundary). Auto error capture (window.onerror / unhandledrejection / React boundary) makes it the drop-in error-tracking replacement. Secrets and PII are scrubbed client-side before an error leaves the device. SSR-safe, fail-soft, beacon-on-unload.

Build is a tsup dual bundle: CJS → .cjs, ESM → .mjs (required under "type": "module" — a CJS .js is parsed as ESM and crashes require() with "exports is not defined"). Each exports condition carries its own types.

Interaction analytics — <Hanzo analytics> is the one wiring

An app instruments nothing. <Hanzo analytics> (pkg/ui/src/root.tsx) is the whole setup, and every click / change / submit / route change inside the tree reaches POST /v1/event named by the component it happened on:

<Hanzo analytics={{ product: 'console', ingestKey: process.env.NEXT_PUBLIC_PUBLISHABLE_KEY }}>

Four packages, one of each concern, no duplication:

Concern Where Note
client + wire @hanzo/event (pkg/event) one endpoint, one key
capture engine @hanzo/observe (pkg/observe) delegated listeners, semantic annotation, redaction
provider + consent @hanzogui/telemetry (~/work/hanzo/gui) <TelemetryProvider/>; owns DNT/GPC + stored choice
curated events @hanzo/ui/product instrument.ts emit({component, action}) — what autocapture cannot know

analytics is a prop, not a default. Mounting a component library must not start a network conversation the app did not ask for. Off, no provider renders.

Component names are real in production. Every primitive already carries a data-slot (via slot()); componentName() in pkg/observe/src/annotate.ts reads it, ranked ABOVE the React fiber owner deliberately — the fiber name is dev-only, so grouping on it silently empties the dashboard at deploy. Labels keep the qualifier: card/button[Save].

It cannot double-count. The engine installs delegated listeners on a root, so two engines on one root report everything twice — which is what an app got by mounting a library provider AND <ObserveProvider/>, both correct instructions. Since observe 0.1.7 the first engine claims its root under a Symbol.for registry (page-wide, so duplicate copies of the package still see each other) and any later one stays inert (engine.capturing === false). Verified in Chromium, not only in jsdom.

The CLIENT cannot be doubled either. The same shape one layer down, and it was live on hanzo.ai/pricing until event 0.3.28: two clients on one page, each with its own queue, putting two batches on /v1/event in the same frame — one authenticated (200) and one with no Authorization at all (401 ingest_key_required), because the library asked for its client before the app supplied the key. Both batches held a $pageview for the same page, so the number was over- and under-counted at once and neither said so.

Since 0.3.28 createAnalytics returns THE client for a (host, product) stream, held on the page under Symbol.for('hanzo.event.clients'). The slot is global for the same reason observe's is, and here it is load-bearing rather than defensive: @hanzo/event and @hanzo/event/react are separate tsup entries that each carry their own copy of core, so on any page importing both there are always TWO module scopes — a module-scope map would dedupe nothing. A caller arriving with a credential the client lacks hands it over (the key belongs to the stream, not to whoever asked first), and the error plane, which derives from that key, comes up with it.

pageview() records a view once, keyed on path + location. Counting a page is the client's rule, not each emitter's: AnalyticsProvider's autoPageview, the telemetry route hook and nav autocapture each correctly believe they count the first view and cannot see one another. Without this half, sharing the client turns two half-counted pageviews into two counted ones.

AnalyticsProvider no longer memoizes construction. useMemo(…, [client]) never saw a config change, and adding config builds a client per render since call sites pass an object literal — the memo was only ever standing in for an identity the registry now supplies.

Consent is decided in ONE layer. The engine takes enabled as a value; the provider resolves policy (GPC, DNT, stored hz_consent, build kill switch) and passes the answer down. Do not add a second, partial copy to the engine — the two then disagree about an explicit opt-in. Only a client that can emit takes the stream: createAnalytics skips the registry for enabled: false, and adopt fills in a missing credential and nothing else, so no surface overrules another's reading of consent in either direction. 0.3.27 registered the disabled one — TelemetryProvider renders once reporting enabled: false before its ownership resolves in an effect, and the client built in that moment became the one every later caller got, which took hanzo.ai's telemetry to ZERO. Whenever you touch this registry, read enabled off the live client (globalThis[Symbol.for('hanzo.event.clients')]), not just the request count: silence and correctness look identical in a network panel.

One way — supersessions (no divergent telemetry client)

Package Status Note
@hanzo/event canonical pkg/event, posts /v1/event only
@hanzo/capture (npm) deprecated → @hanzo/event the old name of this package; @hanzo/event is a superset
pkgs/capture (@hanzo/[email protected] dup) deleted stale in-repo duplicate, removed
hanzoai/analytics packages/event (@hanzo/[email protected]) deleted An unpublished FORK of this package in another repo. It was the only copy that could actually reach Sentry, while the published one here could not — the fleet's error telemetry died in that gap. Its envelope + scrub implementation was merged here in 0.3.2. Never fork this package again; it publishes from pkg/event only.

Package Exports

import { Button, Card } from '@hanzo/ui'
import { Button } from '@hanzo/ui/components'
import * as Dialog from '@hanzo/ui/primitives/dialog'
import { cn } from '@hanzo/ui/lib/utils'

Adding a Component

src/backends/gui/ is the surface and src/gallery.tsx is the list. Add the component to the backend, export it from the backend barrel, and render it once in the gallery — the styles test, the render test and the consumer screenshots all read that one list, so a component missing from it is a component three layers do not check.

pnpm gen:primitives                 # refresh the per-member entrypoints
pnpm --filter @hanzo/ui... build
pnpm --filter @hanzo/ui test:unit

The registry flow — two themes, an example, an MDX page, pnpm build:registry — belongs to hanzoai/shadcn now, along with the registry itself.

Tech Stack

React 19, @hanzo/gui on the @hanzo/tokens scale, plain tsc (no bundler), Turborepo + pnpm, vitest + playwright.

Upstream Sync

Nothing here syncs from upstream shadcn any more; that relationship moved with the registry and the CLI to hanzoai/shadcn. @hanzo/ui@8 is clean-room on @hanzo/gui.

Where Tailwind belongs, and where it is a bug

Two different things wear the same clothes here, and confusing them breaks something either way.

Framework — pkg/ui. @hanzo/ui@8 is @hanzo/gui style props on the @hanzo/tokens scale. Zero @radix-ui imports, zero utility classes; the only class names are hz-* handles its own theme.css defines. A Tailwind class appearing in pkg/ui/src is a mistake. (One exception, on purpose: hover-card.test.tsx passes text-xs as a caller className to prove an arbitrary class survives the merge, and that gui's own width outranks it — that is the interop contract for call sites still on Tailwind.)

Product — the v5 holdouts. pkg/commerce, pkg/checkout and pkg/shop still emit Tailwind class strings against the @hanzo/ui-shadcn@^5 peer. Tailwind there is the deliverable, not a defect. The registry and the CLI that hand those classes to customers moved to hanzoai/shadcn — do not "clean up" a registry, and do not go looking for one here.

The defect that survives a live pipeline. Tailwind reads SOURCE TEXT. grid-cols-${n}, rounded-${size}, scale-${n*100} never become rules — and the failure hides, because a neighbouring file that spells one literally lends you its rule. grid-cols-3 is literal in two commerce files, so a three-option selector laid out and a four-option one stacked.

Ask Tailwind's own extractor rather than reasoning about it (from a tree that has it installed — this repo no longer does):

import { Scanner } from '@tailwindcss/oxide'
new Scanner({ sources: [{ base: '/abs/dir', pattern: '**/*.tsx', negated: false }] }).scan()

Anything the interpolation was reaching for is absent from that list. Two fixes, both one-way: a count or a length becomes an inline style (gridTemplateColumns: repeat(n, minmax(0, 1fr)) is what the utility compiles to); a value off a fixed scale becomes a literal lookup table, so the extractor can see every arm.

Commerce is still on the v5 line and cannot leave yet. @hanzo/commerce peers on npm:@hanzo/ui-shadcn@^5 and holds the repo's last direct @radix-ui/* import (react-radio-group, for an image tile — v5's RadioGroupItem hardcodes a 16px dot and takes no children). v8 has gained RadioGroup/RadioGroupItem/Image; what it still lacks, and commerce imports, is ApplyTypography, MediaStack, Skeleton, Carousel, the Form* set, and the media type surface (Dimensions, ImageDef, MediaStackDef, MediaTransform, VideoDef, AnimationDef). The peer is one choice for the whole package, so commerce moves when those land, not file by file.

A primitive that discards a prop is the migration's real blocker

Two components here silently dropped the prop their caller cared about, and both were what stopped hanzo.chat converting its last Radix call sites. Neither was visible as a failure: a discarded prop is not an error, the component still renders, and the test suite was green through both. Fixed in 8.0.73.

  • PopoverContent destructured align into a variable it never read. Every caller asking for a left- or right-aligned panel got a centred one. gui keeps the whole placement fact on the popper ROOT as one floating-ui string while the compound API splits it into a side and an align, so Content now publishes into the root exactly as sideOffset already did. place(side, align) is the rejoining and it is a PURE function, because the panel is portalled and positioned at run time — it never reaches server-rendered markup, so no snapshot could have caught this and the decision is the only assertable thing.
  • Slider spread caller props onto the root, but gui puts role="slider" on the Thumb — so every aria-label landed on a plain container and the control announced as unnamed. named() routes the four ARIA naming properties to the thumb and leaves value/range/step on the root, where gui reads them.

Both tests are mutation-checked: reverting either fix fails them (2 and 3 respectively). A test nobody has watched fail is not known to run.

  • DialogContent rendered <DialogOverlay /> with no props and no way in, fixed in 8.0.115. Content owning its own portal and overlay is the point — it is what lets a caller mount Content alone — but owning is not hiding, and with nothing through, the dim, the stacking order and the click target were unreachable from outside the package. A consumer stacking a preview over a dialog had no way to say which one dims which. overlay?: DialogOverlayProps is the way through; absent, nothing changes. This is the last of the three things keeping hanzo.chat's dialog files on Radix, whose own Dialog lets them render the overlay themselves.

    Its test reads the COMPUTED z-index, never el.style: gui compiles a style prop to one atomic class (_z-1234) and writes no inline style at all, so el.style.zIndex is '' on an overlay that is correctly stacked. Written the inline way first — and the test failing against working code is what said so.

Before believing a report that a primitive is MISSING, check the version it was measured against. A fleet pass concluded @hanzo/ui "cannot receive" Accordion, HoverCard or RadioGroup and that <TabsTrigger>Label</TabsTrigger> renders an empty tab. All four claims were true of 8.0.63 and false of 8.0.72 — the three primitives exist and ink() wraps bare text children in a Text host. That stale answer is what a consumer repo reads to decide the migration is blocked, so it costs a whole conversion.

The deepest instance of this family is NOT ours to fix: a ref to dialog content never reaches the DOM. src/backends/gui/dialog.ref.test.tsx pins it, and its assertions are deliberately wrong — they describe the defect, so the day it is fixed the file goes red and is deleted.

Measured on @hanzo/gui 8.1.0 AND 8.2.0, so it is not a version anyone can upgrade past today. The reading is only trustworthy because of three controls, and each was needed:

  • a bare gui stack in the identical harness DOES deliver a node, so a zero is a fact about Dialog rather than about jsdom or the provider;
  • the content is proven MOUNTED — a dialog that never opened answers zero refs correctly and reads identical;
  • role="dialog" is in the document, which is DialogContentFrame's and marks the one branch of gui's DialogContentImpl that DOES attach the composed ref (the adapt/portal-item branch attaches none). So the ref-attaching branch ran and the ref still never arrived — it is lost inside gui between DialogContent's .styleable wrapper and that frame.

The callback fires ZERO times, not once with null, and the distinction is worth keeping: an object ref cannot tell "never attached" from "attached then detached", which is why the pin uses a callback.

Do not "fix" this by adding forwardRef here. It would forward into a component that discards it, producing a wrapper that typechecks, renders and delivers nothing — worse than the honest gap, because the next reader stops looking. Only 7 of the 49 gui components take a ref at all today.

What it costs: any consumer whose behaviour is a DOM measurement on the content — drag, snap, getComputedStyle().transform, getBoundingClientRect — silently no-ops. No crash, no type error, no failing build. It is why the de-Tailwind sweep correctly REFUSED to convert react-drawer, whose whole mechanism is drawerRef.current.

One trap to skip on re-measure: the run emits React's "error during concurrent rendering but React was able to recover", and vitest flags it as possibly causing false positives — alarming, since a broken render is the other thing that yields zero calls. It fires in all three cases INCLUDING the control, and the control still delivers, so it is ambient to mounting <Hanzo>.

And bumping @hanzo/gui alone to check is not a check — it is the split the next section is about. Dev-bumping to 8.2.0 left @hanzogui/web resolved at 8.1.0 and every dialog render died on Missing theme. before any ref could be observed. Move the whole train, or measure on the pinned version.

The gui packages are one train, and a lone bump is a split

@hanzo/gui re-exports @hanzogui/web and @hanzogui/core, and src/gui-env.d.ts augments GuiCustomConfig inside both. That augmentation is what gives every component its shorthand props — bg, px, items, rounded — and the compiled .d.ts bakes the result in, so a consumer never re-declares it.

A declare module binds to a resolved FILE, not to a name. Move @hanzo/gui alone and pnpm nests the NEW @hanzogui/web under gui while this package keeps the old one: the augmentation lands on a file nothing reads, GuiCustomConfig stays empty, and every shorthand collapses at once. Measured here, only the pins changing:

pins tsc --noEmit -p tsconfig.json
whole train 8.1.0 0
@hanzo/gui 8.2.1, rest of train 8.1.0 462
whole train 8.2.0 0
whole train 8.2.1 0

So there is no 8.2.0 regression, and the 462 are one fact wearing 462 masks: unknown-property errors on shorthands (items ×122, bg ×100, minW ×33, p ×27, rounded ×22, px ×22), not one of which names a version or a package. The shape reads as an upstream API break with every call site wrong. None were.

src/gui.test.ts is the guard. It resolves @hanzogui/web and @hanzogui/core from this package AND from @hanzo/gui, and fails when the two are different files, printing both paths — so the answer is the version numbers in the store path rather than a hunt through 462 errors. It reads the INSTALL, not the pins: pnpm keeps a satisfied lockfile entry rather than re-resolving, so a pin is what was asked for and a resolved path is what arrived.

The peer floors move WITH the train (>=8.2.1 as of 8.4.13). Left at >=8.1.0, a consumer satisfies them with 8.1.0 beside gui 8.2.1 and rebuilds the same two copies in their app, where it surfaces as Missing theme. at first paint rather than as 462 errors at compile time.

Two packages removed public exports in a PATCH — decided, not an oversight

@hanzo/agent-ui 0.1.0→0.1.1 dropped getStatusTone, getStatusBadgeClasses, STATUS_TONES, type StatusTone and the ./style/* subpath, and moved its @hanzo/ui peer from ^5.0.0 to >=8. @hanzo/react 1.0.0→1.0.1 dropped cn. Both are live on npm and cannot be unpublished.

Publishing 0.2.0 / 1.1.0 would fix nothing, and that is the part worth knowing: ^0.1.0 resolves >=0.1.0 <0.2.0, so 0.1.1 is still the version a caret range picks. Only a RESTORING patch or a deprecation changes what anyone installs.

So it was measured instead. Nothing in the fleet imports @hanzo/agent-ui at all — the four grep hits are comments inside its own barrel — nothing imports @hanzo/agent-ui/style, and nothing imports cn from @hanzo/react. Last-month downloads are 83 and 107, which is CI traffic against packages with two and twenty-three versions. And every removed name is a Tailwind class-string helper this repo is deliberately deleting, so restoring them would re-import the thing the whole migration exists to remove.

Accepted, deliberately, with no version churn. Recorded here so the next reader who notices it does not spend a release cycle repairing a break with no consumer. If an outside consumer ever appears, the lever is npm deprecate on those two exact versions, not a new minor.

Gotchas

  • First run is CLI-first (8.27.87, onboarding/cli.tsx, launch.ts): a new account (made within NEW_WITHIN, Session.owesCli) meets "Set up the Hanzo CLI" after the terms and before the plans: curl -fsSL hanzo.sh | sh, then hanzo (browser sign-in, links Hanzo Tabs, asks once for the coding agent). The page polls the cloud's GET /v1/link (readLinks) and moves on when a computer registers; on a phone it offers the share sheet instead. @hanzo/ui/launch is the logic alone (commands, message, usePhone, useComputer) for hosts that draw their own surface (platform.hanzo.ai): the onboarding barrel reaches Checkout and so @hanzo/pay, which a host without it cannot resolve.
  • Phone rules in this package: a field is 16px on a touch screen ($touchable in Input and Textarea; iOS zooms under 16), and an inline link or link-button pads its hit area to 44px with $touchable padding and an equal negative margin, so the line does not move. The cookie bar (consent/Consent.tsx) publishes its height as --consent-h on :root and pads body by it while shown; a sticky footer sits at bottom: var(--consent-h, 0px).
  • pnpm run build in a worktree re-runs pnpm install when package.json changes and that hoists react-native into node_modules/.pnpm/node_modules, which turns gui's web types into RN's and fails tsc in files nobody touched. Delete that link, or run the build's commands directly.
  • Build with ... or not at all — pnpm --filter @hanzo/ui build alone reports its siblings as missing modules and blames @hanzo/ui for it
  • tsconfig.check.json does not exist, so pnpm typecheck:ui fails on a missing file. Use pnpm --filter @hanzo/ui exec tsc --noEmit until someone writes it
  • @hanzo/auth v2.6.0 uses a pluggable provider registry: registerAuthProvider('firebase', FirebaseAuthService)

Rules

  1. Use pnpm, not npm/yarn
  2. Never commit symlinked files (AGENTS.md, CLAUDE.md, etc.)
  3. Knowledge goes in this file, not random root MD files
  4. Anything shadcn-lineage belongs in hanzoai/shadcn, not here