chain-rdeveloper portal
build

Frontend Component Kits

How to build a page in modules/fe without writing markup that already exists. Read this before adding any page, and before declaring a component at the top of a page file.

The two apps have different jobs — fe-core is a logged-in control plane, fe-public a marketing and docs site — so they have separate kits rather than one shared one. fe-core is below, fe-public after it, fe-shared — the small package they both draw on — after that, and Testing last.

fe-core

fe-core has two shared kits. Between them they cover the two shapes almost every page in the app takes:

KitShape it ownsReach for
components/detailone resourceDetailPage + SectionCard

The rule behind both: a page supplies what is genuinely its own — its data, its fields, its actions — and nothing else. Spacing, loading branches, empty states, badge colours and dialog behaviour belong to the kit. When a page re-derives one of those, it drifts from every other page, and that drift is what these kits exist to stop.

Before writing a local const Foo: React.FC at the top of a page, check both kits. Skeleton, SectionCard, MetaItem and CopyButton were each hand-declared in 9–23 page files before they were extracted. If something looks worth declaring locally, it is usually worth declaring once in a kit.

Resource list pages — components/collection

Every list page (agents, skills, tools, knowledge, rules, experiments, worlds, …) renders through ResourceCollection: description → stats strip → the page's own summary, if any → search/filter/action toolbar → grid or list, with skeletons and empty states.

const filters = useCollectionFilters({
  defaults: { type: "all", sort: "recent" },
  unfiltered: ["sort"], // reordering hides nothing, so it is not an active filter
});

<ResourceCollection<Skill>
  description="Skills are reusable graphs an agent can call."
  stats={[{ label: "Skills", value: skills.length, Icon: BrainCog }]}
  shown={visible.length}
  search={{ value: filters.search, onChange: filters.setSearch }}
  filters={<FilterSelect … />}
  actions={<><GenerateButton … /><CreateButton … /></>}
  items={visible}
  itemKey={(s) => s.id}
  renderCard={(s) => <SkillCard skill={s} />}
  renderRow={(s) => <SkillRow skill={s} />}
  empty={{ Icon: BrainCog, title: "No skills yet." }}
  {...filters.toolbarProps}
/>

Conventions baked in:

  • Sort keys go in unfiltered so they are not counted as active filters and survive clear().

  • The grid/list toggle appears only when both renderCard and renderRow exist, so passing toolbarProps wholesale never produces a dead control.

  • Actions order is GenerateButton then CreateButton, so the primary action sits nearest the view toggle on every page. Both take either an onClick (open a modal — most resources) or a to (navigate to a setup flow — agents generate through GenerativeSetup), never both.

  • Every collection carries a description. One or two sentences saying what the resource is and when to reach for it, in the same place on every page. A tab that opens straight onto a toolbar makes the reader work out what they are looking at from the cards.

  • A kind is named, not tinted. A rule's layer (Access, Input, Tools, Output — where in a request it acts) is shown by its icon, its label and the section it sits in, from one registry (rules/ruleLayer.ts: the icon, the place in the flow, one grey class set). Rule cells were once tinted red, blue and amber with a saturated rail per type, which read louder than the rules; colour is kept for meanings — a StatusBadge scale (RULE_STATE, GOVERNANCE_OUTCOME). A record from before layers reads through layerOf. A knowledge source's type is the same: one registry (knowledge/sourceTypes.ts: label, icon, what one of its items is called, one neutral pill and tile), its keys pinned to svc-core's SOURCE_TYPES. The cards and the source page each kept a tinted copy, and they had drifted.

  • summary is a page's own overview, rendered between the stats and the toolbar, for what a row of numbers cannot say. The Rules tab puts its layer flow there (rules/LayerFlow.tsx): each layer's count, in the order a request meets them, doubling as the layer filter. Most pages leave it out.

  • gridVariant="wide" is for a page's primary resource — agents on Inference, repositories on Knowledge. It halves the grid to two columns so the thing the page is about does not render at the same size as the supporting resources beside it. Everything else keeps the three-column default. The class strings are whole and static in GRID_CLS: an interpolated grid-cols-${n} is purged by Tailwind and the grid collapses to one column in production only.

  • Heterogeneous groups (yours vs. the platform's) use sections with collectionSection<T>(…) to type-erase each group. A section's hint is a quiet line after its label ("What may the model read?"), and its action sits at the right of the heading. The Rules tab's sections are its layers, each holding the workspace's rules and then that layer's built-ins as templates (folded behind "Show N templates" once the layer holds rules of the workspace's), so one renderer tells a template from a rule by isSystemManaged.

  • Built-in rows are asked for, and cached apart. A listing that includes the platform's rows (include_system=true, e.g. listTestSuites({ includeSystem: true })) uses the query key [KEY, INCLUDE_SYSTEM] from services/query_keys ("include_system", the suffix the skillset and knowledge pickers already use), never the bare key. The bare key feeds counts (the Governance tab, Overview), and sharing it would count the gold datasets as the user's own. Invalidating the bare key still refreshes both, because the key is a prefix. Split the result with isSystemManaged, render a Built-in section above the user's own, and give a built-in row no delete: the API refuses it.

  • SegmentedFilter options take an optional count, so a filter can carry the "how much is in here?" number a sidebar leaf used to.

The URL is the filter state. useCollectionFilters reads and writes ?q=, ?view= and one param per filter key, so a narrowed list is a link: /user/knowledge?section=sources&type=graph is "the graph sources". That is what replaced the Knowledge page's per-type sidebar leaves — one list, filtered, with the old ?section=<type> links rewritten to it.

  • Only what is away from its default appears. An untouched collection has a clean URL, and setting a filter back to its default takes the param with it. defaults is what a param is compared against, so it is also what clear() restores.

  • Everything else in the query string is left alone. ?section= picks the tab a collection renders on; a filter write must not drop it. Writes replace the history entry — otherwise typing a search buries the previous page under one entry per keystroke.

  • Multi-selects repeat the key (?tags=a&tags=b) rather than joining on a comma, because a tag may contain one.

  • Give a page's second collection a prefix if it ever renders two at once. Nothing does today; the tabs mean only one collection is mounted at a time.

  • Changing tab drops the filters (setSearchParams({ section })): they name fields the next collection does not have.

Section navigation — components/nav/SectionNav

A page that holds several resources (Inference, Knowledge, Governance) navigates with SectionTabBar, driven by ?section=. Three rules keep that one control instead of two:

  • Every root resource is a tab. If a thing is not owned by another thing on the page, it is a tab — not a sidebar leaf under a neighbouring tab. Inference is Agents / Skills / MCP Servers for this reason; filing skillsets under "agents" made a root resource read as an agent's property. A tab also belongs to the page whose question it answers: Evaluation measures whether the fleet is fit for purpose, so it is a tab of Governance (Rules / Evaluation), not of Inference beside the things it measures.

  • A secondary relation uses SubsectionLinks, offered on the tab's own page, with SubsectionBackLink coming back out. The tab opens on what the reader works with, and the subsection is the step after it: Skills opens on skills (what a user builds and runs), with Skillsets (bundling skills to grant them to an agent) one link away; MCP Servers opens on the servers (what a user connects), with Toolkits (bundling servers for an agent) one link away; Agents holds Models. Governance's Rules opens on the rules, with Activity (what they did) and Reviews (what they asked a person) one link away: they were tabs, which made the evidence of one standard read as two more standards beside it. Skills and MCP servers used to be subsections of Skillsets and Toolkits, which is the containment order. It was the wrong order for the reader, because it opened on the bundle rather than the thing in it.

  • A feature that is not available yet keeps its tab, marked. A tab may carry a badge ("Soon") instead of a count, and its body says what is coming and what to use meanwhile. MCP Servers is one: MCP is off in every environment (util/mcp.ts, MCP_AVAILABLE), so the tab shows McpComingSoon (components/mcp), the toolkit route redirects to it, and nothing on any page requests, links to or offers an MCP server or toolkit. Gate a withdrawn feature on its constant at every surface — route, tab, picker, query and link — rather than deleting its pages, so it comes back by changing one value.

  • SubpageSidebar has no remaining use. Evaluation kept it for a while on the argument that Evaluations, Datasets and Reports were three readings of one body of runs — which is true, and still produced the one tab on the page with a 224px column beside a wide empty body. It now opens on the evaluations list and offers Datasets and Reports as SubsectionLinks, like every other tab. The component stays exported for a page that genuinely needs a persistent switcher; nothing does today.

