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)