fix(devices): stop tabs writing to Firestore on their own

Bells, Clock and General tabs ran a silent "reconcile" on mount that read
the device config and wrote any drift straight to Firestore, with no user
action. Combined with oldest-first ack matching (backend health-check pongs
and other tabs' replies resolved bells.get_config), this wrote 16-item
bellOutputs on load and emptied them on tab switch.

- Remove the auto-write reconciles from Bells/Clock/General tabs
- useDeviceCommand: match acks to commands by payload.type (ping->pong,
  playback.* -> playback), ignore health-check pongs, drop late replies,
  register pending entries before the POST
- update_device: write nested maps as dotted field paths so only the sent
  leaves are touched, never the whole parent map
- Clock modals: stop re-sending the whole clockSettings copy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 13:15:05 +02:00
co-authored by Claude Opus 5.5
parent 565aca4d56
commit eff9e72681
9 changed files with 100 additions and 237 deletions
+2 -2
View File
@@ -553,8 +553,8 @@ async def reset_device_stats(
# Firestore device_stats — field-level only. DeviceStatistics mixes true
# counters with warranty/maintenance fields in one object; a blanket
# clear would destroy warranty data, so only the 4 named counter fields
# are ever sent here (deep-merge in service.update_device preserves
# every other key, including warrantyActive/warrantyStart/etc.).
# are ever sent here (service.update_device writes field paths only, so
# every other key is untouched, including warrantyActive/warrantyStart/etc.).
stats_update = {}
if body.bell_stats:
stats_update["totalHammerStrikes"] = 0
+22 -14
View File
@@ -2,6 +2,7 @@ import secrets
import string
from google.cloud.firestore_v1 import DocumentReference
from google.cloud.firestore_v1.field_path import FieldPath
from shared.firebase import get_db
from shared.exceptions import NotFoundError
@@ -137,15 +138,22 @@ def create_device(data: DeviceCreate) -> DeviceInDB:
return _doc_to_device(doc_ref.get())
def _deep_merge(base: dict, overrides: dict) -> dict:
"""Recursively merge overrides into base, preserving unmentioned nested keys."""
result = dict(base)
for k, v in overrides.items():
if isinstance(v, dict) and isinstance(result.get(k), dict):
result[k] = _deep_merge(result[k], v)
def _leaf_field_paths(value: dict, prefix: tuple = ()) -> dict:
"""Flatten a nested map into {firestore field path: leaf value}.
Lists and scalars are leaves; a non-empty map is descended into, so writing
{"device_attributes": {"hasBells": True}} touches ONLY
device_attributes.hasBells — never the sibling fields of the parent map.
An empty map is kept as a leaf (it explicitly sets that map to {}).
"""
out: dict = {}
for k, v in value.items():
path = prefix + (k,)
if isinstance(v, dict) and v:
out.update(_leaf_field_paths(v, path))
else:
result[k] = v
return result
out[FieldPath(*path).to_api_repr()] = v
return out
def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
@@ -162,17 +170,17 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
sent = data.model_dump(exclude_unset=True)
update_data = firestore_v1.to_firestore({k: v for k, v in sent.items() if v is not None}, db)
# Deep-merge nested structs so unmentioned sub-fields are preserved, then
# normalize the merged map again: that also repairs pre-v1 junk already
# stored in the device (""-timestamps, octet-array IPs, misspelled keys).
# Nested structs are written field-by-field (dotted paths), so only the
# exact leaves the caller sent are touched. Rewriting the whole parent map
# (the old read-merge-write) clobbered sibling fields whenever two writes
# raced, or the FlutterFlow apps wrote in between our read and our write.
existing = doc.to_dict()
nested_keys = (
"device_attributes", "device_subscription", "device_stats", "device_health_settings",
)
for key in nested_keys:
if key in update_data and isinstance(existing.get(key), dict):
merged = _deep_merge(existing[key], update_data[key])
update_data[key] = firestore_v1.to_firestore({key: merged}, db)[key]
if isinstance(update_data.get(key), dict) and update_data[key]:
update_data.update(_leaf_field_paths(update_data.pop(key), (key,)))
if "user_list" not in update_data:
doc_ref.update(update_data)
+46 -14
View File
@@ -5,8 +5,8 @@
//
// Device replies arrive on control/ack. They can optionally echo a req_id
// (see CommandEnvelope.hpp / vesper_mqtt_topic_spec_v2.md), but this hook
// doesn't send one yet, so in-flight commands are matched FIFO against
// whichever command is oldest for this device — see the API Reference's wire
// doesn't send one yet, so replies are matched to in-flight commands by the
// command name the device echoes in payload.type (see findPendingFor) — see the API Reference's wire
// envelope: { type: 'control/ack', device_serial, payload: { status, type, message, data } }.
//
// Usage:
@@ -27,6 +27,28 @@ import api from '@/lib/api'
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
import { useToast } from '@/components/ui/Toast'
// Which in-flight command does a control/ack reply belong to? The device echoes
// the command name in payload.type, with two exceptions: ping → "pong", and
// playback.play / playback.stop → "playback". Handing a reply to the wrong
// command (plain oldest-first) made tabs act on another command's data — e.g.
// a backend health-check pong resolving bells.get_config with no bells.
function findPendingFor(pending, type) {
if (!pending.length) return -1
if (!type) return 0
const exact = pending.findIndex((a) => a.cmd === type)
if (exact !== -1) return exact
// The backend's own health-check pings also reply here — only a console
// ping may take a pong, never any other command.
if (type === 'pong') return pending.findIndex((a) => a.cmd === 'ping')
const family = pending.findIndex((a) => a.cmd.startsWith(`${type}.`))
if (family !== -1) return family
// A dotted type is a v2 command name — if none is pending, it's a late reply
// to one that already timed out. Drop it rather than hand it to another command.
if (type.includes('.')) return -1
// Unrecognized legacy type — fall back to the oldest in-flight command.
return 0
}
export function useDeviceCommand({ deviceSerial, onNonAckMessage, onCommandSent } = {}) {
const { toast } = useToast()
const [sendingCmd, setSendingCmd] = useState('')
@@ -43,8 +65,9 @@ export function useDeviceCommand({ deviceSerial, onNonAckMessage, onCommandSent
return
}
const ack = pendingAcksRef.current.shift() // oldest in-flight command
if (!ack) return
const idx = findPendingFor(pendingAcksRef.current, msg.payload?.type)
if (idx === -1) return
const [ack] = pendingAcksRef.current.splice(idx, 1)
const payload = msg.payload || {}
clearTimeout(ack.timeoutId)
@@ -73,12 +96,15 @@ export function useDeviceCommand({ deviceSerial, onNonAckMessage, onCommandSent
const toastId = toast.pending(cmd, 'Sent — waiting for reply…')
return new Promise((resolve, reject) => {
api.post(`/mqtt/command/${deviceSerial}`, { cmd, contents })
.then(() => {
onCommandSent?.(cmd)
// Registered before the POST so a reply that beats the HTTP response
// still finds its command.
const ackEntry = { cmd, toastId, resolve, reject, timeoutId: null }
ackEntry.timeoutId = setTimeout(() => {
const forget = () => {
clearTimeout(ackEntry.timeoutId)
pendingAcksRef.current = pendingAcksRef.current.filter((a) => a !== ackEntry)
}
ackEntry.timeoutId = setTimeout(() => {
forget()
toast.update(toastId, {
variant: 'warning',
title: 'No reply received',
@@ -89,8 +115,11 @@ export function useDeviceCommand({ deviceSerial, onNonAckMessage, onCommandSent
reject(new Error(`"${cmd}" timed out waiting for a reply.`))
}, 5000)
pendingAcksRef.current.push(ackEntry)
})
api.post(`/mqtt/command/${deviceSerial}`, { cmd, contents })
.then(() => onCommandSent?.(cmd))
.catch((err) => {
forget()
toast.update(toastId, {
variant: 'danger',
title: 'Failed to send',
@@ -110,16 +139,19 @@ export function useDeviceCommand({ deviceSerial, onNonAckMessage, onCommandSent
return new Promise((resolve, reject) => {
if (!deviceSerial) { reject(new Error('No device id.')); return }
api.post(`/mqtt/command/${deviceSerial}`, { cmd, contents })
.then(() => {
const ackEntry = { cmd, resolve, reject, timeoutId: null }
ackEntry.timeoutId = setTimeout(() => {
const forget = () => {
clearTimeout(ackEntry.timeoutId)
pendingAcksRef.current = pendingAcksRef.current.filter((a) => a !== ackEntry)
}
ackEntry.timeoutId = setTimeout(() => {
forget()
reject(new Error(`"${cmd}" timed out waiting for a reply.`))
}, timeoutMs)
pendingAcksRef.current.push(ackEntry)
})
.catch(reject)
api.post(`/mqtt/command/${deviceSerial}`, { cmd, contents })
.catch((err) => { forget(); reject(err) })
})
}, [deviceSerial])
@@ -176,7 +176,6 @@ export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, i
await api.put(`/devices/${id}`, {
device_attributes: {
clockSettings: {
...clock,
ringAlerts: alertType,
ringIntervals: alertType === 'multi' ? ringIntervals : clock?.ringIntervals,
hourAlertsBell: Number(hourBell),
@@ -59,7 +59,6 @@ export default function EditBacklightModal({ open, onClose, onSaved, attr, clock
await api.put(`/devices/${id}`, {
device_attributes: {
clockSettings: {
...clock,
isBacklightAutomationOn: enabled,
backlightOutput: Number(output),
backlightTurnOnTime: enabled && onTime ? timeToIso(onTime) : null,
@@ -110,7 +110,6 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
device_attributes: {
hasClock,
clockSettings: {
...clock,
clockOutputs: [out1, out2].filter(o => o > 0),
clockTimings: [runPulse, pauseMs],
faceSyncMode: faceSync,
@@ -2,7 +2,7 @@
// Bell Mechanisms tab — displays Bell Commander/Guard status, connected bell count,
// master switch, and per-bell glass cards with output, timing, size, and strike stats.
import { useState, useCallback, useEffect, useRef } from 'react'
import { useState, useCallback } from 'react'
import api from '@/lib/api'
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
@@ -271,9 +271,7 @@ export default function BellsTab({
attr,
canEdit,
loadDevice,
reloadDeviceSilent,
sendMqttCommand,
sendMqttCommandSilent,
onEditBellOutputs,
}) {
const [togglingCommander, setTogglingCommander] = useState(false)
@@ -281,75 +279,15 @@ export default function BellsTab({
const [liveCounters] = useState(null)
const [confirmDisable, setConfirmDisable] = useState(false)
// Derived data — shown instantly from Firestore on load, then silently
// reconciled against the device's true on-device config (see effect below).
// Shown exactly as saved. This tab never writes on its own — bell settings
// are only written by Edit Outputs / the Commander toggle, after the device
// confirms the change.
const bellOutputs = attr?.bellOutputs || []
const hammerTimings = attr?.hammerTimings || []
const totalBells = attr?.totalBells || 0
const hasBells = attr?.hasBells ?? false
const bellGuardOn = attr?.bellGuardOn ?? false
// ── Background refresh: pull true state from the device right after load ──
// Fires at most once per mount (hasSyncedRef guard — belt-and-suspenders
// against StrictMode's double-invoke or any parent re-render retriggering
// this effect). Reconciles bells_enabled/durations/outputs against Firestore
// and silently corrects any drift — no toast, this is a quiet sync.
const hasSyncedRef = useRef(false)
useEffect(() => {
if (!sendMqttCommandSilent || !device) return
if (hasSyncedRef.current) return
hasSyncedRef.current = true
const deviceId = device.id || device.device_id
sendMqttCommandSilent('bells.get_config').then((reply) => {
const data = reply?.data || {}
const durations = data.durations || {}
const outputs = data.outputs || {}
const channelCount = Math.max(
Object.keys(durations).length,
Object.keys(outputs).length,
totalBells,
)
if (channelCount === 0) return
// Firmware uses both 0 and 65535 (uint16 "unset") as "no output assigned" —
// treat both as disabled so unconfigured channels are never mistaken for
// connected bells.
const isDisabledOutput = (o) => !o || o === 65535
// The console's data model assumes bells are a contiguous block starting at
// index 0 (see EditBellOutputsModal / totalBells). The device, however, can
// report enabled channels at any index with gaps in between — so compact
// only the genuinely-connected channels down to a contiguous list, in
// channel order, rather than naively slicing the raw 16-slot arrays.
const connectedIndexes = Array.from({ length: channelCount }, (_, i) => i)
.filter((i) => !isDisabledOutput(Number(outputs[i] ?? 0)))
const trueOutputs = connectedIndexes.map((i) => Number(outputs[i]))
const trueTimings = connectedIndexes.map((i) => Number(durations[i] ?? 0))
const trueEnabled = !!data.bells_enabled
const trueActiveCount = trueOutputs.length
const outputsDiffer = JSON.stringify(trueOutputs) !== JSON.stringify(bellOutputs)
const timingsDiffer = JSON.stringify(trueTimings) !== JSON.stringify(hammerTimings)
const enabledDiffers = trueEnabled !== hasBells
if (!outputsDiffer && !timingsDiffer && !enabledDiffers) return
api.put(`/devices/${deviceId}`, {
device_attributes: {
hasBells: trueEnabled,
totalBells: trueActiveCount,
bellOutputs: trueOutputs,
hammerTimings: trueTimings,
},
}).then(() => reloadDeviceSilent?.())
}).catch(() => {
// Device offline or didn't reply — keep showing the last-known Firestore values.
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [device?.id, device?.device_id])
// Request strike counters via MQTT
const requestStrikeCounters = useCallback(async () => {
if (!sendMqttCommand) return
@@ -300,7 +300,6 @@ export default function ClockTab({
sendMqttCommand,
sendMqttCommandSilent,
loadDevice,
reloadDeviceSilent,
}) {
const { toast } = useToast()
const [now, setNow] = useState(new Date())
@@ -320,94 +319,15 @@ export default function ClockTab({
return () => clearInterval(id)
}, [])
// ── Background refresh: pull true state from the device right after load ──
// Fires at most once per mount (hasSyncedRef guard — belt-and-suspenders
// against StrictMode's double-invoke or any parent re-render retriggering
// this effect). Reconciles enabled/outputs/timings/alerts/backlight/silence
// against Firestore using semantic (not raw-string) comparison, and silently
// corrects any real drift — no toast.
const hasSyncedRef = useRef(false)
// ── Live read of time / timezone / NTP / face, once per mount ─────────────
// Read-only: this tab never writes the device record on its own. Clock
// settings are only written by the Edit modals, after the device confirms.
const hasLoadedLiveRef = useRef(false)
useEffect(() => {
if (!sendMqttCommandSilent || !device) return
if (hasSyncedRef.current) return
hasSyncedRef.current = true
const deviceId = device.id || device.device_id
sendMqttCommandSilent('clock.get_config').then((reply) => {
const data = reply?.data || {}
if (!data || Object.keys(data).length === 0) return
const trueAlertType = { OFF: 'disabled', SINGLE: 'single', HOURS: 'multi' }[data.alert_type] ?? 'disabled'
const trueHourBell = data.hour_bell === 255 ? 0 : (data.hour_bell || 0)
const trueHalfBell = data.half_bell === 255 ? 0 : (data.half_bell || 0)
const trueQuarterBell = data.quarter_bell === 255 ? 0 : (data.quarter_bell || 0)
const trueC1 = data.c1output || 0
const trueC2 = data.c2output || 0
const truePulse = data.pulse_duration || 0
const truePause = data.pause_duration || 0
const trueBacklightOutput = data.backlight_output === 255 ? 0 : (data.backlight_output || 0)
// Semantic comparison — normalize times to HH:MM via extractTime so format
// differences (timezone suffix, seconds, etc.) never register as false drift.
const hasDrift =
!!data.enabled !== (attr?.hasClock ?? false) ||
trueC1 !== (clock?.clockOutputs?.[0] || 0) ||
trueC2 !== (clock?.clockOutputs?.[1] || 0) ||
truePulse !== (clock?.clockTimings?.[0] || 0) ||
truePause !== (clock?.clockTimings?.[1] || 0) ||
trueAlertType !== (clock?.ringAlerts || 'disabled') ||
(trueAlertType === 'multi' && data.alert_interval !== clock?.ringIntervals) ||
trueHourBell !== (clock?.hourAlertsBell || 0) ||
trueHalfBell !== (clock?.halfhourAlertsBell || 0) ||
trueQuarterBell !== (clock?.quarterAlertsBell || 0) ||
!!data.daytime_silence !== (clock?.isDaySilenceOn ?? false) ||
data.daytime_on !== extractTime(clock?.daySilenceFrom) ||
data.daytime_off !== extractTime(clock?.daySilenceTo) ||
!!data.night_silence !== (clock?.isNightSilenceOn ?? false) ||
data.night_on !== extractTime(clock?.nightSilenceFrom) ||
data.night_off !== extractTime(clock?.nightSilenceTo) ||
!!data.backlight !== (clock?.isBacklightAutomationOn ?? false) ||
trueBacklightOutput !== (clock?.backlightOutput || 0) ||
(!!data.backlight && data.backlight_on !== extractTime(clock?.backlightTurnOnTime)) ||
(!!data.backlight && data.backlight_off !== extractTime(clock?.backlightTurnOffTime)) ||
(data.face_sync_mode != null && data.face_sync_mode !== (clock?.faceSyncMode || 'force')) ||
(data.smart_max_wait_min != null && data.smart_max_wait_min !== (clock?.smartMaxWaitMin ?? 61))
if (!hasDrift) return
api.put(`/devices/${deviceId}`, {
device_attributes: {
hasClock: !!data.enabled,
clockSettings: {
...clock,
clockOutputs: [trueC1, trueC2],
clockTimings: [truePulse, truePause],
ringAlerts: trueAlertType,
ringIntervals: data.alert_interval,
hourAlertsBell: trueHourBell,
halfhourAlertsBell: trueHalfBell,
quarterAlertsBell: trueQuarterBell,
isDaySilenceOn: !!data.daytime_silence,
daySilenceFrom: data.daytime_on ? `2000-01-01T${data.daytime_on}:00Z` : (clock?.daySilenceFrom ?? null),
daySilenceTo: data.daytime_off ? `2000-01-01T${data.daytime_off}:00Z` : (clock?.daySilenceTo ?? null),
isNightSilenceOn: !!data.night_silence,
nightSilenceFrom: data.night_on ? `2000-01-01T${data.night_on}:00Z` : (clock?.nightSilenceFrom ?? null),
nightSilenceTo: data.night_off ? `2000-01-01T${data.night_off}:00Z` : (clock?.nightSilenceTo ?? null),
isBacklightAutomationOn: !!data.backlight,
backlightOutput: trueBacklightOutput,
backlightTurnOnTime: data.backlight_on ? `2000-01-01T${data.backlight_on}:00Z` : null,
backlightTurnOffTime: data.backlight_off ? `2000-01-01T${data.backlight_off}:00Z` : null,
faceSyncMode: data.face_sync_mode ?? clock?.faceSyncMode ?? 'force',
smartMaxWaitMin: data.smart_max_wait_min ?? clock?.smartMaxWaitMin ?? 61,
},
},
}).then(() => reloadDeviceSilent?.())
}).catch(() => {
// Device offline or didn't reply — keep showing the last-known Firestore values.
}).finally(() => {
// Replies are matched FIFO (no req_id), so the live reads start only after this one
if (hasLoadedLiveRef.current) return
hasLoadedLiveRef.current = true
loadLive()
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [device?.id, device?.device_id])
@@ -856,7 +856,6 @@ export default function GeneralTab({
onEditAttributes,
sendMqttCommand,
sendMqttCommandSilent,
reloadDeviceSilent,
}) {
const { toast } = useToast()
const [locationName, setLocationName] = useState(null)
@@ -879,11 +878,10 @@ export default function GeneralTab({
if (Number.isFinite(attr?.mqttLogLevel)) setMqttLevel(attr.mqttLogLevel)
}, [attr?.serialLogLevel, attr?.sdLogLevel, attr?.mqttLogLevel])
// ── Background refresh: pull true log levels + network info from the device ──
// Fires at most once per mount (hasSyncedRef guard). Log levels are reconciled
// against Firestore and silently corrected on drift. Network info is read-only
// and always reflects whatever the device just reported — no drift comparison
// needed since nothing else in the console ever writes it.
// ── Live read of network info + firmware status, once per mount ──────────
// Read-only display data. This tab never writes the device record on its
// own — log levels are only written when the user moves a slider and the
// device confirms (handleSaveLogging).
const hasSyncedRef = useRef(false)
const [networkInfo, setNetworkInfo] = useState(null)
const [firmwareStatus, setFirmwareStatus] = useState(null)
@@ -891,36 +889,6 @@ export default function GeneralTab({
if (!sendMqttCommandSilent || !device) return
if (hasSyncedRef.current) return
hasSyncedRef.current = true
const deviceId = device.id || device.device_id
sendMqttCommandSilent('log.get_config').then((reply) => {
const data = reply?.data || {}
const trueSerial = data.serial_level
const trueSd = data.sd_level
const trueMqtt = data.mqtt_level
if (trueSerial == null && trueSd == null && trueMqtt == null) return
const hasDrift =
(trueSerial != null && trueSerial !== (attr?.serialLogLevel ?? 0)) ||
(trueSd != null && trueSd !== (attr?.sdLogLevel ?? 0)) ||
(trueMqtt != null && trueMqtt !== (attr?.mqttLogLevel ?? 0))
if (!hasDrift) return
if (trueSerial != null) setSerialLevel(trueSerial)
if (trueSd != null) setSdLevel(trueSd)
if (trueMqtt != null) setMqttLevel(trueMqtt)
api.put(`/devices/${deviceId}`, {
device_attributes: {
serialLogLevel: trueSerial ?? attr?.serialLogLevel ?? 0,
sdLogLevel: trueSd ?? attr?.sdLogLevel ?? 0,
mqttLogLevel: trueMqtt ?? attr?.mqttLogLevel ?? 0,
},
}).then(() => reloadDeviceSilent?.())
}).catch(() => {
// Device offline or didn't reply — keep showing the last-known Firestore values.
})
sendMqttCommandSilent('network.info').then((reply) => {
setNetworkInfo(reply?.data || null)