Tabs carry a count badge; subsection links carry a hint. Old ?section= values must keep resolving — map them to the owning tab rather than letting an unknown value fall back to the first one, which reads as the resource having been deleted.

URLs — routes/const.tsx

APP_ROUTES mirrors the navigation, and the test file beside it pins that it does:

  • A tab or a filter is a query on the page that owns it; a detail page is a path under that page. Everything on the Inference surface lives under /user/inference/… — tools and the evaluation viewers were outside it while rendering inside it, which made the URL and the navigation disagree.

  • A list has one home. /user/evaluation/experiments and /user/inference/simulations were standalone pages duplicating what the tab already rendered, reachable only by typing the URL. They are gone; the paths redirect.

  • A route is named for what the product calls the resource, even where the backend still calls it something else. The evaluation section's two detail pages were the last place the old vocabulary was visible to a user — a dataset opened at /inference/evaluation/test-suites/id/…, with the breadcrumb spelling it out — while the types and the API router keep mirroring svc-core's experiments / test_suites, because those name real endpoints. The split is deliberate: product vocabulary on the surface, backend vocabulary at the boundary.

  • Moved paths redirect, they do not disappear — APP_ROUTES.USER.LEGACY plus legacyRedirect(target), which carries route params and the query string across. Redirect pages are exempt from the "every page is lazy" and page-smoke tests via their redirectsTo marker.

  • A legacy path is spelled with the new param name. legacyRedirect fills params by name, so an old /id/:testSuiteId redirecting to a template asking for :datasetId substitutes nothing and lands the user on a literal /id/:datasetId — a URL matching no route, which looks exactly like a deleted resource. routes/apps/apps.test.tsx fails when the two sides disagree.

Workspaces — routes/workspace.ts, components/owner

Every page shows one workspace — Personal, an organisation or a project — and fe-core mounts the same pages under /user, /organisation/<id> and /project/<id> (apps/workspace/WorkspaceApp; routes/apps/Workspace.tsx says which of Personal's pages a workspace shows — opt-in, so a new page stays Personal's until added there). Write a page once, against APP_ROUTES.USER:

  • Links follow the workspace on their own. react-router-dom is aliased (vite and vitest configs) to src/routes/router.tsx, whose Link, NavLink, Navigate and useNavigate move any /user/… target under the current workspace's prefix (pathIn). Account pages (Personal's settings tabs, invites, organisations) stay personal; Stats is per workspace. To go between workspaces — the workspace menu, "Open in Acme" — import from react-router directly.

  • The workspace menu (components/nav/WorkspaceMenu) sits in the header beside the account button, never in the sidebar. NavHeader reads the path as its Personal page (asPersonalPath), so the breadcrumb names the workspace rather than its id and Back finds the list inside the workspace.

  • Sidebar entries carry their icon (NavTitle), the workspace's home included, and a link is the current page where it goes: SectionLink and NavItem match through linkActive (routes/workspace.ts), never the /user/… route they are written as — which no organisation's URL is.

  • Settings is a tab bar, in every workspace. Personal's account tabs (SettingsTabs) and an organisation's or project's (WorkspaceSettingsTabs: General, Members, and Policies or Inheritance, at APP_ROUTES.USER.WORKSPACE_SETTINGS) draw the same TabGroups (components/page/TabGroups); each tab is its own route, and the sidebar has one Settings entry. The old /members and /inheritance paths redirect. Personal's tabs add a Developer group (Scenario runs) only for the developer platform role: a page or tab for a platform role reads the user with useCurrentUser() and asks hasPlatformRole (util/platformRoles.ts; a superuser holds every role), and still renders without an AuthProvider, as the smoke tests mount it.

  • Requests name it. useApiHandler adds ?workspace=<key>, so lists are the workspace's and creates land in it: a create form has no owner picker. Each workspace has its own query cache.

  • Read it with useWorkspace() (context/WorkspaceContext.tsx): its kind, id, key, prefix and, once resolved, its name, parent and your role. Never read an organisation's or project's id from route params.

  • Say why a row is there. Lists annotate origin (own / inherited / required / built_in); OriginBadge draws "Inherited" / "Required". On a detail page, WorkspaceGuard (built into DetailPage) sends a resource opened in the wrong workspace to its own, and marks an inherited one read-only with "Open in Acme" and, given copyKind, "Make a copy here".

  • Tests: renderPage(el, { workspace }) renders inside one; Personal is the default.

Resource detail pages — components/detail

DetailPage owns the frame: back link → title → actions → AI-provenance banner → your body → edit history. Critically it owns the three states — loading, error, not-found — so all three keep the page's chrome instead of collapsing to a bare red <div>.

const ruleId = useResourceId("ruleId");            // never bare atob()
const { data } = useQuery<Rule | null>({ … });
const rule: Rule | null = data ?? null;            // see "Typing" below

<DetailPage<Rule>
  resource={rule}
  loading={isLoading}
  error={error}
  label="rule"                                      // used in the not-found copy
  title={rule?.name}
  icon={<ShieldAlert className="size-5" />}
  back={APP_ROUTES.USER.rules}
  actions={[<button key="delete" … />]}
  resourceId={ruleId}
  history={{ source: api.rule_router, queryKey: QUERY_KEYS.GET.RULE_HISTORY,
             fieldLabels: { name: "Name", conditions: "Conditions" } }}
  overlay={confirming && <ConfirmDialog … />}       // survives every state
>
  {(r) => <RuleBody rule={r} />}                    {/* never sees null */}
</DetailPage>

history is deliberately not optional. Every user-creatable resource has an edit history (see CLAUDE.md, Resource History & Generative Provenance); pass history={false} only for a documented exception, with a comment saying which — e.g. scenarios, which are versioned through their world.

Tabs on a detail page — DetailTabs, useDetailTab

