Reeve Docs

Docs / Development

The web frontend

The frontend lives in frontend/. It is a React 19 and TypeScript (strict) single-page app built with Vite. It uses MUI for components, TanStack Query for the server cache, Zustand for local UI state, SignalR for realtime and Zod for response validation. Residents, operators and administrators all use it.

Layout

Path Holds
src/features/<slice>/ Domain-sliced feature modules (admin, auth, automations, blueprints, dashboard, devices, home, plugins, scenes, workloads and others). A slice owns its pages, components, hooks and copy.
src/lib/ Cross-cutting code: the axios instance, the query client, the query-key factory, brand tokens and theme, shared formatters.
src/contracts/ TypeScript mirrors of the backend DTOs, mostly generated from the C# contract types, and Zod-validated.
src/app/ Providers, router, lazy route wrappers.
src/test/ Request-mock server, the shared render helper, fixtures.
e2e/ The browser suite. See e2e-testing.md.

Two view modes

One application serves two audiences through a basic | advanced mode. Basic is the default. It trims the sidebar to household destinations and replaces the technical device inventory with a room-grouped Start screen and a per-device drawer. Advanced is the full operator surface. The design is described in clients.

  • The mode toggle renders only for a user whose permission-filtered navigation holds an Advanced-only item with a non-empty required-permission set the user holds, or who holds one of the few in-page Advanced capabilities that have no navigation item. Everyone else gets no control. Add an Advanced destination to the navigation config and the toggle follows.
  • Mode is presentation only. No authorization decision keys off it.
  • Read the clamped effective mode from the composition hook, never the raw store. The raw stored mode survives a sign-out on a shared tablet.
  • canUseAdvanced is derived from the navigation config (items flagged advancedOnly, with permissions and the deployment-capability flag). Feed it the unfiltered navigation. A mode-filtered navigation hides the very items it looks for.
  • basicHidden hides a navigation item in Basic and is the only flag the mode filter reads. advancedOnly only feeds the toggle gate.
  • Hiding a navigation item never hides its route. A Basic-only route carries its own ModeRoute guard, consulted when the mode switches. Only a switch made while standing on a now-hidden destination redirects, with history replacement.
  • Basic device detail is overlay state on Start, not a route. Opening it must not navigate. A dismissal other than Back pops the pushed history entry.
  • The first paint reads a per-device localStorage cache, then reconciles with the server value once, unless the user already chose a mode. Drop the cached mode on session teardown.
  • A surface that holds unsaved work registers a switch guard. The first refusal stops the chain. A guard that throws counts as consent.

A navigation item is visible when the user holds at least one of its requiredPermissions and, if it has requiredFeature, the backend reports that feature enabled in CurrentUser.features.

  • List both the view and the manage permission when either should reach the item.
  • The Matter Bridge page and the workload-plane documentation page are not feature-gated, because the flag is set by the same Helm value that deploys the sidecar.
  • Groups are keyed by label. Reuse the label to join an existing group. A group left with no items is dropped.
  • Route-to-tab matching takes the longest matching prefix. Start matches by equality.

Product rules for resident surfaces

These rules apply to every surface designed for Basic.

What may not appear

  • A Basic surface never renders a device id, source id, plugin or protocol name, freshness token, raw or unmapped properties, metadata editing or the device's room (the section heading names it).
  • This includes attribute values: an id in an accessible name, a title, or an id/htmlFor pair.
  • A surface may decide from a signal it keeps off screen. It must not print it.
  • Every user-visible string is English. Resident-copy modules are checked by a test for non-English literals.

History charts

This covers device pages, the Basic drawer and the dashboard chart widget.

  • Never plot radio diagnostics (link quality, signal strength, noise ratio) on a resident chart. Never name a resident series after its raw identifier. Battery, energy, power, current and mains voltage stay.
  • Basic also hides pan, tilt, the voltage of a device that reports a battery level, and any reading without a unit. Advanced keeps every series.
  • Draw one small chart (about 100 px) per unit. Charts of a card share one time axis: the requested window, round local-time ticks, labels under the last chart only, hover linked across them.
  • Fit the y axis to the data on round ticks (1, 2, 2.5 or 5 times a power of ten, at most four intervals). Do not force it to zero.
  • Order charts as the tiles are (group, then reading rank) and name series as the tiles do (CO₂, PM2.5, VOC).
  • A series joins the first chart of its unit in which every member keeps at least a fifth of the combined range. The dashboard widget never splits, because its series are grouped by its author.
  • Draw a cumulative energy counter (any Wh or kWh series) as use between readings, in kWh once a step reaches 1000 Wh. A reset counts the new reading. No step is a gap: a long silence is drawn at the reading that ends it.
  • Follow the chart response. A step series is drawn as steps, with the value carried in from before the window as the first point. A series with heldUntilUtc is drawn flat to that instant. One without is not extended.
  • The carried-in value has no time of its own. No sentence, tooltip or last value states one.
  • A step series ends in a dot, as does a held tail that stops well short of the window end.
  • Basic opens on the first chart and puts the rest behind "More readings". It never states a count of withheld readings. A chart of unheld single readings is stated as a sentence. Advanced shows every chart and its ten-series caption.

Availability and staleness

  • Unavailability has one representation: the label "Unavailable" on a dimmed tile with the quick action disabled. Never use a freshness token.
  • The verdict is "unavailable" for any of: no canonical state, no declared capability, Offline or Orphaned availability, or the server's silent flag. Online and Unknown availability are reachable.
  • silent is true only for a sensor or presence reporter whose last report is older than 24 h by default. A device that reports on change is healthy however quiet.
  • The client ages nothing and Basic never reads the freshness label. A state or descriptor push never sets silent to true.
  • A Basic surface that shows availability re-reads the device list every five minutes while mounted.
  • The drawer's unavailability copy names no cause.
  • The Start heading greets by the household time zone, or the browser's while it is unread: morning from 05:00, afternoon from 12:00, evening from 18:00, night from 22:00. It re-reads the clock every minute.

The Basic drawer

  • It is 480 px wide (full width on a phone) and sits above the phone app bar.
  • The header names the device once, with its room read-only beneath.
  • Configuration (power-on behaviour, child lock, indicator, backlight, calibration) collapses into one "Settings" disclosure after the cards. It is dimmed with the controls when the device is unavailable.
  • A sensor shows up to three readings, then battery and voltage as one meta line, never link quality. An outlet shows power, energy and voltage in one row.

