Skip to content

Admin client state (XState conventions) ​

Path: apps/admin/web/src/features/ (conventions in features/CONTRIBUTING.md, dev inspector in features/inspect.ts) Status: The full 8-step admin XState stack is on main: foundations in #922 (merged 2026-10-15 10:02 IDT, merge 05e72158), router search params in #923 (merged 2026-10-15 10:13 IDT, merge dd420a03), the dashboard chat machine in #925 (merged 2026-10-15 10:23 IDT, merge b95347c0), the flag drawer machine in #926 (merged 2026-10-15 10:33 IDT, merge 09d982ca), the SQL console store in #927 (merged 2026-10-15 10:43 IDT, merge 8cf743ba), the email template editor machine in #929 (merged 2026-10-15 10:54 IDT, merge 309b1b69), the shared reason-dialog machine in #930 (merged 2026-10-15 11:04 IDT, merge 1381a225), and the ownership check that locks the two useState exceptions in #931 (merged 2026-10-15 11:14 IDT, merge 2a664467).

#971 (PostHog step 4, merged 2026-10-15 16:41 IDT, merge cb7500e1) removed the admin BI, dashboards, SQL console and dashboard-chat pages, so the dashboard chat machine (#925) and the SQL console store (#927) described below are gone from the code; their sections are kept as history. The other machines stay. See PostHog — Step 4.

Why ​

Admin client workflows (drafts, dialogs, streams) used to keep their state in component useState. The admin XState stack moves the ones with real modes into XState machines, while TanStack Query and TanStack Router keep the jobs they already do. #922 adds the packages, the features/ folder layout and the ownership rules; #925 is the first admin workflow on a machine (dashboard assistant chat).

