A new release almost always keeps the previous release's upgrade-chain
floor, so the upload form now defaults Min FW to the newest existing
release for the same board (same channel preferred, any channel as
fallback; bespoke matched by UID). Empty when no previous release set one.
It re-derives when board/channel change until the user edits the field,
and a hint shows which release the value came from. Edit mode unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Health → Logs gets two actions above the log explorer:
- Clear view (view-only): hides everything received before now so only
fresh entries show. Text channels use it as the server-side `since`
bound; alerts/heartbeats/commands filter client-side. "Show all" undoes
it; nothing is deleted.
- Delete logs… (devices:edit): DeleteDeviceLogsModal permanently deletes
selected history by type — Device Logs and Info (optionally only some
levels) via DELETE /mqtt/logs/{serial}, and alert history / heartbeats /
commands via the existing reset-stats endpoint. Press-and-hold confirm,
like Reset Stats. Device SD-card logs are untouched.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The device list and detail page showed empty status columns/fields until
every request finished. They now render instantly from the last-known data
and refresh in the background, with a small "Syncing…" spinner in the page
header while fresh data is in flight.
- lib/deviceCache.js: last-known device list (per query), devices by id,
fleet status map, list metrics and Health-overview datasets. In memory
plus sessionStorage (except the large Health datasets); every storage
access is guarded.
- DeviceList: seeded from cache; status + metrics fetched in parallel with
the device list instead of after it; out-of-order search responses are
ignored; live heartbeats are written back to the cache.
- DeviceDetail: seeded from cache (DeviceList already holds the device),
reloads after modal saves refresh in place instead of unmounting the
tab, status comes from the new /mqtt/status/{serial}.
- HealthTab overview: same stale-while-revalidate per device + range.
Health tab firmware lag: the Firmware/OTA tile read the version from the
latest diagnostics report, which the firmware sends only every 5 minutes
(the first 5 minutes after boot), and the tab never re-fetched it while
open — so after an OTA it kept showing the old version. Firmware reports the
same compiled FW_VERSION in heartbeat and diagnostics, so the tile now uses
the heartbeat (30s, pushed live over WebSocket) and only shows the OTA
"update available" badge when the diagnostics report describes the
firmware that is running now. HealthTab also passes deviceId/canEdit down
to LogsTab for the log management actions in the next commit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
Device docs now store hardware identity under the firmware's NVS names.
Future sessions need to know that, and that the firmware catalog keeps
hw_type as a variable name on purpose.
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 tablet and phone apps read the same Firestore device documents as the
console; a wrongly typed field makes them silently hide the device. CLAUDE.md
already documents this for Claude sessions; the README now states the rule
for humans too: device writes go through devices/firestore_v1.py, and shared
fields change in the bellsystems-schema repo first.
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>
The example still showed gmtOffsetSec/daylightOffsetSec, removed in firmware
3.0.0; it now shows the ntp and tz objects.
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>
Firmware 3.0.0+ (project-vesper F-079) keeps the RTC in UTC and, in
timezone mode "auto", evaluates a POSIX TZ rule string sent by whoever sets
the timezone. Devices don't carry the IANA database and POSIX signs are
inverted, so the console and apps need one place to get the right rule.
GET /api/public/timezones[?country=GR] returns every country with its zones
(zone.tab), each with the POSIX rule (TZif footer), std/DST offsets in
minutes east of UTC, and the current offset/DST state.
GET /api/public/timezones/zone?name=... resolves one zone, including
aliases zone.tab doesn't list (e.g. a phone reporting Asia/Calcutta).
Public on purpose: IANA data, needed by the phone app (Firebase auth, MQTT)
and for the tablet app's offline bundle (save the full response, ~130 KB).
Source is the tzdata pip package, now pinned (2026.6 = IANA 2026f); bumping
the pin is how new DST rules arrive. Docs in docs/device-timezones.md;
tests in tests/test_timezones.py.
Stage 4 of project-vesper docs/features/timekeeper-overhaul.md.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mirrors project-vesper F-081: clock.sync_ntp queues a session and returns
{ started: true }, the outcome is read from clock.get_ntp last_sync;
clock.set_ntp sets auto / sync_time / servers; clock.get_config reports
"ntp" instead of "ntp_server".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mirrors project-vesper F-079: the RTC holds UTC and the timezone is one
object with modes auto (POSIX rule) / manual (DST dates) / fixed / local.
clock.set_time takes timestamp (UTC) or local plus an optional timezone,
clock.get_config reports "timezone" instead of gmt_offset_sec/dst_offset_sec,
system.get_time gains local/offset_min/dst_active/tz_mode/tz_name/rtc_synced.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mirrors firmware F-071..F-073 (project-vesper, v2.4.0):
- New mqtt.status command (MQTT connection health: connect/disconnect
counters, last disconnect reason, forced self-recovery resets and reason,
resent_messages).
- status/playback and control/reports are QoS 1 with PUBACK tracking
(playback republished on reconnect, reports resent); control/ack, alerts
and info are QoS 0. Heartbeat unchanged (QoS 1).
Verified the page parses with esbuild.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
751cac7 switched the base compose file to an external named volume
(bellsystems-postgres-data) to dodge a WSL2/Docker Desktop bind-mount bug.
That volume only exists on the Windows dev machine: on the VPS, where the
push auto-deploys via deploy-host.sh, `docker compose up` would fail on the
missing external volume (or, if created, start Postgres on an empty
database while the real data sat unused in ./data/postgres).
The base file goes back to the ./data/postgres bind mount the server has
always used (Linux has no such bug). The named volume now lives in
docker-compose.override.yml, which Compose loads automatically, is
gitignored, and is created from docker-compose.override.example.yml on
Windows machines only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- CrashDetail (components/shared): headline is abort_msg when present,
else the Xtensa exception name. For aborts, pc/exception/fault address are
shown muted with a note that they describe abort() and that the first
2-4 frames are abort internals. Shows task, uptime at crash, heap stats with
a "likely heap exhaustion / fragmentation" badge (largest_block < 12000 or
free_heap < 25000, F-055), PC + backtrace as 0x%08X in ESP serial format,
a copyable addr2line command (PC, backtrace, then the PC parsed from
"abort() was called at PC ..."), elf_sha256, and a backtrace-corrupted
flag. When the server has the build's ELF and addr2line, a Decode button
shows function + file:line per frame.
- Health tab boot history uses it, previews the headline in the row, and
gets a "Sync from device" button (telemetry.get_boot_history, merged
server-side).
- New /devices/crashes page (linked from the Fleet header): crashes grouped
across devices with per-device counts and the latest occurrence.
- Firmware release modal: optional firmware.elf attachment.
- API reference: boot_report payload documents the F-070 fields.
- lib/crashReport.js holds the parsing/formatting rules; lib/clipboard.js
a copy helper with a non-secure-context fallback.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Crash reports carry elf_sha256 (first 16 hex chars of the crashing build's
ELF SHA-256). ELFs are now stored under that key in
{firmware_storage_path}/elf/, uploaded either with a firmware release
(optional elf_file on POST /upload and PUT /{id}) or standalone via
POST /api/firmware/elf. The ELF is validated before the release is created.
GET /api/firmware/elf/{sha} reports whether that build's ELF exists and
whether the decoder is available; POST /api/firmware/elf/{sha}/decode runs
xtensa-esp32-elf-addr2line -pfiaC over the addresses. The decoder is looked
up via settings.addr2line_path or PATH. It is NOT in the Docker image yet,
so decoding reports "not installed" until the toolchain is added; the
console falls back to a copy-paste addr2line command.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Firmware F-070 adds a fuller `crash` object (backtrace, backtrace_corrupted,
elf_sha256) and a new `pre_crash` snapshot (uptime, heap stats, optional
abort_msg) to boot_report and to telemetry.get_boot_history entries.
- Migration c9d0e1f2a3b4: device_boot_events gains crash / pre_crash JSONB,
stored verbatim so later additive fields need no migration. The legacy
crash_* columns are still filled; old rows and old firmware are unchanged.
JSON is bound as CAST(CAST(:x AS TEXT) AS JSONB): a bare JSONB cast makes
asyncpg JSON-encode the already-encoded string a second time.
- boot_report ingestion passes both objects through.
- telemetry.get_boot_history replies (control/ack) are merged into boot
history whoever sent the command: an entry matches an existing row on
boot_count + reset_reason + time within 30 min (boot_count alone is not
unique - the counter gets reset), and only fills crash/pre_crash the row
lacks; unmatched entries are boots we never saw live and are inserted at
the device's timestamp; entries without ts are skipped.
- GET /api/mqtt/crash-groups: fault boots grouped by abort_msg with hex
addresses stripped, else task + exception cause, else reset reason. When
abort_msg is present, pc/exc_cause describe abort() itself and are
ignored for grouping.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The firmware publishes status/heartbeat, system/alerts, system/info and
status/playback with retain=true. On every backend (re)connect - every
restart and every uvicorn --reload - the broker replays the last message on
each of those topics for every device that ever connected. We handled those
replays as if they had just happened:
- heartbeats: a row with received_at=now() for every device, so devices
that have been dead for months showed ONLINE for 90s after each restart
and got pinged. ~770k such rows exist locally.
- boot_report: the last boot logged again as a new reboot (the phantom
PANIC entries on the Health tab).
- alerts / other info events: logged again as new occurrences.
MQTT delivers retain=1 only for replays caused by a new subscription; live
publishes always arrive with retain=0. The flag is now passed through to the
handlers and the WS broadcast:
- heartbeat: replays are not stored. A live heartbeat is.
- {"state":"offline"} heartbeat (LWT / graceful disconnect) is no longer
stored as a sign of life. It marks the device offline immediately in
a small in-memory set (mqtt/presence.py) used by /mqtt/status and the ping
loop; a later live heartbeat clears it. Replayed offline markers also mark
offline, since a retained message is the device's last word.
- boot_report: live -> always a new boot. Replay -> stored only if it
differs from the device's latest boot row (i.e. we missed it while down).
- alerts: replay still syncs the current-alert row; history gets a row on a
live alert (even an identical repeat - faults recur) or on a replay that
changes state. Replaces the 98dd16b rule that dropped identical live alerts.
- other info events: replays are not logged.
- Frontend (DeviceList, DeviceDetail, LogsTab) ignores retained WS messages
for live updates, and flips a device offline on the offline marker instead
of marking it online.
Verified locally after a backend restart: only the 7 actually-live devices
got new heartbeat rows (none from the replays), and no boot/alert/info rows
were created.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
98dd16b skipped a boot_report if ANY earlier row had the same boot_count.
That is wrong: the firmware's lifetime boot counter gets reset (reflash /
telemetry reset), and the data shows counts 1-4 recurring in July and again
in September. With that rule a real later boot reusing a number would be
dropped forever.
A retained redelivery is always a copy of the device's most recent boot, so
compare only against the latest row (boot_count + reset_reason). A genuine
new boot always differs from it - the counter moves forward or was reset.
Note: the one-off cleanup run on 2026-09-30 used the same wrong
(serial, boot_count) key and deleted some genuine boot rows along with the
redelivery duplicates; see the session notes / heartbeat-based reboot list.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The firmware publishes boot_report on system/info and alerts on
system/alerts with retain=true. Every time the backend (re)connects - which
under uvicorn --reload means every backend file save - the broker redelivers
the last retained message and we inserted it again with occurred_at=now().
Result: the Health tab showed fresh PANIC boots and "Device reset due to
fault" alerts for a device that had been up for 4 days.
- insert_boot_event skips the insert when a row with the same
(device_serial, boot_count) already exists. boot_count is the firmware's
lifetime counter, so it uniquely identifies a boot.
- upsert_alert only writes when state/message actually changed and returns
whether it did; the alert-event history row is only added on a change.
A redelivered identical alert no longer bumps updated_at either.
Existing duplicate rows are not touched by this commit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Both create paths (Users > Add User page and the CreateUserModal used during
device onboarding) now have a Confirm Password field. A mismatch shows an
inline error and blocks the create call, so a typo can't silently become the
user's Firebase Auth password. The confirm value is client-side only and is
never sent to the backend.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
create_user wrote the profile with .add() (random doc ID). On first login the
FlutterFlow app looks for users/{uid}, doesn't find it, and creates a second,
bare doc - so every console-created user ended up duplicated, and devices
assigned in the console pointed at the doc the app never reads.
Now the profile is written to users/{uid} with created_time set, and the email
is lowercased to match what Firebase Auth stores. If the Firestore write
fails, the just-created Auth account is deleted so no orphan is left.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The amber diagonal slash on offline devices was too loud on the Fleet list.
Offline now renders all arcs unlit in the neutral dim colour. The amber "?"
for online-but-no-rssi (legacy v1 firmware) is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TLS for the phone app went live on the VPS on 2026-09-30:
- Mosquitto got a second, non-published listener on 8083 with
`protocol websockets`; port 1883 stays plain TCP for the boards
(ESP32s can't spare RAM for TLS).
- The mosquitto service joined the external Docker network npm_npmnet so
NPM (NPMplus) can reach mosquitto:8083 by name; it stays on `default`
to reach the Console backend at 172.20.0.1:8000.
- NPM proxy host mqtt.bellsystems.net -> http://mosquitto:8083 terminates
TLS and renews the Let's Encrypt cert. proxy_read/send_timeout 3600s
added so NPM doesn't drop idle MQTT connections after 60s. NPMplus has no
"Websockets Support" toggle (always on).
- Verified end to end: a paho client over wss://mqtt.bellsystems.net:443
(path /mqtt) authenticated via the Console backend and received a
heartbeat.
Chosen over native 8883 because NPM already owns 80/443 and certificate
renewal, so there is no extra cert handling on the host, and 443 also gets
through networks that block 8883.
The doc now gives the app's final transport (wss, 443, /mqtt, never 1883,
keepalive < 3600s), the listener/network/NPM layout, the end-to-end test,
rollback steps, and a new known gap: the backend's port 8000 is published
on 0.0.0.0, so the /mqtt/auth/* endpoints are reachable from the internet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Broker logs after the 2026-09-30 restart show some boards (PV26B02BP01R01,
BSVSPR-26C20B-STD10R-2KCDPH) subscribing to vesper/{serial}/control rather
than control/command. The app ACL only allows publishing to control/command,
so the app can't command those boards until their firmware is updated.
Recorded so nobody widens the ACL by accident.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The full mosquitto.conf (2026-09-30) has a single plain listener on 1883,
used by the boards. The phone app sends a Firebase ID token as its MQTT
password, so a TLS listener must be added before app users go live.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Checked the live broker on 2026-09-30:
- mosquitto.conf sets no files-backend ACL path. A live test (device A
subscribing to device B's topics) was denied while A's own topics were
delivered, so the files backend does not grant-all and every ACL check
reaches the Console. The missing ACL file is therefore harmless.
- Recorded the container/image, config and passwd locations, which lines
already match the new code, and the one change still pending
(auth/acl cache 300s -> 60s before app users go live).
- Added the copy-paste isolation test so it can be re-run after any broker
config change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/mqtt-app-user-auth.md records what future sessions (and whoever builds
the phone app) need and can't get from the code alone:
- app connection contract: username app_<uid>, Firebase ID token as
password, client id prefix app_<uid>_, TLS only, allowed topics per acc,
- serial field (serial_number, legacy device_id) and the device_serials
mirror + every code path that must keep it in sync,
- the uid-field lookup rule and ACL cache invalidation,
- legacy "vesper" password flag and its log line,
- rollout checklist: backfill, go-auth VPS config (required/recommended),
files-ACL check, TLS listener,
- decisions/gaps: FlutterFlow must sync device_serials itself; the
device_users subcollection is intentionally ignored.
CLAUDE.md gets a short section pointing agents at it before they touch
MQTT auth or anything that edits user_list/status.
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>
First pytest suite in the backend (backend/tests/, run from backend/ with
`python -m pytest tests`). firebase_admin.verify_id_token and Firestore
are mocked, so no network access is needed. 82 cases:
- /user devices: HMAC ok / wrong / other serial's HMAC, kiosk HMAC,
legacy password with flag on/off, legacy rejected for non-device-shaped
usernames and for app_ users, HMAC rejected for app_ users, legacy-login
log rate limiting.
- /user app users: valid token (asserts check_revoked=True), token for a
different uid, revoked, expired, blocked user, unknown uid, empty uid,
and that a denied token never appears in logs.
- /acl app users: acc 1/2/4 allow/deny per topic, unsupported acc values,
wildcards, foreign serial, malformed topics, wrong clientid prefixes
(incl. uid-prefix collision), blocked/unknown users, cache hit +
invalidate, cache expiry.
- /acl devices/kiosk/superuser: unchanged behaviour.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The shared legacy password is still needed for boards on pre-HMAC
firmware, but it was accepted for any username. Now:
- controlled by MQTT_ALLOW_LEGACY_PASSWORD (config.py, default true;
documented in .env.example) so it can be switched off without a deploy,
- only accepted for device-shaped usernames (uppercase alphanumeric
segments joined by "-", optional "-kiosk"), never for app_ users or
any other shape,
- every successful legacy login is logged at WARNING with the username,
rate-limited to once per username per hour, so the boards still
depending on it are visible before the flag is turned off.
HMAC auth is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
POST /mqtt/auth/acl now handles "app_<uid>" users:
- topic must be exactly vesper/{serial}/<a>/<b> with serial in the user's
device_serials (resolved by the users doc `uid` field),
- publish (acc 2): only control/command,
- subscribe (acc 4) and read/delivery (acc 1): only control/ack,
status/heartbeat, status/playback,
- wildcard topics (+ / #) are denied,
- clientid must start with "app_<uid>_" so one user cannot reuse another
user's client id to kick them off,
- blocked users are denied; anything else (incl. other acc values) is 403.
Lookups go through mqtt/app_users.py's 60s TTL cache so per-message
checks don't hit Firestore every time; assign/unassign/block invalidate it.
Also fixes the acc comment: mosquitto passes 1 = read (delivery),
2 = write (publish), 4 = subscribe - not "1 = subscribe, 3 = both".
Device/kiosk ACL is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The remote FlutterFlow app connects to Mosquitto as "app_<firebase_uid>"
with a Firebase ID token as the password, so no per-user MQTT accounts
need to exist anywhere.
For app_ usernames, POST /mqtt/auth/user now:
- verifies the token with firebase_admin.auth.verify_id_token
(check_revoked=True),
- requires the decoded uid to equal the uid in the username,
- requires a users doc with that `uid` field (queried, not by doc id)
whose status is not "blocked" (same meaning as users.service.block_user).
It returns 200/403 and logs the deny reason - never the token.
app_ usernames never fall through to the HMAC / legacy "vesper" check.
Device and kiosk auth are unchanged. App users are still denied every
topic by the existing ACL until the app ACL lands in the next commit.
Both handlers are now plain `def` so the blocking Firestore / Firebase
calls run in FastAPI's threadpool instead of stalling the event loop.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One-off script to populate the new device_serials array for assignments
made before the assign/unassign sync existed. Treats each device's
user_list as the source of truth and sets every user's device_serials to
exactly the matching serials, so re-running it is a no-op.
Dry run by default; --apply writes (batched, <=400 per commit).
It also reports users whose doc ID != uid field (MQTT resolves users by the
uid field), users with no uid, devices with users but no serial, and
user_list entries pointing at non-existent users. user_list entries are
accepted as DocumentReferences, "users/{id}" paths or raw doc IDs, and an
entry that matches a uid field rather than a doc ID is mapped to its doc.
Dry run against current data: 13 devices, 13 users, 11 users to update,
0 doc-ID/uid mismatches, 1 dangling user_list entry
(Cx2Va72sUzDbr1T8Ebbh on BSVSPR-26I047-STD10R-88YFJP).
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>
Replaces the generic "Playback command failed" with the firmware's specific
messages, documents "Already stopped" as SUCCESS, url no longer sticky,
and the stricter field validation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pid, speed, duration, started_at, source, ts on status/playback (and the
same fields on the WebSocket playback INFO event), plus how to handle a
stale retained message and when the epoch fields are 0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Follow-up on 529e866 after review:
- SignalIndicator: offline now renders a diagonal slash (standard
"no signal" convention) instead of an X. Added a distinct amber "?"
state for devices that are online but whose firmware never reports rssi
at all (legacy v1 heartbeats predate the rssi/state/ok fields — see API
Reference's v2 migration notes) — previously this looked identical to
"not loaded yet". DeviceListCardView's online block now opts into this
by passing isOnline explicitly.
- Copy-to-clipboard for the serial number was invisible: the icon button
had opacity:0 as an inline style, which beats a CSS hover rule at equal
specificity, so the reveal-on-hover code paths never fired. Replaced
with a shared CopyableSerial component (components/shared/) where the
whole serial text is clickable, not just a trailing icon, and the icon
sits at partial opacity at rest instead of fully hidden. Wired into both
DeviceDetail's header and OverviewTab's hero Serial Number field.
- GeneralTab firmware hero: all stat columns are now equal-width via a
grid instead of ad-hoc flex gaps, and backup_version's "Unknown" sentinel
(the device's own placeholder when no second OTA slot has ever been
flashed) is no longer rendered as the literal string "vUnknown".
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
SignalIndicator now takes an isOnline prop — when a device is offline it
renders a dimmed amber glyph with an X instead of showing the last-known
(possibly full-bars) RSSI reading, which was misleading on the Device List
table view. Card view already special-cased offline devices and is
unaffected.
Also, while working the device details surface:
- DeviceDetail: hover-to-reveal copy button next to the serial number
subtitle in the page header.
- OverviewTab hero: swapped the redundant "Location" field (already shown
in detail on the General tab's map) for live Firmware Version.
- GeneralTab: new full-width, compact Firmware hero row (version, channel,
validation state, boot count, backup slot) sourced from firmware.status.
- ControlTab: max width brought in line with every other tab (2000, was
1400), and added a 4th "Firmware" section with channel selection,
Update Now, custom-URL flash, and commit/rollback controls, wired to the
firmware.status / ota.* / firmware.commit / firmware.rollback commands
documented in the API Reference.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
req_id (added 2026-09-21 in the v2 topic rebuild, F-062):
- New Extras tab documents it fully: envelope-level (sibling of cmd,
not inside contents), always optional, exact echo/reply behavior,
parse-failure edge case, and an MQTT-only gap — WebSocket and HTTP
transports don't actually read or echo it despite CommandBus
supporting it generically at the bus level.
- Every command's Contents section now carries a persistent note
pointing to Extras, instead of duplicating the explanation 40+ times
or only mentioning it in one Transports card.
- Removed the old "req_id Correlation" card from the Transports tab —
superseded by the Extras tab.
Transports tab: dropped the V2/Legacy sub-tab switcher. It only ever
showed a "not documented yet" placeholder for Legacy, and the legacy
topic set belongs with the rest of the migration reference, not
alongside the current transport list.
Legacy Migration tab (renamed from "v1 → v2 Migration"): added a
"Legacy Topic Migration" table ahead of the command migration table,
mapping every MQTT topic from the old pre-rewrite firmware
("Controller - Production FW") to its v2 equivalent — including three
v2 topics (system/alerts, system/info, system/metrics) that have no
legacy predecessor at all. Reconstructed from that firmware's source;
it has been fully replaced, so this is historical reference only.
playback.play: filled in the full contents field set per the current
Player.cpp implementation — segment_duration, pause_duration,
total_duration, and continuous_loop are the legacy (no "mode") path,
while duration is the v2 path read only when mode is present. Added a
warning callout since sending mode alongside the legacy duration
fields doesn't merge behavior — only one path is read, based solely on
whether mode is present. This is intentional: mode is how a v2 caller
opts in, and its absence is how a v1 caller's request still works.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>