A detail page with more than one view of its resource (a knowledge source's Overview, Content and Usage; a repository's Overview, Sources, Usage and Agents) puts them behind tabs in the address: const [tab, setTab] = useDetailTab(KEYS), then <DetailTabs tabs={…} active={tab} onChange={setTab} /> as the first thing in the body. ?tab= is the state, so a tab is a link and Back returns to it; the default tab is never written; an unknown value falls back to the default rather than blanking the page; every other parameter (?workspace=, a list's filters) is kept. The bar is the section navigation's SectionTabBar, so a detail page's tabs look like a section page's. The edit history stays under every tab — DetailPage renders it after the body. Agent.tsx still keeps its tabs in component state; move it when it is next touched.

What goes inside the body

ComponentUse it forNotes
MetaGrid + MetaItemthe metadata stripsize="sm" for dense headers
StatusBadgeany status pillalways pass a scale
TagLista resource's tagsself-guarding; shows +N rather than dropping
CopyButtoncopy-to-clipboardvariant="bare" for inline, icon-only
ConfirmDialogdestructive confirmationnever window.confirm()
Modal + ModalActionsany dialog with a form in itnever a hand-rolled overlay — see below
Skeleton / SkeletonLinesloading placeholdersSkeletonCard/SkeletonRow from collection for whole cards

Dialogs — Modal, and why not a fixed inset-0 of your own

Two dialogs, and nothing else. ConfirmDialog asks a question and offers two buttons; Modal holds a form. Both close on Escape and on a backdrop click, trap focus while they are open and hand it back on the way out, lock the page behind them, and announce themselves to assistive technology.

<Modal
  title="New case"
  icon={TestTube}
  size="lg"
  busy={save.isPending}
  onClose={close}
  description="What this dialog is for, if it needs saying."
  footer={
    <ModalActions
      onCancel={close}
      onConfirm={submit}
      confirmLabel="Save"
      loading={save.isPending}
      disabled={!prompt.trim()}
    />
  }
>
  …fields…
</Modal>

Do not write the overlay yourself. Nine pages did, all with the same markup — fixed inset-0 … flex items-center justify-center around a max-w-lg card — and all with the same defect. A panel taller than the viewport is centred inside its container, and the part that overflows the top of a centred flex item cannot be scrolled to. Adding overflow-y-auto to the overlay does not help; that is what those nine copies already did. The dataset page's "New case" form is long enough to overflow a laptop, so its heading, its first field and its close button sat off the top of the screen with no way to reach them.

Modal bounds the panel instead — a flex column no taller than the viewport, whose header and footer hold their place while only the body scrolls — which also keeps the title and the Save button visible on a long form.

ModalActions is the Cancel/Confirm pair. Its tone is a meaning, the same way StatusBadge's scales are: generative for an action that asks a model to write something, danger for one that destroys something or overrides a refusal. Anything on the left of the row (a checkbox, a reason why Confirm is disabled) goes in as children.

SectionCard variants

One shell, three clusters. Pick the variant that matches the page; drop to className / bodyClassName only for something genuinely one-off.

VariantHeaderBodyUsed by
formtinted, boxed icon when it has a descriptionpx-5 py-5 space-y-5New* / Edit* pages
settingsplain, top-aligned with a descriptionchildren divided by a hairlineSettings pages

Optional props are additive: subtitle (beside the title), description (below it), action (right-aligned), className, bodyClassName.

When a whole section of the app always wants the same variant or spacing, bind it once rather than repeating it at every call site — agents/setup/primitives.tsx exports a form-bound SectionCard, and evaluation/components.tsx exports one carrying the section's mb-4. Both are one-line specialisations of the shared component, not copies of it.

StatusBadge and status scales

Status colour is a meaning, not a palette choice. STATUS_TONE_CLASSES maps seven tones to classes, and each domain declares which of its statuses carries which tone:

<StatusBadge status={world.status} scale={LIFECYCLE_STATUS} />
<StatusBadge status={run.status} scale={RUN_STATUS} size="sm" />

Three scales ship: LIFECYCLE_STATUS (draft/active/running/completed/archived/failed), RUN_STATUS (queued/running/completed/failed/cancelled) and EVALUATION_STATUS. A swarm run and its tasks have their own (SWARM_RUN_STATUS, SWARM_TASK_STATUS): partial — answered from part of the work — is a warning, and a task skipped when its run wrapped up is muted, set aside on purpose. Note completed is done in the first and success in the second — a finished simulation is merely finished, a finished run succeeded. That is why they are separate scales rather than one lookup.

For a domain vocabulary of your own, declare a StatusScale beside the page and pass it. Adding a status means adding one entry to a scale — never a new colour string, and never a new badge component.

Route ids

Resource ids travel base64-encoded in the URL. Always decode with useResourceId("agentId"), never atob(param):

const agentId = useResourceId("agentId");   // string | null

Bare atob throws on input that is not valid base64 — a hand-typed URL, a stale bookmark, or a navigation that forgot to encode — taking the whole page down with an uncaught InvalidCharacterError instead of showing "not found". useResourceId returns null for both "absent" and "unreadable", which is the only distinction a page acts on. Encode with encodeResourceId(id) when building a route.

Built-in resources

A system row (isSystemManaged) is read and used, never changed. That covers CHAINR Bot, the guide, News, the built-in skillsets and the gold datasets. On its detail page:

  • Offer no write the API refuses: no edit, delete, add / remove member, upload, re-index, move or delete-document. Browse, preview, download, search, history and (for a skill) Run stay. Badge the title with BuiltInBadge, and use a note to say what the user can do with it.

  • Using a built-in changes the user's resource, not the built-in. A repository goes into an agent through the agent's grant routes, from either side: the agent's Knowledge tab, or Use in your agents (RepositoryAgentsCard) on the repository's page. Each change is a version of the agent.

  • Check that the API sends the flag. A test whose fixture already says is_system: true proves that the page reads the flag, not that the flag arrives. The repository responses left it out, so News looked like the user's own while every frontend test passed. Pin the response on the backend (tests/test_builtin_repositories.py).

Cost — components/cost

Every page whose resource calls a model carries a ResourceCostCard — agent (Activity tab), skill, evaluation, and a dashboard with automation or comparison tiles. It reads GET /app/stats/cost for source + sourceId, so a dashboard's card counts its tiles whichever agent they borrowed.

<ResourceCostCard source="skill" sourceId={skillId} noun="skill" className="mb-4" />

Write any figure of spend through format.ts, never toFixed: describeCost({cost_usd, unpriced}) renders null as Unknown (never $0) and a figure with unpriced calls as ≥ $x, which is what the backend's cost contract means; formatUsd writes a bare amount (evaluation's formatCost is it with an em dash for unknown). A new resource that invokes a model gets a card, a UsageEnum.Source, and a row in docs/guides/cost-monitoring.md.

A page-level figure of the viewer's spend — Overview, Stats, the stat tile, Activity — comes from useSpend({ period }) (or { since, until }), which reads the same ledger with mine=true; never sum svc-ai's traces for money. Caption it with spendLabel(cost): Your spend or Workspace spend, as the response says it counted.