Who owns which state (#922, merged) ​

Kind of stateOwner
Server data (lists, entities, changelog, versions, chat history)TanStack Query. Query keys stay as they are.
Shareable UI (search, filters, tab, range, selected id, open drawer)Router search params (validateSearch), read with Route.useSearch(), written with navigate({ search }).
Workflows with modes, drafts, concurrency, streaming or multi-step dialogsAn XState machine (setup), mounted at the route or component and keyed by the route param.
Event-driven local UI with no modes@xstate/store (createStoreLogic and useStore).
A single toggle in a tiny leaf, or one of the two allowed exceptionsuseState. Anything larger is a machine or a store.
DOM instances (Tiptap Editor, textarea refs)Refs, never machine context.

A machine may read Query data through input or an event, and it may run mutations and invalidate queries. It does not cache server data and does not mirror search params.

Folder layout ​

web/src/features/<feature>/
  <feature>.machine.ts      // setup({...}).createMachine, no React
  <feature>.machine.test.ts // createActor + provide(fake actors)
  <feature>.store.ts        // createStoreLogic when there are no modes
  <feature>.selectors.ts    // module-level selectors
  <feature>.context.ts      // createActorContext when a subtree shares one actor
  api.ts                    // query keys, options, fetchers
  components/*.tsx
  • Event names are past-tense facts: draft.edited, save.requested.
  • I/O actors are declared in setup({ actors }) with placeholders and swapped in with provide() where the component has queryClient. Tests provide fakes the same way.
  • React bindings: useActorRef plus useSelector, with selectors defined outside the component. useMachine is for a small leaf only; feature code under features/ must not call it (the ownership test fails on useMachine / useMachine<…>(…) there). Pass dynamic props as input, not closures.

Packages ​

Added to apps/admin: xstate 5.33.2, @xstate/react 6.1.0, @xstate/store 4.3.0, @xstate/store-react 2.1.0, and dev-only @statelyai/inspect 0.7.2. After #927, Knip no longer ignores @xstate/store or @xstate/store-react for apps/admin (the SQL console imports them); it still treats web/src/**/*.test.ts as test entries. xstate and @xstate/react were already real imports after #925.

The studio web app already uses xstate and @xstate/react for its own machines (see Control plane: builder preview XState machine); the admin app has its own copy and conventions.

Shareable admin UI lives in the URL (#923, merged) ​

#923 puts the "shareable UI" row of the table above into practice. Each admin route now declares validateSearch with a Zod schema from web/src/features/search/params.ts, so a copied admin link reopens the same view. The old useUrlSearch hook and the billing page's own history.replaceState effect are gone, and every write uses navigate({ search, replace: true }), so typing or filtering does not add history entries.

PageParamBehaviour
Tenants (/) and Users (/users)qSettled text search. Blank or non-string values are dropped.
SQL console (/sql)rangeOne of ALLOWED_RANGES; a missing or unknown value falls back to 7d.
Flags (/flags)flagKey of the open targeting drawer. The row itself still comes from the flags query, and a blank key closes the drawer.
Billing (/billing)tenant, monthmonth is YYYY-MM. An absent or invalid month means the current month and is not written to the URL until the operator changes it.
  • Search box debounce: useSearchQuery(query, delayMs, commit) (in features/search/) keeps keystrokes local and writes q after 300 ms on Tenants and 250 ms on Users. Submitting the tenants form flushes at once. A keystroke typed while the previous q is still being applied stays in the field; the field resets only when q changes in a way the hook did not commit (back, forward, or a link that clears it). The rule is the pure helper inputAfterQueryChange.
  • Route objects moved next to their pages: rootRoute, tenantsRoute, usersRoute, sqlConsoleRoute, flagsRoute and billingRoute are exported from their routes/*.tsx files, and router.tsx only assembles the tree.
  • Testing pages without a router: FlagsPage (selectedFlag, onSelectFlag) and BillingPage (month, tenantId, onMonthChange, onTenantIdChange) take URL values as props; the route wrapper owns navigate. Parsing rules are covered by apps/admin/test/search-params.test.ts.
  • Not in this step: route loaders with ensureQueryData (pages still fetch on mount, and putting queryClient in router context is a separate change). Also deferred: a keyboard draft for the billing month, flag-drawer history details (replace on open, a stale ?flag= after a delete), a memory-router click test and a vite dev click-through.

Dashboard assistant chat runs as a state machine (#925, merged) ​

#925 is the first admin workflow on an XState machine. The old use-dashboard-chat.ts hook (chat history in useState plus a side AbortController) is gone. Live transcript, streaming, stop, retry and new-chat now live in dashboardChatMachine under web/src/features/dashboard-chat/.

PieceRole
StatesloadingHistory → idle ↔ streaming / resetting. A finished, closed-early, failed, or stopped turn returns to idle with the flag on the assistant message.
HistoryTanStack Query still owns the history fetch (["dashboard-chat", dashboardId]). The machine holds the live transcript only. History arrives as history.loaded.
Epoch guardEach fetch records the chat epoch at request time. The first load applies whatever the cache hands it (including a payload whose epoch belongs to a previous mount). Idle applies a later payload only when that epoch is still current. Leaving streaming bumps the epoch, so a fetch that started mid-turn cannot replace the finished reply, and a refocus after Stop can. History during streaming is ignored.
Stream actorA fromCallback actor (dashboardStreamChat). Stop leaves streaming, which stops the actor and aborts the fetch. The actor does not receive stream.stopped. Dashboard and version queries are invalidated whenever the stream ends, including Stop.
Panel APIAssistantPanel receives { messages, isStreaming, isBusy, send, stop, retry, newChat }. isBusy covers streaming and resetting, so Enter during New chat does not clear text the machine will drop. The panel is keyed by the dashboard id so the actor's lifetime matches the route param.

A failed New chat still returns to idle with the previous messages and no error (same as the old hook ignoring a non-ok archive POST). Follow-ups (stalled-fetch abort test, visible error for a failed New chat, vite-dev click-through) are listed under Follow-ups in features/CONTRIBUTING.md on the later cleanup PR.

Flag drawer edits and saves through a state machine (#926, merged) ​

#926 (opened 2026-10-14 by yoni-monday, merged 2026-10-15 10:33 IDT, merge 09d982ca) moves the Feature Flags targeting drawer (FlagDetailDrawer.tsx) off five separate useStates (enabled, default variation, targeting, reason, error) and a useMutation. The draft and the save now live in flagDrawerMachine under web/src/features/flags/.

PieceRole
Statesediting → saving → done (final, closes the drawer). A refused draft or a failed PUT goes to error, which keeps the form and accepts the same edit events. A targeting edit from error returns to editing and clears the message.
Eventsenabled.changed, default.changed, targeting.edited, advanced.removed, reason.edited, save.requested.
ValidationflagDraftIssue (in flagDraft.ts) is the canSave guard. It refuses an empty reason, a compileTargeting failure (for example a rollout outside 0–100%), a partial rollout whose default is not the off variation, and a rule or default that names a variation that doesn't exist. The save actor is never invoked for a refused draft. flagSaveBody builds the PUT body (trimmed reason, compiled rules).
Targeting editsAny targeting edit turns the flag on. A rollout below 100% also switches the default to the off variation, so users outside the release stay off. Removing an advanced rule does not turn the flag on or invent a rollout.
Save actorThe machine declares a placeholder saveFlag. The drawer provides the real one: PUT /api/flags/:key, then invalidates ["flags"] and ["flag-changelog", key], and provides close. The changelog itself stays in TanStack Query.
Component APIThe drawer reads { enabled, defaultVariation, targeting, reason, error, saving } through selectFlagForm with shallowEqual (flagDrawer.selectors.ts), and passes devInspect() so the Stately inspector can trace it.

Tests: flagDrawer.machine.test.ts (5 cases: empty reason, rollout outside 0–100, partial release with an on default, a successful plus a rejected PUT, advanced-rule removal). The existing flag page, lifecycle, targeting and create tests still pass. User-facing drawer behaviour is unchanged; see Admin Feature Flags.

SQL console draft lives in an XState store (#927, merged) ​

#927 (opened 2026-10-14 by yoni-monday, merged 2026-10-15 10:43 IDT, merge 8cf743ba) moves the SQL console page (routes/sql-console.tsx) off four useStates (sql, showSaved, saveTitle, clientMs). The draft and local UI now live in sqlConsoleLogic (createStoreLogic) under web/src/features/sql-console/. This is the first admin @xstate/store (event-driven local UI with no modes), matching the ownership table above.

PieceRole
Store contextsql, showSaved, saveTitle (string or null), clientMs
Eventssql.edited, savedPanel.toggled, save.opened, save.titleEdited, save.dismissed, save.succeeded, query.timed
RangeStill the URL search param from #923; the store does not hold it
Run and saveStay TanStack mutations. Result rows stay in the mutation cache, not the store. Recording clientMs does not replace the draft
Save UXDismissing the title prompt does not open the saved list; a successful save does (save.succeeded sets showSaved: true and clears saveTitle)

React bindings: useStore(sqlConsoleLogic, { sql }) plus useSelector for the whole context. Tests: sqlConsole.store.test.ts (3 cases via store.transition: edit plus timing, title dismiss vs successful save, toggling the saved list). User-facing console behaviour is unchanged.

Email template editor runs as a state machine (#929, merged) ​

#929 (opened 2026-10-14 by yoni-monday, merged 2026-10-15 10:54 IDT, merge 309b1b69) moves the welcome email template editor off component useState into emailEditorMachine under web/src/features/emails/. TanStack Query still loads the template once; the machine keeps the working draft and expectedVersion, and a refresh arrives as an event. The Tiptap editor stays a ref; editorGeneration remounts it. User-facing behaviour is unchanged.

PieceRole
ShapeParallel setup() machine with regions for the draft (pristine / dirty / saving / conflict), tab backup, dialog, mobile tab, and in-flight work (activity).
Query vs machineQuery loads the template. The machine owns draft content, expectedVersion, notices/errors, dialog and tab, and workDepth. DOM Editor instances stay in refs.
HookuseEmailEditor provides the real actors (saveDraft, loadDraft, publishDraft, activateDraft, importDraft, exportDraft), mounts with useActorRef + devInspect(), and restores a tab backup when one exists.
Conflict and refreshA 409 leaves both drafts in place. A dirty refresh stays stale until “Keep edits against reviewed version”. A clean refresh replaces the draft and clears the backup.
Save and enableSave does not close an open dialog. Enable updates the expected version without replacing local text. Dismiss is ignored while a save is in flight.

Tests: emailEditor.machine.test.ts (6 cases with fake actors, no DOM: restore, conflict, stale refresh then save, clean refresh, dialogs that ignore dismiss while saving, enable-while-dirty). Unused re-exports (EmailLiveAction, EmailEditorView, EmailEditorChoice) and hideDialog are gone so Knip stays clean.

Deferred: edit/preview tab stays in the machine, not the URL; EmailTemplatePage still holds the navigation-blocker dirty flag in useState; email test and lifecycle dialogs keep their own field state. Follow-ups listed in the PR include backup/storageOk, workDepth beside selectBusy, capturing editor generation at mount, and moving sessionStorage writes out of transition resolution.

See also Transactional email.

Audited staff actions share one reason-dialog machine (#930, merged) ​

#930 (opened 2026-10-14 by yoni-monday, merged 2026-10-15 11:04 IDT, merge 1381a225) moves the three dialogs that ask staff for an audit reason off component useState onto one reasonDialogMachine under web/src/features/reason-dialog/: ReasonDialog (tenant and user actions), ImpersonateDialog ("Log in as user"), and the billing ActionDialog in BillingActions.tsx. submitReason is unchanged and is still what the reason and impersonate dialogs call.

PieceRole
Statesediting → submitting → closed (final), with failure on a refused or rejected submit and link when impersonation returns a login link that has to stay on screen.
Eventsreason.edited, submit.requested, link.copied
ValidationreasonIssue(reason, required) uses the same limits as submitReason: an empty (after trim) or over-500-character reason goes to failure with "Reason is required." or "Reason must be 500 characters or less." and never reaches confirm. Buttons use the same check to disable submit.
ConfirmThe confirm actor is provided by each dialog and gets the trimmed reason. A thrown error keeps the dialog open with the message; a result with no loginUrl runs close.
Impersonation linkwindow.open with noopener returns null even when the tab opened, so a null keeps the login link on screen (Open link, Copy link) instead of closing.
Optional reasonThe billing dialog passes reasonRequired: false for actions whose note is their own field; a blank reason then submits and closes.
HookuseReasonDialog({ reasonRequired, confirm, onClose }) mounts with useActorRef + devInspect(), keeps confirm and onClose in refs, and exposes reason, error, pending, loginUrl, copied (via selectReasonDialog) plus editReason, submit, markCopied.
Fresh each openingThe dialogs render nothing while closed and mount the actor only while open, so each opening starts with an empty reason and no reset useEffect.

Billing field values (credits, expiry, organization, note) stay in the billing dialog as inputs to the action, not part of the reason workflow. Tests: reasonDialog.machine.test.ts (6 cases: empty reason, 500-character cap, trimmed confirm closes, rejected confirm stays open, login link stays open and records copy, optional reason submits blank).

Deferred: CreateFlagDialog and NewDashboardDialog still keep their own open/submit state; the email lifecycle and email test dialogs keep local field state.

Ownership check locks the two useState exceptions (#931, merged) ​

#931 (opened 2026-10-14 by yoni-monday, merged 2026-10-15 11:14 IDT, merge 2a664467) is the last PR in the admin XState stack. It does not change runtime behaviour. It documents the two intentional useState exceptions in features/CONTRIBUTING.md and adds state-ownership.test.ts so new ones fail the suite.

PieceRole
ScopeThe check walks features/ (non-test .ts / .tsx). components/ and routes/ may still use useState. One extra assertion covers the email route outside features/.
FailuresAnother useState or useReducer under features/, including a typed call such as useState<Foo>(…), fails the test. A useMachine / useMachine<…>(…) call under features/ also fails (select from an actor instead). An import of useState alone does not.
Allowed in features/Only features/search/useSearchQuery.ts: keystrokes that have not been committed to ?q=. The URL is the query the page fetches.
Email pageroutes/email-template.tsx may keep exactly one useState/useReducer — the dirty flag useBlocker reads. The editor machine owns the draft.
Runbun test apps/admin/web/src/features/state-ownership.test.ts (4 cases). The package test script is bun test from apps/admin, so this file runs in pkg:apps/admin.

Still local and not moved in this stack: routes/dashboard-detail.tsx (copies data.spec into useState from useEffect, keeps range in useState), routes/config.tsx (settings search box), components/flags/TenantPicker.tsx and UserPicker.tsx (fetch into useState), create-flag and new-dashboard dialogs, route loaders with ensureQueryData, and the email edit/preview tab as a search param (the tab stays in the editor machine). Leaf fields that are not a workflow (billing amounts, email test form, lifecycle reason) can stay in the component that renders them. Do not copy a Query result into useState from useEffect; send an event instead (dashboard chat uses history.loaded).

Follow-ups accepted on the stack (billing month draft, flag drawer history, email backup / workDepth / generation / storage / casts, reason-dialog REASON_MAX / resultOf, impersonate with pop-ups blocked, chat archive error, flag save body fold, SQL save component test, and the rest) live under Follow-ups in features/CONTRIBUTING.md, with the file each one belongs to, until someone files issues and replaces that section with links.

Debugging with the Stately inspector ​

To trace machines live during local admin dev, start vite dev with VITE_XSTATE_INSPECT=1. devInspect() (in features/inspect.ts) then creates the Stately browser inspector, which opens https://stately.ai/inspect and streams actor events to it.

  • It only runs when import.meta.env.DEV is true and VITE_XSTATE_INSPECT is exactly "1" ("true" or empty does not count). inspectorRequested is the only check of the flag.
  • Nothing calls it at boot, so a normal vite dev session does not open the window or send events anywhere.
  • A production admin build does not contain stately.ai/inspect (Vite folds DEV to false, so the call is dead code).
  • The email browser test harness (apps/admin/test/email-browser.ts) defines import.meta.env.DEV and VITE_XSTATE_INSPECT itself, because Bun.build has no import.meta.env. Any new Bun-built harness that mounts admin code needs the same defines.

The admin XState stack ​

Each step is its own PR, stacked on the one before. All eight steps are on main.

  1. Packages, inspector, conventions (#922, merged).
  2. Router validateSearch (search, range, selected flag, billing) (#923, merged; see Shareable admin UI lives in the URL).
  3. Dashboard chat machine (#925, merged; see Dashboard assistant chat runs as a state machine).
  4. Flag drawer machine (#926, merged; see Flag drawer edits and saves through a state machine).
  5. SQL console store (#927, merged; see SQL console draft lives in an XState store).
  6. Email template editor machine (#929, merged; see Email template editor runs as a state machine).
  7. Shared reason-dialog machine (#930, merged; see Audited staff actions share one reason-dialog machine).
  8. Ownership check locking the two useState exceptions (#931, merged; see Ownership check locks the two useState exceptions).

Admin Feature Flags · Admin Config · Admin Secrets · Transactional email · Control plane: studio XState machines