Phone navigation and list filters

  • Below 600 px, Basic navigates from a bottom bar: Start, Scenes, Automations and Energy where the user may see them, and "More", which opens the sidebar. Advanced and wider windows keep the sidebar.
  • The bar sits below the sidebar, the Basic drawer and every dialog in the stacking order.
  • A page reserves the bar's height plus the device's bottom inset through the --reeve-bottom-nav-height CSS variable (0 without the bar). A page sized to the viewport subtracts it.
  • Page-level toasts sit beneath drawers, dialogs and menus. A toast that belongs to a dialog stays above it.
  • On a phone, list filters show one search field and a Filters button (badged with the filter count) that opens a bottom sheet. From 600 px the search and filters share one card.

When a control may be offered

  • A tile's inline quick action is an unambiguous power toggle or a ranged number. Never "the first controllable toggle": descriptors declare test mode, mute, away mode, child lock and strobe as controllable.
  • A controllable number with no declared min and max gets no inline control. Only the step may be absent.
  • A device with several controllable power gangs and an automatic quick action gets one switch that drives them together. It is on while any gang is on, and a tap sets every gang to the opposite. A household none, or a chosen gang the device lost, draws no switch. The drawer holds the per-gang control. Never split a device into several tiles.
  • A non-favourite's star shows on hover and keyboard focus only, and not where nothing hovers. A favourite's star always shows. The drawer's star is the touch path.
  • A control whose own reading is null is disabled and named by its capability, not by an action that asserts the current position. Null is unknown, never off. A level control is exempt.
  • A control's accessible name states its action and the device name.

One formatter, one verdict

Human state, units, rounding, locale grouping, capability ordering, cover wording, the unavailability verdict and the on/off words live in shared modules that both modes import. Never restate a value domain, unit spelling, on/off word, failure message or availability verdict in a second module.

Numbers

Send every displayed number through the shared number formatter (lib/formatNumber.ts).

  • The unit sets the digits: degrees, percent, hPa and ppm are whole. °C and mains V take one decimal. kWh and A take two. Trailing zeros are trimmed.
  • Some units keep more digits below a threshold: V under 10 shows two decimals, W and lx under 10 one decimal, A under 1 three.
  • Halves round away from zero for both signs. Wh switches to kWh after rounding.
  • A non-breaking space precedes a symbol ("53 %", "22,6 °C"). A bare degree sign takes none. Separators follow the browser locale and symbols stay English.
  • Tiles, controls, slider labels and chart axes and tooltips use it. Raw JSON diagnostics show values verbatim. Costs, coordinates, byte sizes and the weather widget format their own.
  • Utility-widget shares, changes and coverage are ratios with one decimal. A change that rounds to 0 is unsigned and neutral. A first period with no previous cost shows no change.

Typed decimals

Send a decimal typed by a user through the shared decimal field (components/DecimalField.tsx).

  • The field shows a number with the browser locale's decimal mark and no grouping. It reads an optional sign, digits and at most one "." or ",", so "1.1" and "1,1" are both 1.1.
  • Exponents and grouping show an error. So does text the locale would read as a thousands group ("1,500" in English, "1.500" in German).
  • The host holds number | null. An empty field gives null, unreadable text gives NaN. A host whose setting travels as text converts a finite number at its edge.
  • min, max and step are checked as typed. A whole-number step refuses fractions.
  • A decimal field must sit inside the decimal guard. Its host disables save, Next or commit while the guard reports a blocked field.
  • Do not use type="number" for decimals. Whole-number fields (counts, seconds, priorities) keep it.
  • The geofence form keeps plain text fields with its own schema.

Enum labels

Send a closed enum token shown to a user through lib/enumLabel.ts. It has a table of known values and otherwise splits snake, camel or SCREAMING case into a sentence-cased phrase. A name that a device or driver supplies (a light effect, a media source) stays as supplied.

Command log rows

A row says what happened ("Channel 1 turned on", "Brightness set to 30 %"), using the device descriptor for channel names and units. It prints no JSON. A caller with devices.manage can open the payload ("Show payload").

Timestamps

Send a displayed instant through lib/formatDate.ts, or the Timestamp component where the text must stay current.

  • The text is English in the viewer's time zone. Under 24 hours it is relative ("just now", "2 min ago", "3 hr ago"). Otherwise it reads "Oct 26, 18:02", with the year when it is not the current one.
  • Variants: absolute (never relative: a future instant such as an expiry, a tooltip), precise (year and seconds: audit log, state timeline, logs), and the compact time, timeSeconds, day, date and trace for chart axes, log lines and calendar days.
  • The Timestamp component renders a <time> element with the precise form as its title.
  • Use absolute for text built into a string or embedded in a sentence ("since …") and for a value that lies ahead. A future stamp reads "just now" in auto.

Fallback names and renaming

Where a device gives no name, the screen says so in English from lib/fallbackNames.ts.

  • A channel that is blank or the bare "State" reads "Channel N" by position. A vacuum area known only by its numeric id reads "Unnamed area" (numbered when several). A name the device supplies is never replaced.
  • A caller with devices.manage sees a pencil beside the device name and each channel name of a full control. The pencil is the page's only rename control.
  • The pencil renames the layer the page shows. On a logical page it renames the device's own name and per-channel label. On the physical page it renames the source's name and channel names (PUT /api/devices/sources/{id}/channel-names). The physical page says so beside the pencil and links to the logical device.
  • A vacuum's areas get the same pencil on Advanced pages. The Basic drawer has one "Edit names" action instead.
  • Area names are stored per logical device (GET/PUT /api/devices/{id}/area-labels). Every surface that turns an area token into text uses those labels.

Other shared rules

  • Energy readings convert by the unit each row declares. Skip a row whose unit is absent or unrecognised.
  • The capability that leads a state line comes from the shared treatment registry's group order (environment, air quality, power, security, device), never from descriptor order.