A budget's spend against its cap is a BudgetBar (a tick where its forecast lands), coloured by its BUDGET_STATUS — the same meaning as its badge. Any "this much of that" bar is the detail kit's MeterBar (share, a MeterTone, an optional marker), which replaced the hand-drawn bars on Overview and Settings → Subscription. Governance → Spend (apps/user/pages/spend) is built from these, and its Add budget dialog writes an ordinary cost_cap rule (budgetRule). The platform allowance, when the deployment sets one, is an AllowanceCard in the same list (a BudgetBar, no link: no rule backs it). Each budget card says when it alerts (alertText, from the catalogue's quota_alerts). Its Statements card lists each month (StatementsCard, statementHref), and a month opens as pages/spend/Statement.tsx: a DetailPage with no edit history (a record, not a resource), its month read from the address with parseMonth rather than useResourceId (a month is not an encoded id), Download CSV and Print as actions (print:hidden, so the printed page is the statement alone). For those who govern the workspace (governs, from GET /app/budgets) the card also offers Export for finance: a From / To month range downloading one CSV (statement_router.downloadExport). A statement under a plan draws its Charges card, and every amount on it goes through the cost kit's formatUsdCents — always to the cent, since formatUsd drops the cents past $1,000 and a bill must not. The workspace's cost centre is in the Spend figures and each project's beside it on the by-project table; an admin sets them on the workspace's General settings (CostCentreRow).

Agent and skill pages put TokenStepsCard ("Where the tokens go", GET /app/stats/steps) under the cost card; stepLabel names each step from nodeMeta's system node labels — every system node's name and icon is objects/systemNodes.ts, which the execution pipeline, Activity's trace and a skill run's steps all read. A chat answer's cost (cost_usd / unpriced_calls on the message) shows on hover in ChatPanel's meta strip.

Charts — components/charts

The marks every chart draws with, in one place: they had sat in an evaluation page (AXIS, ChartTitle, TooltipCard) and a dashboard tile (the assurance sparkline).

  • AXIS — recessive axes and ticks for a recharts chart, in a caption's text colour.

  • SPARK — a sparkline's inks as whole class strings: history in the de-emphasis grey, the current period in the accent, an empty period a hairline, a reference line. Checked with the dataviz palette validator against the card surfaces (white, gray-800): each clears 3:1, the pair separates under every colour-vision deficiency, and both sit in the lightness band. Marks draw in currentColor, so no SVG holds a hex.

  • Sparkline — a small line, oldest left (values, null for no reading, which breaks the line rather than drawing a zero), with an optional dashed reference and dotted breaks titled with what changed. The assurance tile's bot sparkline is it on the score scale.

  • SparkBars — thin columns, one per period, the latest in the accent; each column's hover names its period and count over a target the strip's full height, and the whole reads aloud as what it adds up to. A knowledge card's 30 days of citations is one.

  • ChartTitle, TooltipCard — a chart's title and note, and the card its hover shows.

  • KpiStrip / StatTile — a page's headline figures: label, value (proportional figures), and a line under it — a comparison against the period before, or what the figure counts. Whole-string grid classes by tile count.

  • StackedBars — columns split into series (a crawl's pages by what became of them), bottom first, a 2px surface gap between segments, a legend naming every series, a hover readout of the column, and a hidden table. Series classes are the caller's, from a palette checked with the validator (the crawl history's is in CrawlHistoryChart.tsx).

  • RankedList — things ranked by a count (agents citing a source, its most cited documents, its sites): label, value and a thin bar on a lighter step of the same ramp; rows in the order given, so ordered buckets (how recently pages changed) keep their order.

  • TimeSeriesChart (components/charts/TimeSeriesChart, outside the index) — a count per day as recharts columns with a per-column hover card. Stub it in a page test: vi.mock("@/components/charts/TimeSeriesChart", …).

The index exports only plain SVG and HTML pieces. A recharts component goes in a file of its own, outside the index, so a page test can vi.mock it (ResponsiveContainer needs a layout box jsdom does not have — RiskReturnChart.tsx is the pattern). A "this much of that" bar is still the detail kit's MeterBar.

Graph canvases — FlowFrame, and which layout

Every read-only graph canvas — the network tiles (NetworkCanvas), a graph source's entities (EntityGraph) and a repository's source map (knowledge/map/SourceMapCanvas) — draws in components/dashboard/widgets/network/FlowFrame. It is React Flow in a bordered, dot-gridded pane with zoom controls, fitted to what it holds, nothing draggable or connectable, and its chrome themed for dark mode through React Flow's CSS variables, once (its own colour mode follows the OS, not the app). Pass the flow's nodes, edges and handlers; size the pane with frameClassName.

Pick the layout by the graph's shape:

  • Layered (network/layout.ts layeredLayout) — kinds in columns, every edge crossing one column to the next: agent → repository → source, agent → conversation → memory. Selection lights a lineage (lineageOf). columnsByDistance makes columns for a graph with no kinds.

  • Force (knowledge/map/forceLayout.ts, d3-force) — a web of undirected, weighted ties with no layers. It is deterministic: nodes are sorted by id, the random source is seeded, and the simulation is stopped as it is built and ticked synchronously. Compute it once per graph and let filters only hide (hidden on React Flow's nodes and edges), so nothing moves under the reader. Selection lights one hop (neighboursOf), since a lineage would light the whole component.

Under a canvas, give a table of what it draws: it is the graph for a screen reader and for a graph too dense to read (the source map's Connections). A node's status as a ring is STATUS_TONE_RING (components/detail), the badges' meanings as border classes, each clearing 3:1 on the card surfaces; name the status on hover or beside it, never by colour alone. Keep the canvas in its own module so a page test can stub it, as with TimeSeriesChart.

A skill's inputs — components/form/RunFields

A skill's run schema (its RunFields) is drawn by RunFieldControl, one field at a time: an enum is a select, a number a number box, an array a list, an object a JSON editor, anything else a text box. Two places take a skill's inputs, and both use it, so a skill asks for the same thing wherever it runs: the skill page's Run form (SkillRunForm) and the chat's command form (components/chat/CommandForm, under a /execute skill token).

<div className="@container">
  <div className="grid @md:grid-cols-2 gap-x-4 gap-y-3">
    {fields.map((f) => (
      <RunFieldControl key={f.name} field={f} value={values[f.name]}
        error={errors[f.name]} onChange={(v) => set(f.name, v)} idPrefix={id} />
    ))}
  </div>
</div>
  • The values and their checks are util/runForm.ts: initialValues (defaults, or a previous run's), toInputs (typed values, and an error per field svc-core would refuse; REQUIRED for a blank required one; blank optional fields left out so they cannot shadow a default).

  • Lay the fields out with a container query, not a breakpoint: the form is as wide as the card or chat it sits in. A list or object field spans both columns.

  • Give each form its own idPrefix (useId()): the ids label the controls, and two forms on one page must not share them.

Maps — components/map

Every Leaflet map — the sessions map in Settings, a map block in a chat response — draws on BasemapLayer, so the tile provider, its key and its credit are decided once, in tiles.ts:

<MapContainer center={center} zoom={4}>
  <BasemapLayer dark={resolvedTheme === "dark"} />
  {/* markers, GeoJSON … */}
</MapContainer>

The tiles are CARTO's (Positron in light mode, Dark Matter in dark), and CARTO requires a key. It does not refuse a request without one: it answers with an "API KEY REQUIRED" watermark, which reads as a broken map. So with no key configured BasemapLayer requests nothing and puts Map tiles not configured in the attribution corner; markers and shapes still draw on the plain background.

Tiles come from the URL CARTO documents for keys, https://basemaps.cartocdn.com/rastertiles/<style>/…?key= (with @2x tiles for high-DPI screens), rather than the older https://{s}.basemaps.cartocdn.com/<style>/… form still common in examples. A watermark means the key is missing or isn't a basemaps key: it comes from carto.com/basemaps/apikey, not from a CARTO account's API access tokens (the ones shown beside its …api.carto.com base URL), which don't work here. A 403 (blank tiles) means the key is locked to domains that don't include the page's.

  • The key is VITE_CARTO_API_KEY, baked in at build time. Locally it goes in core/.env (or .env.standalone.local). Deployed builds read it from SSM — /chainr/dev/fe-core/VITE_CARTO_API_KEY, set with tools/seed-ssm-params.sh — in infra/aws/cicd/buildspec.yml, so a new key needs a new build, not just a redeploy. none means no key.

  • It is public by construction. CARTO's terms forbid proxying or caching tiles server-side, so — unlike site icons, which svc-core fetches and caches so no third party learns what a user reads — the browser fetches tiles from CARTO directly, key included. Lock the key to the app's domains in CARTO's dashboard. CARTO checks the Referer, which is why the layer pins referrerPolicy="strict-origin" (the origin and nothing else) whatever the page's own policy becomes.

  • CARTO sees who looks at what. Each tile request carries the user's IP and the area in view — on the sessions map, the area around their own sign-ins. Taking that away means serving tiles from the platform, which CARTO's terms rule out: self-hosted OpenStreetMap tiles, not another hosted provider's.

  • The free tier is 1M tile requests a month for commercial use (October 2026); a map view is a dozen or so tiles. The next plan is $500/month.

Times from the server

svc-core and svc-ai store naive UTC. Their API responses now carry an explicit offset (+00:00, see docs/system/data/timestamps.md), but timestamps kept inside stored JSON (edit-history snapshots, older experiment config) still have no zone ("2026-09-24T10:00:00"). new Date(str) and moment(str) read a zone-less date-time as local time, so every time shown would be off by the viewer's UTC offset, and "5 minutes ago" would turn into "in an hour". Read every server timestamp through @/util/time, whichever form it arrives in:

parseServerDate(row.created_at).toLocaleString()   // a Date in the viewer's zone
parseServerDateOrNull(row.finished_at)             // optional fields: null, never "Invalid Date"
serverTime(a.created_at) - serverTime(b.created_at) // sorting / bucketing
moment(parseServerDate(msg.sent_at)).fromNow()

It reads naive ISO as UTC, leaves anything with a zone alone (svc-auth's +00:00, …Z, RSS's …GMT), and reads a bare YYYY-MM-DD as that calendar day locally. new Date would read it as UTC midnight, which is the previous day west of Greenwich. The hygiene test fails any new Date(…) that is not built from a number, and any moment(…) not wrapping parseServerDate. A string that genuinely is local time (a datetime-local input's value) says so with a local-time: comment.

Typing

fe-core pins TypeScript 5.0.2, which cannot infer @tanstack/react-query v5's useQuery return type. data therefore arrives as any and every field read off it goes unchecked. Bind the result to an explicitly typed const:

const { data, isLoading } = useQuery<Rule | null>({ … });
const rule: Rule | null = data ?? null;

ResourceCollection<T> and DetailPage<T> both take an explicit generic for the same reason — passing it pins the type the query could not.

There is no lint or typecheck script. To typecheck, write a scratch tsconfig.json extending core's whose include is only src (the checked-in config pulls in vite.config.ts, which the pinned compiler cannot parse), run npx tsc --noEmit from modules/fe/core, and diff against a baseline — the clean tree already reports ~145 pre-existing errors.

Tests

Every kit component is covered in components/detail/detail.test.tsx and components/collection/collection.test.tsx. When you add a component to a kit, add its tests there. Page-level tests live beside the page.

One gotcha: several kit tests render the same markup with different props. Give each render its own container and unmount() it, or getByText becomes ambiguous across a shared document.

Showing that something was AI-generated

Two components, and the distinction between them is not cosmetic.

GeneratedMark marks a resource — a sparkle on the corner of its icon. It wraps the icon rather than replacing it, so the glyph underneath still says what kind of resource it is:

<GeneratedMark generated={skill.is_ai_generated} label="AI generated skill">
  <div className="p-2.5 rounded-lg bg-violet-100 dark:bg-violet-900/30">
    <Network className="size-5 text-violet-600 dark:text-violet-400" />
  </div>
</GeneratedMark>

AppearanceSwatch takes aiGenerated / aiLabel and does this for you, so a resource with a stored icon and accent needs no wrapper at the call site. DetailPage marks its own title icon from the resource it was given.

This replaced a pill reading "AI Generated" beside the resource name. On a list page that pill competed with the name, the tags and the status badge for one row of space — three things saying what the resource is and a fourth saying where it came from, all weighted the same. Provenance is a property of the resource, so it belongs on the thing that identifies it.

AIGeneratedBadge marks an event — a version in an edit history, a row in the activity feed. An event has no icon to mark and no tags to compete with, so the pill is still right there. Do not reach for it on a resource.

Tracing a resource to the invocation that made it

is_ai_generated says that something was generated and stops there. generation_id — served on every generated resource's Read schema, not only on its version trail — resolves through GET /app/generations/{id} to the invocation: the flow, the exact arguments the user gave, the model that answered, warnings, and everything else the same run produced.

DetailPage mounts AIProvenance for you. It states in one line whether the resource was generated directly or alongside a parent agent (linking that agent), and offers "View invocation" — which is when the run is fetched, not before. Provenance is a fact about the resource, not a warning about it, so it does not open a panel of JSON in front of what the reader came to see.

For a page that does not use DetailPage, mount it yourself:

{board.is_ai_generated && (
  <AIProvenance
    resourceLabel="dashboard"
    generationId={board.generation_id}
    resourceId={board.id}
  />
)}

resourceId keeps the resource off its own "also created" list. Pass generatedByAgentId for a dependent resource — a skill, worker, knowledge stub, repository or rule created alongside an agent.

Underneath both this and the history panel is one component, diff/GenerationDetails, keyed on the run's id. A history row also holds an inlined GenerationRef and passes it as summary so its header paints before the request lands; a resource has only its generation_id and passes nothing. Its variant="full" adds who invoked it, when, and what else came out.

A run is scoped to whoever invoked it, so a teammate's resource states its provenance and says the arguments are not available to you, rather than failing.

Saving a chat response as a PDF

components/chat/ExportPdf/SaveAsPdfButton sits in the assistant message's action row, and the same button with a .pdf label sits beside the .md and .json exports in the conversation toolbar. Both hand a DOM node to util/pdfExport's exportNodeToPdf, which clones it into a hidden iframe and opens the browser's print dialog — where every OS offers Save as PDF.

It prints the rendered node, not the markdown behind it. That is what makes diagrams come out right: Mermaid diagrams, Recharts charts and plots, the network graph and KaTeX math are already SVG on screen, so they print as vector rather than being re-derived by a rasteriser that would have to understand the stylesheet (and would choke on Tailwind v4's oklch() colours). Adding a new renderer to RichMarkdown therefore needs nothing here — if it renders, it prints.

Three things the export does have to handle:

  • Dark mode. The print document carries no dark class, so every dark: variant (&:is(.dark *)) drops out and the page prints light. Mermaid is the exception, because it bakes its theme into the SVG it emits — so the rendered block carries its source as data-mermaid-source and the exporter re-renders it light, restoring the app's own Mermaid theme afterwards.

  • Chrome. Buttons, Leaflet's map controls and anything marked data-pdf-hide (the expanded-diagram overlays) are dropped from the clone, and hover-only rows have their opacity-0 removed so they do not print invisible.

  • Canvas. A <canvas> does not survive cloneNode, so each one is replaced by a PNG snapshot of the live element at its displayed size.

  • Maps. Leaflet tiles are <img>, so a map prints as the static snapshot you were looking at — same centre, same zoom. A dark basemap is swapped for the light one (same tile server, a URL swap that keeps the key), the map keeps its own overflow: hidden while everything else has its scroll box opened up, and the attribution control is kept while the zoom control is dropped — OpenStreetMap and CARTO require the credit to travel with the tiles, and an exported PDF leaves the platform.

Mark anything that is an affordance rather than content with data-pdf-hide.

A page whose state outlives a section — SectionErrorBoundary

The app-wide ErrorBoundary (main.tsx) replaces the whole tree and its buttons reload, which is right for an unexpected page and wrong for a wizard holding something already paid for. Wrap the part that may fail — a wizard's step body — in SectionErrorBoundary (components/ErrorBoundary.tsx) with a resetKey (the step) and a fallback: the section is replaced, the parent's state and its own navigation stay, and moving on tries again. The generative agent wizard does this, and keeps its draft in this tab's sessionStorage (apps/user/pages/agents/setup/draftStore.ts) so a reload restores it.

Layout that depends on the room a component has

The width a component gets often depends on what else is showing: the app's navigation, a sidebar beside it, full screen. A viewport breakpoint can't know any of that, so size these layouts from the component's own width.

  • Arrangement that changes structure (the chat's conversation list beside the chat, or a bar above it): measure the element with hooks/useElementWidth. It measures in a layout effect, so the first paint uses it, then follows the element with a ResizeObserver. 0 means unmeasured (jsdom, a hidden element), and callers keep the wide layout for it, so tests see today's layout. ChatLayout stacks below STACK_BELOW_PX (768) and tells the sidebar (sidebar(fill, stacked)).

  • Styling only: use CSS. Tailwind v4 has container queries built in (@container on the parent, @xs:/@sm:/… on children), as in the stacked bar's New chat, which drops its label under 20rem. Or use a wrapping flex row.

  • flex-1 zeroes a basis. It is flex: 1 1 0%, so beside basis-56 it wins and the item never wraps. Use grow basis-56 for "take the rest, or wrap to a line of my own below 14rem". With flex-1 beside the tools the chat's message box was 26px wide. It now wraps only before the row is measured: a measured narrow row is compact (see "A chat's controls").

  • An auto-height textarea must refit when its width changes, not only when its text does (ChatPanel's fitTextarea). A box measured while narrow keeps the height of its wrapped placeholder.

A chat's controls

  • Above the agent chat is one row, components/chat/AgentChat/AgentChatToolbar:

    • the skill graph switch;

    • the model, a dropdown with "Agent default" naming the agent's own model;

    • the tools, AgentToolsMenu, a popover with the count on its trigger.

    Detail goes behind a dropdown rather than into another bar.

  • Beside the message box are actions only: attach, commands and Response settings. The paperclip is a menu (ChatPanel/AttachMenu): Upload from computer, the library's five newest ready documents not on the message (Recent, recentDocuments, so one uploaded in another conversation is attached again in one step), and All documents, the library above the box (its separate button is gone). Settings that change what comes back live in Response settings, which every chat has:

    • the response format (ResponseFormatSection), on every chat;

    • temperature, thinking and the system prompt, where the model takes them (supports*).

    The button is highlighted, and its title names the format, while one other than Markdown is chosen.

  • A narrow composer folds them into one menu. Below COMPACT_BELOW_PX (560px of input row, measured: the chat dock, a phone, a chat page beside its list on a small screen) the actions are ChatPanel/ComposerMenu, a ⋯ button beside the message box, which takes the rest of the line. It draws the paperclip's own items (AttachItems), so the two menus never differ. In the dock they had left the box about half its row. The trigger follows the settings button's rule (highlighted while a panel is open or a format is chosen, the format in its title), and Commands opens the palette once the menu has closed, so the caret lands in the box. Compact, the keyboard hint goes; the AI disclosure and the note that a turn outlives the page stay.

  • A sent message names its documents by id (svc-core meta.attachments, read through messageAttachments, which still reads a block pasted into an older message). Each chip opens the original (ChatPanel/SentAttachments, util/chatAttachments.openAttachment): a PDF or an image in a tab of its own, anything else — HTML and SVG included — saved, never opened from a blob in the app's origin. An attached document's citation card opens it the same way (CitationRow, attachedDocumentId). See Attachments.

  • A Radix menu or popover inside a chat needs z-[70]. It portals to <body> at z-50, under full screen's z-[60]. ChatLayout leaves full screen on Escape only when no dialog, menu, popover or command palette is open (ChatLayout/escape.ts, escapeTakenBelow), so one key takes one step back. The chat dock minimises by the same rule.

Check a layout like this in a real browser at 390, 768, 1024 and 1440px: report document.documentElement.scrollWidth, which should equal the window, and list the outermost elements whose right edge passes the window. jsdom lays nothing out, so unit tests can only pin the classes and the measured branch.

A chat on its page or in the dock — AgentChatView, ModelChatView

The chat itself (socket or request per turn, stream ownership, running turns, HITL, commands) is one component per kind of target: components/chat/AgentChat/AgentChatView and components/chat/ModelChat/ModelChatView. Each takes the decoded id and a frame:

  • "page" (the chat routes). apps/user/pages/agents/agent/Chat.tsx and apps/user/pages/models/Chat.tsx are thin wrappers: they decode the route id with useResourceId and pass the ?conversation= / ?message= deep link. The view draws SubPage and a ChatLayout that runs to the bottom of the window, as before.

  • "panel" (the chat dock). ChatLayout frame="panel" fills the box it is given, with no heading, full screen, Escape or scroll lock: those belong to the panel. The list goes above the chat as a bar when the box is narrow, and both always fill it.

ChatView/ChatViewFrame draws the loading, error and ready states for each frame. A panel never renders SubPage. SubPage names the page (usePageMeta: the header title, the back button, document.title) and clears it on unmount, so a chat in the dock would rename the page it is open over. A change to the chat goes in the view, never in a page wrapper, so the page and the dock cannot drift.

The chat dock — components/chat/ChatDock

A button in the bottom-right corner of every signed-in page opens a chat panel above it: CHAINR Bot first, any of the workspace's agents or models from its picker, and full screen on request.

  • Mounted once, by the shell. MyApp takes a dock slot, rendered outside the pages' Suspense. UserApp and WorkspaceApp pass <ChatDock />; Developer and Legal do not. The dock survives navigation and page suspends, and is keyed by workspace, since a chat is governed in the workspace it is held in.

  • Nothing loads until it is opened. ChatDock.tsx is in the main chunk, so it imports no chat code. ChatDockPanel (the picker and the view) is lazy, fetched on first open and warmed on the button's pointerenter and focus. It has its own SectionErrorBoundary (Try again re-imports) and Suspense.

  • Opens on CHAINR Bot (target.ts defaultTarget): found by its is_system flag, never by position or id; else the first agent, else the first selectable model. Nothing is chosen while agents load. The choice lasts as long as the dock, not past a reload. Changing it keys a fresh view; a turn the old one was streaming runs on and is stored.

  • Minimised, not unmounted. Hidden with invisible, aria-hidden and no pointer events, so the draft, the scroll position and an open socket survive. Not display: none: useElementWidth reads 0 there and the layout would flash.

  • It keeps clear of the corners' controls. Docked on a wide screen it is 32rem wide, at most 44rem tall, and keeps 0.75rem from the launcher below it and from the header's row above it (NavHeader, top-5, 42px): sm:max-h-[calc(100dvh-9.625rem)]. With 7.5rem its top reached 2.5rem on a laptop, under the header's buttons (z-50), which covered its own Full screen and Minimise. A change to either corner's controls changes that figure (comments in ChatDock and NavHeader point at each other).

  • It does not block the page. No aria-modal, no focus trap, and no scroll lock while docked (full screen locks the page). Opening focuses the panel and then the message box (ChatPanel autoFocus, which only takes focus from <body> or the chat's own frame). Minimising from inside returns focus to the button.

  • Escape, one step at a time, in the capture phase: anything open over the chat first (escapeTakenBelow), then full screen, then the panel, but only when the key was pressed inside it.

  • Layers.

    • The button and the docked panel sit at z-40, under page dialogs, the header controls and every Radix menu.

    • has-[[aria-modal=true]]:z-[60] lifts the panel while a dialog the chat opened is up, so the dialog's backdrop covers the header.

    • Full screen is z-[60], as on a chat page. The picker's menu is z-[70].

    • Animate the panel with opacity only. A transform would make the chat's inline fixed inset-0 dialogs fill the panel instead of the window.

  • It stands aside on the chat pages (onChatPage: the agent and model /chat routes in any workspace), where its button would cover the page composer's Send. It stays mounted and comes back as it was.

Where things live

components/
  collection/      list pages — ResourceCollection, Toolbar, filters, useCollectionFilters
  detail/          detail pages — DetailPage, DetailTabs/useDetailTab, SectionCard,
                   MetaItem, StatusBadge, TagList, CopyButton, ConfirmDialog,
                   Skeleton, useResourceId
  page/            MainPage / SubPage frames (DetailPage wraps SubPage for you)
  cost/            ResourceCostCard, DailyCostBars, describeCost/formatUsd
  charts/          AXIS, SPARK, Sparkline, SparkBars, StackedBars, KpiStrip,
                   RankedList, ChartTitle, TooltipCard; TimeSeriesChart (recharts,
                   its own import)
  map/             BasemapLayer — the tiles under every map; tiles.ts holds
                   the provider, its key (VITE_CARTO_API_KEY) and the credit
  diff/            ResourceHistorySection — mounted by DetailPage
                   GenerationDetails — one invocation, resolved from its id
  governance/      RuleEventRow — one rule evaluated against one turn, as
                   Governance → Rules → Activity and the decision record draw it
  decisions/       VerdictBar — Accept / Correct / Reject under a chat answer;
                   VerdictModal, AddToDatasetModal — the decision record's
                   verdict and "Add to dataset"
  badge/           AIProvenance — mounted by DetailPage
                   GeneratedMark — the sparkle on a generated resource's icon
                   AIGeneratedBadge — the pill, for *events* only
  appearance/      icon + accent pickers; TONES is the accent palette
                   (distinct from StatusBadge's tones, which encode state)
  chat/            ChatPanel and its message bubbles; RichMarkdown renders a
                   response (diagrams, charts, graphs, maps, math);
                   ExportPdf/SaveAsPdfButton prints one as a PDF;
                   ChatLayout — every chat page's frame: the conversation
                   sidebar beside the chat (above it, as a bar, below 768px
                   of its own width), and Full screen for both (pass `fill`
                   and `stacked` through to ConversationSidebar, `fill` to
                   ChatPanel); CommandPalette — the `/` command list;
                   CommandForm — a chosen command's token, its form, and
                   SentCommand, its record in the thread; ChatPanel/AttachMenu
                   — the paperclip's menu, and SentAttachments — a sent
                   message's document chips;
                   AgentChat/ + ModelChat/ — the chat views (AgentChatView,
                   ModelChatView) the chat pages and the dock both draw, and
                   the agent chat's toolbar; ChatView/ChatViewFrame — a
                   view's frame per page or panel; ChatDock/ — the corner
                   button and its lazy panel (picker, default target)
  form/RunFields/  RunFieldControl — one input of a skill's run schema, for
                   the Run form and the chat's command form
  ui/              low-level primitives (button, input, select, table)

fe-public

The public site is a marketing and docs surface: long scrolling pages of prose, cards and diagrams, with no resources, no queries and no auth-gated state. It has no use for ResourceCollection or DetailPage, so it has its own, much smaller kits.

Do not import between the two apps. They ship as separate bundles; anything genuinely common belongs in modules/fe/shared.

Scroll reveal — components/reveal

Every marketing page fades its sections up as they scroll into view. Wrap the block:

<Reveal size="xl">
  <Hero />
</Reveal>

{services.map((svc, i) => (
  <Reveal key={svc.id} size="lg" delay={i * 0.1}>
    <ServiceCard service={svc} />
  </Reveal>
))}

Pick size by how large the revealed block is — sm a paragraph, md a card, lg a group of cards, xl a whole page section. That is the only thing the six hand-rolled copies varied, so it is the only knob: travel distance and duration move together, which is what kept them looking like one site.

delay staggers a list; feed it the index. useReveal is exported for an animation that is not a fade-and-rise, but prefer the component.

Two behaviours live in the hook so no page has to remember them:

  • prefers-reduced-motion is respected — content renders in place with no transition. None of the six copies did this.

  • A missing IntersectionObserver reveals immediately rather than leaving content at opacity: 0 forever. This is why the pages render at all under jsdom.

Brand colour — components/theme/accents

Card tints and section labels come from a named palette, never a hex literal:

import { ACCENTS, BRAND_BLUE } from "@/components/theme/accents";

const SERVICES = [
  { title: "Governed inference", accent: ACCENTS.blue },
  { title: "Knowledge", accent: ACCENTS.violet },
];

ACCENTS holds the six-colour family (blue, violet, cyan, emerald, amber, pink) that Contact, Help, Services and the docs categories all draw from; ACCENT_CYCLE is the same set in display order for pages that assign one per item. BRAND_BLUE is the lighter blue used for eyebrow text on the page background — deliberately not ACCENTS.blue, which is a card tint and reads muddy as text.

These are hex strings, not Tailwind classes, because they are applied as inline style={{ color: accent }} on content whose colour comes from data. Tailwind cannot see a class name assembled at runtime and would purge it.

Page-level colours that are not part of this family — gradient stops, a single section's dark ground — stay where they are. The palette names what recurs; it is not an attempt to centralise every colour in the site.

Keep it dead-free

fe-public accumulated a lot of unused scaffolding. When you remove the last consumer of something, remove the thing:

  • components/ui/ is shadcn output. Only what a component actually imports belongs there — npx shadcn add <name> regenerates any of it in seconds, so unused components are pure cost. Only popover.tsx is in use today.

  • A route commented out of routes/apps/Home.tsx means its page is dead. Delete the page, not just the route entry.

  • Check package.json after deleting components. Removing the shadcn scaffolding took six runtime dependencies and 279 installed packages with it.

  • Declare what you import. popover.tsx imported @radix-ui/react-popover for months without it being in package.json — it resolved only because the radix-ui meta-package hoisted it into the workspace root, which is the kind of thing that breaks on a clean install.

Where things live

components/
  reveal/          Reveal + useReveal — the scroll-reveal animation
  theme/           accents.ts — ACCENTS, ACCENT_CYCLE, BRAND_BLUE
  page/            MainPage / SubPage frames
  app/             MyApp, AppShell, Pages — the nav-driven page-config shell
  nav/             Navbar, Footer, NavItem, NavTitle
  docs/            DocTree — the documentation sidebar
  ui/              shadcn primitives; only what is imported

Docs content lives in apps/home/pages/docs/ — docsData.tsx is the tree, docsContent.tsx the bodies, and components/DocBlocks.tsx the renderers (Callout, StepList, DocTable, CodeBlock, DiagramView). Adding a doc page means adding data, not markup.

fe-shared

modules/fe/shared is a real npm package (chainr-frontend-shared) that both apps depend on by file: path. It is small on purpose, and it holds exactly two kinds of thing:

  • Presentational components — the canvas animations both sites render, MyButton / MyLink / ThemeButtons, Card and its wrappers, CountUp, and the legal text (PrivacyPolicyBody, TermsOfServiceBody).

  • Theme — ThemeProvider / useTheme, the accent palette, and BRAND_RAMP.

Nothing else. In particular not routes, and not app constants.

Each app owns its own routes

APP_ROUTES, APP_PREFIXES, APP_NAME and APP_EMAILS live in each app's own src/routes/const.tsx — modules/fe/core/src/routes/const.tsx and modules/fe/public/src/routes/const.tsx. They are not a contract between the apps; each is an app's private description of itself, and each app needs granular control of its own URLs.

The tables already differ in ways that make sharing them wrong. APP_PREFIXES.HOME is "" in fe-public, because fe-public is the site at the root; in fe-core it is VITE_APP_DOMAIN, because fe-core links out to that site across a vhost. A single shared value cannot be both.

They did live in shared, and it went exactly as you would expect: a stale copy of the logged-in routes sat there for months describing resources fe-core had long since renamed, while fe-core quietly built its own table and stopped reading it.

The one genuine overlap is the legal pages, which both apps serve at the same paths. Both tables spell them out under APP_ROUTES.LEGAL, and both apps' const.test.ts pin the three paths, so editing one side alone fails a test instead of 404ing in production. Their text is one component each in shared (components/legal), wrapped in each app's own SubPage. Before that, each app kept its own copy and only fe-public's was ever written: fe-core's Privacy Policy and Terms of Service were empty pages, which the in-app links pointed at.

Shared components may use Tailwind classes, because both apps' tailwind.config.ts scan ../shared/src. Without that, a class used only in shared is purged from the production CSS, and the component renders unstyled in production only. The Docker build places the packages side by side, so the relative path holds there too.

Components that need the app's name take it as a prop (ComplexFlowNetwork's appName) rather than importing a constant, which is what keeps shared free of them.

The rule for putting something here

Two consumers, or it does not belong. A helper used by one app belongs in that app.

This is not a style preference — the package has repeatedly accumulated things with one consumer or none, and they rot: util/string.tsx sat here byte-identical to fe-core's copy with fe-public never importing it; MyButton drifted a missing text-white behind both apps' copies; routes/App.tsx still typed PageConfig.page as React.ReactNode long after both apps moved to React.ComponentType. A forked copy nobody imports is worse than no copy, because the next person imports it and gets the stale one.

So before adding: check that both apps will import it, and that neither already has a local version you would be forking.

It builds to dist/

The apps resolve chainr-frontend-shared to dist/index.js, not to src. There is no vite alias. Editing shared source does nothing until you rebuild it:

cd modules/fe/shared && npm run build      # or: make rebuild-shared

prepare runs the build on npm install, so a fresh checkout is fine; it is mid-session edits that catch people out. If a change to shared seems to have no effect in an app, this is why.

Colour lives in one ramp

BRAND_RAMP in src/context/palette.ts holds the Tailwind 600-level hues. Two features draw from it — the theme accent picker here (accents.ts, a labelled list the user chooses from) and fe-public's marketing card tints (components/theme/accents.ts, a fixed lookup). One set of values, two structures; neither inlines a hex.

fe-core's components/appearance/tones.ts is a different ramp — the 500 level, for tinted surfaces behind icons rather than solid fills. Keep them distinct; BRAND_BLUE in fe-public is the 500-level blue for the same reason (600 reads muddy as text).

Dependencies

Only what the package's own source imports. It once declared 18 runtime dependencies while importing exactly one (lucide-react) — the other 17 were the transitive trees of react-markdown and react-grid-layout, copied in wholesale. Both of those are fe-core's dependencies and fe-core declares them itself; shared never imported either.

Adding a dependency here adds it to both apps' bundles, so check the import is real first.

Testing

Run everything with make test-fe. It builds fe-shared first, because the apps resolve it from dist/.

The suite is built in four layers, each catching a class the others cannot, plus a guard that checks the run itself was complete.

1. The console guard — on by default, everywhere

modules/fe/vitest.setup.ts fails any test that writes to console.error or console.warn.

This is not tidiness. React reports genuine defects through those channels and nothing else: missing list keys, act() violations, invalid DOM nesting, state updates on unmounted components, controlled/uncontrolled input flips. All of them render "fine" in a browser, and none of them fail a test that only asserts on markup.

When a test drives an error path deliberately, declare it:

import { expectConsole } from "../../../vitest.setup";

it("reports a failed save", async () => {
  expectConsole(/Failed to save/);
  …
});

Keep the pattern tight — a bare /./ re-opens the hole.

The setup also gives jsdom a plausible layout box (1024×768). Without it anything that sizes itself from the DOM — recharts' ResponsiveContainer, virtualised lists — renders nothing and warns.

2. Page smoke tests — every routed page mounts

src/routes/apps/pages.smoke.test.tsx in each app walks the app's page configs and renders every page against an API that answers with empty bodies (the fresh-account shape, and the one most likely to break naive code).

A page passes if it mounts without throwing and without console output. It asserts nothing about what a page shows — that is deliberate. This is the floor, not a substitute for a page's own tests, and its value is breadth: 84 pages in fe-core, 13 in fe-public, most of which no other test opens.

Add a page to a route config and it is smoke-tested automatically. There is nothing to wire up.

One failure it cannot see: a page reading a route param by the wrong name. React Router answers undefined, useResourceId turns that into null, and the page renders its own "invalid link" branch — a clean mount with no console output, which passes. That is how the dataset page shipped reading suiteId on a route declaring :testSuiteId, so every dataset link in the app said "Invalid dataset link." with the suite green. src/routes/apps/pageParams.test.ts closes it statically: it resolves every routed page in fe-core to its source file through the lazyPage import and fails when the file reads a param (useResourceId("…") or a useParams() destructure) its route does not declare. Spell param names exactly as ROUTE_PARAMS does.

3. Contract tests — fe-core against svc-core

src/services/api/contract.test.ts is the one that catches the failure nobody else can.

The frontend and backend are separate deployables with no shared type definition. A renamed or removed route is invisible until something 404s in a browser: unit tests mock the API, so they happily assert against endpoints that no longer exist, and the type checker cannot help because the URL is a string.

The test drives every method on every router against a stubbed transport, records the URL each one actually builds, and matches it against docs/spec/api/svc-core.md — generated from svc-core's FastAPI routers by make spec, with CI failing when it is stale. Run it alone with make test-fe-contract, which regenerates the spec first.

When it fails, one of three things happened, and the message says which: the backend moved a route, the frontend invented an endpoint, or the spec is stale.

KNOWN_GAPS holds endpoints the frontend calls that svc-core does not implement. Each entry needs a reason. The list is deliberately awkward: the test also fails when an entry stops being violated, so it cannot rot into a mute button.

4. Static hygiene — src/test/hygiene.test.ts in all three packages

Properties of the source itself, no browser needed:

CheckWhy
no interpolated Tailwind classbg-${tone}-500 compiles, type-checks and renders, then Tailwind purges it and the element is unstyled in production only
className, never classReact silently ignores class; the element renders unstyled
no merge-conflict markersan unresolved conflict compiles more often than you would like
no .only/.skip in test filesa focused or skipped test passes CI while testing nothing. Scanned over the test files via readTestFiles — this check previously scanned the shipped source, which readSourceFiles excludes every test file from, so it could never match and passed unconditionally
(fe-shared) every import is declareda dependency resolved by hoisting works locally and breaks on a clean install

The Tailwind check scans className expressions specifically, not whole files — an SVG gradient id like ` id={fill-${w.id}} ` is fine and must not be flagged.

5. The collection guard — did the run actually run everything?

modules/fe/vitest.collectionGuard.ts is a reporter wired into all three vitest.config.ts files. After a run it walks src itself and fails the process if vitest collected fewer test files than exist on disk, naming the ones it missed.

It exists because this suite has been seen reporting a clean Test Files 39 passed (39) when there are 40 — running 29 fewer tests than it claims, and exiting 0.

The cause is environmental, not a bug in any test. In the devcontainer /workspace is the host's disk bind-mounted through Docker Desktop (fakeowner over VirtioFS), and that layer intermittently answers readdirSync with ENOENT for a directory that plainly exists — statSync on the same path in the same tick succeeds, and an immediate retry returns the real listing. Vitest globs for test files exactly once at startup and trusts the answer, so a late listing silently costs it a whole file. The file it loses is the one under src/apps/user/pages/evaluation/, which is one of the directories observed failing to scan.

Nothing inside the container can make that filesystem honest. Two things follow:

  • modules/fe/vitest.fsRetry.ts wraps readdirSync/readFileSync with retries, and all three packages' src/test/sourceScan.ts read through it. Swallowing the error instead would turn a loud failure into a silent under-scan — the hygiene suite quietly skipping two directories — so after the retries are exhausted it throws.

  • The guard turns vitest's own silent under-run into a failed run. It cannot prevent the short collection; it makes sure nobody ships on the strength of it.

The guard is deliberately one-directional and conservative. It stands down entirely for a filtered run (vitest run src/util/array.test.ts is supposed to collect one file), and it declines to judge if its own walk hits trouble. A guard against flakiness must not become a new source of it.

If it fires, re-run. If it keeps firing, the machine is short of memory — free some, or lower parallelism further with vitest --maxWorkers=2.

Worker count: the container's quota, not the host's cores

Vitest sizes its pool from os.availableParallelism(), which counts the host's cores and ignores a container's CPU quota. The devcontainer sees 12 cores under a 4-CPU cgroup limit, so vitest ran 11 jsdom workers on 4 CPUs of time. Tests that take 0.3s alone passed the 5s timeout, a different handful on every run (about ten under --coverage). A timed-out test's pending render then landed in the next test, which failed on a DOM it never produced.

modules/fe/vitest.workers.ts reads the cgroup quota (v2 cpu.max, or v1 cfs_quota_us) and sets maxWorkers from it in all three configs: one fewer than the quota's whole CPUs. With no quota (CI, a laptop) it is vitest's own default, one fewer than the cores, and --maxWorkers on the command line still overrides it. The fe-core coverage run went from 98s with failures to 41s green.

The spare CPU is the main process's. It transforms every module the workers import and, under --coverage, collects the coverage. At first the pool was the whole quota (4 workers on 4 CPUs), which left it none. As the suite grew, a coverage run's page tests ran ten times slower than alone: the Activity page's paging tests take 0.25s alone and passed 5s in the run, and Governance's assurance tests missed findByText's 1s. With 3 workers the same run finished sooner (102s, against 120s) and green, its summed test time 59s instead of 150s.

Two test-side habits still help on a loaded machine. A test that await import()s its page or component should preload it in beforeAll(…, 60_000), so the first test does not pay the whole transform. A test that types whole sentences should use userEvent.setup({ delay: null }): every key event still fires, but there is no timer between keys.

One gotcha: module identity

Both apps' vitest.config.ts dedupe and inline chainr-frontend-shared. Do not remove that.

React context is compared by module identity. The shared package ships as a built dist/, so a stale vitest pre-bundle sitting alongside a freshly built one hands the provider and the hook two different context objects — and useTheme reports "must be used within a ThemeProvider" for a tree that visibly has one. It only reproduces when the package is rebuilt in the same run, which is exactly what make test-fe does, so it looked like flakiness in CI and passed locally.

Writing a new test

  • A page: nothing to do for smoke coverage. Write a normal test beside it for behaviour.

  • A router method: nothing to do — the contract test finds it by enumeration.

  • A component: test it beside the component. The console guard applies automatically.

  • Rendering anything that uses queries, routing or theme: use renderPage from src/test/harness.tsx rather than bare render, so you are asserting on the component and not on a missing provider.

fe-shared ships only what it should

shared/tsconfig.build.json excludes src/test. Test helpers are not part of the published package, and one of them (sourceScan.ts) imports ../../../vitest.fsRetry from the monorepo root — which works under vitest and breaks everywhere the package is built on its own.

That escape cost two days of red CI: the Docker build context holds only the package, so npm ci failed with TS2307. It also relocated dist/index.js to dist/shared/index.js locally, silently, because nothing cleans dist between builds.

Two checks in shared/src/test/hygiene.test.ts hold the line: shipped source may not import ../../../, and the build must keep excluding src/test. When you change anything in shared, verify it the way CI does — move modules/fe/vitest.fsRetry.ts aside, rm -rf dist, then npm run build.

Every routed page is loaded on demand

routes/apps/*.tsx declare pages with lazy(() => import(...)), never a static import. components/app/MyApp wraps <Routes> in the one Suspense boundary that serves all of them, and test/harness provides the same boundary so a test can render a routed page directly.

This is not a micro-optimisation. Imported eagerly, fe-core's fifty-two user pages compiled into a single 3.6 MB entry chunk that every visit had to download in full before anything rendered; splitting them took the entry to 217 KB across 316 chunks. fe-public went from 549 KB to 409 KB. The total bytes are unchanged — a visitor simply stops paying for the pages they did not open.

apps.test.tsx fails if a page drifts back to a static import, because the app still works when that happens, it just gets slower for everyone. notfound is exempt by name: it is eighteen lines and is the fallback for every route, so deferring it would spend a round trip on the one path where the user is already lost.

Testing a lazy page

Pages are declared with lazyPage, not lazy — it keeps the loader on the component so a test can await Page.load() before rendering. That is not a convenience. A bare lazy suspends on a real module load, so the first render is the fallback, and a smoke test that only asserts "it did not throw" is satisfied by an empty div. When routes first became lazy that is exactly what happened: all 83 page tests stayed green while mounting nothing, and the only signal was coverage halving (38.6% → 20.8% in fe-core, 48.7% → 23.6% in fe-public). Awaiting the resolution instead of preloading trades that for an "a suspended resource finished loading outside act()" warning — a race either way.

So the smoke suites now preload, then render, then settle, then assert the container is not empty. The last part is the guard that was missing: a test asserting nothing passes whatever happens.

Each step earns its place:

  • Preload happens once per suite in beforeAll, in parallel, so no single test pays a cold module transform. One heavy page doing that inside its own test exceeded the per-test timeout on a slow runner and failed as though it were broken, while passing in isolation.

  • Settle is settlePage(client), which waits for isFetching() and isMutating() to reach zero. The previous helper waited a single macrotask and hoped; under load a query would resolve after the act window and React reported "an update was not wrapped in act(...)", which the console guard failed. Asking the query client when it is idle is deterministic — and quicker than a fixed wait when the page is fast.

One trap worth stating: never wrap waitFor in act. waitFor already does that internally, and nesting them throws "the current testing environment is not configured to support act(...)".

The inbox and cost profiles

The inbox is components/nav/NotificationBell, beside the workspace menu in NavHeader: the person's notifications across every workspace (GET /app/notifications, read again every minute), each naming its workspace. Opening one marks it read and navigates to notificationHref(n) — pathIn(workspaceFromKey(n.workspace_key), n.link) — with plain react-router's useNavigate, never the app's workspace-aware one, which would move a link into the workspace being viewed rather than the one the notification is about.

An agent's cost profile is chosen with apps/user/pages/agents/CostProfilePicker (from GET /app/agents/cost-profiles; a profile the platform has not measured carries "Not yet measured" and how to measure it), and an evaluation variant's with the Cost profile field of VariantSettings (costProfiles prop; agents only). A quality check a profile skipped is skipped in QUALITY_CHECK (neutral) and quiet in needsAttention. Given agentId, the picker asks for that agent (?agent_id=) and says under Economy which lighter model it would use, or why none (lighterText). An answer the lighter model wrote names it in the chat's model chip ("· lighter model", the reason in its title, from meta.lighter_model), and the decision record's Configuration names the cost profile.

A document a used-up budget holds reads Waiting for budget (budgetHoldUntil, objects/Knowledge; when it will be indexed in the title), and a crawl one held is held in RUN_STATUS (warning: waiting on money, not broken), its reason in the badge's title. A refusal by a budget arrives as a 403 whose structured detail errorDetail already reads.