Device list and device detail took several seconds to show online status
because every /mqtt/status call ran SELECT DISTINCT ON (device_serial) over
the whole heartbeats + alert-event history (one heartbeat row per device
every 30s, kept for the full retention window). /mqtt/latest-metrics and
the 60s ping loop paid the same fleet-wide scans for ping samples and
diagnostics.
- database/latest_cache.py: newest heartbeat / alert event / ping sample /
diagnostics row per device, held in memory. Seeded once at startup
(warm_latest_cache) or lazily on first read; every insert writes through
via RETURNING, keeping whichever row is newer so writes that land while
the seed query runs are never lost. Per-device deletes and the retention
purge drop the matching entries so the cache never outlives the DB.
Single uvicorn process owns the MQTT client, so no cross-worker drift.
- GET /api/mqtt/status/{serial}: one device's status (cache, or a single
indexed lookup) so DeviceDetail no longer downloads the whole fleet.
- devices router: 11 GET/notes/tags handlers were `async def` but call the
synchronous Firestore client, blocking the event loop (MQTT ingest,
WebSocket, every other request) for each Firestore round trip. They are
plain `def` now so FastAPI runs them in its threadpool.
- DELETE /api/mqtt/logs/{serial}?source=&level=&until=: filtered delete of
console-stored device logs, for the Health tab's new "Delete logs".
Requires devices:edit and is audit-logged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The firmware moved its NVS identity keys from hw_type / hw_version to
hw_family / hw_revision (NvsMigration.cpp), and the NVS generator, cloudflash
and the device models already used the new names. Firestore device docs and
the manufacturing code still wrote and read hw_type / hw_version, so the
device API's hw_family / hw_revision were always "" (0 of 14 docs had them)
and the console used two names for one value.
Device docs now use the firmware's names (schema v1.1.0, decision D2 in the
bellsystems-schema repo). The apps don't read these fields, so no app change.
- Manufacturing batch-create writes hw_family / hw_revision; the inventory
API exposes hw_family / hw_revision (filters: ?hw_family= / ?hw_families=).
Reads fall back to hw_type / hw_version so docs not yet migrated still work.
- devices/firestore_v1.py renames hw_type / hw_version on read and write and
rejects a hw_family that isn't a code (e.g. "Bell Plus"): when the console
generates NVS from it, the firmware builds its OTA URL from that value.
- Inventory, provisioning, onboarding and overview pages use the new names.
Unchanged on purpose: the firmware catalog and flash assets
(/api/firmware/{hw_type}/..., hw_type_override) — a separate store and the
URL devices call; same values, only the variable name differs. The public
cloudflash response keeps its hw_type field (public contract).
Data migration (rename + fix 3 display-label values) runs from the
bellsystems-schema repo AFTER this is deployed: the currently deployed
console still reads hw_type.
Verified: 118 backend tests pass; frontend builds; ESLint errors in
ProvisioningWizard.jsx (7) are pre-existing and unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The FlutterFlow tablet and phone apps parse each device doc inside safeGet:
one wrongly typed field makes them silently drop the whole device from the
user's list. The console was the source of every such field found in
production on 2026-11-08:
- New devices: DeviceCreate defaulted times to "" and IPs to [], and
create_device wrote them as-is. Every console-created device was invisible
in the apps from birth. It also set device_id but not serial_number.
- Round trip: reads formatted Timestamps as "15 January 2026 at 22:01:00
UTC+0000", the frontend echoed that back on save, and _restore_timestamps
could not parse it (nor ""), so it stored the string. towerClockTime was
not in its list at all.
- Key spelling: the console wrote bellGuardSafetyOn / useStaticIP; the apps
read bellguardSafetyOn / usesStaticIP, so console edits never reached them
and docs ended up with both spellings disagreeing.
- MelodyMainItem used the melodies-collection shape (information, url, ...)
instead of the device shape the apps read (mainInformation, binaryUrl, ...);
Pydantic dropped every real key on read.
- Manufacturing batches created devices with serial_number but no device_id,
which both apps use to connect over MQTT (7 of 14 devices affected).
The contract now lives in the bellsystems-schema repo (v1 = what the shipped
apps read). backend/devices/firestore_v1.py enforces it on every device
write (to_firestore) and read (to_api):
- Timestamps: ISO 8601 in the API, Firestore Timestamps in the DB, null for
unset. The old display format is still accepted on write so an open
browser tab can't corrupt data; anything unparseable is a 422.
- IPs: dotted strings; octet arrays are joined; invalid values are a 422.
- Legacy keys are renamed (v1 key wins over a duplicate); users_list dropped.
- device_id mirrors serial_number (decision D1); conflicting values are a 422.
- user_list / melodyReference entries become DocumentReferences.
- update_device re-normalizes the merged nested maps, so saving a device
also repairs pre-v1 junk already stored in it.
Models and the frontend now use v1 names and send null (not "") for unset
times. The firmware's network.set_config MQTT payload keeps its own names.
Verified: 114 backend tests pass (new tests/test_firestore_v1.py covers the
production failure shapes; test_timezones.py not run locally, needs tzdata).
A read-only dry run of a console save against all 14 production devices
produced v1-valid docs with no fields lost. Frontend builds. Not deployed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Manage tab and Onboarding page list users via GET /devices/{id}/users,
which read the device_users sub-collection first and only fell back to
user_list when it was empty. Every write (add/remove on those pages, the
Users page, PUT with user_list) went to user_list only, so on any device
that had a device_users doc the list showed stale data: users added in the
Console never appeared and removed users never went away. A production
survey found 6 device_users docs (all role "admin") on 6 devices; 2 of them
disagree with user_list.
user_list is now the single source of truth:
- get_device_users reads only user_list; role comes from the mirror if any.
- Every user_list write also adds/removes the device_users mirror doc
({role: "admin", user_reference}) in the same atomic batch, in case the
phone app still reads the sub-collection. It is meant to go away later.
- users.service.assign_device and PUT /devices/{id} now store
DocumentReferences (the app's format) instead of "users/{id}" strings.
scripts/sync_device_users_mirror.py (dry run by default) reports and fixes
pre-existing drift between the two. Not run yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Console side of the firmware 3.x TimeKeeper overhaul (project-vesper
F-079/F-081/F-083). The Clock tab's "Network & Time" card was read-only and
showed fields the firmware no longer reports, and both analog clocks drew
the browser's own time.
- Time & Timezone card: device local time, zone, mode, UTC offset, DST state
(incl. expired manual dates), next change, RTC synced. Read live from the
device (system.get_time, clock.get_timezone) - the device is the source of
truth for time settings; nothing about them is mirrored to Firestore.
- EditTimezoneModal: Automatic (country -> zone from the backend timezone
table, or a custom yearly rule built into a POSIX string), Manual DST (std
offset, amount, this season's start/end), Fixed, Local only.
- SetDeviceTimeModal: this computer's UTC time, or a typed local time.
- NTP Sync card + NtpSettingsModal: automatic on/off, nightly time, servers,
last result/drift; Sync Now queues clock.sync_ntp and polls clock.get_ntp.
- SyncClockModal (was a placeholder): pause, enter what the face shows,
clock.set_face + resume.
- EditClockSettingsModal: face sync policy force/smart + max wait; mirrored
as clockSettings.faceSyncMode / smartMaxWaitMin (added to the backend model,
which silently dropped unknown keys - the old gmtOffsetSec/ntpServer mirror
never persisted, so those dead drift checks are removed).
- Device Time / Clocktower clocks now show the device's wall clock and the
real face position (refreshed every 30 s while the clock runs).
Live reads are chained after the existing clock.get_config drift check and
face polling pauses while a modal or Sync Now is sending, because device
replies are matched FIFO without a request id.
Stage 5 of project-vesper docs/features/timekeeper-overhaul.md.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DeviceUpdate accepts user_list, so a device PUT could add or remove users
without touching their device_serials - leaving the MQTT app ACL stale
(a removed user would keep access; an added user would be denied).
update_device now diffs the old vs new user_list and, in the same atomic
batch as the device write, ArrayUnion/ArrayRemoves the device's serial on
each added/removed user, then invalidates their MQTT ACL cache entries.
Dangling user references are skipped (updating a missing doc would fail
the whole batch). PUTs without user_list take the old single-update path.
Covered by tests/test_device_serials_sync.py (fake Firestore).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds a `device_serials: [string]` array to Firestore `users` docs so the
MQTT ACL (and get_user_devices) can answer "which boards may this user
reach?" without streaming the entire devices collection.
- The serial is the value used in MQTT topics vesper/{serial}/...: the
device doc's `serial_number` (flashed into NVS, used by the firmware as
its MQTT id), falling back to the legacy `device_id` for old docs.
Centralised in users.service.device_serial_of().
- assign_device / unassign_device now write the device's user_list and the
user's device_serials (ArrayUnion/ArrayRemove) in one atomic batch.
- The device Manage tab endpoints (POST/DELETE /api/devices/{id}/user-list)
also edit user_list, so they get the same batched sync - otherwise the
most common assignment path would silently leave device_serials stale.
- get_user_devices resolves devices via device_serials with chunked
Firestore "in" queries instead of a full collection scan. Requires the
backfill script (next commit) to be run for existing assignments.
- New mqtt/app_users.py: resolves users by the `uid` FIELD (not doc id -
create_user uses .add(), FlutterFlow uses uid as doc id) with a 60s
in-process TTL cache. Assign/unassign, update, block/unblock and delete
invalidate that uid's entry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Missed from the previous Reset Stats commit — these are the
request/response schemas for POST /devices/{id}/reset-stats.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
New POST /devices/{id}/reset-stats + ResetStatsModal lets staff clear
QA/bench test data accumulated before a device ships to a customer:
Firestore bell/playback counters and Postgres history tables (logs,
heartbeats, commands, boot events, alert events, ping samples,
diagnostics reports, control/reports, and opt-in live alerts). The two
firmware-side resets (telemetry.reset_boot_data, logs.clear) go over
the existing MQTT command/ack flow instead, since they need the device
online and duplicating that round-trip server-side would just be a
second, inferior implementation.
Also includes two incidental cleanups in devices/router.py: audit-log
entries for create/update now use console_name in their label (missed
by the earlier console_name commit), and add/remove-device-user rename
their local Firestore client from `db` to `fs` to stop shadowing the
`db: AsyncSession` dependency param in the same function scope.
AddDeviceUserModal's results list also gets a max-height + scroll so a
long match list doesn't grow the modal off-screen.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Lets staff set a friendly name for a device independent of whatever
name the end user gave it in the app. console_name is never shown to
app users and never synced from/to device_name; every display label
across search, equipment/helpdesk name resolution, device search, and
the Manage tab's issue linker now falls back through console_name ->
device_name -> serial rather than device_name alone.
Also includes an incidental one-line fix in devices/service.py: the
nested-struct deep-merge in update_device() was missing the newly
added device_health_settings key.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
subscrStart, warrantyStart, and maintainedOn are written to Firestore as
Timestamps like the other date fields here, but were missing from
_TIMESTAMP_FIELD_NAMES, so they weren't being converted back to ISO
strings on read.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Two-tier (warning/critical) threshold config per device — restarts/week,
RSSI floor, free-heap floor, CPU temp ceiling, plus an offline timeout
used for both a client-computed health status icon and the Health tab
chart's gap detection. Purely advisory for now: no server-side
email/push alerting infra exists yet, so email_on_threshold and
push_on_crash_boot are placeholders for that future work.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>