The home screen

  • Coordinators and presence devices are hidden. An unrecognised device type is shown.
  • Non-actionable devices (thermometers, contact sensors, buttons) and unavailable devices stay visible.
  • A favourite is a pin, not a move. A favourited in-room device appears in Favourites and in its room, rendered from the same summary object.
  • At most 60 tiles mount. A section past the budget shows its heading and a one-tap reveal with the section's full device count.
  • Room order comes from the household's room list. If that read fails (it needs a permission a resident may not hold), fall back to the device list's order.
  • Devices with no room, or a room with no readable name, go to a trailing "Other" section.
  • A failed favourites read renders an alert with in-place retry.
  • A favourite star is disabled until a preferences baseline has loaded. The list is replaced wholesale, so an empty array would erase every favourite.
  • While any favourites write is in flight, every star disables. Its accessible name does not change, and there is no spinner or optimistic label.
  • Scope an empty-state message to the window the data covers. A 24-hour query cannot say "Nothing has changed yet".

Dialogs, failures and media

  • Resident failure copy is data on the mutation (meta.residentFacingError), not an error handler. A failed command reports through the app-wide snackbar.
  • Never add onError only to roll back an optimistic write, because it opts the mutation out of the net. Roll back in onSettled.
  • A surface holding unsaved work registers a mode-switch guard.
  • The onboarding wizard is not closed by Escape or backdrop click. Only its step actions close it. Skip is offered from the second step on.
  • Destructive actions use the shared confirmation dialog, not a native browser confirm.
  • A command that writes a critical capability goes through features/devices/critical. See critical commands.
  • Show an error inside the dialog that produced it.
  • A camera stream of any type (snapshot, motion JPEG, adaptive) falls back to an icon on load failure or a missing URL.

components/PageHeader is the h1 of the screens that use it: a title equal to the page's navigation label, a one-line subtitle and the primary action on the right (below the title on a phone). While one is mounted the shell's visually hidden h1 steps aside. A back link sits above the title on the left and is never the primary action.

The device detail pages, the login and privacy-policy pages, the home view, trusted keys and OIDC keep their own header.

Data layer

  • Send all API traffic through the shared axios instance. Importing axios directly bypasses the credential and 401 interceptors. External hosts use the external-fetch helper, which carries no credentials.
  • Parse responses through Zod schemas. Do not use any or an untyped cast.
  • Take query keys from the shared factory.

The device list

  • It is one query. Every reader (home screen, room widgets, pickers, trigger forms) uses the shared typed-devices query options and narrows with select. Realtime patches that single entry.
  • After a command or scene, mark the list stale without refetching. Refetch only when membership changes (an access edit, new devices).
  • A device-state push that arrives during a post-command detail read wins over that read.
  • The list is read in its lean view (view=lean): no capabilities rows, an empty unmappedProperties, no null members. A mirrored member the list can omit is .nullish() or .nullable().default(null).
  • A reader that needs capability rows or raw properties queries that device's detail and shows a disabled control that keeps the saved value while it loads (devices).
  • A capability-filtered picker matches on the descriptor only.

Cache timings

The query client uses a 30 s stale time and a 60 s collection time. Keep the collection time short: the reconnect path reads every cached device entry to build its invalidation set.

Preferences and favourites

  • The preferences endpoint replaces the custom-properties bag wholesale whenever the field is present. Merge onto a loaded baseline. If the baseline cannot load, keep the change optimistic and defer the write. Never send a single-key payload.
  • Favourites is one wholesale-replaced list under one shared lock. Every writer takes the shared mutation key and serialisation scope. View-mode persistence and onboarding dismissal are writers too.
  • A favourite control blocks (guard plus scope). A preference writer serialises only and reads its payload after its turn comes.
  • Do not narrow the server-side favourites read. It must mirror what is stored.

The workflow editor

@reeve-iot/workflow-* carries no network code. Anything the editor needs from the API arrives through a seam implemented over the shared axios instance. See automation and workflows.

Capabilities and channels

  • Capability presence comes from the descriptor, not from a non-null value. A null model means the device has no canonical surface.
  • Channel membership for pickers and controls comes from the descriptor's channels. Canonical state supplies current values only.
  • A picker scoped to one device shows the resolved channel label. A cross-device picker may add the device name.

Session and teardown

Auth state is in memory only, with no token in local or session storage. The session is a server-side HttpOnly, SameSite cookie.

One teardown function clears the query cache, the view-mode cache and store, the dashboard draft, the workflow-editor canvas and the hidden presence-device set. It runs on sign-out, on any 401, on a bootstrap that failed for any reason but an unreachable provider, and on an identity swap through the identity-provider callback.

  • Any new session-scoped singleton joins that function. Drop the storage cache before re-seeding a store from it.
  • Optimistic writers snapshot the session generation when they start and do not touch the cache once it has moved on. Ending the session moves it.
  • Mark a request that re-verifies a credential inside an authenticated session (password, step-up code, passkey) as a credential recheck. Its 401 is then a verdict on the credential, not on the session.
  • A 503 from an unreachable identity provider is not a session end. The same request is retried, and the bootstrap keeps retrying on Retry-After while the route guards hold their spinner. Only a 401 ends a session.

Cluster answers

  • replica_not_serving, replica_fenced and replica_behind mean the action did not run. The HTTP interceptor waits Retry-After (1 s when absent, delta-seconds or HTTP date) and resends once, for any method. A second refusal is an ordinary ApiError. A read may also be retried by react-query's retry: 1.
  • write_refused means the handler ran and nothing was written. It is never resent and rejects with WriteRefusedError.
  • A 202 write_unconfirmed rejects with WriteUnconfirmedError before the Zod parse. It means the handler committed locally and not every replica confirmed.
  • The interceptor announces these, and any 4xx or 5xx carrying Reeve-Replication: unconfirmed, with one reeve:notification and a cache invalidation. The mutation net adds nothing for an error that carries that notice.
  • Reeve-Skipped on an acknowledged success is logged. An administrator (home.manage) is told "Saved. Skipped by the cluster: …".
  • The same codes arrive on hub calls as a HubException. A refused hub connection is stopped so the restart loop reconnects, normally to another replica.
  • The workflow save paths treat these codes as refusals and repeat nothing.

Real-time updates

