fix(devices): read device users from user_list, mirror writes to device_users

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>
This commit is contained in:
2026-11-07 10:37:21 +02:00
co-authored by Claude Opus 5.5
parent fba5110cc0
commit 2a6f9697b8
7 changed files with 330 additions and 142 deletions
+4 -1
View File
@@ -462,13 +462,15 @@ async def add_user_to_device(
elif isinstance(entry, str):
existing_ids.add(entry.split("/")[-1])
# user_list and the user's device_serials (MQTT ACL lookup) commit together.
# user_list, the user's device_serials (MQTT ACL lookup) and the
# device_users mirror commit together.
user_ref = fs.collection("users").document(body.user_id)
batch = fs.batch()
if body.user_id not in existing_ids:
user_list.append(user_ref)
batch.update(device_ref, {"user_list": user_list})
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=True)
service.stage_device_users_mirror(batch, device_ref, user_ref, linked=True)
batch.commit()
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
@@ -512,6 +514,7 @@ async def remove_user_from_device(
user_doc = user_ref.get()
if user_doc.exists:
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=False)
service.stage_device_users_mirror(batch, device_ref, user_ref, linked=False)
batch.commit()
if user_doc.exists:
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())