From ceca99227866243dc69dfd58f9def2df68090943 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:00:55 -0500 Subject: [PATCH 1/6] Refresh the plugin catalogs from the cloud with the stored login The snapshot keeps the cloud login and the plugin catalogs fetched at sign-in, and the plugin routes serve those. Newer robots can need newer plugins than the snapshot holds, so CloudImportManager.refresh_plugin_catalogs asks the cloud again with the stored login and replaces only the catalogs. The sign-in now also stores the device identifier the cloud ties the login to. A rejected login or an empty answer leaves the snapshot as it was. Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Opus 5.5 --- src/roborock_local_server/backend.py | 2 + src/roborock_local_server/cloud.py | 79 +++++++++++++++++++ tests/test_cloud.py | 109 +++++++++++++++++++++++++++ 3 files changed, 190 insertions(+) diff --git a/src/roborock_local_server/backend.py b/src/roborock_local_server/backend.py index 526d7a93..008e04f1 100644 --- a/src/roborock_local_server/backend.py +++ b/src/roborock_local_server/backend.py @@ -24,6 +24,7 @@ def _resolve_backend_path() -> Path: _build_inventory, _fetch_additional_web_cache, _fetch_cloud_home_data_with_api, + _fetch_plugin_catalogs, _flatten_device_scenes, _load_existing_inventory_for_merge, _merge_existing_inventory_mutations, @@ -52,6 +53,7 @@ def _resolve_backend_path() -> Path: "_extract_inventory_vacuums", "_fetch_additional_web_cache", "_fetch_cloud_home_data_with_api", + "_fetch_plugin_catalogs", "_flatten_device_scenes", "_load_existing_inventory_for_merge", "_load_inventory", diff --git a/src/roborock_local_server/cloud.py b/src/roborock_local_server/cloud.py index b0c96c93..ac7bcaf9 100644 --- a/src/roborock_local_server/cloud.py +++ b/src/roborock_local_server/cloud.py @@ -12,12 +12,14 @@ from typing import Any, Literal import aiohttp +from roborock.data import UserData from roborock.web_api import RoborockApiClient from .backend import ( _build_inventory, _fetch_additional_web_cache, _fetch_cloud_home_data_with_api, + _fetch_plugin_catalogs, _flatten_device_scenes, _load_existing_inventory_for_merge, _merge_existing_inventory_mutations, @@ -30,6 +32,27 @@ from shared.inventory_io import atomic_write_inventory, inventory_transaction +def summarize_plugin_catalogs(catalogs: dict[str, Any]) -> dict[str, Any]: + """The plugin catalogs reduced to what picks a plugin: versions, levels and download URLs.""" + keep = ("version", "apiLevel", "apilevel", "pluginLevel", "productid", "categoryId", "category", "moduleType", "url", "id", "model") + summary: dict[str, Any] = {"fetched_at_utc": catalogs.get("fetched_at_utc")} + for name, catalog in catalogs.items(): + if not isinstance(catalog, dict): + continue + entry: dict[str, Any] = {"params": catalog.get("params") or catalog.get("json") or {}} + if "error" in catalog: + entry["error"] = catalog["error"] + data = catalog.get("data") + if isinstance(data, dict): + data = data.get("categoryPluginList") + records = data if isinstance(data, list) else [] + entry["plugins"] = [ + {key: record[key] for key in keep if key in record} for record in records if isinstance(record, dict) + ] + summary[name] = entry + return summary + + def _to_jsonable(value: Any) -> Any: if value is None or isinstance(value, (str, int, float, bool)): return value @@ -127,6 +150,61 @@ async def request_code(self, *, email: str, base_url: str = "") -> dict[str, Any "expires_at": datetime.fromtimestamp(expires_at_ts, tz=timezone.utc).isoformat(), } + def _read_snapshot(self) -> dict[str, Any]: + try: + parsed = json.loads(self.snapshot_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + return parsed if isinstance(parsed, dict) else {} + + def plugin_catalogs(self) -> dict[str, Any]: + """The stored plugin catalogs, summarized, without any cloud request.""" + web_cache = self._read_snapshot().get("web_api_cache") + catalogs = web_cache.get("plugin_catalogs") if isinstance(web_cache, dict) else None + return summarize_plugin_catalogs(catalogs) if isinstance(catalogs, dict) else {} + + async def refresh_plugin_catalogs(self) -> dict[str, Any]: + """Re-reads the plugin catalogs from the cloud with the login the snapshot already holds. + + Only the plugin catalogs in the snapshot change; the inventory is left alone. A rejected + login needs the email-code sign-in again, which stores a fresh one. + """ + snapshot = self._read_snapshot() + meta = snapshot.get("meta") if isinstance(snapshot.get("meta"), dict) else {} + try: + user_data = UserData.from_dict(snapshot.get("user_data")) + except (TypeError, ValueError, KeyError): + user_data = None + email = str(meta.get("username") or "") + if user_data is None or not user_data.token or not email: + raise ValueError("No cloud login is stored. Request a code and sign in first.") + + timeout = aiohttp.ClientTimeout(total=120) + async with aiohttp.ClientSession(timeout=timeout) as session: + api = RoborockApiClient(username=email, base_url=str(meta.get("base_url") or "") or None, session=session) + if meta.get("device_identifier"): + setattr(api, "_device_identifier", str(meta["device_identifier"])) + try: + home_data = await _fetch_cloud_home_data_with_api(api, user_data) + catalogs = await _fetch_plugin_catalogs(api, user_data, home_data) + except Exception as exc: # noqa: BLE001 + raise ValueError( + f"The cloud rejected the stored login ({exc}). Request a code and sign in again." + ) from exc + + failed = [name for name, item in catalogs.items() if isinstance(item, dict) and "error" in item] + if failed and len(failed) == sum(1 for item in catalogs.values() if isinstance(item, dict)): + errors = "; ".join(str(catalogs[name]["error"]) for name in failed) + raise ValueError(f"The cloud returned no plugin catalogs ({errors}). Request a code and sign in again.") + + web_cache = snapshot.get("web_api_cache") + if not isinstance(web_cache, dict): + web_cache = {} + snapshot["web_api_cache"] = web_cache + web_cache["plugin_catalogs"] = _to_jsonable(catalogs) + self.snapshot_path.write_text(json.dumps(snapshot, indent=2) + "\n", encoding="utf-8") + return {"success": True, "step": "plugins_refreshed", **summarize_plugin_catalogs(catalogs)} + async def submit_code(self, *, session_id: str, code: str) -> dict[str, Any]: normalized_session_id = session_id.strip() normalized_code = code.strip() @@ -180,6 +258,7 @@ async def submit_code(self, *, session_id: str, code: str) -> dict[str, Any]: "generated_at_utc": datetime.now(timezone.utc).isoformat(), "username": session_data.email, "base_url": session_data.base_url, + "device_identifier": session_data.device_identifier, "source": "admin_email_code_login", }, "user_data": _to_jsonable(user_data), diff --git a/tests/test_cloud.py b/tests/test_cloud.py index 98be0b26..9944e745 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -265,3 +265,112 @@ def test_submit_code_expired_session_raises_value_error(tmp_path, monkeypatch) - with pytest.raises(ValueError): asyncio.run(manager.submit_code(session_id=request_result["session_id"], code="123456")) + + +_STORED_USER_DATA = { + "rriot": {"u": "u", "s": "s", "h": "h", "k": "k", "r": {"r": "EU", "a": "https://api", "m": "ssl://mqtt", "l": "https://l"}}, + "uid": 1, + "token": "stored-token", +} +_NEW_CATALOGS = { + "fetched_at_utc": "2026-11-11T00:00:00+00:00", + "plugins": { + "path": "/api/v1/plugins", + "params": {"type": 2, "apiLevel": 10043}, + "data": {"categoryPluginList": [{"categoryId": 1, "category": "robot.vacuum.cleaner", "version": 7006, "url": "https://files.roborock.com/p.zip", "md5": None}]}, + }, + "appplugin": { + "path": "/api/v1/appplugin", + "json": {"type": 2, "apilevel": 10043, "productids": [110]}, + "data": [{"productid": 110, "version": 7006, "apilevel": 10043, "url": "https://files.roborock.com/a.zip"}], + }, +} + + +def _write_snapshot(manager: CloudImportManager, **overrides) -> None: + snapshot = { + "meta": {"username": "user@example.com", "base_url": "https://euiot.roborock.com", "device_identifier": "dev-9"}, + "user_data": _STORED_USER_DATA, + "web_api_cache": {"rooms": [1, 2], "plugin_catalogs": {"fetched_at_utc": "old"}}, + } + snapshot.update(overrides) + manager.snapshot_path.write_text(json.dumps(snapshot), encoding="utf-8") + + +def _patch_plugin_fetch(monkeypatch: pytest.MonkeyPatch, catalogs: dict, seen: dict | None = None) -> None: + async def fake_catalogs(api, user_data, home_data): + if seen is not None: + seen.update(token=user_data.token, device_identifier=api._device_identifier) + return catalogs + + monkeypatch.setattr(cloud_module, "RoborockApiClient", _FakeRoborockApiClientV4) + monkeypatch.setattr(cloud_module, "_fetch_cloud_home_data_with_api", _fake_fetch_cloud_home_data_with_api) + monkeypatch.setattr(cloud_module, "_fetch_plugin_catalogs", fake_catalogs) + + +def test_refresh_plugin_catalogs_replaces_only_the_catalogs(tmp_path, monkeypatch) -> None: + manager = _make_manager(tmp_path) + _write_snapshot(manager) + seen: dict = {} + _patch_plugin_fetch(monkeypatch, _NEW_CATALOGS, seen) + + result = asyncio.run(manager.refresh_plugin_catalogs()) + + assert seen == {"token": "stored-token", "device_identifier": "dev-9"} + assert result["success"] is True + assert result["plugins"]["plugins"] == [ + {"version": 7006, "url": "https://files.roborock.com/p.zip", "categoryId": 1, "category": "robot.vacuum.cleaner"} + ] + assert result["appplugin"]["plugins"][0]["url"] == "https://files.roborock.com/a.zip" + stored = json.loads(manager.snapshot_path.read_text(encoding="utf-8")) + assert stored["web_api_cache"]["rooms"] == [1, 2] + assert stored["web_api_cache"]["plugin_catalogs"]["plugins"]["data"]["categoryPluginList"][0]["version"] == 7006 + assert manager.plugin_catalogs()["appplugin"]["plugins"][0]["version"] == 7006 + + +def test_refresh_plugin_catalogs_needs_a_stored_login(tmp_path, monkeypatch) -> None: + manager = _make_manager(tmp_path) + _patch_plugin_fetch(monkeypatch, _NEW_CATALOGS) + + with pytest.raises(ValueError, match="No cloud login"): + asyncio.run(manager.refresh_plugin_catalogs()) + _write_snapshot(manager, user_data={}) + with pytest.raises(ValueError, match="No cloud login"): + asyncio.run(manager.refresh_plugin_catalogs()) + + +def test_refresh_plugin_catalogs_keeps_the_snapshot_when_the_cloud_gives_nothing(tmp_path, monkeypatch) -> None: + manager = _make_manager(tmp_path) + _write_snapshot(manager) + before = manager.snapshot_path.read_text(encoding="utf-8") + failing = {"fetched_at_utc": "now", "plugins": {"path": "/p", "error": "code 2010"}, "appplugin": {"path": "/a", "error": "code 2010"}} + _patch_plugin_fetch(monkeypatch, failing) + + with pytest.raises(ValueError, match="no plugin catalogs"): + asyncio.run(manager.refresh_plugin_catalogs()) + assert manager.snapshot_path.read_text(encoding="utf-8") == before + + +def test_refresh_plugin_catalogs_reports_a_rejected_login(tmp_path, monkeypatch) -> None: + manager = _make_manager(tmp_path) + _write_snapshot(manager) + _patch_plugin_fetch(monkeypatch, _NEW_CATALOGS) + + async def rejected(api, user_data): + raise RuntimeError("invalid token") + + monkeypatch.setattr(cloud_module, "_fetch_cloud_home_data_with_api", rejected) + with pytest.raises(ValueError, match="sign in again"): + asyncio.run(manager.refresh_plugin_catalogs()) + + +def test_submit_code_stores_the_device_identifier(tmp_path, monkeypatch) -> None: + monkeypatch.setattr(cloud_module, "RoborockApiClient", _FakeRoborockApiClientV4) + _patch_backend_calls(monkeypatch) + manager = _make_manager(tmp_path) + + request_result = asyncio.run(manager.request_code(email="user@example.com")) + asyncio.run(manager.submit_code(session_id=request_result["session_id"], code="123456")) + + stored = json.loads(manager.snapshot_path.read_text(encoding="utf-8")) + assert stored["meta"]["device_identifier"] == _fake_client_instances[0]._device_identifier From 22db56cdb59dbc9490b81725785ed96f8f8617f8 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:00:57 -0500 Subject: [PATCH 2/6] Add admin endpoints to refresh and list the plugin catalogs POST /admin/api/cloud/refresh-plugins re-reads them with the stored login, taking an optional platform type. GET /admin/api/cloud/plugins shows what is stored without a cloud request. Both return each plugin's version, API level and download URL. Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Opus 5.5 --- docs/roborock_app.md | 16 +++++++++ src/roborock_local_server/standalone_admin.py | 15 ++++++++ tests/test_admin_api.py | 34 +++++++++++++++++++ 3 files changed, 65 insertions(+) diff --git a/docs/roborock_app.md b/docs/roborock_app.md index 5775efbf..0c969a9f 100644 --- a/docs/roborock_app.md +++ b/docs/roborock_app.md @@ -170,6 +170,22 @@ During `JNI_OnLoad`, `librrcodec.so` calls a verification function that retrieve --- +## Refreshing the Plugin List + +The official app downloads each device's screens as plugins, and the server hands it the list it saved from the cloud when you signed in. Newer robots can need newer plugins than that saved list holds. Refresh it without signing in again: + +```sh +curl -c jar -X POST https://your-server/admin/api/login -H 'Content-Type: application/json' -d '{"password": "..."}' +curl -b jar -X POST https://your-server/admin/api/cloud/refresh-plugins +curl -b jar https://your-server/admin/api/cloud/plugins +``` + +The refresh reuses the login stored by the email-code sign-in and only replaces the plugin catalogs, with the product ids of every device on the account. The reply lists each plugin's version, API level and download URL. `GET /admin/api/cloud/plugins` shows what is stored now without asking the cloud. + +If the cloud rejects the stored login, or the snapshot predates this feature and has none, sign in again with the email code; that stores a login the refresh can use. + +--- + ## LocalRock (Third-Party App) [LocalRock](https://github.com/DonSidro/LocalRock) is an open-source app created by **Sidon Kodraliu** ([@DonSidro](https://github.com/DonSidro)) that connects directly to the local Roborock server. diff --git a/src/roborock_local_server/standalone_admin.py b/src/roborock_local_server/standalone_admin.py index 8dd4d8c5..946801d5 100644 --- a/src/roborock_local_server/standalone_admin.py +++ b/src/roborock_local_server/standalone_admin.py @@ -492,3 +492,18 @@ async def admin_cloud_submit_code(request: Request) -> JSONResponse: result = {"success": False, "step": "code_submit_failed", "error": str(exc)} supervisor.runtime_state.record_cloud_request(result) return JSONResponse(result, status_code=200 if result.get("success") else 400) + + @app.get("/admin/api/cloud/plugins") + async def admin_cloud_plugins(request: Request) -> JSONResponse: + supervisor._require_admin(request) + return JSONResponse({"success": True, **supervisor.cloud_manager.plugin_catalogs()}) + + @app.post("/admin/api/cloud/refresh-plugins") + async def admin_cloud_refresh_plugins(request: Request) -> JSONResponse: + supervisor._require_admin(request) + try: + result = await supervisor.cloud_manager.refresh_plugin_catalogs() + except Exception as exc: # noqa: BLE001 + result = {"success": False, "step": "plugin_refresh_failed", "error": str(exc)} + supervisor.runtime_state.record_cloud_request(result) + return JSONResponse(result, status_code=200 if result.get("success") else 400) diff --git a/tests/test_admin_api.py b/tests/test_admin_api.py index 9f0fd4c3..57b2a72c 100644 --- a/tests/test_admin_api.py +++ b/tests/test_admin_api.py @@ -1635,3 +1635,37 @@ def test_create_room_with_new_capitalization_updates_existing_room(tmp_path: Pat stored_inventory = json.loads(paths.inventory_path.read_text(encoding="utf-8")) for stored_rooms in (stored_inventory["home"]["rooms"], stored_inventory["rooms"]): assert stored_rooms == [{"id": 11100, "name": "Master Bedroom"}, {"id": 11101, "name": "Hallway"}] + + +def test_admin_plugin_catalog_endpoints_require_auth_and_report_the_snapshot(tmp_path: Path) -> None: + config_file = write_release_config(tmp_path) + config = load_config(config_file) + paths = resolve_paths(config_file, config) + supervisor = ReleaseSupervisor(config=config, paths=paths) + client = TestClient(supervisor.app) + + assert client.get("/admin/api/cloud/plugins").status_code == 401 + assert client.post("/admin/api/cloud/refresh-plugins", json={}).status_code == 401 + + assert client.post("/admin/api/login", json={"password": "correct horse battery staple"}).status_code == 200 + assert client.get("/admin/api/cloud/plugins").json() == {"success": True} + + paths.cloud_snapshot_path.write_text( + json.dumps( + { + "web_api_cache": { + "plugin_catalogs": { + "appplugin": {"json": {"type": 2}, "data": [{"productid": 110, "version": 7006, "url": "https://files.roborock.com/a.zip"}]}, + } + } + } + ), + encoding="utf-8", + ) + stored = client.get("/admin/api/cloud/plugins").json() + assert stored["appplugin"]["plugins"] == [{"productid": 110, "version": 7006, "url": "https://files.roborock.com/a.zip"}] + + refused = client.post("/admin/api/cloud/refresh-plugins", json={}) + assert refused.status_code == 400 + assert refused.json()["step"] == "plugin_refresh_failed" + assert "No cloud login" in refused.json()["error"] From 447c1068fe758d1cdf0245c20335a969db25f16d Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:17:41 -0500 Subject: [PATCH 3/6] Keep stored plugin catalogs on partial failure and write the snapshot safely A refresh where one catalog errored replaced the good stored entry with the error, and the fallback then served iOS the Android zips. Merge catalog by catalog and keep the previous entry wherever the new one has an error. The snapshot holds the only stored login and is read on every request, so write it with atomic_write_inventory (also in submit_code). The refresh now re-reads the snapshot under a lock after the cloud wait, so a sign-in that finished meanwhile is not reverted; if the login changed, the refresh stops and asks to run again. The result gains kept_previous when entries were kept. Co-Authored-By: Claude Sonnet 5.5 --- src/roborock_local_server/cloud.py | 45 ++++++++++--- tests/test_cloud.py | 103 +++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+), 8 deletions(-) diff --git a/src/roborock_local_server/cloud.py b/src/roborock_local_server/cloud.py index ac7bcaf9..3331b58f 100644 --- a/src/roborock_local_server/cloud.py +++ b/src/roborock_local_server/cloud.py @@ -70,6 +70,20 @@ def _to_jsonable(value: Any) -> Any: return str(value) +def _merge_plugin_catalogs(stored: dict[str, Any], fresh: dict[str, Any]) -> tuple[dict[str, Any], list[str]]: + """Catalog by catalog: a fresh entry with an error never replaces a stored one that has none.""" + merged = dict(stored) + kept: list[str] = [] + for name, entry in fresh.items(): + previous = stored.get(name) + failed = isinstance(entry, dict) and "error" in entry + if failed and isinstance(previous, dict) and "error" not in previous: + kept.append(name) + continue + merged[name] = entry + return merged, kept + + @dataclass class PendingCloudSession: session_id: str @@ -91,6 +105,7 @@ def __init__(self, *, inventory_path: Path, snapshot_path: Path, ttl_seconds: in self.ttl_seconds = ttl_seconds self._sessions: dict[str, PendingCloudSession] = {} self._lock = threading.Lock() + self._snapshot_lock = threading.Lock() def _cleanup_locked(self) -> None: now = time.time() @@ -197,13 +212,26 @@ async def refresh_plugin_catalogs(self) -> dict[str, Any]: errors = "; ".join(str(catalogs[name]["error"]) for name in failed) raise ValueError(f"The cloud returned no plugin catalogs ({errors}). Request a code and sign in again.") - web_cache = snapshot.get("web_api_cache") - if not isinstance(web_cache, dict): - web_cache = {} - snapshot["web_api_cache"] = web_cache - web_cache["plugin_catalogs"] = _to_jsonable(catalogs) - self.snapshot_path.write_text(json.dumps(snapshot, indent=2) + "\n", encoding="utf-8") - return {"success": True, "step": "plugins_refreshed", **summarize_plugin_catalogs(catalogs)} + fresh = _to_jsonable(catalogs) + # The cloud wait is over; re-read under the lock so a sign-in that finished meanwhile is not reverted. + with self._snapshot_lock: + snapshot = self._read_snapshot() + current = snapshot.get("user_data") + if not isinstance(current, dict) or current.get("token") != user_data.token: + raise ValueError("A new sign-in finished while the refresh ran. Run the refresh again.") + web_cache = snapshot.get("web_api_cache") + if not isinstance(web_cache, dict): + web_cache = {} + snapshot["web_api_cache"] = web_cache + stored = web_cache.get("plugin_catalogs") + stored = stored if isinstance(stored, dict) else {} + merged, kept = _merge_plugin_catalogs(stored, fresh) + web_cache["plugin_catalogs"] = merged + atomic_write_inventory(self.snapshot_path, snapshot) + result = {"success": True, "step": "plugins_refreshed", **summarize_plugin_catalogs(merged)} + if kept: + result["kept_previous"] = kept + return result async def submit_code(self, *, session_id: str, code: str) -> dict[str, Any]: normalized_session_id = session_id.strip() @@ -275,7 +303,8 @@ async def submit_code(self, *, session_id: str, code: str) -> dict[str, Any]: ) atomic_write_inventory(self.inventory_path, normalized_inventory) - self.snapshot_path.write_text(json.dumps(normalized_snapshot, indent=2) + "\n", encoding="utf-8") + with self._snapshot_lock: + atomic_write_inventory(self.snapshot_path, normalized_snapshot) with self._lock: self._sessions.pop(normalized_session_id, None) diff --git a/tests/test_cloud.py b/tests/test_cloud.py index 9944e745..16a80ec3 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -364,6 +364,108 @@ async def rejected(api, user_data): asyncio.run(manager.refresh_plugin_catalogs()) +def test_refresh_plugin_catalogs_keeps_stored_entries_that_failed_this_time(tmp_path, monkeypatch) -> None: + manager = _make_manager(tmp_path) + stored_ios = {"path": "/ios", "json": {"type": 1}, "data": [{"productid": 110, "version": 1, "url": "https://files.roborock.com/ios.zip"}]} + _write_snapshot(manager, web_api_cache={"plugin_catalogs": {"fetched_at_utc": "old", "appplugin_ios": stored_ios}}) + partial = dict(_NEW_CATALOGS, appplugin_ios={"path": "/ios", "error": "No product ids available"}) + _patch_plugin_fetch(monkeypatch, partial) + + result = asyncio.run(manager.refresh_plugin_catalogs()) + + assert result["kept_previous"] == ["appplugin_ios"] + assert result["appplugin_ios"]["plugins"][0]["url"] == "https://files.roborock.com/ios.zip" + assert "error" not in result["appplugin_ios"] + stored = json.loads(manager.snapshot_path.read_text(encoding="utf-8"))["web_api_cache"]["plugin_catalogs"] + assert stored["appplugin_ios"] == stored_ios + assert stored["appplugin"]["data"][0]["version"] == 7006 + + +def test_refresh_plugin_catalogs_stores_an_error_entry_when_nothing_good_was_stored(tmp_path, monkeypatch) -> None: + manager = _make_manager(tmp_path) + _write_snapshot(manager) + partial = dict(_NEW_CATALOGS, appplugin_ios={"path": "/ios", "error": "No product ids available"}) + _patch_plugin_fetch(monkeypatch, partial) + + result = asyncio.run(manager.refresh_plugin_catalogs()) + + assert "kept_previous" not in result + assert result["appplugin_ios"]["error"] == "No product ids available" + + +def test_refresh_plugin_catalogs_does_not_revert_a_sign_in_that_finished_meanwhile(tmp_path, monkeypatch) -> None: + manager = _make_manager(tmp_path) + _write_snapshot(manager) + + async def slow_catalogs(api, user_data, home_data): + # A sign-in lands while the cloud request is in flight. + _write_snapshot(manager, user_data=dict(_STORED_USER_DATA, token="new-token"), meta={"username": "user@example.com", "source": "new"}) + return _NEW_CATALOGS + + _patch_plugin_fetch(monkeypatch, _NEW_CATALOGS) + monkeypatch.setattr(cloud_module, "_fetch_plugin_catalogs", slow_catalogs) + + with pytest.raises(ValueError, match="new sign-in finished"): + asyncio.run(manager.refresh_plugin_catalogs()) + stored = json.loads(manager.snapshot_path.read_text(encoding="utf-8")) + assert stored["user_data"]["token"] == "new-token" + assert stored["meta"]["source"] == "new" + + +def test_refresh_plugin_catalogs_keeps_other_snapshot_changes_made_meanwhile(tmp_path, monkeypatch) -> None: + manager = _make_manager(tmp_path) + _write_snapshot(manager) + + async def slow_catalogs(api, user_data, home_data): + _write_snapshot(manager, web_api_cache={"rooms": [9], "plugin_catalogs": {"fetched_at_utc": "old"}}) + return _NEW_CATALOGS + + _patch_plugin_fetch(monkeypatch, _NEW_CATALOGS) + monkeypatch.setattr(cloud_module, "_fetch_plugin_catalogs", slow_catalogs) + + asyncio.run(manager.refresh_plugin_catalogs()) + + stored = json.loads(manager.snapshot_path.read_text(encoding="utf-8")) + assert stored["web_api_cache"]["rooms"] == [9] + assert stored["web_api_cache"]["plugin_catalogs"]["appplugin"]["data"][0]["version"] == 7006 + + +def test_snapshot_writes_go_through_the_atomic_writer(tmp_path, monkeypatch) -> None: + written: list[Path] = [] + real = cloud_module.atomic_write_inventory + + def spy(path, data): + written.append(path) + real(path, data) + + monkeypatch.setattr(cloud_module, "atomic_write_inventory", spy) + manager = _make_manager(tmp_path) + _write_snapshot(manager) + _patch_plugin_fetch(monkeypatch, _NEW_CATALOGS) + asyncio.run(manager.refresh_plugin_catalogs()) + _patch_backend_calls(monkeypatch) + request_result = asyncio.run(manager.request_code(email="user@example.com")) + asyncio.run(manager.submit_code(session_id=request_result["session_id"], code="123456")) + + assert written.count(manager.snapshot_path) == 2 + assert not list(manager.snapshot_path.parent.glob(".*.tmp")) + + +def test_refresh_plugin_catalogs_leaves_the_snapshot_intact_when_the_write_fails(tmp_path, monkeypatch) -> None: + manager = _make_manager(tmp_path) + _write_snapshot(manager) + before = manager.snapshot_path.read_text(encoding="utf-8") + _patch_plugin_fetch(monkeypatch, _NEW_CATALOGS) + + def boom(path, data): + raise OSError("disk full") + + monkeypatch.setattr(cloud_module, "atomic_write_inventory", boom) + with pytest.raises(OSError): + asyncio.run(manager.refresh_plugin_catalogs()) + assert manager.snapshot_path.read_text(encoding="utf-8") == before + + def test_submit_code_stores_the_device_identifier(tmp_path, monkeypatch) -> None: monkeypatch.setattr(cloud_module, "RoborockApiClient", _FakeRoborockApiClientV4) _patch_backend_calls(monkeypatch) @@ -374,3 +476,4 @@ def test_submit_code_stores_the_device_identifier(tmp_path, monkeypatch) -> None stored = json.loads(manager.snapshot_path.read_text(encoding="utf-8")) assert stored["meta"]["device_identifier"] == _fake_client_instances[0]._device_identifier + From 6b97054e41e5d7870f10a1d4d484e3b4a7fa7140 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:17:47 -0500 Subject: [PATCH 4/6] Give each plugin refresh failure its own message Every exception was reported as a rejected login with advice to sign in again, including timeouts, an unreachable cloud and RoborockRateLimit, which made users re-run the rate-limited code login. Only RoborockInvalidCredentials and RoborockAccountDoesNotExist now say to sign in again; rate limit, timeout and connection errors get their own text, and anything else says the stored catalogs were kept. The home-data helper now chains its RuntimeError to the last error so the original type is visible to the classifier. Co-Authored-By: Claude Sonnet 5.5 --- .../import_web_inventory_from_cloud.py | 2 +- src/roborock_local_server/cloud.py | 35 +++++++++++++++-- tests/test_cloud.py | 39 ++++++++++++++++++- 3 files changed, 70 insertions(+), 6 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py b/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py index ca095047..76fd566d 100644 --- a/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py +++ b/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py @@ -638,7 +638,7 @@ async def _fetch_cloud_home_data_with_api(api: RoborockApiClient, user_data: Use # The library applies request rate-limits per method family. # Back off a bit before trying legacy endpoint variants. await asyncio.sleep(1.2) - raise RuntimeError(f"Failed to fetch cloud home_data: {last_error}") + raise RuntimeError(f"Failed to fetch cloud home_data: {last_error}") from last_error async def _fetch_cloud_home_data_from_dict( diff --git a/src/roborock_local_server/cloud.py b/src/roborock_local_server/cloud.py index 3331b58f..86cabb8b 100644 --- a/src/roborock_local_server/cloud.py +++ b/src/roborock_local_server/cloud.py @@ -13,6 +13,14 @@ import aiohttp from roborock.data import UserData +from roborock.exceptions import ( + RoborockAccountDoesNotExist, + RoborockConnectionException, + RoborockInvalidCredentials, + RoborockNoResponseFromBaseURL, + RoborockRateLimit, + RoborockTimeout, +) from roborock.web_api import RoborockApiClient from .backend import ( @@ -84,6 +92,27 @@ def _merge_plugin_catalogs(stored: dict[str, Any], fresh: dict[str, Any]) -> tup return merged, kept +def _describe_refresh_error(exc: BaseException) -> str: + """Only a rejected login says to sign in again; other failures get their own advice.""" + chain: list[BaseException] = [] + current: BaseException | None = exc + while current is not None and current not in chain: + chain.append(current) + current = current.__cause__ or current.__context__ + if any(isinstance(item, RoborockRateLimit) for item in chain): + return f"The cloud is rate limiting requests ({exc}). Wait a few minutes and refresh again." + if any(isinstance(item, (RoborockInvalidCredentials, RoborockAccountDoesNotExist)) for item in chain): + return f"The cloud rejected the stored login ({exc}). Request a code and sign in again." + if any(isinstance(item, (TimeoutError, RoborockTimeout)) for item in chain): + return "The cloud did not answer in time. Try the refresh again." + if any( + isinstance(item, (aiohttp.ClientError, OSError, RoborockConnectionException, RoborockNoResponseFromBaseURL)) + for item in chain + ): + return f"The cloud could not be reached ({exc}). Check the network and try again." + return f"The cloud request failed ({exc}). The stored catalogs were kept." + + @dataclass class PendingCloudSession: session_id: str @@ -203,14 +232,12 @@ async def refresh_plugin_catalogs(self) -> dict[str, Any]: home_data = await _fetch_cloud_home_data_with_api(api, user_data) catalogs = await _fetch_plugin_catalogs(api, user_data, home_data) except Exception as exc: # noqa: BLE001 - raise ValueError( - f"The cloud rejected the stored login ({exc}). Request a code and sign in again." - ) from exc + raise ValueError(_describe_refresh_error(exc)) from exc failed = [name for name, item in catalogs.items() if isinstance(item, dict) and "error" in item] if failed and len(failed) == sum(1 for item in catalogs.values() if isinstance(item, dict)): errors = "; ".join(str(catalogs[name]["error"]) for name in failed) - raise ValueError(f"The cloud returned no plugin catalogs ({errors}). Request a code and sign in again.") + raise ValueError(f"The cloud returned no plugin catalogs ({errors}). The stored catalogs were kept.") fresh = _to_jsonable(catalogs) # The cloud wait is over; re-read under the lock so a sign-in that finished meanwhile is not reverted. diff --git a/tests/test_cloud.py b/tests/test_cloud.py index 16a80ec3..3faf4936 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -3,7 +3,9 @@ from pathlib import Path from types import SimpleNamespace +import aiohttp import pytest +from roborock.exceptions import RoborockInvalidCredentials, RoborockRateLimit, RoborockTimeout from roborock_local_server import cloud as cloud_module from roborock_local_server.backend import _merge_existing_inventory_mutations @@ -357,7 +359,7 @@ def test_refresh_plugin_catalogs_reports_a_rejected_login(tmp_path, monkeypatch) _patch_plugin_fetch(monkeypatch, _NEW_CATALOGS) async def rejected(api, user_data): - raise RuntimeError("invalid token") + raise RoborockInvalidCredentials("invalid token") monkeypatch.setattr(cloud_module, "_fetch_cloud_home_data_with_api", rejected) with pytest.raises(ValueError, match="sign in again"): @@ -477,3 +479,38 @@ def test_submit_code_stores_the_device_identifier(tmp_path, monkeypatch) -> None stored = json.loads(manager.snapshot_path.read_text(encoding="utf-8")) assert stored["meta"]["device_identifier"] == _fake_client_instances[0]._device_identifier + +@pytest.mark.parametrize( + ("error", "expected"), + [ + (RoborockRateLimit("slow down"), "rate limiting"), + (RoborockInvalidCredentials("bad token"), "sign in again"), + (TimeoutError(), "did not answer in time"), + (RoborockTimeout("t"), "did not answer in time"), + (aiohttp.ClientConnectionError("dns"), "could not be reached"), + (RuntimeError("something odd"), "request failed"), + ], +) +def test_refresh_plugin_catalogs_gives_each_failure_its_own_message(tmp_path, monkeypatch, error, expected) -> None: + manager = _make_manager(tmp_path) + _write_snapshot(manager) + _patch_plugin_fetch(monkeypatch, _NEW_CATALOGS) + + async def failing(api, user_data): + raise error + + monkeypatch.setattr(cloud_module, "_fetch_cloud_home_data_with_api", failing) + with pytest.raises(ValueError, match=expected) as raised: + asyncio.run(manager.refresh_plugin_catalogs()) + if expected != "sign in again": + assert "sign in again" not in str(raised.value) + + +def test_refresh_error_classifier_follows_the_cause_chain() -> None: + try: + try: + raise RoborockInvalidCredentials("expired") + except RoborockInvalidCredentials as inner: + raise RuntimeError("Failed to fetch cloud home_data: expired") from inner + except RuntimeError as outer: + assert "sign in again" in cloud_module._describe_refresh_error(outer) From 6c0322041b79747157d6c5b071063ef68cfa4bb5 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:09:37 -0500 Subject: [PATCH 5/6] Give a missing or unreadable stored login its own refresh message When the snapshot vanished or was corrupted during the cloud wait, the refresh said a new sign-in had finished, which was wrong. It now says the stored login is missing or unreadable. Co-Authored-By: Claude Sonnet 5.5 --- src/roborock_local_server/cloud.py | 4 +++- tests/test_cloud.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/roborock_local_server/cloud.py b/src/roborock_local_server/cloud.py index 86cabb8b..b098528c 100644 --- a/src/roborock_local_server/cloud.py +++ b/src/roborock_local_server/cloud.py @@ -244,7 +244,9 @@ async def refresh_plugin_catalogs(self) -> dict[str, Any]: with self._snapshot_lock: snapshot = self._read_snapshot() current = snapshot.get("user_data") - if not isinstance(current, dict) or current.get("token") != user_data.token: + if not isinstance(current, dict) or not current.get("token"): + raise ValueError("The stored cloud login is missing or unreadable. Request a code and sign in again.") + if current.get("token") != user_data.token: raise ValueError("A new sign-in finished while the refresh ran. Run the refresh again.") web_cache = snapshot.get("web_api_cache") if not isinstance(web_cache, dict): diff --git a/tests/test_cloud.py b/tests/test_cloud.py index 3faf4936..2ddcb9a6 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -414,6 +414,21 @@ async def slow_catalogs(api, user_data, home_data): assert stored["meta"]["source"] == "new" +def test_refresh_plugin_catalogs_reports_a_snapshot_that_vanished_meanwhile(tmp_path, monkeypatch) -> None: + manager = _make_manager(tmp_path) + _write_snapshot(manager) + + async def slow_catalogs(api, user_data, home_data): + manager.snapshot_path.write_text("{ not json", encoding="utf-8") + return _NEW_CATALOGS + + _patch_plugin_fetch(monkeypatch, _NEW_CATALOGS) + monkeypatch.setattr(cloud_module, "_fetch_plugin_catalogs", slow_catalogs) + + with pytest.raises(ValueError, match="missing or unreadable"): + asyncio.run(manager.refresh_plugin_catalogs()) + + def test_refresh_plugin_catalogs_keeps_other_snapshot_changes_made_meanwhile(tmp_path, monkeypatch) -> None: manager = _make_manager(tmp_path) _write_snapshot(manager) From a38d78db0198392759132c91a9121518b745da2c Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:11:21 -0500 Subject: [PATCH 6/6] Show the real age of plugin catalogs kept after a failed refresh A kept catalog sat under a fresh top-level fetched_at_utc, so it looked as new as the ones just fetched. Kept entries now carry their own stamp, and the summary reports it. Co-Authored-By: Claude Sonnet 5.5 --- src/roborock_local_server/cloud.py | 4 ++++ tests/test_cloud.py | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/roborock_local_server/cloud.py b/src/roborock_local_server/cloud.py index b098528c..bf9949c3 100644 --- a/src/roborock_local_server/cloud.py +++ b/src/roborock_local_server/cloud.py @@ -48,6 +48,8 @@ def summarize_plugin_catalogs(catalogs: dict[str, Any]) -> dict[str, Any]: if not isinstance(catalog, dict): continue entry: dict[str, Any] = {"params": catalog.get("params") or catalog.get("json") or {}} + if catalog.get("fetched_at_utc"): + entry["fetched_at_utc"] = catalog["fetched_at_utc"] if "error" in catalog: entry["error"] = catalog["error"] data = catalog.get("data") @@ -87,6 +89,8 @@ def _merge_plugin_catalogs(stored: dict[str, Any], fresh: dict[str, Any]) -> tup failed = isinstance(entry, dict) and "error" in entry if failed and isinstance(previous, dict) and "error" not in previous: kept.append(name) + # Stamp the kept entry with its real age so the new top-level stamp does not make it look fresh. + merged[name] = {"fetched_at_utc": stored.get("fetched_at_utc"), **previous} continue merged[name] = entry return merged, kept diff --git a/tests/test_cloud.py b/tests/test_cloud.py index 2ddcb9a6..167e0abd 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -379,7 +379,9 @@ def test_refresh_plugin_catalogs_keeps_stored_entries_that_failed_this_time(tmp_ assert result["appplugin_ios"]["plugins"][0]["url"] == "https://files.roborock.com/ios.zip" assert "error" not in result["appplugin_ios"] stored = json.loads(manager.snapshot_path.read_text(encoding="utf-8"))["web_api_cache"]["plugin_catalogs"] - assert stored["appplugin_ios"] == stored_ios + assert stored["appplugin_ios"] == {"fetched_at_utc": "old", **stored_ios} + assert result["appplugin_ios"]["fetched_at_utc"] == "old" + assert "fetched_at_utc" not in result["appplugin"] assert stored["appplugin"]["data"][0]["version"] == 7006