The realtime client is the consumer of the device hub. See signalr.md.

  • The client probes the session endpoint before every restart and when a reconnect begins, so an expired session is torn down. It skips the probe before the first connection.
  • It invokes no hub method. The connection receives every device its user may see, and a push is applied only to what the cache holds.
  • deviceStateChanged patches the typed and physical caches and, per source, the Last seen of the logical device detail (a source that is not Online refetches it). Paged logical lists show no timestamp and are not patched. A logicalDeviceChanged push invalidates them, and a reconnect refetches them once.
  • After a reconnect or a restart following a drop, missed pushes are not replayed. The hook invalidates the cached device-detail queries at once. It refetches the typed, physical and paged logical lists and the scene forms' bulk device read once, at a random moment within five seconds.
  • A logicalDeviceChanged push patches the physical list from its snapshot. It refetches the list only when the snapshot adds, drops or moves a source, changes the room, or brings an Offline source back. Those refetches are throttled to one per two seconds.

Theming

Both palettes live in one brand-token module. The theme is built with CSS variables and a data-theme selector and defaults to light. A shell toggle flips the scheme. Pass an explicit default mode, because the component library's own default follows the OS.

  • With CSS variables on, theme.palette.* is frozen to the light values. Read theme.vars.palette.* or sx tokens for anything that must switch scheme.
  • Status values go through the shared status pill or tone helper, never a raw colour string.
  • Radii, spacing, elevation, widths and colour roles beyond the palette are named in design-tokens.md and exposed as theme.reeve. Use those names.
  • Breakpoints: single column below 600 px, two-column forms from 600 px, the login side panel from 900 px, the permanent drawer from 1280 px.

Build and code rules

  • A .tsx file under src exports only components (the fast-refresh lint rule is an error, and lint allows no warnings). Constants, pure helpers and shared copy live in sibling .ts modules.
  • Build and typecheck run a project-references build. A bare no-emit typecheck skips project references.
  • Routes are code-split. Heavy pages are lazy wrappers that also export only components. The build puts the component library, SignalR, charts, maps, video and the code editor into named vendor chunks under a 500 kB warning limit. A new heavy dependency needs a chunk entry.
  • A store selector returns a value that is stable between renders. Do not build a fresh array or object inside it (state.user?.permissions ?? []). Read permissions through the permission hooks.
  • Use the sx prop or component props. Do not write custom CSS classes. Import components individually, not from the barrel.
  • Render user-authored markdown through the allowlist sanitizer. Raw-HTML injection is only for hard-coded application CSS and never receives user content.
  • The content security policy forbids inline scripts. Inline styles stay allowed for the CSS-in-JS runtime.
  • nginx drops every inherited add_header in a location that declares one of its own. Repeat each security header in such a location.
  • Each security header is a server-level add_header over a map $uri that is empty for /api/, /hubs/ and /ws/, so proxied responses keep the backend's headers. Keep both halves when you edit the nginx configuration.

Maps

Maps use Leaflet through src/lib/map, a small binding. Do not use react-leaflet. Each component owns one Leaflet object: it creates it on first render, adds it on mount, keeps it in step with the props below and removes it on unmount.

  • MapContainer reads center, zoom, bounds, boundsOptions, className and the Leaflet map options once, at creation. Move the view afterwards through useMap().
  • A child's effect cleanup must not call into the map, which is removed first. Leaflet's removeLayer and off are safe.
  • A Suspense boundary that hides the map keeps it. An <Activity> that hides it removes it, and showing it again builds a new map from the initial props.
  • An icon, opacity or zIndex that goes back to undefined keeps its last value, and a key left out of a later pathOptions keeps its last style.
Component Behaviour
Marker Follows position, icon and draggable. A new icon object resets dragging and ends a drag in progress, so keep icons stable across renders.
Circle, CircleMarker Follow center, radius (metres for a circle, pixels for a circle marker) and pathOptions.
Polyline Follows positions and pathOptions. className applies only at creation.
TileLayer Switches url, opacity and zIndex in place. A new attribution replaces the layer.
Popup, Tooltip Bind to the enclosing layer and render children into the overlay through a portal. Options are read once, content is not accepted, and outside a layer they throw.
Layer eventHandlers Bound before the layer joins the map and unbound before it leaves. add fires for the first mount. remove does not fire when the layer unmounts alone, but does when the whole map unmounts.
useMapEvents Binds while mounted and rebinds when the handler object changes.

Sizing and assets

Leaflet measures its container once. A map mounted in a zero-sized container, or one whose container changes size (drawer animation, hidden tab, accordion, window resize, orientation change), stays grey or keeps its first size until invalidateSize() is called.

  • Use MapAutoSizer for any map that can mount inside a Drawer, Dialog, Collapse, Accordion or tab panel, or with a fluid height. The geofence editor map has one fixed grid mount site and does not need it.
  • Vite hashes the marker image filenames. Pass an explicit marker icon to every <Marker>.
  • A map with no point to centre on shows a world view, not (0,0).
  • The map re-frames when the set of points changes, not on each coordinate or radius tweak. It pans to a draft centre only when that moves off-screen.

Presence and geofence maps

  • Location fixes arrive every 60 seconds, so the map polls no faster. The all-devices fixes route returns an array and the single me fix does not, so they never share a query key.
  • Key markers and visibility by presence device, not by user id. A location route can be scoped to one reporter (the unlabelled reporter travels as a fixed sentinel, never an empty string).
  • Per-device visibility is a local browser or handset choice and is never synced. An unknown device is visible. The set is dropped on principal change. With one reporter the filter is hidden unless that device is already hidden.
  • Reading needs geofences.view (or locations.view or home.manage for the route). Changing needs geofences.manage. A read-only mount omits every affordance that would answer 403.

Custom widgets

Third-party widgets run as sandboxed iframes without same-origin. They use message passing only, never receive a token, and touch only devices named in their dashboard data bindings. The host bridge enforces this on every action and subscription. Do not widen the sandbox or pass credentials across the bridge. See custom-widgets.md.

  • Bindings live in widget.dataBindings, separate from widget.config, and are merged with bindings winning.
  • Widget binding matching widens by unit only, from the canonical catalogue, because an outlet publishes power under a different key than a standalone meter. A key the catalogue does not declare, or declares without a unit, matches exactly.
  • Widgets use the canonical command path only. A non-canonical key answers 400 and is rejected before dispatch.
  • A posted range is reduced to valid window fields and a finite positive limit. A malformed one falls back to the default window.
  • A device whose critical flags cannot be read is treated as all-critical.
  • The backend proxies a device camera tile and does not expose its workload.
  • The gallery preview mounts the runtime in an iframe whose sandbox is exactly allow-scripts, the same as production. Never add allow-same-origin or another token. The "preview" badge is a CSS overlay.
  • Join an installed widget to its catalogue entry on (repositoryId, widgetId).

Wire contracts and the API client

Backend version skew

The Zod mirrors of backend contracts parse when the frontend is deployed ahead of its backend.

  • Fields the backend may lack are optional or defaulted.
  • An unrecognised enum string degrades to a neutral rendering. Health, freshness and availability stay plain strings.
  • Do not use a default that invents a fact. A "why is the list empty" reason has no default.
  • Some mirrored enums must list every backend member, because one unknown value rejects a whole list page.
  • Objects that cross into plain typed code are not .passthrough().
  • Where the server always writes nulls, a missing key is drift and fails closed.

Generated mirrors

backend/contracts-codegen generates the mirrors from the C# contract types. Each area registers its root types in backend/contracts-codegen/Areas/.

dotnet run --project backend/contracts-codegen -- generate   # writes frontend/src/contracts/generated/<area>.ts and primitives.ts
dotnet run --project backend/contracts-codegen -- check      # CI: fails when a committed file differs
  • Never edit a generated file.
  • Member names, nullability and conditional omission follow the types as the host serialises them. A response object is a plain z.object, so an unknown key is stripped.
  • A request schema carries the DataAnnotations bounds of its C# type.
  • Tolerances are per-member overrides in the area file, each with its reason: Optional, LooseEnum, Default and DefaultEmpty.
  • A schema the frontend narrows (a C# string the UI keys on as an enum, a check across members) lives in the area's hand-written module, which extends the generated schema and says why.

Whole-body PUTs

Several settings endpoints replace the whole document: workload provider entries and selection, parameter sets, preference lists. Mirror every field of the stored document and send a closed literal with all of them, or a save erases the rest.

  • A parameter posted as the *** mask keeps the stored secret.
  • The automation trigger list follows the same shape. Omitting it leaves triggers alone. Sending it replaces the set (matched by id, omitted ones deleted). The edit form always sends it.
  • Baby-monitor settings carry an optimistic version. A newer save makes the PUT answer 409.

Reads after writes

With several replicas, a GET right after a PUT can hit a replica that has not seen the write.

  • Seed caches from the PUT response (or the preferences or dashboard answer) and mark them stale without refetching (refetchType: 'none').
  • Write a SignalR device push into the cache again after any in-flight fetch of the same entry settles, so a stale read cannot overwrite it.
  • On reconnect invalidate only cached detail entries, not the whole list.

Critical commands need confirmation

A capability flagged critical asks the resident to confirm the exact (device, capability, value) before a command is sent, on web and mobile. A slider confirms once, on release.

  • When the critical flags cannot be read, every value is treated as critical.
  • Identical pending requests join. Others queue. With no mounted host a request is declined.
  • A decline is not a failure. Nothing is sent, the error net stays silent and controls roll back their optimistic echo.
  • The sender derives the critical items, and one confirmation host beside the router asks for them. A decline is an error the global mutation net ignores, and every control draft resets to the reported value.
  • Critical flags live on the logical device. A source's descriptor never carries them.

Step-up

  • stepUpToken is required on protected calls. The purpose is bound into the token.
  • The binding verifier is mandatory. A blank one is refused.
  • Every step-up failure is the same 401.
  • The password answer has its own route, because rate limiting is per endpoint.
  • The provider answer carries no provider id. The provider callback is a POST.

Mutation error net

The query client has a global mutation error net, built by a factory (a test client made with a bare new QueryClient has none).

  • A mutation with its own onError owns its error UX and silences the net.
  • Supply resident wording through the mutation meta: copy per errorCode (matched first), copy per HTTP status, and a fallback for rejections with no status. A meta with no usable message counts as absent.
  • The backend's detail is operator wording, for diagnostics only.
  • If the HTTP interceptor already showed a cluster notice, the net shows no second one.
  • Branch on the machine-readable errorCode from the ProblemDetails extensions, or on status. Never match message text.

Plugins in the admin UI

Signing keys

A repository's pinned Ed25519 key (base64) enables signature verification. Null means verification is impossible. A key advertised by a resource index is only a candidate until the operator pins it.

State Meaning
NotConfigured No key
Proposed An index offered a key
Pinned The operator pinned the key
RotationProposed An index offers a different key. Never applied automatically
  • The key fingerprint is SHA-256 over the raw 32 key bytes. The operator compares it with the publisher.
  • The global trusted-key list is global: an active entry verifies releases in any repository, though a repository's own key wins for it. Trust for an already-trusted proposed key lands in the global list.
  • Revoked entries stay listed.
  • Repositories materialised from an index are read-only.

Install and update

A first install makes two calls: the install (grant and consent), then a create-instance call with name, enabled switch and config. A failure of the second is reported as "installed, instance not created", never as a failed install.

An update targets an existing instance:

  • Re-send the instance's display name and enabled state. Omitting the name renames the live instance.
  • Omit config until the operator edits a field. Prefill only declared parameter names.

Other rules:

  • A plugin whose manifest has a deployment section with workloads goes through the consent wizard and sends the workload-consent acknowledgement. A deep link is navigation, never consent.
  • A 409 requires_confirmation opens the anomaly dialog (changed signing key, dropped signature, changed DLL name). The retry carries the same grant plus the acknowledged codes.
  • "Installed but outside this backend's version range" and "refused on this replica; the next boot repeats the refusal" are persistent. Never show them with restart prompts.
  • The fleet verdict is the same from every replica. Name a replica only when its own report decided it.

Plugin-supplied content

  • Plugin diagnostics views dispatch a descriptor to a fixed renderer set (Markdown, key/value, allowlist-gated iframe). Unknown kinds render "view unavailable".
  • Markdown is sanitised (rehype-sanitize). Marketplace descriptions use a text-only renderer. Repair hints are sanitised Markdown.
  • Link only a plugin-supplied https docsUrl.
  • The diagnostics iframe uses sandbox="", never allow-scripts or allow-same-origin.
  • An OAuth config-flow popup posts {code, state} back. Forward it only when the message origin equals the page origin.

Sign-in, step-up and secrets

Challenge binding

A login or step-up challenge is bound to the browser that began it by a verifier the client mints.

  • Read the verifier only from this origin's storage, never from a query parameter, hash, route prop or postMessage.
  • Mint it before the request that creates the challenge. It outlives the challenge TTL as a relative age.
  • Keep a step-up verifier in memory only.
  • With storage blocked the password path works and OIDC fails closed.
  • verify returns one expired_challenge for several causes. The client tells expiry apart by the clock and never renders the server detail.
  • A step-up proof is single-use and may cost a backup code. Keep it across a failed attempt and drop it only on the step_up_required detail.
  • Mount the ceremony dialog only while it runs.
  • Offer the fallback password pair only when the server lists it for an account with no second factor.
  • State that survives the IdP round trip lives in sessionStorage. It is consumed on a match and dropped at sign-out.

Recovery codes and credential secrets

Backup codes exist in plaintext only in the response that mints them.

  • Put them straight into a sheet that backdrop click and Escape cannot dismiss and whose Done needs an acknowledgement. Never send them to a snackbar, the console or the React Query cache.
  • One shared sheet serves first-passkey enrolment and regeneration.
  • The clipboard API is undefined outside a secure context (plain-http LAN installs are supported), so report a copy failure.
  • A raw API token is cleared on dismiss. S3 secret keys are write-only.
  • The low-codes interstitial offers "Later".
  • Setting a first password drops every session including the current one, and unlinking an identity revokes the target's sessions. The UI says so first.

Network egress

Unblocking a BlockedPrivateIp address needs an explicit confirmation. Plugin-grant and other not-fixable reasons never reach that dialog (the buttons are disabled with a hint). An unknown reason is treated as not fixable. Show rejections (400, 409, 404) inline.

Managed features and capability switches

A managed feature's controls sit inside the managed section and use the managed text field, checkbox and switch. Inside it a text field is read-only (the value stays legible and copyable) and a checkbox or switch is disabled. Do not use a native fieldset disabled.

  • Home settings: when the deployment manages them the page shows the notice, makes the time zone, coordinates and radius read-only, locks the map and hides Save. The demo content action stays. The onboarding wizard drops its home step and completes with the server's suggestions.
  • Egress allowlist: when managed the page shows the managed-feature notice, hides Add, Edit note and Delete, disables the enable switches and Unblock, and closes open dialogs. The list stays visible.
  • A write answered with 409 feature_managed makes the HTTP client reload me once.
  • The system status Overview lists managed features and the last configuration error.

C# scripting

The me flags carry cSharpScripting (absent means on). When the deployment turned it off (Managed:Capabilities:CSharpScripting), the capability reads as off and:

  • The workflow palette locks the script block with a reason naming the deployment and the setting.
  • The workflow list calls GET /api/workflows/script-holders and marks each named workflow Scripting off, with a tooltip saying whether the published version, the draft or both hold the block. It warns when that request fails.
  • The editor shows a banner while the published version or the canvas holds a script block, in any sub-canvas.
  • The canvas and node panel draw the stored block as the library's placeholder.
  • A publish or rollback marks the list and script holders stale.
  • The blueprint install dialog explains the refusal and disables Install for a blueprint whose template holds a C# script node.

Capability switches in general

Read a switched-off capability (Managed:Capabilities) through the capability hook, keyed by the member of the me flags. It answers true unless the flags say false. contracts/capabilitySwitches.ts lists each switch with its capability name and its system-status label, and requires one entry per member of the generated SystemCapabilities.

A page whose write controls depend on a switched-off capability keeps its data visible, disables or hides those controls and shows the "Switched off by the deployment" notice. A 409 capability_switched_off for a switch the flags still show on makes the HTTP client reload me once.

Cameras

A camera picture is a ladder of three rungs: a negotiated WebRTC session, a live WebSocket stream (fragmented MP4 into a source buffer at the live edge), then snapshots.

  • Each live rung holds a viewer slot while mounted. Tiles and thumbnails take one still, never a live rung, and stay a placeholder until the viewer asks. A stream or snapshot dials the camera and wakes a battery or cloud one.
  • A negotiation that never played drops quietly to the rung below. One that played and lost its path is redialled first.
  • Failure reasons are silent (a deadline passed, one more attempt), stated (a verdict) and dropped. Only a playing element clears the escalation.
  • Recovery backs off and probes the progressive route with a HEAD request. A retry waits less, because the first attempt starts the on-demand pull.
  • The camera embed route sits outside RequireAuth on purpose.

Workflow editor, blueprints and scenes

Workflow editor

Automations run the published version. Draft edits take effect on publish.

  • A 503 save stored the draft with its publish owed. It is retried once after Retry-After, resending the original body. A create or import that answered 503 is never re-sent.
  • Never read a cluster answer as "nothing was done, ask again".
  • Node ids must be identifiers an expression can name. The library's UUID default contains -, which ${previous.<id>.Value} cannot hold.
  • The expression preview runs outside any workflow. The server compile decides node-output reads.
  • Opening a sub-canvas whose container the catalogue does not know is refused.
  • The simple wizard wires input, action and output. A workflow that fails to publish is removed so no automation binds to it.

Blueprints

A community blueprint's scripts run only when the operator ticks the approval for that specific install, update, repair or rollback. The decision is never remembered.

  • On a 403 script_approval_required (a script that only the chosen input values bring in) the dialog shows the checkbox with the script nodes the server names and resends once it is ticked.
  • The install dialog's scripting-switch check looks only for real CSharpScript nodes, in any casing of the template's keys.
  • A rollback dialog cannot know a snapshot's scripts, so a community repository always shows the approval box.
  • The input picker resolves the chosen device's typed detail. A binding saved with a vendor key stays selected.

Scenes

Scene actions are canonical (kind-tagged envelopes with a key). A device's state is raw vendor data. The preview unwraps current and target to plain scalars before comparing, and a canonical key never resolves against raw state.

  • Compare sets (a vacuum's areas) by key, not rendered text.
  • An empty set is a target (the vacuum cleans every room), not "Not set".
  • An unknown current or target counts as a change. Only two resolved, equal values are a no-op. An action whose device was removed is skipped on activation. Remove it in the editor.
  • A device without a descriptor offers a vendor allowedValues select or free-text JSON. Stored values that are not JSON are tolerated.
  • A stored value no longer advertised keeps its chip and is named stale.
  • "Scene activated" appears only when every action ran. Skips are counted per action for operators and per device for residents.
  • Disabled scenes are listed in Basic and cannot be activated.

Basic Start screen

Tiles and optimistic commands

A Start tile commands a device through one canonical command and echoes the result into the shared typed-device list cache (the same query key as the Advanced list).

  • Every command takes an increasing id. A favourited in-room device renders twice, each tile with its own mutation writing one cache entry, so only the tile that issued the latest command retires the local echo.
  • Rollback restores a snapshot of the one commanded device's entry, never the whole array.
  • The confirmation read is scoped to the one device and routed through the detail key, so a second tap cancels it. A push never loses to a read.
  • The quick action is inert when the device is unreachable, its reading is unknown, the user lacks permission or the device type has no canonical command surface.
  • A multi-gang device gets an inline control only while the quick action is automatic. An unreported capability is named by the capability, never "Turn on".
  • A critical value is confirmed before any command is sent.

State line

  • A tile speaks only its category's headline list (readings, detections, state tokens), never a setting such as pan, volume or a countdown.
  • The lead word is the state word, else the device's first reported state enum, else a cover's motion and openness.
  • Household overrides add readings after the lead in the chosen order. A chosen key the device no longer declares leaves its slot empty.
  • A toggle counts as device state by capability name whatever its controllability.
  • A thermostat is credited with work only when it reports a running state. Otherwise the line shows mode, the setpoint (or range) for that mode, then the room.
  • Unavailable devices are left out of the summary strip. Devices the household excludes from the average temperature are left out of the average.
  • Button and scene tiles show the newest press from the list's lastEvent. Events expire, so no press is not a claim that there never was one.

Mounting, favourites and drawer history

  • Only Favourites reads the preferences list. Room sections take no favourites input.
  • A failed preferences read shows a warning with retry. The app default is retry: 1 with no refetch on focus.

System status and safe mode

The system status page is a catalogue of boxes in a fixed order. A box with a problem sorts first and opens expanded.

  • Each alert is filed under one box and shown above its body when the box asks for attention or cannot be read. A box's own line may claim an alert only while that line is on screen. Otherwise the alert is a row.
  • A failed request is an error with retry, not an empty state. A box that could not load adds "status incomplete" to its line. A failed read of the plugin list says so.
  • The server sends each box only to a viewer who may see it.
  • A replica's boot failure shows only while current (open streak, safe mode, or failed).
  • Logs are read when the box opens and on Refresh, never on a timer. The log buffer is per replica, so a log request names the replica. An unknown id is a 404, never a fan-out.
  • A 409 on replica removal means the replica came back or changed.
  • The safe-mode banner refreshes on every realtime connect, because a replica that engages safe mode drops the socket and the reconnect is the event that matters.
  • Plugin switches that matter in safe mode show on the Cluster tab.

Utility meters

Unit rules in the meter form mirror the backend. Offer only properties that can meter the chosen utility.

  • Instantaneous power integrates watts into kWh and accepts two unit spellings. A volume utility (water, gas) is not offered the instantaneous-power kind, but an already-saved meter keeps it listed.
  • watt_hour and kWh are convertible (a factor of 1000), so only the source property's own unit reveals a scale mismatch. The form warns on a convertible-but-wrong-quantity pairing and offers one spelling per quantity, smallest scale first. m³ is folded on typed input.
  • The UI derives the unsupported-conversion warning from the saved row.
  • In a tariff, an absent variable is a hard evaluation error, so a no-constant resolves to 0.
  • A measured-usage variable's mapping is no mapping (every meter in scope), one meter id, or text naming no meter (which resolves to no meter).

Workloads in the admin UI

Gated and fail-closed actions

Permission checks are mirrored client-side only to avoid dead clicks (disable and explain). The server enforces them.

  • workloads.approve gates revealing a manual-mode token, widening a host or device path, the provider test, force-adopt, retained-volume purge, execute-relocate, the update escape, and the plugin roll Retry and Give up.
  • integrations.manage gates observe-only and the lifecycle commands.
  • Consent and preflight steps fail closed. Loading, error, a blocked preview or no provider never advances. The preview fetch has no silent retry.
  • The install path re-derives the privilege profile and refuses an unacknowledged privileged deployment. A transient failure of a disclosure panel must not strand the operator on the last step.
  • Render privileges from backend severity tokens with Reeve-authored copy. Author prose is length-capped, quoted, attributed and kept apart from privilege lines.
  • An unknown severity renders quiet, not red. An unknown privilege token or network mode renders as raw text.

Parameters

The parameter screens parse the raw manifest JSON: the install wizard (one form for the whole deployment) and the edit form (one workload instance). There is no typed frontend mirror of the manifest.

Keep these closed vocabularies set-equal to the backend or schema: parameter widget kinds (an unknown manifest type folds to text), deviceKind (unknown folds to null, meaning no filter) and the unavailable-reason tokens.

  • Reserved parameters such as network.mode never appear in a manifest. The server projects their descriptors and only renderable ones render. applicableModes is server-computed.
  • A same-named author declaration wins for default and hint only. required is forced false.
  • A device slot with maxCount > 1 binds indexed keys only. The form must not write the declared key. maxCount is clamped, because N mounts at one mountPath are rejected by Kubernetes.
  • The install-time-only existingClaim.* family is filtered out of the edit form.
  • A node-selector change is a relocation. The edit form deflects to Relocate.
  • Seeding happens once per target and only for absent keys. Stored values win over descriptor defaults.

Install wizard

The wizard is a stepper only for plugins whose manifest has a deployment section.

  • Parameters come before Prerequisites, because the preflight is a function of the resolved parameters (device path, nodeSelector, storageClass). The preflight query is keyed on them, and Re-run re-checks the live cluster. Error-severity checks block. Warning and info do not.
  • The deployment provider is the single global effective provider. Only that card carries the live probe. There is no per-install "Select".
  • Retained volumes are chosen per retained-volume row id. The wizard snapshots {volumeId, resourceName} at selection. Only one existingClaim.{volumeId} binding can survive, so rows sharing a volumeId conflict.
  • Kubernetes storage classes and node-attributed device inventory are discovered only on the Kubernetes provider. An empty or failed discovery degrades to free text and never blocks. Values the probe did not list stay selectable.
  • An update with an unchanged network posture does not re-ask consent. Editing the network mode asks again.

Network attachments

A workload's network attachments are an ordered, comma-separated list. Endpoints connect in that order and the spec hash depends on the order, so the control is an ordered chip list, not a multi-select.

  • Enumeration is scoped server-side. Every degraded case answers 200 with an empty list and a reason.
  • Only the manual provider accepts free text, under the strict rule. Other providers enumerate or are disabled with a reason.
  • Reeve judges an attachment by name and existence only. Every listed name is selectable and the picker shows names only.
  • In a mode with no attachments the control is hidden, not disabled.

Update flow

The update flow has a consent mode and an observe-only progress-watch mode.

  • Phase progress comes from the last poll, because there is no update-phase SignalR event. A rolling-back phase marks no happy-path phase done.
  • Reject advances the baseline without installing. Close only hides the dialog, and the banner returns on the next poll.
  • A diff that adds a new required parameter cannot be approved in place. Abandoning restores the previous version and marks the update failed. A settled intent has nothing to abandon, and a mid-swap intent cannot be abandoned (the server returns 409).
  • A certified N+1 is never rolled back. The dialog explains that one phase with no escape.
  • Added workloads that require approval are privileged additions, and escalations are itemised in red. The protocol-floor row (envelope to the backend) and the pair-contract row (payload dialect to the sidecar) stay separate.
  • The preview carries no author changelog, only backend-derived notes. When there are none the dialog says so.
  • The banner prefers the parked state over in-progress. A not-parked answer is 204 (the client returns null, retry: false). Approve and reject address the plugin type, not the instance.
  • Adopting changed resource declarations is opt-in.

Status

WorkloadStatusChanged events go only to the hub's admins group.

  • The aggregate health shows the worst non-suspended state and "any suspended" as separate chips. Suspended sorts below every ranked state. Instances sort worst-first, with workloadId as tie-breaker.
  • For a manual-mode workload the only connection signal is what the gateway observed. The copy-paste probe carries a <REEVE_WORKLOAD_TOKEN> placeholder, never the real token.
  • The log section shows the REST tail. The live tail uses SignalR only after the viewer turns on Follow live, only for the current container of a provider-backed workload. It keeps a bounded buffer, falls back silently to the REST snapshot and renders a restart marker as a divider.
  • Volume unknown renders as indeterminate, never "stable". A missing claim stays missing for observe-only, suspended or externally managed workloads. The volumes panel is hidden when the provider has no live status (docker, manual).

Tests

  • The unit suite runs with worker isolation off: one window, one module registry and one set of module-scoped stores per worker. Global mocks are plain functions, not spies.
  • Web storage does not reset between tests. Clear it before re-seeding a store that reads from it.
  • Charts do not render headlessly. Keep labelling and series-selection decisions in pure modules.
  • Drive user interaction through the shared setupUser() helper (src/test/userEvent.ts), which works under a fake clock. Reach a control that stays disabled until its query loads through findEnabled().
  • A wait the code under test schedules (a backoff, a Retry-After, a poll) runs on fake timers. Prove "nothing happened" by advancing the fake clock past the deadline.
  • Select options render into portals inside hidden trees, so role queries miss them. Query the DOM directly. Set textarea values containing curly or square brackets with a change event, because user-event reads them as keyboard modifiers.
  • findBy* and waitFor time out after 5000 ms. The shared render helper also waits for the lazy route chunk.

Failure modes a user will meet

Symptom Cause What to do
A working light or blind shows "Unavailable" Its last reading is over 24 hours old, its source is not Online, or it lost its source binding Check the integration on the operator surface. The control returns as soon as it reports again
A device is missing from the home screen but present in the inventory It is a coordinator or a presence device, both hidden by design Use the operator inventory or the location map
A room shows only a heading and a reveal button The household exceeded the tile mount budget Tap it. Nothing is lost
A tile has no on/off control although the device is controllable Its Basic tile quick action is none or names a gang the device lacks, only one gang is controllable, or its only controllable number declares no range Open the drawer, where the full control lives
A device opens with "no controls to show" Its type has no dedicated control, and the resident surface has no raw property writing Operate it from Advanced
The Basic/Advanced toggle is not visible The account holds no permission-gated Advanced-only destination and no in-page Advanced capability It is not a setting. It needs a permission grant
A favourite star is greyed out Preferences have not loaded, or another favourites, view-mode or dismissal write is in flight Wait and retry
A star was tapped and nothing happened A second write raced it inside one frame and the handler dropped it Tap again
"The device is not responding" A timeout or gateway failure. The command may or may not have been applied The wording does not claim it was not
The app returns to the login page mid-session A 401 tore down the session and every cached query Sign in again. Nothing local is corrupt
Every visible tile refetches after a network blip The realtime connection reconnected and re-validated the visible devices Expected
Realtime updates stop app-wide behind a load balancer The route to /hubs drops the WebSocket upgrade, and the client opens the socket directly with no long-polling fallback Forward Upgrade and Connection on /hubs, as the shipped nginx does. No session affinity is needed
The camera tile shows a crossed-out camera icon The stream URL is missing or failed to load Check the source URL. A spinner there is the picture still connecting
A dashboard widget shows a warning strip such as "Device removed" or "Bound device removed" The dashboard's list read reports the device or helper the widget names as deleted, or the widget's own read answers 404 with device.not-found or helper.not-found. A 403 or any other failure stays a load error Edit the dashboard and use the strip's Remove widget, or reconfigure the widget. The banner above the dashboard counts what it lost, see removed devices
A dashboard tile says "This widget could not be shown." That widget threw while rendering. Each widget has its own error boundary Reconfigure or remove the widget. The browser console has the error
A page says "Something went wrong" with a Reload button, inside the navigation The page threw while rendering, or a code chunk failed to load again within 30 seconds of the automatic reload Reload. The navigation and other pages are unaffected
The whole screen says "Something went wrong" with a Reload button and no navigation The sign-in, OIDC callback, camera embed or privacy page threw, or the app layout did Reload. The browser console has the error
A room widget says "This room was deleted." The room it names is no longer in the household's room list Edit the dashboard and remove the widget or pick another room
A room widget says "This widget is not set up yet." It was added while the household had no rooms Edit the dashboard and pick a room
A camera card on a device list shows no picture Cards are collapsed by default and make no media request Press Show preview
A camera tile on Start, or the picture in the Basic drawer or a dashboard widget, is a placeholder Those surfaces make no media request until asked Press Show live. The Advanced device page starts live