From 1857fdd68bffaf07e6fbe25a6d096107b89e53d4 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 27 Sep 2026 10:26:35 -0400 Subject: [PATCH 01/32] Add ROBOROCK_SERVER_* env var config generation Lets Docker Compose deployments generate config.toml from environment variables alone, covering the network/broker/storage/tls sections plus the admin credentials needed for a bootable config. Mirrors the existing Home Assistant add-on options.json -> config.toml flow in ha_addon.py, but supports external broker mode and external_tls reverse-proxy setups that the add-on intentionally doesn't need. Co-Authored-By: Claude Sonnet 5 (cherry picked from commit 2c64eef0f6a546bee4492361da9f1959e564ea7e) --- src/roborock_local_server/env_config.py | 374 ++++++++++++++++++++++++ tests/test_env_config.py | 250 ++++++++++++++++ 2 files changed, 624 insertions(+) create mode 100644 src/roborock_local_server/env_config.py create mode 100644 tests/test_env_config.py diff --git a/src/roborock_local_server/env_config.py b/src/roborock_local_server/env_config.py new file mode 100644 index 0000000..0c406c8 --- /dev/null +++ b/src/roborock_local_server/env_config.py @@ -0,0 +1,374 @@ +"""Generate config.toml from ROBOROCK_SERVER_* environment variables. + +This lets Docker Compose (and similar) deployments boot straight from +environment variables, without running the host-side `configure` wizard +first. It intentionally covers only the deployment/infrastructure-shaped +settings (network, broker, storage, tls) plus the admin credentials needed +to produce a bootable config; it is not meant to grow a variable for every +config.toml key. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import ipaddress +import json +import os +from pathlib import Path +import re +import secrets +import tomllib +from typing import Mapping +from urllib.parse import urlsplit + +from .configure import hash_password + +ENV_PREFIX = "ROBOROCK_SERVER_" + +_HOST_RE = re.compile(r"^[a-z0-9.-]+$") + +DEFAULT_CONFIG_PATH = Path("/data/config.toml") +DEFAULT_CLOUDFLARE_TOKEN_PATH = Path("/run/secrets/cloudflare_token") +DEFAULT_ACME_EAB_KID_PATH = Path("/run/secrets/acme_eab_kid") +DEFAULT_ACME_EAB_HMAC_KEY_PATH = Path("/run/secrets/acme_eab_hmac_key") + + +def _toml_string(value: str) -> str: + return json.dumps(value) + + +def _toml_bool(value: bool) -> str: + return "true" if value else "false" + + +def _get(env: Mapping[str, str], name: str, default: str = "") -> str: + return str(env.get(f"{ENV_PREFIX}{name}", "") or "").strip() or default + + +def _normalize_hostname(raw_value: str, *, field_name: str, require_api_prefix: bool = False) -> str: + text = str(raw_value or "").strip() + if not text: + raise ValueError(f"{field_name} is required") + if "://" in text: + parsed = urlsplit(text) + candidate = parsed.hostname or "" + else: + candidate = text.split("/", 1)[0].strip() + if ":" in candidate: + candidate = candidate.split(":", 1)[0].strip() + normalized = candidate.strip().strip(".").lower() + if normalized.startswith("*."): + normalized = normalized[2:].strip() + if not normalized: + raise ValueError(f"{field_name} is required") + if " " in normalized or not _HOST_RE.fullmatch(normalized): + raise ValueError(f"{field_name} must be a hostname without a scheme or path") + if "." not in normalized: + raise ValueError(f"{field_name} must be a fully qualified domain name") + if require_api_prefix and not normalized.startswith("api-"): + raise ValueError(f"{field_name} must start with api-") + return normalized + + +def _as_port(value: str, *, field_name: str, default: int) -> int: + if not value: + return default + try: + candidate = int(value) + except ValueError as exc: + raise ValueError(f"{field_name} must be an integer") from exc + if not (1 <= candidate <= 65535): + raise ValueError(f"{field_name} must be between 1 and 65535") + return candidate + + +def _as_bool(value: str, *, default: bool) -> bool: + if not value: + return default + lowered = value.strip().lower() + if lowered in {"1", "true", "yes", "on"}: + return True + if lowered in {"0", "false", "no", "off"}: + return False + raise ValueError(f"expected a boolean value, got {value!r}") + + +def _as_trusted_proxies(value: str, *, default: tuple[str, ...]) -> tuple[str, ...]: + if not value: + return default + entries: list[str] = [] + for item in value.split(","): + text = item.strip() + if not text: + continue + try: + ipaddress.ip_network(text, strict=False) + except ValueError as exc: + raise ValueError(f"trusted_proxies entry {text!r} is not a valid IP address or CIDR network") from exc + entries.append(text) + return tuple(entries) if entries else default + + +def _require_non_empty(value: str, *, field_name: str) -> str: + text = str(value or "").strip() + if not text: + raise ValueError(f"{ENV_PREFIX}{field_name} is required") + return text + + +def _require_email(value: str, *, field_name: str) -> str: + text = _require_non_empty(value, field_name=field_name) + if "@" not in text: + raise ValueError(f"{ENV_PREFIX}{field_name} must be an email address") + return text + + +def _require_pin(value: str, *, field_name: str) -> str: + text = _require_non_empty(value, field_name=field_name) + if len(text) != 6 or not text.isdigit(): + raise ValueError(f"{ENV_PREFIX}{field_name} must be exactly 6 digits") + return text + + +def _normalize_acme_server(value: str) -> str: + normalized = value.strip().lower() or "zerossl" + if normalized not in {"zerossl", "actalis"}: + raise ValueError(f"{ENV_PREFIX}ACME_SERVER must be 'zerossl' or 'actalis'") + return normalized + + +def _load_existing_admin_session_secret(config_path: Path) -> str: + if not config_path.exists(): + return "" + try: + parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError): + return "" + admin = parsed.get("admin") + if not isinstance(admin, dict): + return "" + secret = str(admin.get("session_secret", "") or "").strip() + return secret if len(secret) >= 24 else "" + + +@dataclass(frozen=True) +class SecretPaths: + """Where env-supplied plaintext secrets get written, and the Docker-secret + style *_FILE overrides that skip writing entirely.""" + + cloudflare_token_file: Path = DEFAULT_CLOUDFLARE_TOKEN_PATH + acme_eab_kid_file: Path = DEFAULT_ACME_EAB_KID_PATH + acme_eab_hmac_key_file: Path = DEFAULT_ACME_EAB_HMAC_KEY_PATH + + +def has_env_config(env: Mapping[str, str]) -> bool: + """True when enough ROBOROCK_SERVER_* vars are present to attempt generation.""" + return bool(_get(env, "STACK_FQDN")) + + +def render_config_toml_from_env( + env: Mapping[str, str], + *, + config_path: Path, + secret_paths: SecretPaths = SecretPaths(), +) -> tuple[str, dict[Path, str]]: + stack_fqdn = _normalize_hostname(_get(env, "STACK_FQDN"), field_name="STACK_FQDN", require_api_prefix=True) + listener_mode = _get(env, "LISTENER_MODE", "local_tls").lower() + if listener_mode not in {"local_tls", "external_tls"}: + raise ValueError(f"{ENV_PREFIX}LISTENER_MODE must be 'local_tls' or 'external_tls'") + bind_host = _get(env, "BIND_HOST", "0.0.0.0") + region = _get(env, "REGION", "us").lower() + https_port = _as_port(_get(env, "HTTPS_PORT"), field_name=f"{ENV_PREFIX}HTTPS_PORT", default=555) + mqtt_tls_port = _as_port(_get(env, "MQTT_TLS_PORT"), field_name=f"{ENV_PREFIX}MQTT_TLS_PORT", default=8881) + advertised_https_port = _as_port( + _get(env, "ADVERTISED_HTTPS_PORT"), + field_name=f"{ENV_PREFIX}ADVERTISED_HTTPS_PORT", + default=https_port, + ) + advertised_mqtt_tls_port = _as_port( + _get(env, "ADVERTISED_MQTT_TLS_PORT"), + field_name=f"{ENV_PREFIX}ADVERTISED_MQTT_TLS_PORT", + default=mqtt_tls_port, + ) + trusted_proxies = _as_trusted_proxies(_get(env, "TRUSTED_PROXIES"), default=("127.0.0.1", "::1")) + + broker_mode = _get(env, "BROKER_MODE", "embedded").lower() + if broker_mode not in {"embedded", "external"}: + raise ValueError(f"{ENV_PREFIX}BROKER_MODE must be 'embedded' or 'external'") + if broker_mode == "embedded": + broker_host = _get(env, "BROKER_HOST", "127.0.0.1") + broker_port = _as_port(_get(env, "BROKER_PORT"), field_name=f"{ENV_PREFIX}BROKER_PORT", default=18830) + else: + broker_host = _require_non_empty(_get(env, "BROKER_HOST"), field_name="BROKER_HOST") + broker_port = _as_port(_get(env, "BROKER_PORT"), field_name=f"{ENV_PREFIX}BROKER_PORT", default=1883) + + data_dir = _get(env, "DATA_DIR", "/data") + + tls_mode = _get(env, "TLS_MODE", "cloudflare_acme").lower() + if tls_mode not in {"cloudflare_acme", "provided"}: + raise ValueError(f"{ENV_PREFIX}TLS_MODE must be 'cloudflare_acme' or 'provided'") + if listener_mode == "external_tls" and tls_mode != "provided": + raise ValueError( + f"{ENV_PREFIX}LISTENER_MODE='external_tls' requires {ENV_PREFIX}TLS_MODE='provided' " + "(the proxy terminates TLS; the server does not issue certificates)" + ) + + tls_base_domain = "" + tls_email = "" + acme_server = "zerossl" + cloudflare_token_file = "" + acme_eab_kid_file = "" + acme_eab_hmac_key_file = "" + cert_file = "" + key_file = "" + secrets_to_write: dict[Path, str] = {} + + if listener_mode == "local_tls": + if tls_mode == "cloudflare_acme": + tls_base_domain = _normalize_hostname(_get(env, "TLS_BASE_DOMAIN"), field_name="TLS_BASE_DOMAIN") + tls_email = _require_non_empty(_get(env, "TLS_EMAIL"), field_name="TLS_EMAIL") + acme_server = _normalize_acme_server(_get(env, "ACME_SERVER", "zerossl")) + + cloudflare_token_file_override = _get(env, "CLOUDFLARE_TOKEN_FILE") + cloudflare_token = _get(env, "CLOUDFLARE_TOKEN") + if cloudflare_token_file_override: + cloudflare_token_file = cloudflare_token_file_override + elif cloudflare_token: + cloudflare_token_file = str(secret_paths.cloudflare_token_file) + secrets_to_write[secret_paths.cloudflare_token_file] = cloudflare_token + else: + raise ValueError( + f"{ENV_PREFIX}CLOUDFLARE_TOKEN or {ENV_PREFIX}CLOUDFLARE_TOKEN_FILE is required " + f"when {ENV_PREFIX}TLS_MODE='cloudflare_acme'" + ) + + if acme_server == "actalis": + eab_kid_file_override = _get(env, "ACME_EAB_KID_FILE") + eab_kid = _get(env, "ACME_EAB_KID") + eab_hmac_file_override = _get(env, "ACME_EAB_HMAC_KEY_FILE") + eab_hmac = _get(env, "ACME_EAB_HMAC_KEY") + if not (eab_kid_file_override or eab_kid): + raise ValueError(f"Actalis requires {ENV_PREFIX}ACME_EAB_KID or {ENV_PREFIX}ACME_EAB_KID_FILE") + if not (eab_hmac_file_override or eab_hmac): + raise ValueError( + f"Actalis requires {ENV_PREFIX}ACME_EAB_HMAC_KEY or {ENV_PREFIX}ACME_EAB_HMAC_KEY_FILE" + ) + acme_eab_kid_file = eab_kid_file_override or str(secret_paths.acme_eab_kid_file) + if not eab_kid_file_override: + secrets_to_write[secret_paths.acme_eab_kid_file] = eab_kid + acme_eab_hmac_key_file = eab_hmac_file_override or str(secret_paths.acme_eab_hmac_key_file) + if not eab_hmac_file_override: + secrets_to_write[secret_paths.acme_eab_hmac_key_file] = eab_hmac + else: + cert_file = _require_non_empty(_get(env, "CERT_FILE"), field_name="CERT_FILE") + key_file = _require_non_empty(_get(env, "KEY_FILE"), field_name="KEY_FILE") + + admin_password = _require_non_empty(_get(env, "ADMIN_PASSWORD"), field_name="ADMIN_PASSWORD") + admin_session_secret = ( + _get(env, "ADMIN_SESSION_SECRET") + or _load_existing_admin_session_secret(config_path) + or secrets.token_urlsafe(32) + ) + if len(admin_session_secret) < 24: + raise ValueError(f"{ENV_PREFIX}ADMIN_SESSION_SECRET must be at least 24 characters when set") + new_connections_enabled = _as_bool(_get(env, "NEW_CONNECTIONS_ENABLED"), default=True) + protocol_login_email = _require_email(_get(env, "PROTOCOL_LOGIN_EMAIL"), field_name="PROTOCOL_LOGIN_EMAIL") + protocol_login_pin = _require_pin(_get(env, "PROTOCOL_LOGIN_PIN"), field_name="PROTOCOL_LOGIN_PIN") + + password_hash = hash_password(admin_password) + protocol_login_pin_hash = hash_password(protocol_login_pin) + + lines = [ + "[network]", + f"stack_fqdn = {_toml_string(stack_fqdn)}", + f"listener_mode = {_toml_string(listener_mode)}", + f"bind_host = {_toml_string(bind_host)}", + f"https_port = {https_port}", + f"mqtt_tls_port = {mqtt_tls_port}", + f"advertised_https_port = {advertised_https_port}", + f"advertised_mqtt_tls_port = {advertised_mqtt_tls_port}", + f"region = {_toml_string(region)}", + f"trusted_proxies = [{', '.join(_toml_string(p) for p in trusted_proxies)}]", + "", + "[broker]", + f"mode = {_toml_string(broker_mode)}", + f"host = {_toml_string(broker_host)}", + f"port = {broker_port}", + 'mosquitto_binary = "mosquitto"', + "enable_topic_bridge = true", + "", + "[storage]", + f"data_dir = {_toml_string(data_dir)}", + "", + "[tls]", + f"mode = {_toml_string(tls_mode)}", + ] + if listener_mode == "local_tls" and tls_mode == "cloudflare_acme": + lines.extend( + [ + f"base_domain = {_toml_string(tls_base_domain)}", + f"email = {_toml_string(tls_email)}", + f"cloudflare_token_file = {_toml_string(cloudflare_token_file)}", + "renew_days_before = 30", + "renew_check_seconds = 43200", + f"acme_server = {_toml_string(acme_server)}", + 'acme_eab_kid = ""', + 'acme_eab_hmac_key = ""', + f"acme_eab_kid_file = {_toml_string(acme_eab_kid_file)}", + f"acme_eab_hmac_key_file = {_toml_string(acme_eab_hmac_key_file)}", + ] + ) + else: + lines.extend( + [ + 'base_domain = ""', + 'email = ""', + 'cloudflare_token_file = ""', + "renew_days_before = 30", + "renew_check_seconds = 43200", + f"acme_server = {_toml_string(acme_server)}", + 'acme_eab_kid = ""', + 'acme_eab_hmac_key = ""', + 'acme_eab_kid_file = ""', + 'acme_eab_hmac_key_file = ""', + f"cert_file = {_toml_string(cert_file)}", + f"key_file = {_toml_string(key_file)}", + ] + ) + + lines.extend( + [ + "", + "[admin]", + f"password_hash = {_toml_string(password_hash)}", + f"session_secret = {_toml_string(admin_session_secret)}", + "session_ttl_seconds = 86400", + "protocol_auth_enabled = true", + f"new_connections_enabled = {_toml_bool(new_connections_enabled)}", + f"protocol_login_email = {_toml_string(protocol_login_email)}", + f"protocol_login_pin_hash = {_toml_string(protocol_login_pin_hash)}", + "", + ] + ) + return "\n".join(lines), secrets_to_write + + +def write_config_from_env( + env: Mapping[str, str], + *, + config_path: Path = DEFAULT_CONFIG_PATH, + secret_paths: SecretPaths = SecretPaths(), +) -> Path: + config_text, secrets_to_write = render_config_toml_from_env( + env, + config_path=config_path, + secret_paths=secret_paths, + ) + config_path.parent.mkdir(parents=True, exist_ok=True) + config_path.write_text(config_text, encoding="utf-8") + for path, contents in secrets_to_write.items(): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(contents, encoding="utf-8") + if os.name != "nt": + path.chmod(0o600) + return config_path diff --git a/tests/test_env_config.py b/tests/test_env_config.py new file mode 100644 index 0000000..79e7bb2 --- /dev/null +++ b/tests/test_env_config.py @@ -0,0 +1,250 @@ +from __future__ import annotations + +from pathlib import Path +import tomllib + +import pytest + +from roborock_local_server.env_config import SecretPaths, has_env_config, write_config_from_env + +_BASE_ENV = { + "ROBOROCK_SERVER_STACK_FQDN": "api-roborock.example.com", + "ROBOROCK_SERVER_TLS_MODE": "provided", + "ROBOROCK_SERVER_CERT_FILE": "/ssl/fullchain.pem", + "ROBOROCK_SERVER_KEY_FILE": "/ssl/privkey.pem", + "ROBOROCK_SERVER_ADMIN_PASSWORD": "super-secret-password", + "ROBOROCK_SERVER_PROTOCOL_LOGIN_EMAIL": "user@example.com", + "ROBOROCK_SERVER_PROTOCOL_LOGIN_PIN": "123456", +} + + +def test_has_env_config_requires_stack_fqdn() -> None: + assert has_env_config({}) is False + assert has_env_config({"ROBOROCK_SERVER_STACK_FQDN": "api-roborock.example.com"}) is True + + +def test_write_config_from_env_provided_tls(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + + write_config_from_env(_BASE_ENV, config_path=config_path) + + parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) + assert parsed["network"]["stack_fqdn"] == "api-roborock.example.com" + assert parsed["network"]["listener_mode"] == "local_tls" + assert parsed["network"]["https_port"] == 555 + assert parsed["network"]["mqtt_tls_port"] == 8881 + assert parsed["network"]["advertised_https_port"] == 555 + assert parsed["network"]["advertised_mqtt_tls_port"] == 8881 + assert parsed["network"]["trusted_proxies"] == ["127.0.0.1", "::1"] + assert parsed["broker"]["mode"] == "embedded" + assert parsed["broker"]["host"] == "127.0.0.1" + assert parsed["broker"]["port"] == 18830 + assert parsed["tls"]["mode"] == "provided" + assert parsed["tls"]["cert_file"] == "/ssl/fullchain.pem" + assert parsed["tls"]["key_file"] == "/ssl/privkey.pem" + assert parsed["admin"]["protocol_auth_enabled"] is True + assert parsed["admin"]["new_connections_enabled"] is True + assert parsed["admin"]["protocol_login_email"] == "user@example.com" + assert len(str(parsed["admin"]["session_secret"])) >= 24 + assert str(parsed["admin"]["password_hash"]).startswith("pbkdf2_sha256$") + assert str(parsed["admin"]["protocol_login_pin_hash"]).startswith("pbkdf2_sha256$") + + +def test_write_config_from_env_reverse_proxy_ports(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_ADVERTISED_HTTPS_PORT"] = "443" + env["ROBOROCK_SERVER_ADVERTISED_MQTT_TLS_PORT"] = "8883" + + write_config_from_env(env, config_path=config_path) + + parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) + assert parsed["network"]["https_port"] == 555 + assert parsed["network"]["advertised_https_port"] == 443 + assert parsed["network"]["advertised_mqtt_tls_port"] == 8883 + + +def test_write_config_from_env_external_tls_requires_provided(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_LISTENER_MODE"] = "external_tls" + env["ROBOROCK_SERVER_TLS_MODE"] = "cloudflare_acme" + del env["ROBOROCK_SERVER_CERT_FILE"] + del env["ROBOROCK_SERVER_KEY_FILE"] + + with pytest.raises(ValueError, match="external_tls"): + write_config_from_env(env, config_path=config_path) + + +def test_write_config_from_env_external_broker_requires_host(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_BROKER_MODE"] = "external" + + with pytest.raises(ValueError, match="BROKER_HOST"): + write_config_from_env(env, config_path=config_path) + + +def test_write_config_from_env_external_broker(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_BROKER_MODE"] = "external" + env["ROBOROCK_SERVER_BROKER_HOST"] = "mqtt.internal" + + write_config_from_env(env, config_path=config_path) + + parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) + assert parsed["broker"]["mode"] == "external" + assert parsed["broker"]["host"] == "mqtt.internal" + assert parsed["broker"]["port"] == 1883 + + +def test_write_config_from_env_cloudflare_writes_secret(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + token_path = tmp_path / "run" / "secrets" / "cloudflare_token" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_TLS_MODE"] = "cloudflare_acme" + env["ROBOROCK_SERVER_TLS_BASE_DOMAIN"] = "example.com" + env["ROBOROCK_SERVER_TLS_EMAIL"] = "acme@example.com" + env["ROBOROCK_SERVER_CLOUDFLARE_TOKEN"] = "cloudflare-token-123" + del env["ROBOROCK_SERVER_CERT_FILE"] + del env["ROBOROCK_SERVER_KEY_FILE"] + + write_config_from_env( + env, + config_path=config_path, + secret_paths=SecretPaths(cloudflare_token_file=token_path), + ) + + parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) + assert parsed["tls"]["mode"] == "cloudflare_acme" + assert parsed["tls"]["base_domain"] == "example.com" + assert parsed["tls"]["cloudflare_token_file"] == str(token_path) + assert token_path.read_text(encoding="utf-8") == "cloudflare-token-123" + + +def test_write_config_from_env_cloudflare_token_file_override_skips_write(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + existing_token_path = tmp_path / "existing-token" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_TLS_MODE"] = "cloudflare_acme" + env["ROBOROCK_SERVER_TLS_BASE_DOMAIN"] = "example.com" + env["ROBOROCK_SERVER_TLS_EMAIL"] = "acme@example.com" + env["ROBOROCK_SERVER_CLOUDFLARE_TOKEN_FILE"] = str(existing_token_path) + del env["ROBOROCK_SERVER_CERT_FILE"] + del env["ROBOROCK_SERVER_KEY_FILE"] + + write_config_from_env(env, config_path=config_path) + + parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) + assert parsed["tls"]["cloudflare_token_file"] == str(existing_token_path) + assert existing_token_path.exists() is False + + +def test_write_config_from_env_actalis_requires_eab(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_TLS_MODE"] = "cloudflare_acme" + env["ROBOROCK_SERVER_TLS_BASE_DOMAIN"] = "example.com" + env["ROBOROCK_SERVER_TLS_EMAIL"] = "acme@example.com" + env["ROBOROCK_SERVER_ACME_SERVER"] = "actalis" + env["ROBOROCK_SERVER_CLOUDFLARE_TOKEN"] = "cloudflare-token-123" + del env["ROBOROCK_SERVER_CERT_FILE"] + del env["ROBOROCK_SERVER_KEY_FILE"] + + with pytest.raises(ValueError, match="ACME_EAB_KID"): + write_config_from_env(env, config_path=config_path) + + +def test_write_config_from_env_actalis_writes_eab(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + token_path = tmp_path / "cloudflare_token" + kid_path = tmp_path / "acme_eab_kid" + hmac_path = tmp_path / "acme_eab_hmac_key" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_TLS_MODE"] = "cloudflare_acme" + env["ROBOROCK_SERVER_TLS_BASE_DOMAIN"] = "example.com" + env["ROBOROCK_SERVER_TLS_EMAIL"] = "acme@example.com" + env["ROBOROCK_SERVER_ACME_SERVER"] = "actalis" + env["ROBOROCK_SERVER_ACME_EAB_KID"] = "kid-123" + env["ROBOROCK_SERVER_ACME_EAB_HMAC_KEY"] = "hmac-456" + env["ROBOROCK_SERVER_CLOUDFLARE_TOKEN"] = "cloudflare-token-123" + del env["ROBOROCK_SERVER_CERT_FILE"] + del env["ROBOROCK_SERVER_KEY_FILE"] + + write_config_from_env( + env, + config_path=config_path, + secret_paths=SecretPaths( + cloudflare_token_file=token_path, + acme_eab_kid_file=kid_path, + acme_eab_hmac_key_file=hmac_path, + ), + ) + + parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) + assert parsed["tls"]["acme_server"] == "actalis" + assert parsed["tls"]["acme_eab_kid_file"] == str(kid_path) + assert parsed["tls"]["acme_eab_hmac_key_file"] == str(hmac_path) + assert kid_path.read_text(encoding="utf-8") == "kid-123" + assert hmac_path.read_text(encoding="utf-8") == "hmac-456" + + +def test_write_config_from_env_requires_admin_password(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + env = dict(_BASE_ENV) + del env["ROBOROCK_SERVER_ADMIN_PASSWORD"] + + with pytest.raises(ValueError, match="ADMIN_PASSWORD is required"): + write_config_from_env(env, config_path=config_path) + + +def test_write_config_from_env_requires_api_prefix(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_STACK_FQDN"] = "roborock.example.com" + + with pytest.raises(ValueError, match="STACK_FQDN must start with api-"): + write_config_from_env(env, config_path=config_path) + + +def test_write_config_from_env_rejects_bad_pin(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_PROTOCOL_LOGIN_PIN"] = "12" + + with pytest.raises(ValueError, match="PROTOCOL_LOGIN_PIN must be exactly 6 digits"): + write_config_from_env(env, config_path=config_path) + + +def test_write_config_from_env_reuses_existing_session_secret(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + + write_config_from_env(_BASE_ENV, config_path=config_path) + first_secret = tomllib.loads(config_path.read_text(encoding="utf-8"))["admin"]["session_secret"] + + write_config_from_env(_BASE_ENV, config_path=config_path) + second_secret = tomllib.loads(config_path.read_text(encoding="utf-8"))["admin"]["session_secret"] + + assert len(str(first_secret)) >= 24 + assert second_secret == first_secret + + +def test_write_config_from_env_trusted_proxies(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_TRUSTED_PROXIES"] = "10.0.0.0/8, 192.168.1.5" + + write_config_from_env(env, config_path=config_path) + + parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) + assert parsed["network"]["trusted_proxies"] == ["10.0.0.0/8", "192.168.1.5"] + + +def test_write_config_from_env_rejects_invalid_trusted_proxy(tmp_path: Path) -> None: + config_path = tmp_path / "config.toml" + env = dict(_BASE_ENV) + env["ROBOROCK_SERVER_TRUSTED_PROXIES"] = "not-an-ip" + + with pytest.raises(ValueError, match="not a valid IP address"): + write_config_from_env(env, config_path=config_path) From c255c1a086ddfd99ccb9be3db2a44b4ae9b399ce Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 27 Sep 2026 10:26:41 -0400 Subject: [PATCH 02/32] Wire env var config generation into the container entrypoint Falls back to ROBOROCK_SERVER_* env vars only when no config.toml (compose-mounted or previously generated) and no HA add-on options.json are present, so an existing hand-edited config is never clobbered. Co-Authored-By: Claude Sonnet 5 (cherry picked from commit 19acdea61b55948d9579e234d5ed6ce21b31e780) --- .../container_entrypoint.py | 9 ++- tests/test_container_entrypoint.py | 78 +++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) diff --git a/src/roborock_local_server/container_entrypoint.py b/src/roborock_local_server/container_entrypoint.py index 3d423ea..ba8a9a7 100644 --- a/src/roborock_local_server/container_entrypoint.py +++ b/src/roborock_local_server/container_entrypoint.py @@ -5,6 +5,7 @@ import os from pathlib import Path +from .env_config import has_env_config, write_config_from_env from .ha_addon import write_config_from_home_assistant_options @@ -32,8 +33,14 @@ def _run_entrypoint(*, compose_config: Path, data_config: Path, addon_options: P _exec_server(data_config) return + if has_env_config(os.environ): + write_config_from_env(os.environ, config_path=data_config) + _exec_server(data_config) + return + raise SystemExit( - "No config file found. Expected /app/config.toml, /data/config.toml, or /data/options.json." + "No config file found. Expected /app/config.toml, /data/config.toml, /data/options.json, " + "or ROBOROCK_SERVER_* environment variables (see docs/installation.md)." ) diff --git a/tests/test_container_entrypoint.py b/tests/test_container_entrypoint.py index c224947..424c64f 100644 --- a/tests/test_container_entrypoint.py +++ b/tests/test_container_entrypoint.py @@ -65,3 +65,81 @@ def test_run_entrypoint_prefers_compose_config_when_present( ) assert calls == [compose_config] + + +def test_run_entrypoint_prefers_existing_data_config_over_env_vars( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + compose_config = tmp_path / "app-config.toml" + data_config = tmp_path / "data-config.toml" + addon_options = tmp_path / "options.json" + data_config.write_text("existing = true\n", encoding="utf-8") + + monkeypatch.setenv("ROBOROCK_SERVER_STACK_FQDN", "api-roborock.example.com") + calls: list[Path] = [] + monkeypatch.setattr( + container_entrypoint, + "_exec_server", + lambda config_path: calls.append(config_path), + ) + monkeypatch.setattr( + container_entrypoint, + "write_config_from_env", + lambda *args, **kwargs: pytest.fail("should not regenerate an existing config.toml"), + ) + + container_entrypoint._run_entrypoint( + compose_config=compose_config, + data_config=data_config, + addon_options=addon_options, + ) + + assert calls == [data_config] + + +def test_run_entrypoint_generates_config_from_env_vars( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + compose_config = tmp_path / "app-config.toml" + data_config = tmp_path / "data-config.toml" + addon_options = tmp_path / "options.json" + + monkeypatch.setenv("ROBOROCK_SERVER_STACK_FQDN", "api-roborock.example.com") + calls: list[tuple[str, Path]] = [] + monkeypatch.setattr( + container_entrypoint, + "write_config_from_env", + lambda env, *, config_path: calls.append(("write", config_path)), + ) + monkeypatch.setattr( + container_entrypoint, + "_exec_server", + lambda config_path: calls.append(("exec", config_path)), + ) + + container_entrypoint._run_entrypoint( + compose_config=compose_config, + data_config=data_config, + addon_options=addon_options, + ) + + assert calls == [("write", data_config), ("exec", data_config)] + + +def test_run_entrypoint_errors_without_config_or_env_vars( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + compose_config = tmp_path / "app-config.toml" + data_config = tmp_path / "data-config.toml" + addon_options = tmp_path / "options.json" + monkeypatch.delenv("ROBOROCK_SERVER_STACK_FQDN", raising=False) + + with pytest.raises(SystemExit): + container_entrypoint._run_entrypoint( + compose_config=compose_config, + data_config=data_config, + addon_options=addon_options, + ) From d884e06c3858094b6673e743b0c12b0ba07e8413 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 27 Sep 2026 10:27:25 -0400 Subject: [PATCH 03/32] Document the env-var-only Docker Compose bootstrap path Explains the required/optional ROBOROCK_SERVER_* variables and the config.toml bind-mount gotcha (Docker creates an empty file for a nonexistent host path, which the entrypoint then treats as an existing but invalid config instead of falling through to env vars). Co-Authored-By: Claude Sonnet 5 (cherry picked from commit 94262cc6ed729d5a0d8ebba48cf4418dfef5bac3) --- compose.yaml | 3 +++ docs/installation.md | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/compose.yaml b/compose.yaml index f83b329..6e367ea 100644 --- a/compose.yaml +++ b/compose.yaml @@ -9,6 +9,9 @@ services: - "${ROBOROCK_SERVER_HTTPS_PORT:-555}:${ROBOROCK_SERVER_HTTPS_PORT:-555}" - "${ROBOROCK_SERVER_MQTT_TLS_PORT:-8881}:${ROBOROCK_SERVER_MQTT_TLS_PORT:-8881}" volumes: + # Remove this line if you're generating config.toml from ROBOROCK_SERVER_* + # env vars instead of running `configure` first — see the "Environment + # Variables Only" section in docs/installation.md. - ./config.toml:/app/config.toml:ro - ./data:/data - ./secrets:/run/secrets:ro diff --git a/docs/installation.md b/docs/installation.md index b933197..77e7a57 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -139,6 +139,34 @@ If your model already has certificate notes on the tested-vacuums page, follow t For reverse proxy setups, keep `network.https_port` and `network.mqtt_tls_port` set to the backend listener ports and use `network.advertised_https_port` / `network.advertised_mqtt_tls_port` for the public ports. +### Alternative: Environment Variables Only (No `uv` Toolchain) + +If you don't want to install `uv`/Python on the host just to run `configure`, you can set `ROBOROCK_SERVER_*` environment variables instead. On first boot, if `/data/config.toml` doesn't already exist, the container generates one from these variables and starts normally. If `config.toml` already exists (mounted or previously generated), it always wins and the env vars are ignored — this never overwrites a config you've already set up. + +Required variables: + +- `ROBOROCK_SERVER_STACK_FQDN` +- `ROBOROCK_SERVER_ADMIN_PASSWORD` +- `ROBOROCK_SERVER_PROTOCOL_LOGIN_EMAIL` +- `ROBOROCK_SERVER_PROTOCOL_LOGIN_PIN` (6 digits) +- Either `ROBOROCK_SERVER_CERT_FILE` + `ROBOROCK_SERVER_KEY_FILE` (bring your own certificate), or `ROBOROCK_SERVER_TLS_MODE=cloudflare_acme` + `ROBOROCK_SERVER_TLS_BASE_DOMAIN` + `ROBOROCK_SERVER_TLS_EMAIL` + `ROBOROCK_SERVER_CLOUDFLARE_TOKEN` (or `_CLOUDFLARE_TOKEN_FILE` for a Docker secret) + +Commonly-set optional variables: `ROBOROCK_SERVER_HTTPS_PORT`, `ROBOROCK_SERVER_MQTT_TLS_PORT`, `ROBOROCK_SERVER_ADVERTISED_HTTPS_PORT`, `ROBOROCK_SERVER_ADVERTISED_MQTT_TLS_PORT`, `ROBOROCK_SERVER_LISTENER_MODE`, `ROBOROCK_SERVER_BROKER_MODE` + `ROBOROCK_SERVER_BROKER_HOST`. See `env_config.py` for the full list. + +**Important:** if you go this route, remove (or comment out) the `./config.toml:/app/config.toml:ro` line from `compose.yaml`. Docker will otherwise bind-mount a nonexistent host path as an empty file, which the container treats as an existing (but invalid) config and never falls through to the env vars. Keep the `./data:/data` and `./secrets:/run/secrets:ro` mounts. + +```bash +export ROBOROCK_SERVER_STACK_FQDN=api-roborock.example.com +export ROBOROCK_SERVER_ADMIN_PASSWORD=super-secret-password +export ROBOROCK_SERVER_PROTOCOL_LOGIN_EMAIL=user@example.com +export ROBOROCK_SERVER_PROTOCOL_LOGIN_PIN=123456 +export ROBOROCK_SERVER_TLS_MODE=cloudflare_acme +export ROBOROCK_SERVER_TLS_BASE_DOMAIN=example.com +export ROBOROCK_SERVER_TLS_EMAIL=acme@example.com +export ROBOROCK_SERVER_CLOUDFLARE_TOKEN=your-cloudflare-api-token +docker compose up -d --build +``` + ## Method 2: Home Assistant Add-on Use [Home Assistant](home_assistant.md) as the installation guide if you want to run the stack as a Home Assistant add-on instead of Docker Compose. From ba68a415bd5d0b3e9145bb0001a23f74ca1f23e2 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 27 Sep 2026 10:37:07 -0400 Subject: [PATCH 04/32] Let configure answers carry an external broker host The CLI wizard has always left broker.host blank for external brokers, requiring a manual config.toml edit afterward. Add an optional ConfigureAnswers.broker_host so callers that already have the host (the upcoming web setup wizard) can write a ready-to-serve config in one step; the CLI wizard's own behavior is unchanged since it still passes broker_host="". Co-Authored-By: Claude Sonnet 5 (cherry picked from commit 017e9e0a0d38a74c74cf973ad5817137a43caa63) --- src/roborock_local_server/configure.py | 13 ++++++++++--- tests/test_configure.py | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/roborock_local_server/configure.py b/src/roborock_local_server/configure.py index d830acf..7cf4652 100644 --- a/src/roborock_local_server/configure.py +++ b/src/roborock_local_server/configure.py @@ -46,6 +46,7 @@ class ConfigureAnswers: https_port: int mqtt_tls_port: int broker_mode: str + broker_host: str tls_mode: str base_domain: str email: str @@ -227,6 +228,7 @@ def _validated_answers(answers: ConfigureAnswers) -> ConfigureAnswers: https_port=answers.https_port, mqtt_tls_port=answers.mqtt_tls_port, broker_mode=answers.broker_mode, + broker_host=answers.broker_host, tls_mode=answers.tls_mode, base_domain=answers.base_domain, email=answers.email, @@ -282,6 +284,7 @@ def collect_configure_answers() -> ConfigureAnswers: https_port=https_port, mqtt_tls_port=mqtt_tls_port, broker_mode=broker_mode, + broker_host="", tls_mode=tls_mode, base_domain=base_domain, email=email, @@ -322,8 +325,12 @@ def render_config_toml(answers: ConfigureAnswers) -> str: else: lines.extend( [ - "# Fill this in with your existing MQTT broker hostname or IP before starting the stack.", - 'host = ""', + *( + ["# Fill this in with your existing MQTT broker hostname or IP before starting the stack."] + if not answers.broker_host + else [] + ), + f"host = {_toml_string(answers.broker_host)}", "port = 1883", 'mosquitto_binary = "mosquitto"', "enable_topic_bridge = true", @@ -448,7 +455,7 @@ def write_config_setup( cloudflare_token_file=written_token_path, actalis_eab_kid_file=written_actalis_kid_path, actalis_eab_hmac_key_file=written_actalis_hmac_path, - broker_template_needs_edit=answers.broker_mode == "external", + broker_template_needs_edit=answers.broker_mode == "external" and not answers.broker_host, ) diff --git a/tests/test_configure.py b/tests/test_configure.py index 31a9d3d..85bc1b0 100644 --- a/tests/test_configure.py +++ b/tests/test_configure.py @@ -12,6 +12,7 @@ def _answers( https_port: int = 555, mqtt_tls_port: int = 8881, broker_mode: str = "embedded", + broker_host: str = "", tls_mode: str = "cloudflare_acme", acme_server: str = "zerossl", acme_eab_kid: str = "", @@ -22,6 +23,7 @@ def _answers( https_port=https_port, mqtt_tls_port=mqtt_tls_port, broker_mode=broker_mode, + broker_host=broker_host, tls_mode=tls_mode, base_domain="example.com" if tls_mode == "cloudflare_acme" else "", email="you@example.com" if tls_mode == "cloudflare_acme" else "", @@ -85,6 +87,23 @@ def test_write_config_setup_external_broker_requires_host_before_serve(tmp_path: load_config(config_file) +def test_write_config_setup_external_broker_with_host_needs_no_manual_edit(tmp_path: Path) -> None: + config_file = tmp_path / "config.toml" + + result = write_config_setup( + config_file=config_file, + answers=_answers(broker_mode="external", broker_host="mqtt.internal", tls_mode="provided"), + ) + + assert not result.broker_template_needs_edit + rendered = config_file.read_text(encoding="utf-8") + assert 'host = "mqtt.internal"' in rendered + assert "# Fill this in" not in rendered + + config = load_config(config_file) + assert config.broker.host == "mqtt.internal" + + def test_write_config_setup_refuses_overwrite_without_force(tmp_path: Path) -> None: config_file = tmp_path / "config.toml" write_config_setup(config_file=config_file, answers=_answers()) From 7b1036ab3379d6fd864ba229fbecdcc1123273e3 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 27 Sep 2026 10:50:57 -0400 Subject: [PATCH 05/32] Add the bootstrap /admin setup wizard New always-reachable /admin: when config.toml doesn't exist yet, it serves a browser-based setup wizard (the same fields as `configure`, reusing write_config_setup so both paths produce identical output) over plain HTTP on the same https_port the real stack uses once configured. Once ReleaseSupervisor's own TLS'd /admin takes over that port after a restart, this is out of the picture entirely - there is never a second, separate admin surface running at the same time. Co-Authored-By: Claude Sonnet 5 (cherry picked from commit 3db3e9625ed0aa9bc4b6393b53d33e15b6067c29) --- src/roborock_local_server/management_app.py | 326 ++++++++++++++++++++ tests/test_management_app.py | 149 +++++++++ 2 files changed, 475 insertions(+) create mode 100644 src/roborock_local_server/management_app.py create mode 100644 tests/test_management_app.py diff --git a/src/roborock_local_server/management_app.py b/src/roborock_local_server/management_app.py new file mode 100644 index 0000000..5177832 --- /dev/null +++ b/src/roborock_local_server/management_app.py @@ -0,0 +1,326 @@ +"""Bootstrap /admin app, served before config.toml exists. + +There's only one admin surface, at /admin. Before setup, this app serves the +Setup Wizard in plain HTTP on the same https_port the real stack will use +once configured (it can't depend on anything that requires a config - TLS +certs, ReleaseSupervisor, admin auth). Once the wizard writes config.toml, +the process restarts and ReleaseSupervisor's own /admin (standalone_admin.py, +with TLS if local_tls) takes over that same port for good. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +import json +from pathlib import Path +import secrets +from textwrap import dedent +from typing import Any + +from fastapi import FastAPI, Request +from fastapi.responses import HTMLResponse, JSONResponse + +from .configure import ( + ConfigureAnswers, + _normalize_acme_server, + _normalize_hostname, + _validate_protocol_login_pin, + hash_password, + write_config_setup, +) + +DEFAULT_BOOTSTRAP_HTTPS_PORT = 555 +_ENV_HTTPS_PORT = "ROBOROCK_SERVER_HTTPS_PORT" + + +def bootstrap_port_from_env(env: Mapping[str, str]) -> int: + """The port the setup wizard listens on, before config.toml sets https_port. + + Reuses ROBOROCK_SERVER_HTTPS_PORT, the same env var already used for the + Docker Compose port mapping, so there's one port/one env var either way. + """ + raw_value = str(env.get(_ENV_HTTPS_PORT, "") or "").strip() + if not raw_value: + return DEFAULT_BOOTSTRAP_HTTPS_PORT + try: + port = int(raw_value) + except ValueError as exc: + raise ValueError(f"{_ENV_HTTPS_PORT} must be an integer") from exc + if not (1 <= port <= 65535): + raise ValueError(f"{_ENV_HTTPS_PORT} must be between 1 and 65535") + return port + + +def _as_port(value: Any, *, field_name: str, default: int) -> int: + if value in (None, ""): + return default + try: + candidate = int(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"{field_name} must be an integer") from exc + if not (1 <= candidate <= 65535): + raise ValueError(f"{field_name} must be between 1 and 65535") + return candidate + + +def _answers_from_payload(body: Mapping[str, Any]) -> ConfigureAnswers: + def s(key: str, default: str = "") -> str: + return str(body.get(key, default) or "").strip() + + stack_fqdn = _normalize_hostname(s("stack_fqdn"), field_name="stack_fqdn", require_api_prefix=True) + https_port = _as_port(body.get("https_port"), field_name="https_port", default=555) + mqtt_tls_port = _as_port(body.get("mqtt_tls_port"), field_name="mqtt_tls_port", default=8881) + + broker_mode = s("broker_mode", "embedded").lower() + if broker_mode not in {"embedded", "external"}: + raise ValueError("broker_mode must be 'embedded' or 'external'") + broker_host = s("broker_host") + if broker_mode == "external" and not broker_host: + raise ValueError("broker_host is required when broker_mode is 'external'") + + tls_mode = s("tls_mode", "cloudflare_acme").lower() + if tls_mode not in {"cloudflare_acme", "provided"}: + raise ValueError("tls_mode must be 'cloudflare_acme' or 'provided'") + + base_domain = "" + email = "" + acme_server = "zerossl" + acme_eab_kid = "" + acme_eab_hmac_key = "" + cloudflare_token = "" + if tls_mode == "cloudflare_acme": + base_domain = _normalize_hostname(s("base_domain"), field_name="base_domain") + email = s("email") + if not email: + raise ValueError("email is required") + acme_server = _normalize_acme_server(s("acme_server", "zerossl")) + cloudflare_token = s("cloudflare_token") + if not cloudflare_token: + raise ValueError("cloudflare_token is required") + if acme_server == "actalis": + acme_eab_kid = s("acme_eab_kid") + acme_eab_hmac_key = s("acme_eab_hmac_key") + if not acme_eab_kid or not acme_eab_hmac_key: + raise ValueError("Actalis requires both acme_eab_kid and acme_eab_hmac_key") + + admin_password = s("admin_password") + if not admin_password: + raise ValueError("admin_password is required") + protocol_login_email = s("protocol_login_email") + if "@" not in protocol_login_email: + raise ValueError("protocol_login_email must be an email address") + protocol_login_pin = _validate_protocol_login_pin(s("protocol_login_pin")) + + return ConfigureAnswers( + stack_fqdn=stack_fqdn, + https_port=https_port, + mqtt_tls_port=mqtt_tls_port, + broker_mode=broker_mode, + broker_host=broker_host, + tls_mode=tls_mode, + base_domain=base_domain, + email=email, + acme_server=acme_server, + acme_eab_kid=acme_eab_kid, + acme_eab_hmac_key=acme_eab_hmac_key, + cloudflare_token=cloudflare_token, + password_hash=hash_password(admin_password), + session_secret=secrets.token_urlsafe(32), + protocol_login_email=protocol_login_email, + protocol_login_pin_hash=hash_password(protocol_login_pin), + ) + + +def _status_html() -> str: + return dedent( + """\ + +

Roborock Local Server

+

Setup is complete. The stack is restarting into the full dashboard at this same address - + reload in a few seconds.

+ + """ + ) + + +def _setup_wizard_html() -> str: + return dedent( + """\ + + Roborock Local Server Setup + + +

Roborock Local Server Setup

+

This runs once, the first time the stack boots without a config.toml. Fill this in, submit, and the + container will restart into the full HTTPS/MQTT stack.

+
+
+ Network + +
+
+
+
+
+ +
+ MQTT Broker + + + +
+ +
+ Certificates + + +
+ + + + + +
+ +
+ +
+ Admin Access + + +
+ +
+ App / Home Assistant Login + + + +
+ + +
+

+        
+        
+        
+        """
+    )
+
+
+def create_management_app(
+    *,
+    config_file: Path,
+    on_configured: Callable[[], None] | None = None,
+) -> FastAPI:
+    app = FastAPI(title="Roborock Local Server Setup", docs_url=None, redoc_url=None, openapi_url=None)
+
+    @app.get("/", response_class=HTMLResponse)
+    @app.get("/admin", response_class=HTMLResponse)
+    async def index() -> HTMLResponse:
+        return HTMLResponse(_status_html() if config_file.exists() else _setup_wizard_html())
+
+    @app.get("/admin/api/setup/status")
+    async def setup_status() -> JSONResponse:
+        return JSONResponse({"configured": config_file.exists()})
+
+    @app.post("/admin/api/setup")
+    async def submit_setup(request: Request) -> JSONResponse:
+        if config_file.exists():
+            return JSONResponse({"error": "Already configured."}, status_code=409)
+        try:
+            raw_body = await request.body()
+            body = json.loads(raw_body or b"{}")
+            if not isinstance(body, dict):
+                raise ValueError("Request body must be a JSON object.")
+            answers = _answers_from_payload(body)
+            result = write_config_setup(config_file=config_file, answers=answers)
+        except (ValueError, FileExistsError) as exc:
+            return JSONResponse({"error": str(exc)}, status_code=400)
+        if on_configured is not None:
+            on_configured()
+        return JSONResponse({"ok": True, "config_file": str(result.config_file)})
+
+    return app
diff --git a/tests/test_management_app.py b/tests/test_management_app.py
new file mode 100644
index 0000000..d805a07
--- /dev/null
+++ b/tests/test_management_app.py
@@ -0,0 +1,149 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from fastapi.testclient import TestClient
+import pytest
+
+from roborock_local_server.config import load_config
+from roborock_local_server.management_app import (
+    DEFAULT_BOOTSTRAP_HTTPS_PORT,
+    bootstrap_port_from_env,
+    create_management_app,
+)
+
+_VALID_PAYLOAD = {
+    "stack_fqdn": "api-roborock.example.com",
+    "https_port": 555,
+    "mqtt_tls_port": 8881,
+    "broker_mode": "embedded",
+    "tls_mode": "provided",
+    "admin_password": "super-secret-password",
+    "protocol_login_email": "user@example.com",
+    "protocol_login_pin": "123456",
+}
+
+
+def test_bootstrap_port_from_env_default() -> None:
+    assert bootstrap_port_from_env({}) == DEFAULT_BOOTSTRAP_HTTPS_PORT
+
+
+def test_bootstrap_port_from_env_reuses_https_port_var() -> None:
+    assert bootstrap_port_from_env({"ROBOROCK_SERVER_HTTPS_PORT": "9090"}) == 9090
+
+
+def test_bootstrap_port_from_env_rejects_bad_value() -> None:
+    with pytest.raises(ValueError, match="must be an integer"):
+        bootstrap_port_from_env({"ROBOROCK_SERVER_HTTPS_PORT": "not-a-port"})
+
+
+def test_index_serves_setup_wizard_when_unconfigured(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    client = TestClient(create_management_app(config_file=config_file))
+
+    response = client.get("/")
+
+    assert response.status_code == 200
+    assert "Roborock Local Server Setup" in response.text
+
+
+def test_index_serves_status_page_when_configured(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    config_file.write_text("already = true\n", encoding="utf-8")
+    client = TestClient(create_management_app(config_file=config_file))
+
+    response = client.get("/")
+
+    assert response.status_code == 200
+    assert "Setup is complete" in response.text
+
+
+def test_setup_status_reflects_config_existence(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    client = TestClient(create_management_app(config_file=config_file))
+
+    assert client.get("/admin/api/setup/status").json() == {"configured": False}
+
+    config_file.write_text("done = true\n", encoding="utf-8")
+    assert client.get("/admin/api/setup/status").json() == {"configured": True}
+
+
+def test_submit_setup_writes_bootable_config(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    calls: list[str] = []
+    client = TestClient(create_management_app(config_file=config_file, on_configured=lambda: calls.append("done")))
+
+    response = client.post("/admin/api/setup", json=_VALID_PAYLOAD)
+
+    assert response.status_code == 200
+    assert response.json()["ok"] is True
+    assert calls == ["done"]
+
+    config = load_config(config_file)
+    assert config.network.stack_fqdn == "api-roborock.example.com"
+    assert config.admin.protocol_login_email == "user@example.com"
+
+
+def test_submit_setup_with_external_broker_needs_no_manual_edit(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    client = TestClient(create_management_app(config_file=config_file))
+    payload = dict(_VALID_PAYLOAD, broker_mode="external", broker_host="mqtt.internal")
+
+    response = client.post("/admin/api/setup", json=payload)
+
+    assert response.status_code == 200
+    config = load_config(config_file)
+    assert config.broker.mode == "external"
+    assert config.broker.host == "mqtt.internal"
+
+
+def test_submit_setup_rejects_missing_external_broker_host(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    client = TestClient(create_management_app(config_file=config_file))
+    payload = dict(_VALID_PAYLOAD, broker_mode="external")
+
+    response = client.post("/admin/api/setup", json=payload)
+
+    assert response.status_code == 400
+    assert "broker_host" in response.json()["error"]
+    assert config_file.exists() is False
+
+
+def test_submit_setup_rejects_bad_stack_fqdn(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    client = TestClient(create_management_app(config_file=config_file))
+    payload = dict(_VALID_PAYLOAD, stack_fqdn="roborock.example.com")
+
+    response = client.post("/admin/api/setup", json=payload)
+
+    assert response.status_code == 400
+    assert "must start with api-" in response.json()["error"]
+
+
+def test_submit_setup_refuses_to_overwrite_existing_config(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    config_file.write_text("existing = true\n", encoding="utf-8")
+    client = TestClient(create_management_app(config_file=config_file))
+
+    response = client.post("/admin/api/setup", json=_VALID_PAYLOAD)
+
+    assert response.status_code == 409
+    assert config_file.read_text(encoding="utf-8") == "existing = true\n"
+
+
+def test_submit_setup_cloudflare_actalis_requires_eab(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    client = TestClient(create_management_app(config_file=config_file))
+    payload = dict(
+        _VALID_PAYLOAD,
+        tls_mode="cloudflare_acme",
+        base_domain="example.com",
+        email="acme@example.com",
+        cloudflare_token="cf-token",
+        acme_server="actalis",
+    )
+
+    response = client.post("/admin/api/setup", json=payload)
+
+    assert response.status_code == 400
+    assert "Actalis" in response.json()["error"]

From 5d669462cc78c8ea497ee5bc8365c1397a6db217 Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Sun, 27 Sep 2026 10:51:03 -0400
Subject: [PATCH 06/32] Fall into the setup wizard when config.toml is missing
 or invalid

run_server() now catches load_config() failures (missing file, bad
TOML, failed validation) and serves only the bootstrap /admin wizard
instead of crashing, exiting once the wizard writes a config so
Docker's restart policy brings up the full stack. The container
entrypoint no longer errors out when no config source is found at all
- it always execs into serve, which now handles that case gracefully.

Co-Authored-By: Claude Sonnet 5 
(cherry picked from commit 3146e373ca34582853a5d3fa16a054e0ea5bb2d7)
---
 .../container_entrypoint.py                   | 18 ++----
 src/roborock_local_server/server.py           | 55 ++++++++++++++++-
 tests/test_container_entrypoint.py            | 60 ++-----------------
 3 files changed, 64 insertions(+), 69 deletions(-)

diff --git a/src/roborock_local_server/container_entrypoint.py b/src/roborock_local_server/container_entrypoint.py
index ba8a9a7..518bbaf 100644
--- a/src/roborock_local_server/container_entrypoint.py
+++ b/src/roborock_local_server/container_entrypoint.py
@@ -29,19 +29,11 @@ def _run_entrypoint(*, compose_config: Path, data_config: Path, addon_options: P
         _exec_server(data_config)
         return
 
-    if data_config.exists():
-        _exec_server(data_config)
-        return
-
-    if has_env_config(os.environ):
-        write_config_from_env(os.environ, config_path=data_config)
-        _exec_server(data_config)
-        return
-
-    raise SystemExit(
-        "No config file found. Expected /app/config.toml, /data/config.toml, /data/options.json, "
-        "or ROBOROCK_SERVER_* environment variables (see docs/installation.md)."
-    )
+    # No config anywhere yet. `serve` itself now handles this: it serves the
+    # setup wizard on the management port until /data/config.toml exists,
+    # then a container restart (Docker's restart policy) picks up the full
+    # stack once the wizard writes it.
+    _exec_server(data_config)
 
 
 def main() -> int:
diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py
index 105a2aa..a9a2205 100644
--- a/src/roborock_local_server/server.py
+++ b/src/roborock_local_server/server.py
@@ -9,6 +9,7 @@
 import hashlib
 import json
 import logging
+import os
 from pathlib import Path
 import secrets
 import signal
@@ -31,6 +32,7 @@
 from .cloud import CloudImportManager
 from .config import AppConfig, AppPaths, load_config, resolve_paths
 from .log_retention import configure_jsonl_logging
+from .management_app import bootstrap_port_from_env, create_management_app
 from .turn_relay import EmbeddedTurnRelay
 from .standalone_admin import register_standalone_admin_routes
 from .backend import (
@@ -2049,8 +2051,59 @@ def request_shutdown() -> None:
         return 0
 
 
+async def _run_setup_wizard_only(*, config_file: Path) -> int:
+    """Serve only /admin's setup wizard, in plain HTTP, until config.toml exists.
+
+    Listens on the same https_port the real stack will use once configured
+    (ROBOROCK_SERVER_HTTPS_PORT, same env var as the compose port mapping).
+    Exits (0) once the wizard writes a config, or on SIGINT/SIGTERM. Either
+    way, Docker's restart policy is what brings the full stack - and its own
+    TLS'd /admin - up on the next boot, once load_config() succeeds.
+    """
+    logger = logging.getLogger(__name__)
+    port = bootstrap_port_from_env(os.environ)
+    stop_event = asyncio.Event()
+    configured_event = asyncio.Event()
+
+    app = create_management_app(config_file=config_file, on_configured=configured_event.set)
+    bootstrap_server = ManagedFastApiServer(
+        app=app,
+        bind_host="0.0.0.0",
+        port=port,
+        tls_enabled=False,
+    )
+    await bootstrap_server.start()
+    logger.warning(
+        "%s not found. Open http://:%d/admin to finish setup.",
+        config_file,
+        port,
+    )
+
+    def request_shutdown() -> None:
+        stop_event.set()
+
+    loop = asyncio.get_running_loop()
+    for sig in (signal.SIGINT, signal.SIGTERM):
+        try:
+            loop.add_signal_handler(sig, request_shutdown)
+        except NotImplementedError:
+            pass
+
+    await asyncio.wait(
+        {asyncio.create_task(stop_event.wait()), asyncio.create_task(configured_event.wait())},
+        return_when=asyncio.FIRST_COMPLETED,
+    )
+    await bootstrap_server.stop()
+    return 0
+
+
 async def run_server(*, config_file: Path, enable_standalone_admin: bool = True) -> int:
-    config = load_config(config_file)
+    try:
+        config = load_config(config_file)
+    except (OSError, ValueError) as exc:
+        logging.getLogger(__name__).warning("Could not load %s: %s", config_file, exc)
+        return await _run_setup_wizard_only(config_file=config_file)
+
     paths = resolve_paths(config_file, config)
     supervisor = ReleaseSupervisor(
         config=config,
diff --git a/tests/test_container_entrypoint.py b/tests/test_container_entrypoint.py
index 424c64f..efd8262 100644
--- a/tests/test_container_entrypoint.py
+++ b/tests/test_container_entrypoint.py
@@ -67,27 +67,24 @@ def test_run_entrypoint_prefers_compose_config_when_present(
     assert calls == [compose_config]
 
 
-def test_run_entrypoint_prefers_existing_data_config_over_env_vars(
+def test_run_entrypoint_execs_server_even_without_any_config_present(
     tmp_path: Path,
     monkeypatch: pytest.MonkeyPatch,
 ) -> None:
+    # No config source at all, and no ROBOROCK_SERVER_* env vars either: the
+    # entrypoint no longer errors out here, since `serve` now falls into the
+    # Setup Wizard for exactly this case.
     compose_config = tmp_path / "app-config.toml"
     data_config = tmp_path / "data-config.toml"
     addon_options = tmp_path / "options.json"
-    data_config.write_text("existing = true\n", encoding="utf-8")
+    monkeypatch.delenv("ROBOROCK_SERVER_STACK_FQDN", raising=False)
 
-    monkeypatch.setenv("ROBOROCK_SERVER_STACK_FQDN", "api-roborock.example.com")
     calls: list[Path] = []
     monkeypatch.setattr(
         container_entrypoint,
         "_exec_server",
         lambda config_path: calls.append(config_path),
     )
-    monkeypatch.setattr(
-        container_entrypoint,
-        "write_config_from_env",
-        lambda *args, **kwargs: pytest.fail("should not regenerate an existing config.toml"),
-    )
 
     container_entrypoint._run_entrypoint(
         compose_config=compose_config,
@@ -96,50 +93,3 @@ def test_run_entrypoint_prefers_existing_data_config_over_env_vars(
     )
 
     assert calls == [data_config]
-
-
-def test_run_entrypoint_generates_config_from_env_vars(
-    tmp_path: Path,
-    monkeypatch: pytest.MonkeyPatch,
-) -> None:
-    compose_config = tmp_path / "app-config.toml"
-    data_config = tmp_path / "data-config.toml"
-    addon_options = tmp_path / "options.json"
-
-    monkeypatch.setenv("ROBOROCK_SERVER_STACK_FQDN", "api-roborock.example.com")
-    calls: list[tuple[str, Path]] = []
-    monkeypatch.setattr(
-        container_entrypoint,
-        "write_config_from_env",
-        lambda env, *, config_path: calls.append(("write", config_path)),
-    )
-    monkeypatch.setattr(
-        container_entrypoint,
-        "_exec_server",
-        lambda config_path: calls.append(("exec", config_path)),
-    )
-
-    container_entrypoint._run_entrypoint(
-        compose_config=compose_config,
-        data_config=data_config,
-        addon_options=addon_options,
-    )
-
-    assert calls == [("write", data_config), ("exec", data_config)]
-
-
-def test_run_entrypoint_errors_without_config_or_env_vars(
-    tmp_path: Path,
-    monkeypatch: pytest.MonkeyPatch,
-) -> None:
-    compose_config = tmp_path / "app-config.toml"
-    data_config = tmp_path / "data-config.toml"
-    addon_options = tmp_path / "options.json"
-    monkeypatch.delenv("ROBOROCK_SERVER_STACK_FQDN", raising=False)
-
-    with pytest.raises(SystemExit):
-        container_entrypoint._run_entrypoint(
-            compose_config=compose_config,
-            data_config=data_config,
-            addon_options=addon_options,
-        )

From ba11c8bf9dc8fdd07edd7cf543c5d1e807e2c83d Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Sun, 27 Sep 2026 10:51:08 -0400
Subject: [PATCH 07/32] Document the browser-based setup wizard as an
 alternative to the CLI

Co-Authored-By: Claude Sonnet 5 
(cherry picked from commit e0e3dd0ec75d5c6e2145779a4056398196149a3a)
---
 docs/installation.md | 19 ++++++++++++++-----
 1 file changed, 14 insertions(+), 5 deletions(-)

diff --git a/docs/installation.md b/docs/installation.md
index 77e7a57..499b64a 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -92,11 +92,20 @@ If your model already has certificate notes on the tested-vacuums page, follow t
    uv sync
    ```
 
-3. Run the setup wizard:
+3. Run the setup wizard.
 
-   ```bash
-   uv run roborock-local-server configure
-   ```
+   You have two options here, and they write the same `config.toml`:
+
+   - **In your browser (no `uv`/Python needed on the host):** skip straight to step 6 and start the container
+     with no `config.toml` present. It boots into a setup wizard, served in plain HTTP at `/admin` on your
+     configured HTTPS port (`http://:555/admin` by default), that asks for the same fields as the
+     CLI wizard below. Submitting it writes `config.toml`, and the container restarts itself into the full
+     HTTPS/MQTT stack - reload the page after a few seconds and you're at the real (now HTTPS) admin login.
+   - **On the command line:**
+
+     ```bash
+     uv run roborock-local-server configure
+     ```
 
    The wizard asks for:
 
@@ -111,7 +120,7 @@ If your model already has certificate notes on the tested-vacuums page, follow t
 
    It then writes `config.toml`, generates `admin.password_hash` and `admin.session_secret`, and if you chose Cloudflare it also writes `secrets/cloudflare_token`. If you also chose `acme_server = actalis`, it writes `secrets/acme_eab_kid` and `secrets/acme_eab_hmac_key`.
 
-4. If you chose external MQTT, fill in `broker.host` in `config.toml` before starting the stack. See [Custom MQTT](custom_mqtt.md).
+4. If you chose external MQTT with the CLI wizard, fill in `broker.host` in `config.toml` before starting the stack (the browser wizard asks for the broker host directly, so this step doesn't apply there). See [Custom MQTT](custom_mqtt.md).
 
 5. If you skipped Cloudflare, put your certificate files in `data/certs/fullchain.pem` and `data/certs/privkey.pem` (relative to the repository root on the host, which maps to `/data/certs/` inside the container). This is the path to use when your vacuum works better with a certificate chain you manage yourself. See [Custom certificate management](custom_cert_management.md).
 

From 0e8fb81604a3d971c1b04ab35c83cedabac5f72b Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Sun, 27 Sep 2026 11:00:15 -0400
Subject: [PATCH 08/32] Point reverse-proxy users at the env-var config path

Neither the CLI configure wizard nor the browser Setup Wizard can
generate listener_mode, advertised_*_port, or trusted_proxies - they
only produce the simple local_tls case. Those are exactly the
deployment-topology settings the ROBOROCK_SERVER_* env vars already
cover (external_tls, advertised ports, trusted proxies), so a
SWAG/Caddy/Traefik reverse-proxy setup needs no manual config.toml
edits: just set the equivalent env vars instead of running either
wizard.

Co-Authored-By: Claude Sonnet 5 
(cherry picked from commit e7cb4201072e18da79dcd768c3d43a94d09c4e4a)
---
 docs/reverse_proxy.md | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/docs/reverse_proxy.md b/docs/reverse_proxy.md
index 4f42c6b..19abe17 100644
--- a/docs/reverse_proxy.md
+++ b/docs/reverse_proxy.md
@@ -1,6 +1,8 @@
 # Reverse Proxy
 
-Reverse proxy support is mainly useful when public or LAN clients reach the stack on different ports than the backend listeners, or when you already run a proxy (Caddy, Traefik, nginx) that owns your TLS certificates. I do not use a reverse proxy for my own setup, so please report any issues.
+Reverse proxy support is mainly useful when public or LAN clients reach the stack on different ports than the backend listeners, or when you already run a proxy (Caddy, Traefik, nginx, SWAG) that owns your TLS certificates. I do not use a reverse proxy for my own setup, so please report any issues.
+
+> **Neither the `configure` CLI wizard nor the browser Setup Wizard (`/admin` on first boot) can generate `listener_mode`, `advertised_*_port`, or `trusted_proxies` today** — they only produce the simple `local_tls` case. If your setup needs any of the settings on this page (which it will, for a proxy like SWAG that terminates TLS itself), generate `config.toml` from `ROBOROCK_SERVER_*` environment variables instead (see [Installation](installation.md)) - that path covers everything below directly, with no manual `config.toml` edits needed. The TOML shown on this page is what those env vars produce; it's included so you can see (or hand-edit) the result either way.
 
 Whatever endpoint a vacuum or the Roborock app connects to **must present a valid, trusted TLS certificate** — vacuums refuse to connect otherwise. That endpoint can be the server itself or the proxy in front of it; the rest of this page is about choosing which one terminates TLS.
 
@@ -29,6 +31,8 @@ With that config the server listens on `*:555` / `*:8881`, but responses adverti
 - `https://api-roborock.example.com`
 - `ssl://api-roborock.example.com:8883`
 
+Equivalent env vars: `ROBOROCK_SERVER_ADVERTISED_HTTPS_PORT=443`, `ROBOROCK_SERVER_ADVERTISED_MQTT_TLS_PORT=8883`.
+
 ## TLS Termination Modes
 
 ### `local_tls` (default) — the server terminates TLS
@@ -60,6 +64,8 @@ listener_mode = "external_tls"
 mode = "provided"
 ```
 
+Equivalent env vars: `ROBOROCK_SERVER_LISTENER_MODE=external_tls`, `ROBOROCK_SERVER_TLS_MODE=provided`.
+
 Requirements:
 
 - HTTPS: the proxy terminates TLS, preserves the original `Host` header, and forwards plain HTTP to `https_port`.
@@ -133,6 +139,8 @@ List every proxy or SNAT address that forwards traffic to the server in `trusted
 trusted_proxies = ["10.42.0.0/16", "10.1.1.10"]
 ```
 
+Equivalent env var: `ROBOROCK_SERVER_TRUSTED_PROXIES=10.42.0.0/16,10.1.1.10` (comma-separated).
+
 - **HTTP:** requests from a trusted proxy use the `X-Forwarded-For` header to find the vacuum's real IP. The header is ignored from any other client, so it can't be spoofed. Traefik and Caddy set it by default; nginx needs `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`.
 - **MQTT:** during an active onboarding session, a new MQTT login is normally accepted only from the IP that completed `/region` and `/nc`. A connection from a trusted proxy is also accepted, because a stream proxy hides the vacuum's address. The session must still have completed `/region` and `/nc`, and the first publish must be on that vacuum's topic.
 

From c36500f52637c549681b68285f2213154faddb21 Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Sun, 27 Sep 2026 11:14:27 -0400
Subject: [PATCH 09/32] Make the [admin] env vars optional as a group

STACK_FQDN plus network/broker/tls env vars alone now produce a valid
partial config.toml with no [admin] section, so a deployment can set
just the infra/TLS side (including external_tls reverse-proxy setups)
and finish credentials in the Setup Wizard - rather than requiring all
of ADMIN_PASSWORD/PROTOCOL_LOGIN_EMAIL/PROTOCOL_LOGIN_PIN up front or
not being able to use env vars at all. Setting some but not all three
is rejected with a clear error, since a half-set credential is never
what was intended.

Co-Authored-By: Claude Sonnet 5 
(cherry picked from commit 15bddb9d514268ab0d399976956bf53606e70d7d)
---
 src/roborock_local_server/env_config.py | 82 +++++++++++++++----------
 tests/test_env_config.py                | 30 ++++++++-
 2 files changed, 79 insertions(+), 33 deletions(-)

diff --git a/src/roborock_local_server/env_config.py b/src/roborock_local_server/env_config.py
index 0c406c8..12758d3 100644
--- a/src/roborock_local_server/env_config.py
+++ b/src/roborock_local_server/env_config.py
@@ -3,9 +3,14 @@
 This lets Docker Compose (and similar) deployments boot straight from
 environment variables, without running the host-side `configure` wizard
 first. It intentionally covers only the deployment/infrastructure-shaped
-settings (network, broker, storage, tls) plus the admin credentials needed
-to produce a bootable config; it is not meant to grow a variable for every
-config.toml key.
+settings (network, broker, storage, tls); it is not meant to grow a
+variable for every config.toml key.
+
+The [admin] credentials (password, protocol login email/PIN) are optional
+as a group: set none of them and the container boots straight into the
+Setup Wizard (/admin) with network/broker/storage/tls already filled in
+from these env vars - only the credentials are still asked for. Set all
+of them for a fully headless boot with no browser step at all.
 """
 
 from __future__ import annotations
@@ -263,20 +268,21 @@ def render_config_toml_from_env(
             cert_file = _require_non_empty(_get(env, "CERT_FILE"), field_name="CERT_FILE")
             key_file = _require_non_empty(_get(env, "KEY_FILE"), field_name="KEY_FILE")
 
-    admin_password = _require_non_empty(_get(env, "ADMIN_PASSWORD"), field_name="ADMIN_PASSWORD")
-    admin_session_secret = (
-        _get(env, "ADMIN_SESSION_SECRET")
-        or _load_existing_admin_session_secret(config_path)
-        or secrets.token_urlsafe(32)
-    )
-    if len(admin_session_secret) < 24:
-        raise ValueError(f"{ENV_PREFIX}ADMIN_SESSION_SECRET must be at least 24 characters when set")
-    new_connections_enabled = _as_bool(_get(env, "NEW_CONNECTIONS_ENABLED"), default=True)
-    protocol_login_email = _require_email(_get(env, "PROTOCOL_LOGIN_EMAIL"), field_name="PROTOCOL_LOGIN_EMAIL")
-    protocol_login_pin = _require_pin(_get(env, "PROTOCOL_LOGIN_PIN"), field_name="PROTOCOL_LOGIN_PIN")
-
-    password_hash = hash_password(admin_password)
-    protocol_login_pin_hash = hash_password(protocol_login_pin)
+    # The [admin] fields are optional as a group: set none of them to leave
+    # credentials to the Setup Wizard (it fills in just [admin] on top of
+    # this network/broker/storage/tls config), or set all of them for a
+    # fully headless, no-browser-step boot.
+    raw_admin_password = _get(env, "ADMIN_PASSWORD")
+    raw_protocol_login_email = _get(env, "PROTOCOL_LOGIN_EMAIL")
+    raw_protocol_login_pin = _get(env, "PROTOCOL_LOGIN_PIN")
+    admin_fields_present = (bool(raw_admin_password), bool(raw_protocol_login_email), bool(raw_protocol_login_pin))
+    if any(admin_fields_present) and not all(admin_fields_present):
+        raise ValueError(
+            f"Set all of {ENV_PREFIX}ADMIN_PASSWORD, {ENV_PREFIX}PROTOCOL_LOGIN_EMAIL, and "
+            f"{ENV_PREFIX}PROTOCOL_LOGIN_PIN together, or none of them (and finish setup in the "
+            "Setup Wizard at /admin instead)."
+        )
+    include_admin = all(admin_fields_present)
 
     lines = [
         "[network]",
@@ -336,20 +342,34 @@ def render_config_toml_from_env(
             ]
         )
 
-    lines.extend(
-        [
-            "",
-            "[admin]",
-            f"password_hash = {_toml_string(password_hash)}",
-            f"session_secret = {_toml_string(admin_session_secret)}",
-            "session_ttl_seconds = 86400",
-            "protocol_auth_enabled = true",
-            f"new_connections_enabled = {_toml_bool(new_connections_enabled)}",
-            f"protocol_login_email = {_toml_string(protocol_login_email)}",
-            f"protocol_login_pin_hash = {_toml_string(protocol_login_pin_hash)}",
-            "",
-        ]
-    )
+    if include_admin:
+        admin_session_secret = (
+            _get(env, "ADMIN_SESSION_SECRET")
+            or _load_existing_admin_session_secret(config_path)
+            or secrets.token_urlsafe(32)
+        )
+        if len(admin_session_secret) < 24:
+            raise ValueError(f"{ENV_PREFIX}ADMIN_SESSION_SECRET must be at least 24 characters when set")
+        new_connections_enabled = _as_bool(_get(env, "NEW_CONNECTIONS_ENABLED"), default=True)
+        protocol_login_email = _require_email(raw_protocol_login_email, field_name="PROTOCOL_LOGIN_EMAIL")
+        protocol_login_pin = _require_pin(raw_protocol_login_pin, field_name="PROTOCOL_LOGIN_PIN")
+        password_hash = hash_password(raw_admin_password)
+        protocol_login_pin_hash = hash_password(protocol_login_pin)
+
+        lines.extend(
+            [
+                "",
+                "[admin]",
+                f"password_hash = {_toml_string(password_hash)}",
+                f"session_secret = {_toml_string(admin_session_secret)}",
+                "session_ttl_seconds = 86400",
+                "protocol_auth_enabled = true",
+                f"new_connections_enabled = {_toml_bool(new_connections_enabled)}",
+                f"protocol_login_email = {_toml_string(protocol_login_email)}",
+                f"protocol_login_pin_hash = {_toml_string(protocol_login_pin_hash)}",
+                "",
+            ]
+        )
     return "\n".join(lines), secrets_to_write
 
 
diff --git a/tests/test_env_config.py b/tests/test_env_config.py
index 79e7bb2..fcab6b1 100644
--- a/tests/test_env_config.py
+++ b/tests/test_env_config.py
@@ -190,15 +190,41 @@ def test_write_config_from_env_actalis_writes_eab(tmp_path: Path) -> None:
     assert hmac_path.read_text(encoding="utf-8") == "hmac-456"
 
 
-def test_write_config_from_env_requires_admin_password(tmp_path: Path) -> None:
+def test_write_config_from_env_rejects_partial_admin_fields(tmp_path: Path) -> None:
     config_path = tmp_path / "config.toml"
     env = dict(_BASE_ENV)
     del env["ROBOROCK_SERVER_ADMIN_PASSWORD"]
 
-    with pytest.raises(ValueError, match="ADMIN_PASSWORD is required"):
+    with pytest.raises(ValueError, match="Set all of .*ADMIN_PASSWORD.*or none of them"):
         write_config_from_env(env, config_path=config_path)
 
 
+def test_write_config_from_env_omits_admin_section_when_all_admin_fields_absent(tmp_path: Path) -> None:
+    config_path = tmp_path / "config.toml"
+    env = dict(_BASE_ENV)
+    del env["ROBOROCK_SERVER_ADMIN_PASSWORD"]
+    del env["ROBOROCK_SERVER_PROTOCOL_LOGIN_EMAIL"]
+    del env["ROBOROCK_SERVER_PROTOCOL_LOGIN_PIN"]
+
+    write_config_from_env(env, config_path=config_path)
+
+    parsed = tomllib.loads(config_path.read_text(encoding="utf-8"))
+    assert "admin" not in parsed
+    # Network/broker/storage/tls are still fully written - the Setup Wizard
+    # only needs to fill in [admin] on top of this.
+    assert parsed["network"]["stack_fqdn"] == "api-roborock.example.com"
+    assert parsed["tls"]["mode"] == "provided"
+
+
+def test_write_config_from_env_writes_admin_section_when_all_admin_fields_present(tmp_path: Path) -> None:
+    config_path = tmp_path / "config.toml"
+
+    write_config_from_env(_BASE_ENV, config_path=config_path)
+
+    parsed = tomllib.loads(config_path.read_text(encoding="utf-8"))
+    assert parsed["admin"]["protocol_login_email"] == "user@example.com"
+
+
 def test_write_config_from_env_requires_api_prefix(tmp_path: Path) -> None:
     config_path = tmp_path / "config.toml"
     env = dict(_BASE_ENV)

From bef5118f43028f65bc000cd68bfd12052497f77f Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Sun, 27 Sep 2026 11:15:25 -0400
Subject: [PATCH 10/32] Split load_config() so [admin] can be diagnosed
 independently

Extracts network/broker/storage/tls parsing+validation into its own
function so it can succeed or fail on its own, separately from [admin].
Adds diagnose_config(), which classifies a config.toml as "ok",
"missing_admin" (everything but [admin] validates - e.g. a partial
env-var-generated config still waiting on the Setup Wizard for
credentials), or "invalid" (something else is wrong, or the file is
missing). load_config()'s own behavior for existing valid/invalid
configs is unchanged.

Co-Authored-By: Claude Sonnet 5 
(cherry picked from commit e39dd211a1065b753b348228237bdaccff5adf17)
---
 src/roborock_local_server/config.py | 295 ++++++++++++++++------------
 tests/test_config.py                |  53 ++++-
 2 files changed, 224 insertions(+), 124 deletions(-)

diff --git a/src/roborock_local_server/config.py b/src/roborock_local_server/config.py
index 1469631..48d8f00 100644
--- a/src/roborock_local_server/config.py
+++ b/src/roborock_local_server/config.py
@@ -249,18 +249,13 @@ def _as_bool(value: object, default: bool) -> bool:
     return bool(value)
 
 
-def load_config(path: str | Path) -> AppConfig:
-    config_path = Path(path).resolve()
-    parsed = tomllib.loads(config_path.read_text(encoding="utf-8"))
-
+def _load_network_broker_storage_tls(
+    parsed: dict[str, object],
+) -> tuple[NetworkConfig, BrokerConfig, StorageConfig, TlsConfig]:
     network = _get_section(parsed, "network")
     broker = _get_section(parsed, "broker")
     storage = _get_section(parsed, "storage")
-    logging = _get_section(parsed, "logging")
     tls = _get_section(parsed, "tls")
-    admin = _get_section(parsed, "admin")
-    turn = _get_section(parsed, "turn")
-    turn_mode = str(turn.get("mode", "external" if _as_bool(turn.get("enabled"), False) else "disabled")).strip().lower()
     broker_mode = str(broker.get("mode", "embedded")).strip().lower()
     if broker_mode not in {"embedded", "external"}:
         raise ValueError("broker.mode must be 'embedded' or 'external'")
@@ -281,148 +276,202 @@ def load_config(path: str | Path) -> AppConfig:
     https_port = _as_port(network.get("https_port"), "network.https_port", 555)
     mqtt_tls_port = _as_port(network.get("mqtt_tls_port"), "network.mqtt_tls_port", 8881)
 
-    config = AppConfig(
-        network=NetworkConfig(
-            stack_fqdn=_require_stack_fqdn(network.get("stack_fqdn"), "network.stack_fqdn"),
-            listener_mode=listener_mode,
-            bind_host=str(network.get("bind_host", "0.0.0.0")).strip() or "0.0.0.0",
-            https_port=https_port,
-            mqtt_tls_port=mqtt_tls_port,
-            advertised_https_port=_as_port(
-                network.get("advertised_https_port"),
-                "network.advertised_https_port",
-                https_port,
-            ),
-            advertised_mqtt_tls_port=_as_port(
-                network.get("advertised_mqtt_tls_port"),
-                "network.advertised_mqtt_tls_port",
-                mqtt_tls_port,
-            ),
-            region=str(network.get("region", "us")).strip().lower() or "us",
-            localkey=str(network.get("localkey", "")).strip(),
-            duid=str(network.get("duid", "")).strip(),
-            mqtt_username=str(network.get("mqtt_username", "")).strip(),
-            mqtt_password=str(network.get("mqtt_password", "")).strip(),
-            mqtt_client_id=str(network.get("mqtt_client_id", "")).strip(),
-            trusted_proxies=_as_trusted_proxies(
-                network.get("trusted_proxies"),
-                "network.trusted_proxies",
-                NetworkConfig.trusted_proxies,
-            ),
-            timezone=_as_timezone(
-                network.get("timezone", "") or parsed.get("timezone", ""),
-                "network.timezone",
-            ),
+    network_config = NetworkConfig(
+        stack_fqdn=_require_stack_fqdn(network.get("stack_fqdn"), "network.stack_fqdn"),
+        listener_mode=listener_mode,
+        bind_host=str(network.get("bind_host", "0.0.0.0")).strip() or "0.0.0.0",
+        https_port=https_port,
+        mqtt_tls_port=mqtt_tls_port,
+        advertised_https_port=_as_port(
+            network.get("advertised_https_port"),
+            "network.advertised_https_port",
+            https_port,
         ),
-        broker=BrokerConfig(
-            mode=broker_mode,
-            host=broker_host,
-            port=_as_port(broker.get("port"), "broker.port", broker_port_default),
-            mosquitto_binary=str(broker.get("mosquitto_binary", "mosquitto")).strip() or "mosquitto",
-            enable_topic_bridge=_as_bool(broker.get("enable_topic_bridge"), True),
+        advertised_mqtt_tls_port=_as_port(
+            network.get("advertised_mqtt_tls_port"),
+            "network.advertised_mqtt_tls_port",
+            mqtt_tls_port,
         ),
-        storage=StorageConfig(
-            data_dir=str(storage.get("data_dir", "/data")).strip() or "/data",
+        region=str(network.get("region", "us")).strip().lower() or "us",
+        localkey=str(network.get("localkey", "")).strip(),
+        duid=str(network.get("duid", "")).strip(),
+        mqtt_username=str(network.get("mqtt_username", "")).strip(),
+        mqtt_password=str(network.get("mqtt_password", "")).strip(),
+        mqtt_client_id=str(network.get("mqtt_client_id", "")).strip(),
+        trusted_proxies=_as_trusted_proxies(
+            network.get("trusted_proxies"),
+            "network.trusted_proxies",
+            NetworkConfig.trusted_proxies,
         ),
-        logging=LoggingConfig(
-            max_size_mb=logging.get("max_size_mb", LoggingConfig.max_size_mb),
-            backup_count=logging.get("backup_count", LoggingConfig.backup_count),
+        timezone=_as_timezone(
+            network.get("timezone", "") or parsed.get("timezone", ""),
+            "network.timezone",
         ),
-        tls=TlsConfig(
-            mode=tls_mode,
-            base_domain=(
-                _normalize_hostname(tls.get("base_domain"), "tls.base_domain")
-                if str(tls.get("base_domain", "")).strip()
-                else ""
-            ),
-            email=str(tls.get("email", "")).strip(),
-            cloudflare_token_file=str(tls.get("cloudflare_token_file", "")).strip(),
-            renew_days_before=_as_int(tls.get("renew_days_before"), "tls.renew_days_before", 30),
-            renew_check_seconds=_as_int(tls.get("renew_check_seconds"), "tls.renew_check_seconds", 43200),
-            acme_server=_normalize_acme_server(tls.get("acme_server", "zerossl"), "tls.acme_server"),
-            acme_eab_kid=str(tls.get("acme_eab_kid", "")).strip(),
-            acme_eab_hmac_key=str(tls.get("acme_eab_hmac_key", "")).strip(),
-            acme_eab_kid_file=str(tls.get("acme_eab_kid_file", "")).strip(),
-            acme_eab_hmac_key_file=str(tls.get("acme_eab_hmac_key_file", "")).strip(),
-            cert_file=str(tls.get("cert_file", "")).strip(),
-            key_file=str(tls.get("key_file", "")).strip(),
-        ),
-        admin=AdminConfig(
-            password_hash=_require_non_empty(admin.get("password_hash"), "admin.password_hash"),
-            session_secret=_require_non_empty(admin.get("session_secret"), "admin.session_secret"),
-            session_ttl_seconds=_as_int(admin.get("session_ttl_seconds"), "admin.session_ttl_seconds", 86400),
-            protocol_auth_enabled=_as_bool(admin.get("protocol_auth_enabled"), True),
-            new_connections_enabled=_as_bool(admin.get("new_connections_enabled"), True),
-            protocol_login_email=_require_non_empty(admin.get("protocol_login_email"), "admin.protocol_login_email"),
-            protocol_login_pin_hash=_require_non_empty(
-                admin.get("protocol_login_pin_hash"),
-                "admin.protocol_login_pin_hash",
-            ),
-        ),
-        turn=TurnConfig(
-            mode=turn_mode,
-            host=str(turn.get("host", "")).strip(),
-            port=_as_port(turn.get("port"), "turn.port", 3478),
-            username=str(turn.get("username", "") or ("roborock" if turn_mode == "provided" else "")).strip(),
-            password=str(turn.get("password", "")).strip(),
-            realm=str(turn.get("realm", "") or turn.get("host", "")).strip(),
-            ttl=_as_int(turn.get("ttl"), "turn.ttl", 86400),
+    )
+    broker_config = BrokerConfig(
+        mode=broker_mode,
+        host=broker_host,
+        port=_as_port(broker.get("port"), "broker.port", broker_port_default),
+        mosquitto_binary=str(broker.get("mosquitto_binary", "mosquitto")).strip() or "mosquitto",
+        enable_topic_bridge=_as_bool(broker.get("enable_topic_bridge"), True),
+    )
+    storage_config = StorageConfig(
+        data_dir=str(storage.get("data_dir", "/data")).strip() or "/data",
+    )
+    tls_config = TlsConfig(
+        mode=tls_mode,
+        base_domain=(
+            _normalize_hostname(tls.get("base_domain"), "tls.base_domain")
+            if str(tls.get("base_domain", "")).strip()
+            else ""
         ),
+        email=str(tls.get("email", "")).strip(),
+        cloudflare_token_file=str(tls.get("cloudflare_token_file", "")).strip(),
+        renew_days_before=_as_int(tls.get("renew_days_before"), "tls.renew_days_before", 30),
+        renew_check_seconds=_as_int(tls.get("renew_check_seconds"), "tls.renew_check_seconds", 43200),
+        acme_server=_normalize_acme_server(tls.get("acme_server", "zerossl"), "tls.acme_server"),
+        acme_eab_kid=str(tls.get("acme_eab_kid", "")).strip(),
+        acme_eab_hmac_key=str(tls.get("acme_eab_hmac_key", "")).strip(),
+        acme_eab_kid_file=str(tls.get("acme_eab_kid_file", "")).strip(),
+        acme_eab_hmac_key_file=str(tls.get("acme_eab_hmac_key_file", "")).strip(),
+        cert_file=str(tls.get("cert_file", "")).strip(),
+        key_file=str(tls.get("key_file", "")).strip(),
     )
 
-    if len(config.admin.session_secret) < 24:
-        raise ValueError("admin.session_secret must be at least 24 characters")
-    if "@" not in config.admin.protocol_login_email:
-        raise ValueError("admin.protocol_login_email must be an email address")
-
-    if config.broker.mode == "external":
-        _require_non_empty(config.broker.host, "broker.host")
-
-    if config.turn.mode not in {"disabled", "provided", "external"}:
-        raise ValueError("turn.mode must be 'disabled', 'provided', or 'external'")
-    if config.turn.mode != "disabled":
-        _require_non_empty(config.turn.host, "turn.host")
-        _require_non_empty(config.turn.username, "turn.username")
-        _require_non_empty(config.turn.password, "turn.password")
-        _require_non_empty(config.turn.realm, "turn.realm")
-        if config.turn.ttl <= 0:
-            raise ValueError("turn.ttl must be greater than 0")
-    if config.turn.mode == "provided":
-        for name in ("username", "password", "realm"):
-            if any(character in getattr(config.turn, name) for character in "\r\n:="):
-                raise ValueError(f"turn.{name} cannot contain newlines, colons, or equals signs in provided mode")
+    if broker_config.mode == "external":
+        _require_non_empty(broker_config.host, "broker.host")
 
     # In external_tls the proxy terminates TLS and presents the cert to clients,
     # so the server itself needs no certificate material.
-    if config.network.listener_mode == "local_tls":
-        if config.tls.mode == "cloudflare_acme":
-            _normalize_hostname(config.tls.base_domain, "tls.base_domain")
-            _require_non_empty(config.tls.email, "tls.email")
-            _require_non_empty(config.tls.cloudflare_token_file, "tls.cloudflare_token_file")
-            has_kid = bool(config.tls.acme_eab_kid or config.tls.acme_eab_kid_file)
-            has_hmac = bool(config.tls.acme_eab_hmac_key or config.tls.acme_eab_hmac_key_file)
+    if network_config.listener_mode == "local_tls":
+        if tls_config.mode == "cloudflare_acme":
+            _normalize_hostname(tls_config.base_domain, "tls.base_domain")
+            _require_non_empty(tls_config.email, "tls.email")
+            _require_non_empty(tls_config.cloudflare_token_file, "tls.cloudflare_token_file")
+            has_kid = bool(tls_config.acme_eab_kid or tls_config.acme_eab_kid_file)
+            has_hmac = bool(tls_config.acme_eab_hmac_key or tls_config.acme_eab_hmac_key_file)
             if has_kid != has_hmac:
                 raise ValueError(
                     "tls.acme_eab_kid/tls.acme_eab_kid_file and "
                     "tls.acme_eab_hmac_key/tls.acme_eab_hmac_key_file must be set together"
                 )
-            if config.tls.acme_server == "actalis":
+            if tls_config.acme_server == "actalis":
                 if not has_kid:
                     raise ValueError(
                         "Actalis requires tls.acme_eab_kid or tls.acme_eab_kid_file, "
                         "and tls.acme_eab_hmac_key or tls.acme_eab_hmac_key_file"
                     )
         else:
-            _require_non_empty(config.tls.cert_file, "tls.cert_file")
-            _require_non_empty(config.tls.key_file, "tls.key_file")
-    elif config.tls.mode == "cloudflare_acme":
+            _require_non_empty(tls_config.cert_file, "tls.cert_file")
+            _require_non_empty(tls_config.key_file, "tls.key_file")
+    elif tls_config.mode == "cloudflare_acme":
         # external_tls never issues or renews certificates, so cloudflare_acme
         # would be a silent no-op. Require the proxy-managed 'provided' mode.
         raise ValueError(
             "network.listener_mode='external_tls' requires tls.mode='provided' "
             "(the proxy terminates TLS; the server does not issue certificates)"
         )
-    return config
+
+    return network_config, broker_config, storage_config, tls_config
+
+
+def _load_logging(parsed: dict[str, object]) -> LoggingConfig:
+    logging = _get_section(parsed, "logging")
+    return LoggingConfig(
+        max_size_mb=logging.get("max_size_mb", LoggingConfig.max_size_mb),
+        backup_count=logging.get("backup_count", LoggingConfig.backup_count),
+    )
+
+
+def _load_turn(parsed: dict[str, object]) -> TurnConfig:
+    turn = _get_section(parsed, "turn")
+    mode = str(turn.get("mode", "external" if _as_bool(turn.get("enabled"), False) else "disabled")).strip().lower()
+    turn_config = TurnConfig(
+        mode=mode,
+        host=str(turn.get("host", "")).strip(),
+        port=_as_port(turn.get("port"), "turn.port", 3478),
+        username=str(turn.get("username", "") or ("roborock" if mode == "provided" else "")).strip(),
+        password=str(turn.get("password", "")).strip(),
+        realm=str(turn.get("realm", "") or turn.get("host", "")).strip(),
+        ttl=_as_int(turn.get("ttl"), "turn.ttl", 86400),
+    )
+    if turn_config.mode not in {"disabled", "provided", "external"}:
+        raise ValueError("turn.mode must be 'disabled', 'provided', or 'external'")
+    if turn_config.mode != "disabled":
+        _require_non_empty(turn_config.host, "turn.host")
+        _require_non_empty(turn_config.username, "turn.username")
+        _require_non_empty(turn_config.password, "turn.password")
+        _require_non_empty(turn_config.realm, "turn.realm")
+        if turn_config.ttl <= 0:
+            raise ValueError("turn.ttl must be greater than 0")
+    if turn_config.mode == "provided":
+        for name in ("username", "password", "realm"):
+            if any(character in getattr(turn_config, name) for character in "\r\n:="):
+                raise ValueError(f"turn.{name} cannot contain newlines, colons, or equals signs in provided mode")
+    return turn_config
+
+
+def _load_admin(parsed: dict[str, object]) -> AdminConfig:
+    admin = _get_section(parsed, "admin")
+    admin_config = AdminConfig(
+        password_hash=_require_non_empty(admin.get("password_hash"), "admin.password_hash"),
+        session_secret=_require_non_empty(admin.get("session_secret"), "admin.session_secret"),
+        session_ttl_seconds=_as_int(admin.get("session_ttl_seconds"), "admin.session_ttl_seconds", 86400),
+        protocol_auth_enabled=_as_bool(admin.get("protocol_auth_enabled"), True),
+        new_connections_enabled=_as_bool(admin.get("new_connections_enabled"), True),
+        protocol_login_email=_require_non_empty(admin.get("protocol_login_email"), "admin.protocol_login_email"),
+        protocol_login_pin_hash=_require_non_empty(
+            admin.get("protocol_login_pin_hash"),
+            "admin.protocol_login_pin_hash",
+        ),
+    )
+    if len(admin_config.session_secret) < 24:
+        raise ValueError("admin.session_secret must be at least 24 characters")
+    if "@" not in admin_config.protocol_login_email:
+        raise ValueError("admin.protocol_login_email must be an email address")
+    return admin_config
+
+
+def load_config(path: str | Path) -> AppConfig:
+    config_path = Path(path).resolve()
+    parsed = tomllib.loads(config_path.read_text(encoding="utf-8"))
+    network_config, broker_config, storage_config, tls_config = _load_network_broker_storage_tls(parsed)
+    turn_config = _load_turn(parsed)
+    admin_config = _load_admin(parsed)
+    return AppConfig(
+        network=network_config,
+        logging=_load_logging(parsed),
+        broker=broker_config,
+        storage=storage_config,
+        tls=tls_config,
+        admin=admin_config,
+        turn=turn_config,
+    )
+
+
+def diagnose_config(path: str | Path) -> str:
+    """Classify config.toml's state for the setup wizard.
+
+    Returns "ok" (loads cleanly), "missing_admin" (network/broker/storage/tls
+    all validate, but [admin] doesn't - e.g. a partial env-var-generated
+    config still waiting on the wizard for credentials), or "invalid" (file
+    missing/unreadable, or something other than [admin] is wrong).
+    """
+    try:
+        parsed = tomllib.loads(Path(path).read_text(encoding="utf-8"))
+    except (OSError, tomllib.TOMLDecodeError):
+        return "invalid"
+    try:
+        _load_network_broker_storage_tls(parsed)
+        _load_logging(parsed)
+        _load_turn(parsed)
+    except ValueError:
+        return "invalid"
+    try:
+        _load_admin(parsed)
+    except ValueError:
+        return "missing_admin"
+    return "ok"
 
 
 def resolve_paths(config_file: str | Path, config: AppConfig) -> AppPaths:
diff --git a/tests/test_config.py b/tests/test_config.py
index ba56958..8c90b4b 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -3,7 +3,7 @@
 import pytest
 from conftest import write_release_config
 
-from roborock_local_server.config import load_config, resolve_paths
+from roborock_local_server.config import diagnose_config, load_config, resolve_paths
 
 
 def test_logging_defaults_and_overrides(tmp_path):
@@ -557,3 +557,54 @@ def test_load_config_rejects_invalid_trusted_proxy(tmp_path: Path) -> None:
 
     with pytest.raises(ValueError, match="network.trusted_proxies entry 'traefik'"):
         load_config(config_file)
+
+
+_VALID_NETWORK_BROKER_STORAGE_TLS = """
+[network]
+stack_fqdn = "api-roborock.example.com"
+
+[broker]
+mode = "embedded"
+
+[storage]
+data_dir = "data"
+
+[tls]
+mode = "provided"
+cert_file = "certs/fullchain.pem"
+key_file = "certs/privkey.pem"
+"""
+
+_VALID_ADMIN = """
+[admin]
+password_hash = "pbkdf2_sha256$600000$abc$def"
+session_secret = "abcdefghijklmnopqrstuvwxyz123456"
+protocol_login_email = "user@example.com"
+protocol_login_pin_hash = "pbkdf2_sha256$600000$ghi$jkl"
+"""
+
+
+def test_diagnose_config_ok(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    config_file.write_text((_VALID_NETWORK_BROKER_STORAGE_TLS + _VALID_ADMIN).strip(), encoding="utf-8")
+
+    assert diagnose_config(config_file) == "ok"
+
+
+def test_diagnose_config_missing_admin_when_only_admin_section_absent(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    config_file.write_text(_VALID_NETWORK_BROKER_STORAGE_TLS.strip(), encoding="utf-8")
+
+    assert diagnose_config(config_file) == "missing_admin"
+
+
+def test_diagnose_config_invalid_when_file_does_not_exist(tmp_path: Path) -> None:
+    assert diagnose_config(tmp_path / "does-not-exist.toml") == "invalid"
+
+
+def test_diagnose_config_invalid_when_network_is_broken_even_if_admin_is_fine(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    broken_network = _VALID_NETWORK_BROKER_STORAGE_TLS.replace('mode = "embedded"', 'mode = "bogus"')
+    config_file.write_text((broken_network + _VALID_ADMIN).strip(), encoding="utf-8")
+
+    assert diagnose_config(config_file) == "invalid"

From 8f57d630aba8004dca83716b5d12541f17984d4a Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Sun, 27 Sep 2026 11:23:52 -0400
Subject: [PATCH 11/32] Support completing a partial (env-var-generated) config
 in the wizard

Uses diagnose_config() to tell three states apart at /admin: "ok"
(status page), "missing_admin" (a trimmed wizard asking only for admin
credentials, appending just [admin] to the existing config.toml rather
than regenerating it), and anything else (the full wizard, as before -
this also covers a corrupt hand-edited file, which is correctly
refused rather than silently overwritten).

This is what makes the env-var path from feat/env-var-config and this
wizard actually compose: set only FQDN/TLS/network vars and finish
credentials in the browser, instead of an all-or-nothing choice
between the two.

Co-Authored-By: Claude Sonnet 5 
(cherry picked from commit c93a28b617e59d366d5a380eb57df107260e5820)
---
 src/roborock_local_server/management_app.py | 159 +++++++++++++++++++-
 tests/test_management_app.py                | 125 ++++++++++++++-
 2 files changed, 270 insertions(+), 14 deletions(-)

diff --git a/src/roborock_local_server/management_app.py b/src/roborock_local_server/management_app.py
index 5177832..421130d 100644
--- a/src/roborock_local_server/management_app.py
+++ b/src/roborock_local_server/management_app.py
@@ -20,6 +20,7 @@
 from fastapi import FastAPI, Request
 from fastapi.responses import HTMLResponse, JSONResponse
 
+from .config import diagnose_config
 from .configure import (
     ConfigureAnswers,
     _normalize_acme_server,
@@ -131,6 +132,56 @@ def s(key: str, default: str = "") -> str:
     )
 
 
+def _toml_string(value: str) -> str:
+    return json.dumps(value)
+
+
+def _admin_fields_from_payload(body: Mapping[str, Any]) -> tuple[str, str, str]:
+    def s(key: str, default: str = "") -> str:
+        return str(body.get(key, default) or "").strip()
+
+    admin_password = s("admin_password")
+    if not admin_password:
+        raise ValueError("admin_password is required")
+    protocol_login_email = s("protocol_login_email")
+    if "@" not in protocol_login_email:
+        raise ValueError("protocol_login_email must be an email address")
+    protocol_login_pin = _validate_protocol_login_pin(s("protocol_login_pin"))
+    return admin_password, protocol_login_email, protocol_login_pin
+
+
+def complete_admin_section(
+    *,
+    config_file: Path,
+    admin_password: str,
+    protocol_login_email: str,
+    protocol_login_pin: str,
+) -> None:
+    """Append [admin] to a partial config.toml (network/broker/storage/tls
+    already written, e.g. by env_config.py) that's only missing credentials.
+
+    Appending is safe here because env_config.py never writes an [admin]
+    section itself when these vars are unset - there's nothing to collide
+    with or overwrite.
+    """
+    admin_block = "\n".join(
+        [
+            "",
+            "[admin]",
+            f"password_hash = {_toml_string(hash_password(admin_password))}",
+            f"session_secret = {_toml_string(secrets.token_urlsafe(32))}",
+            "session_ttl_seconds = 86400",
+            "protocol_auth_enabled = true",
+            "new_connections_enabled = true",
+            f"protocol_login_email = {_toml_string(protocol_login_email)}",
+            f"protocol_login_pin_hash = {_toml_string(hash_password(protocol_login_pin))}",
+            "",
+        ]
+    )
+    with config_file.open("a", encoding="utf-8") as handle:
+        handle.write(admin_block)
+
+
 def _status_html() -> str:
     return dedent(
         """\
@@ -290,6 +341,84 @@ def _setup_wizard_html() -> str:
     )
 
 
+def _admin_only_wizard_html() -> str:
+    return dedent(
+        """\
+        
+        Roborock Local Server Setup
+        
+        
+        

Roborock Local Server Setup

+

Network, broker, and certificate settings are already set (from environment variables). + Just add admin credentials to finish setup.

+
+
+ Admin Access + + +
+ +
+ App / Home Assistant Login + + + +
+ + +
+

+        
+        
+        
+        """
+    )
+
+
 def create_management_app(
     *,
     config_file: Path,
@@ -300,27 +429,45 @@ def create_management_app(
     @app.get("/", response_class=HTMLResponse)
     @app.get("/admin", response_class=HTMLResponse)
     async def index() -> HTMLResponse:
-        return HTMLResponse(_status_html() if config_file.exists() else _setup_wizard_html())
+        status = diagnose_config(config_file)
+        if status == "ok":
+            return HTMLResponse(_status_html())
+        if status == "missing_admin":
+            return HTMLResponse(_admin_only_wizard_html())
+        return HTMLResponse(_setup_wizard_html())
 
     @app.get("/admin/api/setup/status")
     async def setup_status() -> JSONResponse:
-        return JSONResponse({"configured": config_file.exists()})
+        return JSONResponse({"status": diagnose_config(config_file)})
 
     @app.post("/admin/api/setup")
     async def submit_setup(request: Request) -> JSONResponse:
-        if config_file.exists():
+        status = diagnose_config(config_file)
+        if status == "ok":
             return JSONResponse({"error": "Already configured."}, status_code=409)
+
         try:
             raw_body = await request.body()
             body = json.loads(raw_body or b"{}")
             if not isinstance(body, dict):
                 raise ValueError("Request body must be a JSON object.")
-            answers = _answers_from_payload(body)
-            result = write_config_setup(config_file=config_file, answers=answers)
+
+            if status == "missing_admin":
+                admin_password, protocol_login_email, protocol_login_pin = _admin_fields_from_payload(body)
+                complete_admin_section(
+                    config_file=config_file,
+                    admin_password=admin_password,
+                    protocol_login_email=protocol_login_email,
+                    protocol_login_pin=protocol_login_pin,
+                )
+                result_config_file = config_file
+            else:
+                answers = _answers_from_payload(body)
+                result_config_file = write_config_setup(config_file=config_file, answers=answers).config_file
         except (ValueError, FileExistsError) as exc:
             return JSONResponse({"error": str(exc)}, status_code=400)
         if on_configured is not None:
             on_configured()
-        return JSONResponse({"ok": True, "config_file": str(result.config_file)})
+        return JSONResponse({"ok": True, "config_file": str(result_config_file)})
 
     return app
diff --git a/tests/test_management_app.py b/tests/test_management_app.py
index d805a07..e787a8a 100644
--- a/tests/test_management_app.py
+++ b/tests/test_management_app.py
@@ -5,7 +5,7 @@
 from fastapi.testclient import TestClient
 import pytest
 
-from roborock_local_server.config import load_config
+from roborock_local_server.config import diagnose_config, load_config
 from roborock_local_server.management_app import (
     DEFAULT_BOOTSTRAP_HTTPS_PORT,
     bootstrap_port_from_env,
@@ -23,6 +23,44 @@
     "protocol_login_pin": "123456",
 }
 
+_FULL_CONFIG = """
+[network]
+stack_fqdn = "api-roborock.example.com"
+
+[broker]
+mode = "embedded"
+
+[storage]
+data_dir = "data"
+
+[tls]
+mode = "provided"
+cert_file = "certs/fullchain.pem"
+key_file = "certs/privkey.pem"
+
+[admin]
+password_hash = "pbkdf2_sha256$600000$abc$def"
+session_secret = "abcdefghijklmnopqrstuvwxyz123456"
+protocol_login_email = "user@example.com"
+protocol_login_pin_hash = "pbkdf2_sha256$600000$ghi$jkl"
+""".strip()
+
+_PARTIAL_CONFIG_MISSING_ADMIN = """
+[network]
+stack_fqdn = "api-roborock.example.com"
+
+[broker]
+mode = "embedded"
+
+[storage]
+data_dir = "data"
+
+[tls]
+mode = "provided"
+cert_file = "certs/fullchain.pem"
+key_file = "certs/privkey.pem"
+""".strip()
+
 
 def test_bootstrap_port_from_env_default() -> None:
     assert bootstrap_port_from_env({}) == DEFAULT_BOOTSTRAP_HTTPS_PORT
@@ -49,7 +87,7 @@ def test_index_serves_setup_wizard_when_unconfigured(tmp_path: Path) -> None:
 
 def test_index_serves_status_page_when_configured(tmp_path: Path) -> None:
     config_file = tmp_path / "config.toml"
-    config_file.write_text("already = true\n", encoding="utf-8")
+    config_file.write_text(_FULL_CONFIG, encoding="utf-8")
     client = TestClient(create_management_app(config_file=config_file))
 
     response = client.get("/")
@@ -58,14 +96,29 @@ def test_index_serves_status_page_when_configured(tmp_path: Path) -> None:
     assert "Setup is complete" in response.text
 
 
-def test_setup_status_reflects_config_existence(tmp_path: Path) -> None:
+def test_index_serves_admin_only_wizard_when_only_admin_missing(tmp_path: Path) -> None:
     config_file = tmp_path / "config.toml"
+    config_file.write_text(_PARTIAL_CONFIG_MISSING_ADMIN, encoding="utf-8")
     client = TestClient(create_management_app(config_file=config_file))
 
-    assert client.get("/admin/api/setup/status").json() == {"configured": False}
+    response = client.get("/admin")
+
+    assert response.status_code == 200
+    assert "Just add admin credentials" in response.text
+    assert 'name="stack_fqdn"' not in response.text
 
-    config_file.write_text("done = true\n", encoding="utf-8")
-    assert client.get("/admin/api/setup/status").json() == {"configured": True}
+
+def test_setup_status_reflects_config_state(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    client = TestClient(create_management_app(config_file=config_file))
+
+    assert client.get("/admin/api/setup/status").json() == {"status": "invalid"}
+
+    config_file.write_text(_PARTIAL_CONFIG_MISSING_ADMIN, encoding="utf-8")
+    assert client.get("/admin/api/setup/status").json() == {"status": "missing_admin"}
+
+    config_file.write_text(_FULL_CONFIG, encoding="utf-8")
+    assert client.get("/admin/api/setup/status").json() == {"status": "ok"}
 
 
 def test_submit_setup_writes_bootable_config(tmp_path: Path) -> None:
@@ -120,17 +173,73 @@ def test_submit_setup_rejects_bad_stack_fqdn(tmp_path: Path) -> None:
     assert "must start with api-" in response.json()["error"]
 
 
-def test_submit_setup_refuses_to_overwrite_existing_config(tmp_path: Path) -> None:
+def test_submit_setup_refuses_to_overwrite_a_fully_configured_stack(tmp_path: Path) -> None:
     config_file = tmp_path / "config.toml"
-    config_file.write_text("existing = true\n", encoding="utf-8")
+    config_file.write_text(_FULL_CONFIG, encoding="utf-8")
     client = TestClient(create_management_app(config_file=config_file))
 
     response = client.post("/admin/api/setup", json=_VALID_PAYLOAD)
 
     assert response.status_code == 409
+    assert config_file.read_text(encoding="utf-8") == _FULL_CONFIG
+
+
+def test_submit_setup_refuses_to_overwrite_an_existing_broken_config(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    config_file.write_text("existing = true\n", encoding="utf-8")
+    client = TestClient(create_management_app(config_file=config_file))
+
+    response = client.post("/admin/api/setup", json=_VALID_PAYLOAD)
+
+    assert response.status_code == 400
+    assert "Refusing to overwrite" in response.json()["error"]
     assert config_file.read_text(encoding="utf-8") == "existing = true\n"
 
 
+def test_submit_setup_completes_admin_only_config(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    config_file.write_text(_PARTIAL_CONFIG_MISSING_ADMIN, encoding="utf-8")
+    calls: list[str] = []
+    client = TestClient(create_management_app(config_file=config_file, on_configured=lambda: calls.append("done")))
+
+    response = client.post(
+        "/admin/api/setup",
+        json={
+            "admin_password": "super-secret-password",
+            "protocol_login_email": "user@example.com",
+            "protocol_login_pin": "123456",
+        },
+    )
+
+    assert response.status_code == 200
+    assert calls == ["done"]
+
+    config = load_config(config_file)
+    # Network/broker/storage/tls came from the pre-existing partial config, untouched.
+    assert config.network.stack_fqdn == "api-roborock.example.com"
+    assert config.admin.protocol_login_email == "user@example.com"
+    assert str(config.admin.password_hash).startswith("pbkdf2_sha256$")
+
+
+def test_submit_setup_admin_only_rejects_bad_pin(tmp_path: Path) -> None:
+    config_file = tmp_path / "config.toml"
+    config_file.write_text(_PARTIAL_CONFIG_MISSING_ADMIN, encoding="utf-8")
+    client = TestClient(create_management_app(config_file=config_file))
+
+    response = client.post(
+        "/admin/api/setup",
+        json={
+            "admin_password": "super-secret-password",
+            "protocol_login_email": "user@example.com",
+            "protocol_login_pin": "12",
+        },
+    )
+
+    assert response.status_code == 400
+    assert "6 digits" in response.json()["error"]
+    assert diagnose_config(config_file) == "missing_admin"
+
+
 def test_submit_setup_cloudflare_actalis_requires_eab(tmp_path: Path) -> None:
     config_file = tmp_path / "config.toml"
     client = TestClient(create_management_app(config_file=config_file))

From e2e37eecff1a41c570e3162a7f37da82f1c1c4fd Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Mon, 12 Oct 2026 14:38:22 -0400
Subject: [PATCH 12/32] Let the routine runner start a job without a scene

Split _run_scene so a scheduled job can run the same step executor
without syncing scene IDs to the robot, and add start_job(), which
refuses to interrupt a routine that is already running on the device.
get_routine_runner() gives other callers the per-context instance.

Co-Authored-By: Claude Sonnet 5.5 
(cherry picked from commit c65764810057f9491d35287e7b707e622eb19405)
---
 .../bundled_backend/shared/routine_runner.py  | 47 ++++++++++++++++++-
 1 file changed, 46 insertions(+), 1 deletion(-)

diff --git a/src/roborock_local_server/bundled_backend/shared/routine_runner.py b/src/roborock_local_server/bundled_backend/shared/routine_runner.py
index 71fcca8..460ed5e 100644
--- a/src/roborock_local_server/bundled_backend/shared/routine_runner.py
+++ b/src/roborock_local_server/bundled_backend/shared/routine_runner.py
@@ -801,6 +801,33 @@ def start_scene(self, scene: dict[str, Any]) -> dict[str, Any]:
             "stepCount": len(steps),
         }
 
+    def start_job(
+        self,
+        *,
+        device_id: str,
+        job_id: int,
+        name: str,
+        steps: list[RoutineStep],
+    ) -> dict[str, Any]:
+        """Run a scheduled job's steps; never interrupts a routine already running."""
+        existing = self._tasks_by_device.get(device_id)
+        if existing is not None and not existing.task.done():
+            return {
+                "accepted": False,
+                "status": "routine_in_progress",
+                "jobId": job_id,
+                "deviceId": device_id,
+                "activeSceneName": existing.scene_name,
+            }
+        scene = {"id": job_id, "name": name, "device_id": device_id}
+        task = asyncio.get_running_loop().create_task(
+            self._run_steps(scene=scene, steps=steps, sync_scene_tids=False),
+            name=f"routine-job-{job_id}-{device_id}",
+        )
+        self._tasks_by_device[device_id] = _ActiveRoutine(task=task, scene_id=job_id, scene_name=name)
+        task.add_done_callback(lambda finished: self._on_scene_done(device_id, finished))
+        return {"accepted": True, "status": "started", "jobId": job_id, "deviceId": device_id, "stepCount": len(steps)}
+
     def _on_scene_done(self, device_id: str, task: asyncio.Task[None]) -> None:
         current = self._tasks_by_device.get(device_id)
         if current is not None and current.task is task:
@@ -967,6 +994,15 @@ async def _send_step_command(
                 raise
 
     async def _run_scene(self, *, scene: dict[str, Any], steps: list[RoutineStep]) -> None:
+        await self._run_steps(scene=scene, steps=steps, sync_scene_tids=True)
+
+    async def _run_steps(
+        self,
+        *,
+        scene: dict[str, Any],
+        steps: list[RoutineStep],
+        sync_scene_tids: bool,
+    ) -> None:
         device_id = scene_device_id(scene)
         device = self._device_record(device_id)
         logger = logging.LoggerAdapter(
@@ -988,7 +1024,8 @@ async def _run_scene(self, *, scene: dict[str, Any], steps: list[RoutineStep]) -
         client = _RoutineMqttClient(self._context, device, logger)
         await client.connect()
         try:
-            await self._sync_scene_tids(client=client, scene=scene, device_id=device_id, logger=logger)
+            if sync_scene_tids:
+                await self._sync_scene_tids(client=client, scene=scene, device_id=device_id, logger=logger)
             for step_index, step in enumerate(steps):
                 commands = commands_for_step(step)
                 waits_for_step_complete = RoborockDataProtocol.TASK_COMPLETE.value in step.finish_dp_ids
@@ -1015,3 +1052,11 @@ async def _run_scene(self, *, scene: dict[str, Any], steps: list[RoutineStep]) -
             await client.close()
 
         logger.info("Completed routine scene=%s device=%s", _scene_name(scene), device_id)
+
+
+def get_routine_runner(context: ServerContext) -> RoutineRunner:
+    runner = getattr(context, "_routine_runner", None)
+    if runner is None:
+        runner = RoutineRunner(context)
+        setattr(context, "_routine_runner", runner)
+    return runner

From c12fba03bc3d6463d891b8210258d49e2b3b298d Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Mon, 12 Oct 2026 14:38:22 -0400
Subject: [PATCH 13/32] Add a local executor for cloud-style schedules

Roborock's cloud fires server_scheduled_start jobs at nextFireTime. With
the vacuum pointed at this server nothing did, so imported schedules
never ran. ScheduleRunner evaluates each enabled job's cron in its own
timezone and hands due jobs to the routine runner, carrying fan_power,
water_box_mode and mop_mode so vac-only and vac+mop schedules behave as
configured. One-shot jobs disable themselves after firing.

Co-Authored-By: Claude Sonnet 5.5 
(cherry picked from commit b5203b2ee58a46f0f41fe1f0f9e0f323b1fc206c)
---
 .../bundled_backend/shared/schedule_runner.py | 313 ++++++++++++++++++
 tests/test_schedule_runner.py                 | 160 +++++++++
 2 files changed, 473 insertions(+)
 create mode 100644 src/roborock_local_server/bundled_backend/shared/schedule_runner.py
 create mode 100644 tests/test_schedule_runner.py

diff --git a/src/roborock_local_server/bundled_backend/shared/schedule_runner.py b/src/roborock_local_server/bundled_backend/shared/schedule_runner.py
new file mode 100644
index 0000000..c70fd3d
--- /dev/null
+++ b/src/roborock_local_server/bundled_backend/shared/schedule_runner.py
@@ -0,0 +1,313 @@
+"""Local executor for cloud-style schedules (``server_scheduled_start`` jobs).
+
+Roborock's cloud fires these at ``nextFireTime``. With the vacuum pointed at this
+server, nothing else would, so the server evaluates the stored cron entries
+itself and hands each due job to the routine runner.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+from datetime import date, datetime, timedelta, timezone, tzinfo
+import json
+import logging
+from typing import TYPE_CHECKING, Any
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+
+from .data_helpers import as_bool
+from .inventory_io import inventory_mutation, load_inventory, write_inventory
+from .routine_runner import RoutineExecutionError, RoutineStep, get_routine_runner
+
+if TYPE_CHECKING:
+    from .context import ServerContext
+
+_LOGGER = logging.getLogger(__name__)
+
+TICK_SECONDS = 20
+_SUPPORTED_JOB_METHOD = "server_scheduled_start"
+_CARRIED_ENTRY_KEYS = ("repeat", "fan_power", "water_box_mode", "mop_mode", "mop_template_id")
+
+
+class CronError(ValueError):
+    """Raised for a cron expression this scheduler cannot evaluate."""
+
+
+@dataclass(frozen=True)
+class CronSpec:
+    minutes: tuple[int, ...]
+    hours: tuple[int, ...]
+    days_of_month: frozenset[int]
+    months: frozenset[int]
+    days_of_week: frozenset[int]
+    dom_restricted: bool
+    dow_restricted: bool
+
+    def day_matches(self, day: date) -> bool:
+        if day.month not in self.months:
+            return False
+        dom_ok = day.day in self.days_of_month
+        # cron weekday 0 = Sunday; python's isoweekday() has Sunday as 7.
+        dow_ok = (day.isoweekday() % 7) in self.days_of_week
+        if self.dom_restricted and self.dow_restricted:
+            return dom_ok or dow_ok
+        return dom_ok and dow_ok
+
+
+def _parse_field(text: str, low: int, high: int, *, name: str) -> tuple[frozenset[int], bool]:
+    text = text.strip()
+    if text in ("*", "?"):
+        return frozenset(range(low, high + 1)), False
+    values: set[int] = set()
+    for part in text.split(","):
+        part = part.strip()
+        if not part:
+            raise CronError(f"empty {name} entry in {text!r}")
+        step = 1
+        if "/" in part:
+            part, _, step_text = part.partition("/")
+            try:
+                step = int(step_text)
+            except ValueError as exc:
+                raise CronError(f"bad {name} step {step_text!r}") from exc
+            if step <= 0:
+                raise CronError(f"{name} step must be positive")
+        if part in ("*", "?", ""):
+            start, end = low, high
+        elif "-" in part:
+            first, _, last = part.partition("-")
+            try:
+                start, end = int(first), int(last)
+            except ValueError as exc:
+                raise CronError(f"bad {name} range {part!r}") from exc
+        else:
+            try:
+                start = int(part)
+            except ValueError as exc:
+                raise CronError(f"bad {name} value {part!r}") from exc
+            end = high if step != 1 else start
+        if start < low or end > high or start > end:
+            raise CronError(f"{name} value out of range in {text!r}")
+        values.update(range(start, end + 1, step))
+    return frozenset(values), True
+
+
+def parse_cron(expression: str) -> CronSpec:
+    fields = str(expression or "").split()
+    if len(fields) != 5:
+        raise CronError(f"expected 5 cron fields, got {len(fields)}: {expression!r}")
+    minutes, _ = _parse_field(fields[0], 0, 59, name="minute")
+    hours, _ = _parse_field(fields[1], 0, 23, name="hour")
+    dom, dom_restricted = _parse_field(fields[2], 1, 31, name="day-of-month")
+    months, _ = _parse_field(fields[3], 1, 12, name="month")
+    raw_dow, dow_restricted = _parse_field(fields[4], 0, 7, name="day-of-week")
+    dow = frozenset(0 if value == 7 else value for value in raw_dow)
+    return CronSpec(
+        minutes=tuple(sorted(minutes)),
+        hours=tuple(sorted(hours)),
+        days_of_month=dom,
+        months=months,
+        days_of_week=dow,
+        dom_restricted=dom_restricted,
+        dow_restricted=dow_restricted,
+    )
+
+
+def next_fire(spec: CronSpec, after: datetime) -> datetime | None:
+    """First fire instant strictly after ``after`` (an aware datetime), in its timezone."""
+    zone = after.tzinfo
+    if zone is None:
+        raise ValueError("after must be timezone-aware")
+    start = after.replace(second=0, microsecond=0) + timedelta(minutes=1)
+    start_utc = start.astimezone(timezone.utc)
+    first_day = start.date()
+    for offset in range(0, 800):
+        day = first_day + timedelta(days=offset)
+        if not spec.day_matches(day):
+            continue
+        for hour in spec.hours:
+            for minute in spec.minutes:
+                candidate = datetime(day.year, day.month, day.day, hour, minute, tzinfo=zone)
+                if candidate.astimezone(timezone.utc) >= start_utc:
+                    return candidate
+    return None
+
+
+def _zone(name: str, fallback: str) -> tzinfo:
+    for candidate in (name, fallback):
+        candidate = str(candidate or "").strip()
+        if not candidate:
+            continue
+        try:
+            return ZoneInfo(candidate)
+        except (ZoneInfoNotFoundError, ValueError):
+            continue
+    return timezone.utc
+
+
+def _segment_ids(value: Any) -> list[int]:
+    if isinstance(value, str):
+        items: list[Any] = [part for part in value.replace(";", ",").split(",") if part.strip()]
+    elif isinstance(value, (list, tuple)):
+        items = list(value)
+    elif value is None:
+        items = []
+    else:
+        items = [value]
+    segments: list[int] = []
+    for item in items:
+        try:
+            number = int(str(item).strip())
+        except ValueError:
+            continue
+        if number > 0:
+            segments.append(number)
+    return segments
+
+
+def job_param(job: dict[str, Any]) -> dict[str, Any]:
+    param = job.get("param")
+    if isinstance(param, str):
+        try:
+            param = json.loads(param)
+        except json.JSONDecodeError as exc:
+            raise RoutineExecutionError("schedule param is not valid JSON") from exc
+    if not isinstance(param, dict):
+        raise RoutineExecutionError("schedule is missing its param payload")
+    return param
+
+
+def steps_for_job(job: dict[str, Any]) -> list[RoutineStep]:
+    param = job_param(job)
+    method = str(param.get("method") or "").strip()
+    if method != _SUPPORTED_JOB_METHOD:
+        raise RoutineExecutionError(f"unsupported schedule method {method!r}")
+    params = param.get("params")
+    entry = params[0] if isinstance(params, list) and params else params
+    if not isinstance(entry, dict):
+        raise RoutineExecutionError("schedule params must contain one settings object")
+
+    settings = {key: entry[key] for key in _CARRIED_ENTRY_KEYS if key in entry}
+    name = str(entry.get("name") or job.get("name") or "").strip()
+    if not name or name.isdigit():
+        name = f"Schedule {job.get('id', '')}".strip()
+    segments = _segment_ids(entry.get("segments"))
+    if segments:
+        return [
+            RoutineStep(
+                step_id=1,
+                name=name,
+                method="do_scenes_segments",
+                params={"data": [{**settings, "segs": segments}]},
+                finish_dp_ids=(),
+            )
+        ]
+    return [
+        RoutineStep(
+            step_id=1,
+            name=name,
+            method="do_scenes_app_start",
+            params=[settings],
+            finish_dp_ids=(),
+        )
+    ]
+
+
+def next_fire_time_utc(job: dict[str, Any], *, default_timezone: str = "", now: datetime | None = None) -> datetime | None:
+    if not as_bool(job.get("enabled", True), True):
+        return None
+    try:
+        spec = parse_cron(str(job.get("cron") or ""))
+    except CronError:
+        return None
+    zone = _zone(str(job.get("timeZoneId") or ""), default_timezone)
+    current = (now or datetime.now(timezone.utc)).astimezone(zone)
+    upcoming = next_fire(spec, current)
+    return upcoming.astimezone(timezone.utc) if upcoming is not None else None
+
+
+@inventory_mutation
+def _disable_job(ctx: ServerContext, device_id: str, job_id: Any) -> None:
+    inventory = load_inventory(ctx)
+    schedules = inventory.get("schedules")
+    jobs = schedules.get(device_id) if isinstance(schedules, dict) else None
+    if not isinstance(jobs, list):
+        return
+    for job in jobs:
+        if isinstance(job, dict) and str(job.get("id")) == str(job_id):
+            job["enabled"] = False
+    write_inventory(ctx, inventory)
+
+
+class ScheduleRunner:
+    def __init__(self, context: ServerContext, *, default_timezone: str = "") -> None:
+        self._context = context
+        self._default_timezone = default_timezone
+        self._last_tick: datetime | None = None
+        self._logger = context.loggers.get("api") or context.loggers.get("unknown") or _LOGGER
+
+    def due_jobs(self, since: datetime, until: datetime) -> list[tuple[str, dict[str, Any]]]:
+        inventory = load_inventory(self._context)
+        schedules = inventory.get("schedules")
+        if not isinstance(schedules, dict):
+            return []
+        due: list[tuple[str, dict[str, Any]]] = []
+        for device_id, jobs in schedules.items():
+            if not isinstance(jobs, list):
+                continue
+            for job in jobs:
+                if not isinstance(job, dict) or not as_bool(job.get("enabled", True), True):
+                    continue
+                try:
+                    spec = parse_cron(str(job.get("cron") or ""))
+                except CronError as exc:
+                    self._logger.warning("Skipping schedule %s on %s: %s", job.get("id"), device_id, exc)
+                    continue
+                zone = _zone(str(job.get("timeZoneId") or ""), self._default_timezone)
+                upcoming = next_fire(spec, since.astimezone(zone))
+                if upcoming is not None and upcoming.astimezone(timezone.utc) <= until:
+                    due.append((str(device_id), job))
+        return due
+
+    def tick(self, now: datetime | None = None) -> list[dict[str, Any]]:
+        """Fire anything that came due since the previous tick. Needs a running event loop."""
+        current = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
+        previous = self._last_tick
+        self._last_tick = current
+        if previous is None:
+            return []
+        results: list[dict[str, Any]] = []
+        runner = get_routine_runner(self._context)
+        for device_id, job in self.due_jobs(previous, current):
+            job_id = job.get("id")
+            try:
+                steps = steps_for_job(job)
+                result = runner.start_job(
+                    device_id=device_id,
+                    job_id=int(job_id) if str(job_id).isdigit() else 0,
+                    name=steps[0].name,
+                    steps=steps,
+                )
+            except (RoutineExecutionError, ValueError) as exc:
+                self._logger.warning("Schedule %s on %s not started: %s", job_id, device_id, exc)
+                result = {"accepted": False, "status": "error", "error": str(exc), "deviceId": device_id}
+            else:
+                self._logger.info("Schedule %s on %s fired: %s", job_id, device_id, result.get("status"))
+                if result.get("accepted") and not as_bool(job.get("repeated", True), True):
+                    _disable_job(self._context, device_id, job_id)
+            results.append({"jobId": job_id, **result})
+        return results
+
+    async def run(self, stop_event: asyncio.Event, *, tick_seconds: float = TICK_SECONDS) -> None:
+        self.tick()
+        while not stop_event.is_set():
+            try:
+                await asyncio.wait_for(stop_event.wait(), timeout=tick_seconds)
+            except TimeoutError:
+                pass
+            if stop_event.is_set():
+                return
+            try:
+                self.tick()
+            except Exception as exc:  # noqa: BLE001
+                self._logger.warning("Schedule tick failed: %s", exc)
diff --git a/tests/test_schedule_runner.py b/tests/test_schedule_runner.py
new file mode 100644
index 0000000..8769898
--- /dev/null
+++ b/tests/test_schedule_runner.py
@@ -0,0 +1,160 @@
+import json
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+
+import pytest
+
+import roborock_local_server.backend  # noqa: F401  (puts the bundled `shared` package on sys.path)
+from shared import schedule_runner as sr
+from shared.routine_runner import RoutineExecutionError
+
+NEW_YORK = "America/New_York"
+
+
+def _job(**overrides):
+    job = {
+        "id": 3549431,
+        "cron": "00 11 ? * 1,3,5",
+        "timeZoneId": NEW_YORK,
+        "repeated": True,
+        "enabled": True,
+        "param": {
+            "id": 1,
+            "method": "server_scheduled_start",
+            "params": [
+                {
+                    "repeat": 1,
+                    "water_box_mode": 203,
+                    "segments": "0",
+                    "fan_power": 104,
+                    "mop_mode": 300,
+                    "clean_mop": 1,
+                    "map_index": -1,
+                    "name": "1759965417864",
+                }
+            ],
+        },
+    }
+    job.update(overrides)
+    return job
+
+
+def _utc(*args):
+    return datetime(*args, tzinfo=timezone.utc)
+
+
+def test_next_fire_matches_the_cloud_reported_fire_times():
+    # Values taken from a real cloud snapshot: Monday 2026-09-28 for MWF 11:00 New York.
+    spec = sr.parse_cron("00 11 ? * 1,3,5")
+    zone = sr._zone(NEW_YORK, "")
+    after = _utc(2026, 9, 28, 12, 0).astimezone(zone)
+    assert sr.next_fire(spec, after).astimezone(timezone.utc) == _utc(2026, 9, 28, 15, 0)
+
+    tue_thu = sr.parse_cron("00 11 ? * 2,4")
+    assert sr.next_fire(tue_thu, after).astimezone(timezone.utc) == _utc(2026, 9, 29, 15, 0)
+
+
+def test_next_fire_is_strictly_after_and_skips_to_next_matching_day():
+    spec = sr.parse_cron("00 11 ? * 1,3,5")
+    zone = sr._zone(NEW_YORK, "")
+    on_the_minute = _utc(2026, 9, 28, 15, 0).astimezone(zone)
+    assert sr.next_fire(spec, on_the_minute).astimezone(timezone.utc) == _utc(2026, 9, 30, 15, 0)
+
+
+def test_weekend_cron_uses_sunday_zero():
+    spec = sr.parse_cron("00 11 ? * 0,6")
+    zone = sr._zone(NEW_YORK, "")
+    monday = _utc(2026, 9, 28, 12, 0).astimezone(zone)
+    assert sr.next_fire(spec, monday).astimezone(timezone.utc) == _utc(2026, 10, 3, 15, 0)
+
+
+@pytest.mark.parametrize("expression", ["", "* * * *", "61 * * * *", "* 25 * * *", "a b c d e", "*/0 * * * *"])
+def test_invalid_cron_is_rejected(expression):
+    with pytest.raises(sr.CronError):
+        sr.parse_cron(expression)
+
+
+def test_whole_house_job_becomes_an_app_start_step_carrying_vac_and_mop_settings():
+    steps = sr.steps_for_job(_job())
+    assert len(steps) == 1
+    step = steps[0]
+    assert step.method == "do_scenes_app_start"
+    assert step.params == [{"repeat": 1, "water_box_mode": 203, "fan_power": 104, "mop_mode": 300}]
+    assert step.name == "Schedule 3549431"
+
+
+def test_segment_job_becomes_a_segment_clean_step():
+    job = _job()
+    job["param"]["params"][0]["segments"] = "16,17"
+    step = sr.steps_for_job(job)[0]
+    assert step.method == "do_scenes_segments"
+    assert step.params["data"][0]["segs"] == [16, 17]
+    assert step.params["data"][0]["fan_power"] == 104
+
+
+def test_unsupported_method_is_refused():
+    job = _job()
+    job["param"]["method"] = "something_else"
+    with pytest.raises(RoutineExecutionError):
+        sr.steps_for_job(job)
+
+
+class _FakeRunner:
+    def __init__(self):
+        self.started = []
+
+    def start_job(self, **kwargs):
+        self.started.append(kwargs)
+        return {"accepted": True, "status": "started", "deviceId": kwargs["device_id"]}
+
+
+def _runner_with_inventory(tmp_path, monkeypatch, jobs):
+    inventory = {"schedules": {"duid-1": jobs}}
+    (tmp_path / "web_api_inventory.json").write_text(json.dumps(inventory), encoding="utf-8")
+    ctx = SimpleNamespace(http_jsonl=tmp_path / "http.jsonl", loggers={})
+    fake = _FakeRunner()
+    monkeypatch.setattr(sr, "get_routine_runner", lambda _ctx: fake)
+    return sr.ScheduleRunner(ctx), ctx, fake
+
+
+def test_tick_fires_a_job_that_came_due_since_the_previous_tick(tmp_path, monkeypatch):
+    runner, _ctx, fake = _runner_with_inventory(tmp_path, monkeypatch, [_job()])
+    assert runner.tick(_utc(2026, 9, 28, 14, 59, 40)) == []  # first tick only sets the baseline
+    results = runner.tick(_utc(2026, 9, 28, 15, 0, 5))
+    assert [r["status"] for r in results] == ["started"]
+    assert fake.started[0]["device_id"] == "duid-1"
+    assert fake.started[0]["steps"][0].method == "do_scenes_app_start"
+
+
+def test_tick_does_not_fire_twice_or_when_disabled(tmp_path, monkeypatch):
+    runner, _ctx, fake = _runner_with_inventory(
+        tmp_path, monkeypatch, [_job(), _job(id=2, enabled=False)]
+    )
+    runner.tick(_utc(2026, 9, 28, 14, 59, 40))
+    runner.tick(_utc(2026, 9, 28, 15, 0, 5))
+    runner.tick(_utc(2026, 9, 28, 15, 0, 25))
+    runner.tick(_utc(2026, 9, 28, 15, 0, 45) + timedelta(minutes=5))
+    assert len(fake.started) == 1
+
+
+def test_one_shot_job_disables_itself_after_firing(tmp_path, monkeypatch):
+    runner, _ctx, _fake = _runner_with_inventory(tmp_path, monkeypatch, [_job(repeated=False)])
+    runner.tick(_utc(2026, 9, 28, 14, 59, 40))
+    runner.tick(_utc(2026, 9, 28, 15, 0, 5))
+    saved = json.loads((tmp_path / "web_api_inventory.json").read_text(encoding="utf-8"))
+    assert saved["schedules"]["duid-1"][0]["enabled"] is False
+
+
+@pytest.mark.parametrize("disabled_value", [False, 0, "false", "0"])
+def test_string_typed_disabled_flag_is_respected(tmp_path, monkeypatch, disabled_value):
+    # Imported inventory stores booleans loosely ("false", 0); "false" must not read as enabled.
+    runner, _ctx, fake = _runner_with_inventory(tmp_path, monkeypatch, [_job(enabled=disabled_value)])
+    runner.tick(_utc(2026, 9, 28, 14, 59, 40))
+    runner.tick(_utc(2026, 9, 28, 15, 0, 5))
+    assert fake.started == []
+
+
+def test_next_fire_time_utc_is_none_when_disabled():
+    now = _utc(2026, 9, 28, 12, 0)
+    assert sr.next_fire_time_utc(_job(), now=now) == _utc(2026, 9, 28, 15, 0)
+    assert sr.next_fire_time_utc(_job(enabled=False), now=now) is None

From 03bdb20c987783bfae876d0a188d38c4b35b69f7 Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Mon, 12 Oct 2026 14:38:22 -0400
Subject: [PATCH 14/32] Run the schedule loop with the server and report
 nextFireTime

Start the scheduler alongside the other supervisor tasks and stop it on
shutdown. GET /user/devices/{id}/jobs now computes nextFireTime from the
cron instead of returning whatever value was captured at import time.

Co-Authored-By: Claude Sonnet 5.5 
(cherry picked from commit 14ddb5fcd8a7ec1b50fe3e90c8b7cc4cec5b0b97)
---
 .../https_server/routes/user/devices/service.py    |  4 ++++
 src/roborock_local_server/server.py                | 14 ++++++++++++++
 tests/test_schedules.py                            |  3 +++
 3 files changed, 21 insertions(+)

diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/service.py b/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/service.py
index 0f6990c..3185844 100644
--- a/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/service.py
+++ b/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/service.py
@@ -13,6 +13,7 @@
 from shared.context import ServerContext
 from shared.data_helpers import as_bool, as_int, default_product_name, get_value
 from shared.inventory_io import WEB_API_INVENTORY_FILE, load_inventory
+from shared.schedule_runner import next_fire_time_utc
 _DEFAULT_DEVICE_NAME = "Vacuum 1"
 
 
@@ -652,6 +653,9 @@ def device_jobs_payload(ctx: ServerContext, device_id: str) -> list[dict[str, An
         payload["repeated"] = as_bool(get_value(raw, "repeated", default=True), True)
         payload["enabled"] = as_bool(get_value(raw, "enabled", default=True), True)
         payload["param"] = get_value(raw, "param", default={}) or {}
+        upcoming = next_fire_time_utc(payload, default_timezone=str(getattr(ctx, "timezone", "") or ""))
+        if upcoming is not None:
+            payload["nextFireTime"] = upcoming.strftime("%Y-%m-%dT%H:%M:%S.000+00:00")
         schedules.append(payload)
     return schedules
 
diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py
index 105a2aa..c4669b1 100644
--- a/src/roborock_local_server/server.py
+++ b/src/roborock_local_server/server.py
@@ -54,6 +54,7 @@
 )
 from shared.inventory_io import atomic_write_inventory, inventory_transaction
 from shared.protocol_auth import ProtocolAuthStore
+from shared.schedule_runner import ScheduleRunner
 from https_server.routes.user.scene import validity as scene_validity
 from https_server.routes.auth.service import (
     build_login_data_response,
@@ -362,6 +363,7 @@ def __init__(
         self._mqtt_proxy: MqttTlsProxy | None = None
         self._http_server: ManagedFastApiServer | None = None
         self._renew_task: asyncio.Task[None] | None = None
+        self._schedule_task: asyncio.Task[None] | None = None
         self._stop_event = asyncio.Event()
 
         self.certificate_manager = CertificateManager(config=config, paths=paths)
@@ -1997,10 +1999,22 @@ async def start(self) -> None:
         if self._uses_local_tls() and self.config.tls.mode == "cloudflare_acme":
             self._renew_task = asyncio.create_task(self._renew_loop(), name="tls-renew-loop")
 
+        schedule_runner = ScheduleRunner(self.context, default_timezone=self.config.network.timezone)
+        self._schedule_task = asyncio.create_task(
+            schedule_runner.run(self._stop_event),
+            name="schedule-runner",
+        )
+
     async def stop(self) -> None:
         self._stop_event.set()
         self._turn_relay.stop()
         self._refresh_turn_health()
+        if self._schedule_task is not None:
+            self._schedule_task.cancel()
+            try:
+                await self._schedule_task
+            except asyncio.CancelledError:
+                pass
         if self._renew_task is not None:
             self._renew_task.cancel()
             try:
diff --git a/tests/test_schedules.py b/tests/test_schedules.py
index f97b103..1c0f26f 100644
--- a/tests/test_schedules.py
+++ b/tests/test_schedules.py
@@ -104,6 +104,9 @@ def test_device_jobs_endpoint_returns_imported_schedules(tmp_path: Path) -> None
     payload = response.json()
     assert payload["success"] is True
     assert payload["data"] == payload["result"]
+    # nextFireTime is computed from the cron against "now", so check its shape, not its value.
+    next_fire_time = payload["result"][0].pop("nextFireTime")
+    assert next_fire_time.endswith("T13:03:00.000+00:00")
     assert payload["result"] == [
         {
             **schedule,

From d6841e211d0f1cebb83a59a43a53d524897e9fd2 Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Mon, 12 Oct 2026 16:21:40 -0400
Subject: [PATCH 15/32] Add a schedule store and evaluate crons in the robot's
 timezone

schedule_store holds create/update/delete for the per-device jobs kept in
the inventory, so the timer RPC handler, HTTP routes and dashboard can
share one writer. Crons without their own timeZoneId now evaluate in the
zone the robot is told by /location (America/New_York unless configured)
rather than UTC, so a 11:00 schedule fires at 11:00 local.

Co-Authored-By: Claude Sonnet 5.5 
(cherry picked from commit 0751a7b06b683701a3607eb143258565b548c560)
---
 .../bundled_backend/shared/schedule_runner.py |  22 +---
 .../bundled_backend/shared/schedule_store.py  | 119 ++++++++++++++++++
 tests/test_schedules.py                       |   4 +-
 3 files changed, 128 insertions(+), 17 deletions(-)
 create mode 100644 src/roborock_local_server/bundled_backend/shared/schedule_store.py

diff --git a/src/roborock_local_server/bundled_backend/shared/schedule_runner.py b/src/roborock_local_server/bundled_backend/shared/schedule_runner.py
index c70fd3d..33fa64c 100644
--- a/src/roborock_local_server/bundled_backend/shared/schedule_runner.py
+++ b/src/roborock_local_server/bundled_backend/shared/schedule_runner.py
@@ -15,9 +15,11 @@
 from typing import TYPE_CHECKING, Any
 from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
 
+from .constants import DEFAULT_TIMEZONE
 from .data_helpers import as_bool
-from .inventory_io import inventory_mutation, load_inventory, write_inventory
+from .inventory_io import load_inventory
 from .routine_runner import RoutineExecutionError, RoutineStep, get_routine_runner
+from .schedule_store import set_enabled
 
 if TYPE_CHECKING:
     from .context import ServerContext
@@ -134,7 +136,8 @@ def next_fire(spec: CronSpec, after: datetime) -> datetime | None:
 
 
 def _zone(name: str, fallback: str) -> tzinfo:
-    for candidate in (name, fallback):
+    # DEFAULT_TIMEZONE is what /location tells the robot when none is configured.
+    for candidate in (name, fallback, DEFAULT_TIMEZONE):
         candidate = str(candidate or "").strip()
         if not candidate:
             continue
@@ -226,19 +229,6 @@ def next_fire_time_utc(job: dict[str, Any], *, default_timezone: str = "", now:
     return upcoming.astimezone(timezone.utc) if upcoming is not None else None
 
 
-@inventory_mutation
-def _disable_job(ctx: ServerContext, device_id: str, job_id: Any) -> None:
-    inventory = load_inventory(ctx)
-    schedules = inventory.get("schedules")
-    jobs = schedules.get(device_id) if isinstance(schedules, dict) else None
-    if not isinstance(jobs, list):
-        return
-    for job in jobs:
-        if isinstance(job, dict) and str(job.get("id")) == str(job_id):
-            job["enabled"] = False
-    write_inventory(ctx, inventory)
-
-
 class ScheduleRunner:
     def __init__(self, context: ServerContext, *, default_timezone: str = "") -> None:
         self._context = context
@@ -294,7 +284,7 @@ def tick(self, now: datetime | None = None) -> list[dict[str, Any]]:
             else:
                 self._logger.info("Schedule %s on %s fired: %s", job_id, device_id, result.get("status"))
                 if result.get("accepted") and not as_bool(job.get("repeated", True), True):
-                    _disable_job(self._context, device_id, job_id)
+                    set_enabled(self._context, device_id, job_id, False)
             results.append({"jobId": job_id, **result})
         return results
 
diff --git a/src/roborock_local_server/bundled_backend/shared/schedule_store.py b/src/roborock_local_server/bundled_backend/shared/schedule_store.py
new file mode 100644
index 0000000..1d762fc
--- /dev/null
+++ b/src/roborock_local_server/bundled_backend/shared/schedule_store.py
@@ -0,0 +1,119 @@
+"""Create, update and delete the per-device schedules kept in the inventory."""
+
+from __future__ import annotations
+
+import copy
+from typing import TYPE_CHECKING, Any
+
+from .inventory_io import inventory_mutation, load_inventory, write_inventory
+
+if TYPE_CHECKING:
+    from .context import ServerContext
+
+DEFAULT_JOB_PARAM: dict[str, Any] = {
+    "id": 1,
+    "method": "server_scheduled_start",
+    "params": [{"repeat": 1, "segments": "0"}],
+}
+
+
+def _same_id(job: Any, job_id: Any) -> bool:
+    return isinstance(job, dict) and str(job.get("id")) == str(job_id)
+
+
+def _jobs_for(inventory: dict[str, Any], duid: str, *, create: bool) -> list[Any] | None:
+    schedules = inventory.get("schedules")
+    if not isinstance(schedules, dict):
+        if not create:
+            return None
+        schedules = {}
+        inventory["schedules"] = schedules
+    jobs = schedules.get(duid)
+    if not isinstance(jobs, list):
+        if not create:
+            return None
+        jobs = []
+        schedules[duid] = jobs
+    return jobs
+
+
+def _coerce_id(job_id: Any) -> Any:
+    text = str(job_id).strip()
+    return int(text) if text.isdigit() else text
+
+
+def list_jobs(ctx: ServerContext, duid: str) -> list[dict[str, Any]]:
+    jobs = _jobs_for(load_inventory(ctx), duid, create=False) or []
+    return [copy.deepcopy(job) for job in jobs if isinstance(job, dict)]
+
+
+@inventory_mutation
+def upsert_job(
+    ctx: ServerContext,
+    duid: str,
+    *,
+    job_id: Any,
+    cron: str,
+    enabled: bool,
+    time_zone: str = "",
+    repeated: bool | None = None,
+    param: dict[str, Any] | None = None,
+    override_time_zone: bool = False,
+) -> dict[str, Any]:
+    """Create the job, or update cron/enabled on an existing one while keeping its settings.
+
+    An existing job keeps its own timezone unless ``override_time_zone`` is set.
+    """
+    inventory = load_inventory(ctx)
+    jobs = _jobs_for(inventory, duid, create=True)
+    assert jobs is not None
+    existing = next((job for job in jobs if _same_id(job, job_id)), None)
+    if existing is None:
+        existing = {
+            "id": _coerce_id(job_id),
+            "repeated": True if repeated is None else repeated,
+            "type": "clean",
+            "param": copy.deepcopy(param) if param is not None else copy.deepcopy(DEFAULT_JOB_PARAM),
+        }
+        if time_zone:
+            existing["timeZoneId"] = time_zone
+        jobs.append(existing)
+    else:
+        if repeated is not None:
+            existing["repeated"] = repeated
+        if param is not None:
+            existing["param"] = copy.deepcopy(param)
+        if override_time_zone and time_zone:
+            existing["timeZoneId"] = time_zone
+    existing["cron"] = cron
+    existing["enabled"] = enabled
+    write_inventory(ctx, inventory)
+    return copy.deepcopy(existing)
+
+
+@inventory_mutation
+def set_enabled(ctx: ServerContext, duid: str, job_id: Any, enabled: bool) -> bool:
+    inventory = load_inventory(ctx)
+    jobs = _jobs_for(inventory, duid, create=False) or []
+    found = False
+    for job in jobs:
+        if _same_id(job, job_id):
+            job["enabled"] = enabled
+            found = True
+    if found:
+        write_inventory(ctx, inventory)
+    return found
+
+
+@inventory_mutation
+def delete_job(ctx: ServerContext, duid: str, job_id: Any) -> bool:
+    inventory = load_inventory(ctx)
+    jobs = _jobs_for(inventory, duid, create=False)
+    if not jobs:
+        return False
+    remaining = [job for job in jobs if not _same_id(job, job_id)]
+    if len(remaining) == len(jobs):
+        return False
+    jobs[:] = remaining
+    write_inventory(ctx, inventory)
+    return True
diff --git a/tests/test_schedules.py b/tests/test_schedules.py
index 1c0f26f..e4a9ced 100644
--- a/tests/test_schedules.py
+++ b/tests/test_schedules.py
@@ -105,8 +105,10 @@ def test_device_jobs_endpoint_returns_imported_schedules(tmp_path: Path) -> None
     assert payload["success"] is True
     assert payload["data"] == payload["result"]
     # nextFireTime is computed from the cron against "now", so check its shape, not its value.
+    # No timezone is configured, so the cron runs in the zone the robot is told (America/New_York):
+    # 13:03 local on Dec 15 is 18:03Z.
     next_fire_time = payload["result"][0].pop("nextFireTime")
-    assert next_fire_time.endswith("T13:03:00.000+00:00")
+    assert next_fire_time.endswith("T18:03:00.000+00:00")
     assert payload["result"] == [
         {
             **schedule,

From 4e2be9453b25c8f1a439b347c940e69eff0e52d0 Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Mon, 12 Oct 2026 16:21:40 -0400
Subject: [PATCH 16/32] Answer get/set/upd/del_timer from the schedule store

Timer RPCs carry each schedule's vac and mop settings, and a schedule keeps
the official app's link to its server_timer entry (the robot-side id in its
name) so writing it back goes to the right robot entry.

The four get/set/upd/del_server_timer methods are left to the robot: a robot
that speaks server_timer stores those schedules itself, and answering them
from this store hid the robot's real schedules and, tried once, caused data
loss (the official app deletes server_timer entries it does not recognize when
its schedule screen opens). A parametrized test over all four methods keeps
the interceptor's method list from regressing.

Co-Authored-By: Claude Sonnet 5.5 
---
 .../mqtt_broker_server/topic_bridge.py        |  19 +-
 .../bundled_backend/shared/schedule_store.py  |  73 +++++
 .../bundled_backend/shared/timer_rpc.py       | 233 ++++++++++++++++
 src/roborock_local_server/server.py           |   5 +
 tests/test_schedule_store.py                  |  21 ++
 tests/test_timer_rpc.py                       | 249 ++++++++++++++++++
 6 files changed, 599 insertions(+), 1 deletion(-)
 create mode 100644 src/roborock_local_server/bundled_backend/shared/timer_rpc.py
 create mode 100644 tests/test_schedule_store.py
 create mode 100644 tests/test_timer_rpc.py

diff --git a/src/roborock_local_server/bundled_backend/mqtt_broker_server/topic_bridge.py b/src/roborock_local_server/bundled_backend/mqtt_broker_server/topic_bridge.py
index 7bc087a..1276126 100644
--- a/src/roborock_local_server/bundled_backend/mqtt_broker_server/topic_bridge.py
+++ b/src/roborock_local_server/bundled_backend/mqtt_broker_server/topic_bridge.py
@@ -9,7 +9,7 @@
 from pathlib import Path
 import re
 import time
-from typing import Any
+from typing import Any, Callable
 
 import aiomqtt
 
@@ -73,7 +73,11 @@ def __init__(
         fixed_device_mqtt_usr: str = "",
         runtime_state: Any | None = None,
         inventory_path: Path | None = None,
+        request_interceptor: Callable[[str, bytes], bytes | None] | None = None,
     ) -> None:
+        # Given (duid, payload) for each rr/m request; returns an encoded reply to
+        # publish back to the requester instead of forwarding, or None to forward.
+        self._request_interceptor = request_interceptor
         self._host = host
         self._port = port
         self._logger = logger
@@ -389,6 +393,19 @@ async def _handle_cloud_message(
         cloud_topic: CloudTopicKey,
         src_topic: str,
     ) -> None:
+        if self._request_interceptor is not None:
+            payload = message.payload
+            raw = payload if isinstance(payload, (bytes, bytearray)) else str(payload).encode()
+            try:
+                reply = self._request_interceptor(cloud_topic.duid, bytes(raw))
+            except Exception as exc:  # noqa: BLE001
+                self._logger.warning("MQTT request interceptor failed for %s: %s", src_topic, exc)
+                reply = None
+            if reply is not None:
+                await client.publish(cloud_topic.topic_out, reply, qos=_extract_qos(message))
+                self._logger.info("MQTT bridge answered %s locally -> %s", src_topic, cloud_topic.topic_out)
+                return
+
         device_topic = self._resolve_device_for_cloud(cloud_topic)
         if device_topic is None:
             if cloud_topic.duid not in self._warned_unmapped_duids:
diff --git a/src/roborock_local_server/bundled_backend/shared/schedule_store.py b/src/roborock_local_server/bundled_backend/shared/schedule_store.py
index 1d762fc..8426e54 100644
--- a/src/roborock_local_server/bundled_backend/shared/schedule_store.py
+++ b/src/roborock_local_server/bundled_backend/shared/schedule_store.py
@@ -17,6 +17,79 @@
 }
 
 
+JOB_SETTING_KEYS = (
+    "repeat",
+    "fan_power",
+    "water_box_mode",
+    "mop_mode",
+    "mop_template_id",
+    "segments",
+    "clean_mop",
+)
+_INT_SETTING_KEYS = frozenset(JOB_SETTING_KEYS) - {"segments"}
+
+
+class SettingsError(ValueError):
+    """A schedule setting had a value this server cannot store."""
+
+
+def _normalize_setting(key: str, value: Any) -> Any:
+    if key == "segments":
+        items = value.replace(";", ",").split(",") if isinstance(value, str) else list(value)
+        try:
+            ids = [int(str(item).strip()) for item in items if str(item).strip()]
+        except ValueError as exc:
+            raise SettingsError(f"segments must be room ids, got {value!r}") from exc
+        ids = [room for room in ids if room > 0]
+        return ",".join(str(room) for room in ids) if ids else "0"
+    if isinstance(value, bool) or not isinstance(value, (int, str)):
+        raise SettingsError(f"{key} must be a number, got {value!r}")
+    try:
+        return int(value)
+    except ValueError as exc:
+        raise SettingsError(f"{key} must be a number, got {value!r}") from exc
+
+
+def job_settings(job: dict[str, Any]) -> dict[str, Any]:
+    """The vac/mop settings a job carries, as a flat dict.
+
+    ``name``, when the job has one, rides along too, outside ``JOB_SETTING_KEYS``: it is not a
+    vac/mop setting a client edits, it is the official app's own link from this job to the
+    robot's server_timer entry it saved alongside it (POST/PUT /user/devices/{duid}/jobs carries
+    it in exactly this spot, confirmed live). A client that reads the job back through get_timer
+    needs it to find the robot's entry to edit or delete.
+    """
+    param = job.get("param")
+    params = param.get("params") if isinstance(param, dict) else None
+    entry = params[0] if isinstance(params, list) and params and isinstance(params[0], dict) else {}
+    settings = {key: entry[key] for key in JOB_SETTING_KEYS if key in entry}
+    name = entry.get("name")
+    if isinstance(name, str) and name:
+        settings["name"] = name
+    return settings
+
+
+def merge_job_settings(param: dict[str, Any] | None, settings: dict[str, Any]) -> dict[str, Any]:
+    """Copy of ``param`` with ``settings`` merged in; a None value clears that setting.
+
+    Settings not mentioned are left alone, so editing one option never resets the rest.
+    """
+    merged = copy.deepcopy(param) if isinstance(param, dict) else copy.deepcopy(DEFAULT_JOB_PARAM)
+    params = merged.get("params")
+    if not isinstance(params, list) or not params or not isinstance(params[0], dict):
+        params = copy.deepcopy(DEFAULT_JOB_PARAM["params"])
+        merged["params"] = params
+    entry = params[0]
+    for key, value in settings.items():
+        if key not in JOB_SETTING_KEYS:
+            raise SettingsError(f"unknown schedule setting {key!r}")
+        if value is None:
+            entry.pop(key, None)
+        else:
+            entry[key] = _normalize_setting(key, value)
+    return merged
+
+
 def _same_id(job: Any, job_id: Any) -> bool:
     return isinstance(job, dict) and str(job.get("id")) == str(job_id)
 
diff --git a/src/roborock_local_server/bundled_backend/shared/timer_rpc.py b/src/roborock_local_server/bundled_backend/shared/timer_rpc.py
new file mode 100644
index 0000000..3d93ef3
--- /dev/null
+++ b/src/roborock_local_server/bundled_backend/shared/timer_rpc.py
@@ -0,0 +1,233 @@
+"""Answer the vacuum's legacy timer RPCs (get/set/upd/del_timer) from the schedule store.
+
+On cloud-managed robots the schedules live server-side, not on the robot, so
+clients such as LocalRock that ask the robot for its timers would otherwise see
+nothing and could never change the schedules the cloud imported. The topic
+bridge hands matching requests here instead of forwarding them to the robot.
+
+Deliberately not handled here: get/set/upd/del_server_timer, the newer sibling
+protocol some firmware speaks instead of (or alongside) this one. The robot
+stores those entries itself and the official app reads them back from it, so
+they must always forward to the robot untouched. Answering them from this store
+instead, tried once, hid the robot's real schedules from every client reading
+through the server, and the official app then deleted them (it removes
+server_timer entries it does not recognize when its schedule screen opens).
+
+What runs a server_timer schedule is the cloud's own record of it, the job the
+official app also writes to /user/devices/{duid}/jobs, which ScheduleRunner
+fires like any other. The robot was not seen to run them itself.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import time
+from typing import TYPE_CHECKING, Any
+
+from roborock.protocol import create_mqtt_decoder, create_mqtt_encoder
+from roborock.roborock_message import RoborockMessage, RoborockMessageProtocol
+
+from .constants import DEFAULT_TIMEZONE
+from .schedule_runner import CronError, parse_cron
+from .schedule_store import (
+    JOB_SETTING_KEYS,
+    SettingsError,
+    delete_job,
+    job_settings,
+    list_jobs,
+    merge_job_settings,
+    set_enabled,
+    upsert_job,
+)
+
+if TYPE_CHECKING:
+    from .context import ServerContext
+
+_LOGGER = logging.getLogger(__name__)
+
+TIMER_METHODS = frozenset({"get_timer", "set_timer", "upd_timer", "del_timer"})
+_OK = ["ok"]
+
+
+class TimerRequestError(ValueError):
+    """The request used a shape this handler cannot interpret."""
+
+
+def device_cron(cron: str) -> str | None:
+    """Cron in the robot's own 'm h dom month dow' form, with '?' written as '*'.
+
+    A one-time schedule pins the day of the month and the month ('15 23 18 10 *'), exactly as
+    the robot and the official app write it (confirmed live), so it is shown like any other.
+    A job that pins only one of the two has no such form and is left out of get_timer rather
+    than shown wrong.
+    """
+    fields = str(cron or "").split()
+    if len(fields) != 5:
+        return None
+    minute, hour, dom, month, dow = (field if field != "?" else "*" for field in fields)
+    if (dom == "*") != (month == "*"):
+        return None
+    return f"{minute} {hour} {dom} {month} {dow}"
+
+
+def _timer_entry(job: dict[str, Any]) -> list[Any] | None:
+    cron = device_cron(str(job.get("cron") or ""))
+    if cron is None:
+        return None
+    enabled = job.get("enabled", True)
+    on = enabled not in (False, 0, "0", "false", "False")
+    return [str(job.get("id")), "on" if on else "off", [cron, ["start_clean", job_settings(job)]]]
+
+
+def _parse_set_timer(params: Any) -> tuple[str, bool, str, dict[str, Any]]:
+    entry = params[0] if isinstance(params, list) and params and isinstance(params[0], list) else params
+    if not isinstance(entry, list) or len(entry) < 2:
+        raise TimerRequestError("set_timer needs [id, [status, [cron, action]]]")
+    job_id = str(entry[0])
+    if len(entry) >= 3 and isinstance(entry[1], str):
+        status, detail = entry[1], entry[2]
+    else:
+        spec = entry[1]
+        if not isinstance(spec, list) or len(spec) < 2:
+            raise TimerRequestError("set_timer spec must be [status, [cron, action]]")
+        status, detail = spec[0], spec[1]
+    if not isinstance(detail, list) or not detail:
+        raise TimerRequestError("set_timer is missing its cron")
+    action = detail[1] if len(detail) > 1 else None
+    settings = action[1] if isinstance(action, list) and len(action) > 1 and isinstance(action[1], dict) else {}
+    return job_id, str(status).lower() == "on", str(detail[0]), settings
+
+
+def _id_and_status(params: Any) -> tuple[str, str]:
+    entry = params[0] if isinstance(params, list) and params and isinstance(params[0], list) else params
+    if not isinstance(entry, list) or len(entry) < 2:
+        raise TimerRequestError("upd_timer needs [id, status]")
+    return str(entry[0]), str(entry[1]).lower()
+
+
+def _single_id(params: Any) -> str:
+    if isinstance(params, list) and params:
+        first = params[0]
+        return str(first[0]) if isinstance(first, list) and first else str(first)
+    if params is None or params == []:
+        raise TimerRequestError("del_timer needs a timer id")
+    return str(params)
+
+
+def handle_timer_request(
+    ctx: ServerContext,
+    duid: str,
+    method: str,
+    params: Any,
+    *,
+    default_timezone: str = "",
+) -> Any:
+    """Apply one timer RPC to the store and return the RPC ``result`` value."""
+    if method == "get_timer":
+        entries = (_timer_entry(job) for job in list_jobs(ctx, duid))
+        return [entry for entry in entries if entry is not None]
+
+    if method == "set_timer":
+        job_id, enabled, cron, action_settings = _parse_set_timer(params)
+        try:
+            parse_cron(cron)
+        except CronError as exc:
+            raise TimerRequestError(str(exc)) from exc
+        # An empty action object (what older clients send) leaves the job's settings alone;
+        # keys it does carry are merged in, so a client can change one option at a time.
+        settings = {key: value for key, value in action_settings.items() if key in JOB_SETTING_KEYS}
+        param = None
+        if settings:
+            existing = next((job for job in list_jobs(ctx, duid) if str(job.get("id")) == job_id), None)
+            try:
+                param = merge_job_settings(existing.get("param") if existing else None, settings)
+            except SettingsError as exc:
+                raise TimerRequestError(str(exc)) from exc
+        zone = str(getattr(ctx, "timezone", "") or default_timezone or DEFAULT_TIMEZONE)
+        upsert_job(ctx, duid, job_id=job_id, cron=cron, enabled=enabled, time_zone=zone, param=param)
+        return list(_OK)
+
+    if method == "upd_timer":
+        job_id, status = _id_and_status(params)
+        if status not in ("on", "off"):
+            raise TimerRequestError(f"unknown timer status {status!r}")
+        set_enabled(ctx, duid, job_id, status == "on")
+        return list(_OK)
+
+    if method == "del_timer":
+        delete_job(ctx, duid, _single_id(params))
+        return list(_OK)
+
+    raise TimerRequestError(f"not a timer method: {method!r}")
+
+
+class TimerRpcInterceptor:
+    """Bridge hook: turn an encrypted timer request into an encrypted reply, or None to forward."""
+
+    def __init__(self, context: ServerContext, *, default_timezone: str = "") -> None:
+        self._context = context
+        self._default_timezone = default_timezone
+
+    def _localkey(self, duid: str) -> str:
+        creds = self._context.runtime_credentials
+        device = creds.resolve_device(duid=duid) if creds is not None else None
+        key = str((device or {}).get("localkey") or "").strip()
+        return key or str(getattr(self._context, "localkey", "") or "").strip()
+
+    def __call__(self, duid: str, payload: bytes) -> bytes | None:
+        localkey = self._localkey(duid)
+        if not localkey:
+            return None
+        try:
+            messages = create_mqtt_decoder(localkey)(payload)
+        except Exception:  # noqa: BLE001
+            return None
+        if len(messages) != 1:
+            return None
+        message = messages[0]
+        protocol = int(getattr(message.protocol, "value", message.protocol))
+        if protocol != RoborockMessageProtocol.RPC_REQUEST.value or not message.payload:
+            return None
+        request = _request_body(message)
+        if request is None or request.get("method") not in TIMER_METHODS:
+            return None
+
+        request_id = request.get("id")
+        try:
+            body: dict[str, Any] = {
+                "id": request_id,
+                "result": handle_timer_request(
+                    self._context,
+                    duid,
+                    str(request["method"]),
+                    request.get("params"),
+                    default_timezone=self._default_timezone,
+                ),
+            }
+        except TimerRequestError as exc:
+            _LOGGER.warning("Rejected %s for %s: %s", request.get("method"), duid, exc)
+            body = {"id": request_id, "error": {"code": -1, "message": str(exc)}}
+        reply = RoborockMessage(
+            protocol=RoborockMessageProtocol.RPC_RESPONSE,
+            payload=json.dumps(
+                {
+                    "t": int(time.time()),
+                    "dps": {str(RoborockMessageProtocol.RPC_RESPONSE.value): json.dumps(body)},
+                },
+                separators=(",", ":"),
+            ).encode(),
+            seq=message.seq,
+            version=message.version,
+        )
+        return create_mqtt_encoder(localkey)(reply)
+
+
+def _request_body(message: RoborockMessage) -> dict[str, Any] | None:
+    try:
+        outer = json.loads(message.payload)
+        inner = outer["dps"][str(RoborockMessageProtocol.RPC_REQUEST.value)]
+        body = json.loads(inner) if isinstance(inner, str) else inner
+    except (ValueError, KeyError, TypeError):
+        return None
+    return body if isinstance(body, dict) else None
diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py
index c4669b1..4789505 100644
--- a/src/roborock_local_server/server.py
+++ b/src/roborock_local_server/server.py
@@ -55,6 +55,7 @@
 from shared.inventory_io import atomic_write_inventory, inventory_transaction
 from shared.protocol_auth import ProtocolAuthStore
 from shared.schedule_runner import ScheduleRunner
+from shared.timer_rpc import TimerRpcInterceptor
 from https_server.routes.user.scene import validity as scene_validity
 from https_server.routes.auth.service import (
     build_login_data_response,
@@ -1970,6 +1971,10 @@ async def start(self) -> None:
                 logger=self.loggers["mqtt"],
                 runtime_state=self.runtime_state,
                 inventory_path=self.paths.inventory_path,
+                request_interceptor=TimerRpcInterceptor(
+                    self.context,
+                    default_timezone=self.config.network.timezone,
+                ),
             )
             await self._topic_bridge.start()
             self.runtime_state.set_service("mqtt_topic_bridge", running=True, required=False, enabled=True)
diff --git a/tests/test_schedule_store.py b/tests/test_schedule_store.py
new file mode 100644
index 0000000..85d00ca
--- /dev/null
+++ b/tests/test_schedule_store.py
@@ -0,0 +1,21 @@
+import roborock_local_server.backend  # noqa: F401  (puts the bundled `shared` package on sys.path)
+from shared.schedule_store import job_settings
+
+
+def _job(**entry_overrides):
+    entry = {"repeat": 1, "fan_power": 104, "water_box_mode": 203}
+    entry.update(entry_overrides)
+    return {"id": "1", "enabled": True, "param": {"params": [entry]}}
+
+
+def test_job_settings_carries_name_when_present():
+    # "name" is the official app's link to the robot's server_timer entry, not a JOB_SETTING_KEYS
+    # vac/mop setting, confirmed live in its POST/PUT /user/devices/{duid}/jobs body.
+    job = _job(name="1759965417864")
+    assert job_settings(job) == {"repeat": 1, "fan_power": 104, "water_box_mode": 203, "name": "1759965417864"}
+
+
+def test_job_settings_omits_name_when_absent_or_blank():
+    assert "name" not in job_settings(_job())
+    assert "name" not in job_settings(_job(name=""))
+    assert "name" not in job_settings(_job(name=None))
diff --git a/tests/test_timer_rpc.py b/tests/test_timer_rpc.py
new file mode 100644
index 0000000..c187caf
--- /dev/null
+++ b/tests/test_timer_rpc.py
@@ -0,0 +1,249 @@
+import asyncio
+import json
+import logging
+from types import SimpleNamespace
+
+import pytest
+
+import roborock_local_server.backend  # noqa: F401  (puts the bundled `shared` package on sys.path)
+from roborock.protocol import create_mqtt_decoder, create_mqtt_encoder
+from roborock.protocols.v1_protocol import decode_rpc_response
+from roborock.roborock_message import RoborockMessage, RoborockMessageProtocol
+from roborock_local_server.bundled_backend.mqtt_broker_server.topic_bridge import (
+    CloudTopicKey,
+    MqttTopicBridge,
+)
+from shared import schedule_store, timer_rpc
+
+DUID = "2e2txkqKqxVifcIdyOT1lY"
+LOCALKEY = "AoYY9mpxTOIUZtg4"
+
+
+def _cloud_job(job_id, cron, *, enabled=True, **extra):
+    job = {
+        "id": job_id,
+        "cron": cron,
+        "timeZoneId": "America/New_York",
+        "repeated": True,
+        "enabled": enabled,
+        "param": {
+            "id": 1,
+            "method": "server_scheduled_start",
+            "params": [{"repeat": 1, "water_box_mode": 203, "segments": "0", "fan_power": 104, "mop_mode": 300}],
+        },
+    }
+    job.update(extra)
+    return job
+
+
+@pytest.fixture
+def ctx(tmp_path):
+    inventory = {
+        "schedules": {
+            DUID: [
+                _cloud_job(3549431, "00 11 ? * 1,3,5"),
+                _cloud_job(3549434, "00 11 ? * 0,6", enabled=False),
+                _cloud_job(3878757, "03 13 15 12 ?", repeated=False),
+            ]
+        }
+    }
+    (tmp_path / "web_api_inventory.json").write_text(json.dumps(inventory), encoding="utf-8")
+    creds = SimpleNamespace(resolve_device=lambda duid="": {"localkey": LOCALKEY} if duid == DUID else None)
+    return SimpleNamespace(
+        http_jsonl=tmp_path / "http.jsonl", loggers={}, timezone="America/New_York",
+        runtime_credentials=creds, localkey="",
+    )
+
+
+def test_get_timer_lists_cloud_schedules_in_the_shape_localrock_parses(ctx):
+    result = timer_rpc.handle_timer_request(ctx, DUID, "get_timer", None)
+    # The one-off (Dec 15) keeps its day and month, the form the robot and the official app use.
+    settings = {"repeat": 1, "water_box_mode": 203, "segments": "0", "fan_power": 104, "mop_mode": 300}
+    assert result == [
+        ["3549431", "on", ["00 11 * * 1,3,5", ["start_clean", settings]]],
+        ["3549434", "off", ["00 11 * * 0,6", ["start_clean", settings]]],
+        ["3878757", "on", ["03 13 15 12 *", ["start_clean", settings]]],
+    ]
+
+
+@pytest.mark.parametrize(
+    ("cron", "expected"),
+    [
+        ("15 23 18 10 ?", "15 23 18 10 *"),
+        ("15 23 18 10 *", "15 23 18 10 *"),
+        ("00 11 ? * 1,3,5", "00 11 * * 1,3,5"),
+        ("0 8 * * 0,1,2,3,4,5,6", "0 8 * * 0,1,2,3,4,5,6"),
+        # Only one of day and month pinned has no one-time form.
+        ("0 8 15 * *", None),
+        ("0 8 * 10 *", None),
+        ("not a cron", None),
+    ],
+)
+def test_device_cron_keeps_a_one_time_schedules_date(cron, expected):
+    assert timer_rpc.device_cron(cron) == expected
+
+
+def test_set_timer_creates_a_job_and_get_timer_returns_it(ctx):
+    params = [["1790000000", ["on", ["30 7 * * 1,2", ["start_clean", {}]]]]]
+    assert timer_rpc.handle_timer_request(ctx, DUID, "set_timer", params) == ["ok"]
+
+    job = next(j for j in schedule_store.list_jobs(ctx, DUID) if str(j["id"]) == "1790000000")
+    assert job["cron"] == "30 7 * * 1,2"
+    assert job["enabled"] is True
+    assert job["timeZoneId"] == "America/New_York"
+    assert job["param"]["method"] == "server_scheduled_start"
+
+    listed = timer_rpc.handle_timer_request(ctx, DUID, "get_timer", None)
+    default_settings = {"repeat": 1, "segments": "0"}
+    assert ["1790000000", "on", ["30 7 * * 1,2", ["start_clean", default_settings]]] in listed
+
+
+def test_editing_a_cloud_schedule_keeps_its_vac_and_mop_settings(ctx):
+    params = [["3549431", ["on", ["15 9 * * 1,3,5", ["start_clean", {}]]]]]
+    timer_rpc.handle_timer_request(ctx, DUID, "set_timer", params)
+
+    job = next(j for j in schedule_store.list_jobs(ctx, DUID) if j["id"] == 3549431)
+    assert job["cron"] == "15 9 * * 1,3,5"
+    entry = job["param"]["params"][0]
+    assert (entry["fan_power"], entry["water_box_mode"], entry["mop_mode"]) == (104, 203, 300)
+
+
+def test_upd_timer_toggles_and_del_timer_removes_a_cloud_schedule(ctx):
+    assert timer_rpc.handle_timer_request(ctx, DUID, "upd_timer", [["3549431", "off"]]) == ["ok"]
+    job = next(j for j in schedule_store.list_jobs(ctx, DUID) if j["id"] == 3549431)
+    assert job["enabled"] is False
+
+    assert timer_rpc.handle_timer_request(ctx, DUID, "del_timer", ["3549431"]) == ["ok"]
+    assert all(j["id"] != 3549431 for j in schedule_store.list_jobs(ctx, DUID))
+
+
+def test_set_timer_rejects_an_unparseable_cron(ctx):
+    with pytest.raises(timer_rpc.TimerRequestError):
+        timer_rpc.handle_timer_request(ctx, DUID, "set_timer", [["1", ["on", ["not a cron", []]]]])
+
+
+def _encode_request(method, params, request_id=4242):
+    payload = json.dumps(
+        {"t": 1790000000, "dps": {"101": json.dumps({"id": request_id, "method": method, "params": params})}}
+    ).encode()
+    message = RoborockMessage(protocol=RoborockMessageProtocol.RPC_REQUEST, payload=payload)
+    return create_mqtt_encoder(LOCALKEY)(message)
+
+
+def _decode_reply(reply):
+    (message,) = create_mqtt_decoder(LOCALKEY)(reply)
+    return decode_rpc_response(message)
+
+
+def test_interceptor_answers_get_timer_with_an_encrypted_rpc_response(ctx):
+    reply = timer_rpc.TimerRpcInterceptor(ctx)(DUID, _encode_request("get_timer", []))
+    assert reply is not None
+    response = _decode_reply(reply)
+    assert response.request_id == 4242
+    assert [entry[0] for entry in response.data] == ["3549431", "3549434", "3878757"]
+
+
+def test_interceptor_forwards_everything_that_is_not_a_timer_request(ctx):
+    interceptor = timer_rpc.TimerRpcInterceptor(ctx)
+    assert interceptor(DUID, _encode_request("get_status", [])) is None
+    assert interceptor(DUID, b"not a roborock frame") is None
+    assert interceptor("unknown-duid", _encode_request("get_timer", [])) is None
+
+
+@pytest.mark.parametrize(
+    "method", ["get_server_timer", "set_server_timer", "upd_server_timer", "del_server_timer"]
+)
+def test_interceptor_leaves_server_timer_to_the_robot(ctx, method):
+    # A robot that speaks server_timer stores those entries itself and the official app reads
+    # them back from it; answering this locally hides the robot's real schedules from every
+    # client and has caused real data loss. This must always forward, never answer here.
+    interceptor = timer_rpc.TimerRpcInterceptor(ctx)
+    assert interceptor(DUID, _encode_request(method, [])) is None
+
+
+def test_bridge_answers_timer_requests_locally_and_does_not_forward_them(ctx):
+    class Client:
+        def __init__(self):
+            self.published = []
+
+        async def publish(self, topic, payload, *, qos=0, retain=False):
+            self.published.append((topic, payload))
+
+    bridge = MqttTopicBridge(
+        host="127.0.0.1",
+        port=1883,
+        logger=logging.getLogger("test.timer_bridge"),
+        request_interceptor=timer_rpc.TimerRpcInterceptor(ctx),
+    )
+    cloud = CloudTopicKey(rriot_u="u", mqtt_username="m", duid=DUID)
+    message = SimpleNamespace(payload=_encode_request("get_timer", []), qos=0, retain=False)
+    client = Client()
+
+    asyncio.run(bridge._handle_cloud_message(client, message, cloud, cloud.topic_in))
+
+    assert [topic for topic, _ in client.published] == [cloud.topic_out]
+    assert _decode_reply(client.published[0][1]).request_id == 4242
+
+
+def _job(ctx, job_id):
+    return next(j for j in schedule_store.list_jobs(ctx, DUID) if str(j["id"]) == str(job_id))
+
+
+def test_set_timer_carries_vac_and_mop_settings_in_the_action_object(ctx):
+    action = ["start_clean", {"fan_power": 102, "water_box_mode": 200, "repeat": 2}]
+    params = [["1790000001", ["on", ["0 9 * * 2,4", action]]]]
+    assert timer_rpc.handle_timer_request(ctx, DUID, "set_timer", params) == ["ok"]
+
+    entry = _job(ctx, 1790000001)["param"]["params"][0]
+    assert (entry["fan_power"], entry["water_box_mode"], entry["repeat"]) == (102, 200, 2)
+
+    listed = timer_rpc.handle_timer_request(ctx, DUID, "get_timer", None)
+    row = next(item for item in listed if item[0] == "1790000001")
+    assert row[2][1][1]["water_box_mode"] == 200
+
+
+def test_changing_one_setting_leaves_the_others_alone(ctx):
+    action = ["start_clean", {"water_box_mode": 200}]  # vac only on this cloud schedule
+    timer_rpc.handle_timer_request(ctx, DUID, "set_timer", [["3549431", ["on", ["00 11 * * 1,3,5", action]]]])
+
+    entry = _job(ctx, 3549431)["param"]["params"][0]
+    assert entry["water_box_mode"] == 200
+    assert (entry["fan_power"], entry["mop_mode"]) == (104, 300)
+
+
+def test_an_empty_action_object_does_not_reset_existing_settings(ctx):
+    # What older LocalRock builds send: ["start_clean", {}].
+    action = ["start_clean", {}]
+    timer_rpc.handle_timer_request(ctx, DUID, "set_timer", [["3549431", ["on", ["30 8 * * 1,3,5", action]]]])
+
+    job = _job(ctx, 3549431)
+    assert job["cron"] == "30 8 * * 1,3,5"
+    assert job["param"]["params"][0]["water_box_mode"] == 203
+
+
+def test_null_clears_a_setting_and_segments_are_normalised(ctx):
+    action = ["start_clean", {"mop_mode": None, "segments": [16, 17]}]
+    timer_rpc.handle_timer_request(ctx, DUID, "set_timer", [["3549431", ["on", ["00 11 * * 1,3,5", action]]]])
+
+    entry = _job(ctx, 3549431)["param"]["params"][0]
+    assert "mop_mode" not in entry
+    assert entry["segments"] == "16,17"
+
+
+def test_vac_only_schedule_fires_without_a_mop_template(ctx):
+    from shared import schedule_runner
+
+    action = ["start_clean", {"water_box_mode": 200, "fan_power": 102}]
+    timer_rpc.handle_timer_request(ctx, DUID, "set_timer", [["1790000002", ["on", ["0 9 * * *", action]]]])
+
+    (step,) = schedule_runner.steps_for_job(_job(ctx, 1790000002))
+    assert step.params[0]["water_box_mode"] == 200
+    assert step.params[0]["fan_power"] == 102
+
+
+def test_non_numeric_setting_is_rejected_and_nothing_is_saved(ctx):
+    before = schedule_store.list_jobs(ctx, DUID)
+    action = ["start_clean", {"fan_power": "loud"}]
+    with pytest.raises(timer_rpc.TimerRequestError):
+        timer_rpc.handle_timer_request(ctx, DUID, "set_timer", [["9", ["on", ["0 9 * * *", action]]]])
+    assert schedule_store.list_jobs(ctx, DUID) == before

From 42c21870956d9c523b8c7f34a1b944bc7c6fffc4 Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Mon, 12 Oct 2026 16:21:40 -0400
Subject: [PATCH 17/32] Accept schedule create, update and delete over HTTP

POST /user/devices/{duid}/jobs creates a job (the call python-roborock
makes), and PUT/PATCH and DELETE on /jobs/{id} edit or remove one. The
GET matcher is now method-aware so a write no longer falls through to
the list route. Update and delete paths are not confirmed against the
official app; they follow the scene routes' conventions.

Co-Authored-By: Claude Sonnet 5.5 
(cherry picked from commit 5b838531eaebe34fe369b59e511f9aab1f848d29)
---
 .../https_server/endpoint_rules.py            |   9 ++
 .../https_server/routes/user/devices/jobs.py  | 126 +++++++++++++++++-
 tests/test_schedules.py                       |  87 ++++++++++++
 3 files changed, 219 insertions(+), 3 deletions(-)

diff --git a/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py b/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py
index 7aa3c23..e616716 100644
--- a/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py
+++ b/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py
@@ -114,7 +114,13 @@
 from .routes.user.deviceshare import match_received_devices as _match_get_received_devices
 from .routes.user.deviceshare import match_rooms as _match_get_shared_device_rooms
 from .routes.user.devices.jobs import build as _build_get_schedules
+from .routes.user.devices.jobs import build_create as _build_create_schedule
+from .routes.user.devices.jobs import build_delete as _build_delete_schedule
+from .routes.user.devices.jobs import build_update as _build_update_schedule
 from .routes.user.devices.jobs import match as _match_get_schedules
+from .routes.user.devices.jobs import match_create as _match_create_schedule
+from .routes.user.devices.jobs import match_delete as _match_delete_schedule
+from .routes.user.devices.jobs import match_update as _match_update_schedule
 from .routes.user.devices.newadd import build as _build_add_device
 from .routes.user.devices.newadd import match as _match_add_device
 from .routes.user.homes.item import build as _build_get_home_data
@@ -596,6 +602,9 @@ def default_endpoint_rules() -> Sequence[EndpointRule]:
         EndpointRule("get_device", _match_get_device, _build_get_device),
         EndpointRule("get_device_extra", _match_get_device_extra, _build_get_device_extra),
         EndpointRule("get_schedules", _match_get_schedules, _build_get_schedules),
+        EndpointRule("create_schedule", _match_create_schedule, _build_create_schedule),
+        EndpointRule("update_schedule", _match_update_schedule, _build_update_schedule),
+        EndpointRule("delete_schedule", _match_delete_schedule, _build_delete_schedule),
         EndpointRule("post_app_info", _match_post_app_info, _build_post_app_info),
         EndpointRule("get_inbox_latest", _match_get_inbox_latest, _build_get_inbox_latest),
         EndpointRule("get_products_v4", _match_get_products_v4, _build_get_products_v4),
diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/jobs.py b/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/jobs.py
index d0ab323..1aa3ef8 100644
--- a/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/jobs.py
+++ b/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/jobs.py
@@ -1,17 +1,25 @@
 from __future__ import annotations
 
+import json
 import re
+import time
 from typing import Any
 
+from shared.constants import DEFAULT_TIMEZONE
 from shared.context import ServerContext
+from shared.data_helpers import as_bool
 from shared.http_helpers import wrap_response
+from shared.schedule_runner import CronError, parse_cron
+from shared.schedule_store import delete_job, list_jobs, upsert_job
 
 from .service import device_jobs_payload
 
+_COLLECTION_RE = re.compile(r"/user/devices/([^/]+)/jobs")
+_ITEM_RE = re.compile(r"/user/devices/([^/]+)/jobs/([^/]+)")
 
-def match(path: str) -> bool:
-    clean = path.rstrip("/")
-    return bool(re.fullmatch(r"/user/devices/[^/]+/jobs", clean))
+
+def match(path: str, method: str = "GET") -> bool:
+    return method.upper() == "GET" and bool(_COLLECTION_RE.fullmatch(path.rstrip("/")))
 
 
 def build(
@@ -24,3 +32,115 @@ def build(
     device_id = parts[-2] if len(parts) >= 2 else ""
     return wrap_response(device_jobs_payload(ctx, device_id))
 
+
+def _error(code: int, message: str) -> dict[str, Any]:
+    return {"success": False, "code": code, "msg": message, "data": None, "result": None}
+
+
+def _json_body(body_params: dict[str, list[str]]) -> dict[str, Any]:
+    for raw in body_params.get("__json") or []:
+        try:
+            parsed = json.loads(raw)
+        except (TypeError, json.JSONDecodeError):
+            continue
+        if isinstance(parsed, dict):
+            return parsed
+    return {}
+
+
+def _parse_param(value: Any) -> dict[str, Any] | None:
+    if isinstance(value, str) and value.strip():
+        try:
+            value = json.loads(value)
+        except json.JSONDecodeError:
+            return None
+    return value if isinstance(value, dict) else None
+
+
+def match_create(path: str, method: str = "GET") -> bool:
+    return method.upper() == "POST" and bool(_COLLECTION_RE.fullmatch(path.rstrip("/")))
+
+
+def build_create(
+    ctx: ServerContext,
+    _query_params: dict[str, list[str]],
+    body_params: dict[str, list[str]],
+    clean_path: str,
+) -> dict[str, Any]:
+    duid = _COLLECTION_RE.fullmatch(clean_path.rstrip("/")).group(1)  # type: ignore[union-attr]
+    body = _json_body(body_params)
+    cron = str(body.get("cron") or "").strip()
+    try:
+        parse_cron(cron)
+    except CronError as exc:
+        return _error(400, f"invalid cron: {exc}")
+    param = _parse_param(body.get("param"))
+    if body.get("param") is not None and param is None:
+        return _error(400, "param must be a JSON object")
+    job_id = body.get("id") or int(time.time())
+    created = upsert_job(
+        ctx,
+        duid,
+        job_id=job_id,
+        cron=cron,
+        enabled=as_bool(body.get("enabled", True), True),
+        time_zone=str(body.get("timeZoneId") or getattr(ctx, "timezone", "") or DEFAULT_TIMEZONE),
+        repeated=as_bool(body.get("repeated", True), True),
+        param=param,
+    )
+    return wrap_response(created)
+
+
+def match_update(path: str, method: str = "GET") -> bool:
+    return method.upper() in ("PUT", "PATCH") and bool(_ITEM_RE.fullmatch(path.rstrip("/")))
+
+
+def build_update(
+    ctx: ServerContext,
+    _query_params: dict[str, list[str]],
+    body_params: dict[str, list[str]],
+    clean_path: str,
+) -> dict[str, Any]:
+    match_ = _ITEM_RE.fullmatch(clean_path.rstrip("/"))
+    duid, job_id = match_.group(1), match_.group(2)  # type: ignore[union-attr]
+    existing = next((job for job in list_jobs(ctx, duid) if str(job.get("id")) == job_id), None)
+    if existing is None:
+        return _error(404, "schedule not found")
+    body = _json_body(body_params)
+    cron = str(body.get("cron") or existing.get("cron") or "").strip()
+    try:
+        parse_cron(cron)
+    except CronError as exc:
+        return _error(400, f"invalid cron: {exc}")
+    param = _parse_param(body.get("param")) if "param" in body else None
+    if "param" in body and param is None:
+        return _error(400, "param must be a JSON object")
+    updated = upsert_job(
+        ctx,
+        duid,
+        job_id=job_id,
+        cron=cron,
+        enabled=as_bool(body.get("enabled", existing.get("enabled", True)), True),
+        time_zone=str(body.get("timeZoneId") or ""),
+        repeated=as_bool(body["repeated"], True) if "repeated" in body else None,
+        param=param,
+        override_time_zone=bool(body.get("timeZoneId")),
+    )
+    return wrap_response(updated)
+
+
+def match_delete(path: str, method: str = "GET") -> bool:
+    return method.upper() == "DELETE" and bool(_ITEM_RE.fullmatch(path.rstrip("/")))
+
+
+def build_delete(
+    ctx: ServerContext,
+    _query_params: dict[str, list[str]],
+    _body_params: dict[str, list[str]],
+    clean_path: str,
+) -> dict[str, Any]:
+    match_ = _ITEM_RE.fullmatch(clean_path.rstrip("/"))
+    duid, job_id = match_.group(1), match_.group(2)  # type: ignore[union-attr]
+    if not delete_job(ctx, duid, job_id):
+        return _error(404, "schedule not found")
+    return wrap_response({"id": job_id})
diff --git a/tests/test_schedules.py b/tests/test_schedules.py
index e4a9ced..f362a6a 100644
--- a/tests/test_schedules.py
+++ b/tests/test_schedules.py
@@ -166,3 +166,90 @@ def test_cloud_inventory_build_preserves_device_schedules() -> None:
         "6HL2zfniaoYYV01CkVuhkO": [schedule],
         "ignored": [],
     }
+
+
+def _jobs_client(tmp_path: Path, device_id: str, schedules: list[dict[str, object]]):
+    config_file = write_release_config(tmp_path)
+    config = load_config(config_file)
+    paths = resolve_paths(config_file, config)
+    _write_json(
+        paths.inventory_path,
+        {
+            "home": {"id": 1233716, "name": "My Home"},
+            "devices": [{"duid": device_id, "name": "Roborock Qrevo"}],
+            "schedules": {device_id: schedules},
+        },
+    )
+    _seed_cloud_snapshot(paths.cloud_snapshot_path)
+    supervisor = ReleaseSupervisor(config=config, paths=paths)
+    supervisor.refresh_inventory_state()
+    return TestClient(supervisor.app), paths
+
+
+def _signed_json(paths, path: str, body: dict[str, object]) -> tuple[bytes, dict[str, str]]:
+    raw = json.dumps(body, separators=(",", ":")).encode()
+    user = ProtocolAuthStore(paths.cloud_snapshot_path).availability().user
+    assert user is not None
+    headers = {
+        # Hawk rejects replayed nonces, and _hawk_headers() uses nonce- for plain requests.
+        "Authorization": build_hawk_authorization(
+            user=user, path=path, json_body=raw, nonce=f"write-{path.replace('/', '-')}-{len(raw)}"
+        ),
+        "Content-Type": "application/json",
+    }
+    return raw, headers
+
+
+def test_jobs_can_be_created_updated_and_deleted_over_http(tmp_path: Path) -> None:
+    device_id = "6HL2zfniaoYYV01CkVuhkO"
+    existing = {
+        "id": 3549431,
+        "cron": "00 11 ? * 1,3,5",
+        "timeZoneId": "America/New_York",
+        "repeated": True,
+        "enabled": True,
+        "param": {
+            "id": 1,
+            "method": "server_scheduled_start",
+            "params": [{"repeat": 1, "water_box_mode": 203, "segments": "0", "fan_power": 104, "mop_mode": 300}],
+        },
+    }
+    client, paths = _jobs_client(tmp_path, device_id, [existing])
+    collection = f"/user/devices/{device_id}/jobs"
+
+    body, headers = _signed_json(paths, collection, {"cron": "30 7 * * 1,2", "enabled": True})
+    created = client.post(collection, content=body, headers=headers)
+    assert created.status_code == 200
+    assert created.json()["success"] is True
+    new_id = created.json()["result"]["id"]
+
+    listed = client.get(collection, headers=_hawk_headers(paths.cloud_snapshot_path, collection)).json()["result"]
+    assert {job["id"] for job in listed} == {3549431, new_id}
+    assert all(job.get("nextFireTime") for job in listed)
+
+    item = f"{collection}/3549431"
+    body, headers = _signed_json(paths, item, {"cron": "15 9 ? * 1,3,5", "enabled": False})
+    updated = client.put(item, content=body, headers=headers)
+    assert updated.status_code == 200
+    result = updated.json()["result"]
+    assert (result["cron"], result["enabled"]) == ("15 9 ? * 1,3,5", False)
+    # Vac/mop settings are untouched by a cron/enabled edit.
+    assert result["param"]["params"][0]["mop_mode"] == 300
+
+    deleted = client.delete(item, headers=_hawk_headers(paths.cloud_snapshot_path, item))
+    assert deleted.status_code == 200 and deleted.json()["success"] is True
+    user = ProtocolAuthStore(paths.cloud_snapshot_path).availability().user
+    assert user is not None
+    second_list = {"Authorization": build_hawk_authorization(user=user, path=collection, nonce="second-list")}
+    remaining = client.get(collection, headers=second_list).json()["result"]
+    assert [job["id"] for job in remaining] == [new_id]
+
+
+def test_creating_a_job_with_a_bad_cron_is_rejected(tmp_path: Path) -> None:
+    device_id = "6HL2zfniaoYYV01CkVuhkO"
+    client, paths = _jobs_client(tmp_path, device_id, [])
+    collection = f"/user/devices/{device_id}/jobs"
+    body, headers = _signed_json(paths, collection, {"cron": "nonsense"})
+    response = client.post(collection, content=body, headers=headers)
+    assert response.json()["success"] is False
+    assert response.json()["code"] == 400

From 1cf1dd1a920077ff11c2e398b9eb269233cea736 Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Sun, 18 Oct 2026 13:12:00 -0400
Subject: [PATCH 18/32] Run a schedule the way the cloud does: ask the robot to
 start its timer

A schedule's job (POST /user/devices/{duid}/jobs) carries a settings entry whose
"name" is the id of the matching timer the official app also saved on the robot.
The cloud runs such a job by sending server_scheduled_start with that entry, which
is the method name inside the job itself. The robot accepts it, runs the clean
(rooms or whole home) and records it as "Schedules" in its history; without the
entry it answers -10005 "Invalid timer", and with a bare id "Param should be name
+ fan + segment". python-roborock does not list the command, so it is sent through
a small SchedulerCommand enum.

A schedule with no robot-side id (one saved through the legacy set_timer), or one
the robot refuses, falls back to the plainer ways, since a refused command changes
nothing: a whole-home clean is one app_start carrying the schedule's fields plus
source 3, which the robot also records as "Schedules"; a room schedule is the
settings commands followed by a segment clean. Scenes and routines are untouched.
The new steps are produced only by schedules.

Co-Authored-By: Claude Sonnet 5.5 
---
 .../bundled_backend/shared/routine_runner.py  | 118 +++++++++++--
 .../bundled_backend/shared/schedule_runner.py |  28 ++-
 tests/test_routine_runner.py                  | 162 +++++++++++++++++-
 tests/test_schedule_runner.py                 |  34 +++-
 4 files changed, 318 insertions(+), 24 deletions(-)

diff --git a/src/roborock_local_server/bundled_backend/shared/routine_runner.py b/src/roborock_local_server/bundled_backend/shared/routine_runner.py
index 460ed5e..2c39c2e 100644
--- a/src/roborock_local_server/bundled_backend/shared/routine_runner.py
+++ b/src/roborock_local_server/bundled_backend/shared/routine_runner.py
@@ -3,7 +3,8 @@
 from __future__ import annotations
 
 import asyncio
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
+from enum import StrEnum
 import json
 import logging
 from pathlib import Path
@@ -58,6 +59,21 @@ def _ensure_local_python_roborock_on_path() -> None:
 _ACTION_LOCK_RETRY_DELAY_SECONDS = 5.0
 _ACTION_LOCK_RETRY_ATTEMPTS = 6
 from .inventory_io import WEB_API_INVENTORY_FILE
+class SchedulerCommand(StrEnum):
+    """A robot command python-roborock's RoborockCommand does not list."""
+
+    # The cloud's own way to run a schedule: the robot answers it with the schedule's settings entry
+    # (the same one the cloud job carries, including "name", the robot-side timer id) and records the
+    # clean as "Schedules" in its history, for whole-home and room schedules alike. Confirmed live;
+    # without the entry it answers -10005 "Invalid timer", and with a bare id "Param should be
+    # name + fan + segment".
+    SERVER_SCHEDULED_START = "server_scheduled_start"
+
+
+# A whole-home clean started by a schedule rather than a scene; see commands_for_step.
+SCHEDULE_APP_START = "schedule_app_start"
+# Any schedule that knows its robot-side timer id; the robot runs it itself when asked this way.
+SCHEDULE_SERVER_START = "schedule_server_start"
 _SUPPORTED_METHODS = {
     "do_scenes_app_start",
     "do_scenes_segments",
@@ -67,8 +83,21 @@ def _ensure_local_python_roborock_on_path() -> None:
     RoborockCommand.APP_START,
     RoborockCommand.APP_SEGMENT_CLEAN,
     RoborockCommand.APP_ZONED_CLEAN,
+    SchedulerCommand.SERVER_SCHEDULED_START,
 }
 _ACTION_LOCK_ERROR_CODES = {-10003, -10007}
+_PARAM_ERROR_CODE = -10005
+# What app_start takes in one command, as the official app's own schedule entries carry it. A
+# robot accepted every one of these together and applied the modes (confirmed live); it answers
+# -10005 "Param error" to a value it does not support, such as a route its model lacks.
+_APP_START_KEYS = ("repeat", "water_box_mode", "segments", "fan_power", "mop_mode", "clean_mop", "map_index")
+_APP_START_DEFAULTS = {"repeat": 1, "segments": "0", "clean_mop": 1, "map_index": -1}
+_SETTING_ENTRY_KEYS = ("repeat", "fan_power", "water_box_mode", "mop_mode", "mop_template_id")
+# app_start's "source" field is how the robot learns who started a clean, for its history. 3 is
+# python-roborock's RoborockStartType.schedule, and a robot recorded the clean as "Schedule" in the
+# official app's history; an app start is 2. "start_type", "startType", "start_from", "from" and
+# "trigger" were all accepted but ignored, so the clean was recorded as "App".
+_SCHEDULE_START_SOURCE = 3
 _RESUME_COMMAND_BY_IN_CLEANING: dict[int, RoborockCommand] = {
     RoborockInCleaning.global_clean_not_complete.value: RoborockCommand.APP_START,
     RoborockInCleaning.zone_clean_not_complete.value: RoborockCommand.RESUME_ZONED_CLEAN,
@@ -82,7 +111,7 @@ class RoutineExecutionError(RuntimeError):
 
 @dataclass(frozen=True)
 class RoutineCommand:
-    command: RoborockCommand
+    command: RoborockCommand | SchedulerCommand
     params: dict[str, Any] | list[Any] | None = None
 
 
@@ -376,9 +405,44 @@ def commands_for_step(step: RoutineStep) -> list[RoutineCommand]:
             ),
             RoutineCommand(RoborockCommand.APP_START, None),
         ]
+    if step.method == SCHEDULE_SERVER_START:
+        entry = _single_start_entry(step)
+        body = {key: entry[key] for key in (*_APP_START_KEYS, "name") if key in entry}
+        return [RoutineCommand(SchedulerCommand.SERVER_SCHEDULED_START, [body])]
+    if step.method == SCHEDULE_APP_START:
+        entry = _single_start_entry(step)
+        body = {**_APP_START_DEFAULTS, **{key: entry[key] for key in _APP_START_KEYS if key in entry}}
+        body["source"] = _SCHEDULE_START_SOURCE
+        return [RoutineCommand(RoborockCommand.APP_START, [body])]
     raise RoutineExecutionError(f"Unsupported step method {step.method!r}")
 
 
+def fallback_commands_for_step(step: RoutineStep) -> list[RoutineCommand] | None:
+    """The longer way to run [step], for when the robot refuses the short one; None if there is none.
+
+    A schedule is started by asking the robot to run it (server_scheduled_start), and failing that
+    by one app_start carrying its settings. A refused command changes nothing, so on "Param error"
+    or "Invalid timer" the next, plainer way is tried: a room schedule as a segment clean, a
+    whole-home one as separate setting commands, which is how a routine starts a whole-home clean.
+    """
+    if step.method == SCHEDULE_SERVER_START:
+        entry = _single_start_entry(step)
+        rooms = [
+            int(part)
+            for part in str(entry.get("segments") or "").replace(";", ",").split(",")
+            if part.strip().isdigit() and int(part) > 0
+        ]
+        if rooms:
+            settings = {key: entry[key] for key in _SETTING_ENTRY_KEYS if key in entry}
+            return commands_for_step(
+                replace(step, method="do_scenes_segments", params={"data": [{**settings, "segs": rooms}]})
+            )
+        return commands_for_step(replace(step, method=SCHEDULE_APP_START))
+    if step.method != SCHEDULE_APP_START:
+        return None
+    return commands_for_step(replace(step, method="do_scenes_app_start"))
+
+
 def _is_optional_unsupported_command(command: RoborockCommand, exc: Exception) -> bool:
     return command == RoborockCommand.SET_MOP_TEMPLATE_ID and isinstance(exc, RoborockUnsupportedFeature)
 
@@ -534,7 +598,7 @@ def _on_message(self, payload: bytes) -> None:
 
     async def send_command(
         self,
-        command: RoborockCommand,
+        command: RoborockCommand | SchedulerCommand,
         params: dict[str, Any] | list[Any] | None = None,
     ) -> Any:
         if self._session is None:
@@ -993,6 +1057,29 @@ async def _send_step_command(
                     continue
                 raise
 
+    async def _send_step_commands(
+        self,
+        *,
+        client: _RoutineMqttClient,
+        logger: logging.LoggerAdapter,
+        step: RoutineStep,
+        commands: list[RoutineCommand],
+    ) -> None:
+        for routine_command in commands:
+            logger.info(
+                "Routine step=%s method=%s command=%s params=%s",
+                step.step_id,
+                step.method,
+                routine_command.command.value,
+                routine_command.params,
+            )
+            await self._send_step_command(
+                client=client,
+                logger=logger,
+                step=step,
+                routine_command=routine_command,
+            )
+
     async def _run_scene(self, *, scene: dict[str, Any], steps: list[RoutineStep]) -> None:
         await self._run_steps(scene=scene, steps=steps, sync_scene_tids=True)
 
@@ -1027,22 +1114,21 @@ async def _run_steps(
             if sync_scene_tids:
                 await self._sync_scene_tids(client=client, scene=scene, device_id=device_id, logger=logger)
             for step_index, step in enumerate(steps):
-                commands = commands_for_step(step)
                 waits_for_step_complete = RoborockDataProtocol.TASK_COMPLETE.value in step.finish_dp_ids
-                for routine_command in commands:
-                    logger.info(
-                        "Routine step=%s method=%s command=%s params=%s",
-                        step.step_id,
-                        step.method,
-                        routine_command.command.value,
-                        routine_command.params,
+                try:
+                    await self._send_step_commands(
+                        client=client, logger=logger, step=step, commands=commands_for_step(step)
                     )
-                    await self._send_step_command(
-                        client=client,
-                        logger=logger,
-                        step=step,
-                        routine_command=routine_command,
+                except Exception as exc:  # noqa: BLE001
+                    fallback = fallback_commands_for_step(step)
+                    if fallback is None or _exception_error_code(exc) != _PARAM_ERROR_CODE:
+                        raise
+                    logger.warning(
+                        "Robot refused the single start step=%s (%s); sending the settings as separate commands",
+                        step.step_id,
+                        _exception_error_message(exc),
                     )
+                    await self._send_step_commands(client=client, logger=logger, step=step, commands=fallback)
                 if waits_for_step_complete:
                     logger.info("Waiting for ready state step=%s scene=%s", step.step_id, _scene_name(scene))
                     await client.wait_for_step_complete()
diff --git a/src/roborock_local_server/bundled_backend/shared/schedule_runner.py b/src/roborock_local_server/bundled_backend/shared/schedule_runner.py
index 33fa64c..9925998 100644
--- a/src/roborock_local_server/bundled_backend/shared/schedule_runner.py
+++ b/src/roborock_local_server/bundled_backend/shared/schedule_runner.py
@@ -18,7 +18,13 @@
 from .constants import DEFAULT_TIMEZONE
 from .data_helpers import as_bool
 from .inventory_io import load_inventory
-from .routine_runner import RoutineExecutionError, RoutineStep, get_routine_runner
+from .routine_runner import (
+    SCHEDULE_APP_START,
+    SCHEDULE_SERVER_START,
+    RoutineExecutionError,
+    RoutineStep,
+    get_routine_runner,
+)
 from .schedule_store import set_enabled
 
 if TYPE_CHECKING:
@@ -29,6 +35,7 @@
 TICK_SECONDS = 20
 _SUPPORTED_JOB_METHOD = "server_scheduled_start"
 _CARRIED_ENTRY_KEYS = ("repeat", "fan_power", "water_box_mode", "mop_mode", "mop_template_id")
+_START_ENTRY_KEYS = (*_CARRIED_ENTRY_KEYS, "segments", "clean_mop", "map_index")
 
 
 class CronError(ValueError):
@@ -191,9 +198,24 @@ def steps_for_job(job: dict[str, Any]) -> list[RoutineStep]:
         raise RoutineExecutionError("schedule params must contain one settings object")
 
     settings = {key: entry[key] for key in _CARRIED_ENTRY_KEYS if key in entry}
+    # A whole-home start also carries the rest of the entry, so one app_start can take it all.
+    start_settings = {key: entry[key] for key in _START_ENTRY_KEYS if key in entry}
+    # The robot-side timer id the official app (or LocalRock) saved this schedule under. A schedule
+    # that has one is run the way the cloud runs it: the robot is asked to start that timer.
+    timer_id = entry.get("name")
     name = str(entry.get("name") or job.get("name") or "").strip()
     if not name or name.isdigit():
         name = f"Schedule {job.get('id', '')}".strip()
+    if isinstance(timer_id, str) and timer_id.strip():
+        return [
+            RoutineStep(
+                step_id=1,
+                name=name,
+                method=SCHEDULE_SERVER_START,
+                params=[{**start_settings, "name": timer_id.strip()}],
+                finish_dp_ids=(),
+            )
+        ]
     segments = _segment_ids(entry.get("segments"))
     if segments:
         return [
@@ -209,8 +231,8 @@ def steps_for_job(job: dict[str, Any]) -> list[RoutineStep]:
         RoutineStep(
             step_id=1,
             name=name,
-            method="do_scenes_app_start",
-            params=[settings],
+            method=SCHEDULE_APP_START,
+            params=[start_settings],
             finish_dp_ids=(),
         )
     ]
diff --git a/tests/test_routine_runner.py b/tests/test_routine_runner.py
index 40110c0..eb3070c 100644
--- a/tests/test_routine_runner.py
+++ b/tests/test_routine_runner.py
@@ -9,7 +9,13 @@
 from roborock.exceptions import RoborockException
 from roborock_local_server.bundled_backend.shared.context import ServerContext
 import roborock_local_server.bundled_backend.shared.routine_runner as routine_runner_module
-from roborock_local_server.bundled_backend.shared.routine_runner import RoutineRunner, parse_scene_steps
+from roborock_local_server.bundled_backend.shared.routine_runner import (
+    SCHEDULE_APP_START,
+    SCHEDULE_SERVER_START,
+    RoutineRunner,
+    RoutineStep,
+    parse_scene_steps,
+)
 from roborock.roborock_typing import RoborockCommand
 
 
@@ -711,3 +717,157 @@ async def exercise() -> None:
             await client.wait_for_dock_settle(initial_delay_seconds=0.0)
 
     asyncio.run(exercise())
+
+
+def _schedule_step(**entry) -> RoutineStep:
+    return RoutineStep(step_id=1, name="Schedule 1", method=SCHEDULE_APP_START, params=[entry], finish_dp_ids=())
+
+
+def _run_schedule_step(tmp_path: Path, monkeypatch, step: RoutineStep, *, refuse_single_start_with: dict | None):
+    """Run [step] against a fake robot; returns every command it was sent, refused ones included."""
+    sent_commands: list[tuple[RoborockCommand, object]] = []
+
+    class FakeRoutineClient:
+        def __init__(self, context, device, logger) -> None:
+            _ = context, device, logger
+
+        async def connect(self) -> None:
+            return None
+
+        async def close(self) -> None:
+            return None
+
+        async def send_command(self, command, params=None):
+            sent_commands.append((command, params))
+            if refuse_single_start_with is not None and command == RoborockCommand.APP_START and params is not None:
+                raise RoborockException(refuse_single_start_with)
+            return ["ok"]
+
+        async def wait_for_step_complete(self) -> None:
+            return None
+
+    monkeypatch.setattr(routine_runner_module, "_RoutineMqttClient", FakeRoutineClient)
+    scene = _scene(scene_id=1, device_id="6HL2zfniaoYYV01CkVuhkO", name="Schedule 1")
+    runner = RoutineRunner(_test_context(tmp_path))
+    return sent_commands, asyncio.run(runner._run_steps(scene=scene, steps=[step], sync_scene_tids=False))
+
+
+def test_a_schedule_start_is_one_app_start_carrying_the_whole_entry(tmp_path: Path, monkeypatch) -> None:
+    # A robot accepted app_start with all of these together and applied the modes (confirmed live).
+    step = _schedule_step(fan_power=104, water_box_mode=203, mop_mode=300)
+
+    sent, _ = _run_schedule_step(tmp_path, monkeypatch, step, refuse_single_start_with=None)
+
+    assert sent == [
+        (
+            RoborockCommand.APP_START,
+            [{"fan_power": 104, "water_box_mode": 203, "mop_mode": 300,
+              "repeat": 1, "segments": "0", "clean_mop": 1, "map_index": -1,
+              # "source" 3 is what makes the robot's history say "Schedule" instead of "App".
+              "source": 3}],
+        )
+    ]
+
+
+def test_a_schedule_start_falls_back_to_separate_commands_on_a_param_error(tmp_path: Path, monkeypatch) -> None:
+    # A route the robot's model lacks makes it answer -10005 "Param error", and a refused command
+    # changes nothing, so the same settings go out the longer way.
+    step = _schedule_step(fan_power=104, water_box_mode=203, mop_mode=300)
+
+    sent, _ = _run_schedule_step(
+        tmp_path, monkeypatch, step, refuse_single_start_with={"code": -10005, "message": "Param error"}
+    )
+
+    assert [command for command, _ in sent] == [
+        RoborockCommand.APP_START,
+        RoborockCommand.SET_CUSTOM_MODE,
+        RoborockCommand.SET_WATER_BOX_CUSTOM_MODE,
+        RoborockCommand.SET_MOP_MODE,
+        RoborockCommand.SET_CLEAN_REPEAT_TIMES,
+        RoborockCommand.APP_START,
+    ]
+    assert sent[-1] == (RoborockCommand.APP_START, None)
+
+
+def test_a_schedule_start_does_not_fall_back_on_any_other_refusal(tmp_path: Path, monkeypatch) -> None:
+    step = _schedule_step(fan_power=104)
+
+    with pytest.raises(RoborockException):
+        _run_schedule_step(
+            tmp_path, monkeypatch, step, refuse_single_start_with={"code": -10001, "message": "Busy"}
+        )
+
+
+def _run_schedule_step_refusing(tmp_path: Path, monkeypatch, step: RoutineStep, error: dict):
+    """Like _run_schedule_step, but the robot refuses server_scheduled_start and accepts the rest."""
+    sent_commands: list[tuple[object, object]] = []
+
+    class FakeRoutineClient:
+        def __init__(self, context, device, logger) -> None:
+            _ = context, device, logger
+
+        async def connect(self) -> None:
+            return None
+
+        async def close(self) -> None:
+            return None
+
+        async def send_command(self, command, params=None):
+            sent_commands.append((command, params))
+            if command == routine_runner_module.SchedulerCommand.SERVER_SCHEDULED_START:
+                raise RoborockException(error)
+            return ["ok"]
+
+        async def wait_for_step_complete(self) -> None:
+            return None
+
+    monkeypatch.setattr(routine_runner_module, "_RoutineMqttClient", FakeRoutineClient)
+    scene = _scene(scene_id=1, device_id="6HL2zfniaoYYV01CkVuhkO", name="Schedule 1")
+    runner = RoutineRunner(_test_context(tmp_path))
+    return sent_commands, asyncio.run(runner._run_steps(scene=scene, steps=[step], sync_scene_tids=False))
+
+
+def _server_start_step(**entry) -> RoutineStep:
+    return RoutineStep(step_id=1, name="Schedule 1", method=SCHEDULE_SERVER_START, params=[entry], finish_dp_ids=())
+
+
+def test_a_server_start_asks_the_robot_to_run_the_schedule_with_its_whole_entry(tmp_path: Path, monkeypatch) -> None:
+    # Sent exactly as the cloud job's settings entry, "name" (the robot-side timer id) included;
+    # confirmed live to start a clean the robot records as "Schedules | Rooms".
+    step = _server_start_step(
+        repeat=1, water_box_mode=202, segments="16,17", fan_power=102, mop_mode=300,
+        clean_mop=1, map_index=0, name="1792336598179",
+    )
+
+    sent, _ = _run_schedule_step(tmp_path, monkeypatch, step, refuse_single_start_with=None)
+
+    assert [command for command, _ in sent] == [routine_runner_module.SchedulerCommand.SERVER_SCHEDULED_START]
+    assert sent[0][1] == [
+        {"repeat": 1, "water_box_mode": 202, "segments": "16,17", "fan_power": 102, "mop_mode": 300,
+         "clean_mop": 1, "map_index": 0, "name": "1792336598179"}
+    ]
+
+
+def test_a_refused_server_start_falls_back_to_a_segment_clean_for_a_room_schedule(tmp_path: Path, monkeypatch) -> None:
+    # "Invalid timer" (the robot no longer holds that timer) is a -10005 like any bad parameter.
+    step = _server_start_step(fan_power=102, water_box_mode=202, segments="16,17", name="gone")
+    sent, _ = _run_schedule_step_refusing(tmp_path, monkeypatch, step, {"code": -10005, "message": "Invalid timer"})
+
+    commands = [command for command, _ in sent]
+    assert commands[0] == routine_runner_module.SchedulerCommand.SERVER_SCHEDULED_START
+    assert commands[-1] == RoborockCommand.APP_SEGMENT_CLEAN
+    assert sent[-1][1] == [{"segments": [16, 17], "repeat": 1}]
+
+
+def test_a_refused_server_start_falls_back_to_the_single_app_start_for_a_whole_home_schedule(
+    tmp_path: Path, monkeypatch
+) -> None:
+    step = _server_start_step(fan_power=102, water_box_mode=202, segments="0", name="gone")
+    sent, _ = _run_schedule_step_refusing(tmp_path, monkeypatch, step, {"code": -10005, "message": "Invalid timer"})
+
+    assert sent[0][0] == routine_runner_module.SchedulerCommand.SERVER_SCHEDULED_START
+    assert sent[1] == (
+        RoborockCommand.APP_START,
+        [{"repeat": 1, "segments": "0", "clean_mop": 1, "map_index": -1, "fan_power": 102,
+          "water_box_mode": 202, "source": 3}],
+    )
diff --git a/tests/test_schedule_runner.py b/tests/test_schedule_runner.py
index 8769898..2ee5f09 100644
--- a/tests/test_schedule_runner.py
+++ b/tests/test_schedule_runner.py
@@ -30,7 +30,6 @@ def _job(**overrides):
                     "mop_mode": 300,
                     "clean_mop": 1,
                     "map_index": -1,
-                    "name": "1759965417864",
                 }
             ],
         },
@@ -78,11 +77,38 @@ def test_whole_house_job_becomes_an_app_start_step_carrying_vac_and_mop_settings
     steps = sr.steps_for_job(_job())
     assert len(steps) == 1
     step = steps[0]
-    assert step.method == "do_scenes_app_start"
-    assert step.params == [{"repeat": 1, "water_box_mode": 203, "fan_power": 104, "mop_mode": 300}]
+    assert step.method == "schedule_app_start"
+    assert step.params == [
+        {"repeat": 1, "water_box_mode": 203, "segments": "0", "fan_power": 104, "mop_mode": 300, "clean_mop": 1, "map_index": -1}
+    ]
     assert step.name == "Schedule 3549431"
 
 
+def test_job_with_a_robot_side_timer_id_is_run_by_asking_the_robot_to_start_it():
+    # The official app saves every schedule on the robot too and records its timer id as "name" in
+    # the cloud job's settings; the cloud runs such a job with server_scheduled_start (confirmed
+    # live: the robot records "Schedules" for it, for rooms and whole-home alike).
+    job = _job()
+    job["param"]["params"][0]["name"] = "1759965417864"
+    step = sr.steps_for_job(job)[0]
+    assert step.method == "schedule_server_start"
+    assert step.params == [
+        {
+            "repeat": 1, "water_box_mode": 203, "segments": "0", "fan_power": 104, "mop_mode": 300,
+            "clean_mop": 1, "map_index": -1, "name": "1759965417864",
+        }
+    ]
+
+
+def test_room_job_with_a_robot_side_timer_id_carries_its_rooms_in_the_same_step():
+    job = _job()
+    job["param"]["params"][0].update({"name": "1759965417864", "segments": "16,17", "map_index": 0})
+    step = sr.steps_for_job(job)[0]
+    assert step.method == "schedule_server_start"
+    assert step.params[0]["segments"] == "16,17"
+    assert step.params[0]["map_index"] == 0
+
+
 def test_segment_job_becomes_a_segment_clean_step():
     job = _job()
     job["param"]["params"][0]["segments"] = "16,17"
@@ -123,7 +149,7 @@ def test_tick_fires_a_job_that_came_due_since_the_previous_tick(tmp_path, monkey
     results = runner.tick(_utc(2026, 9, 28, 15, 0, 5))
     assert [r["status"] for r in results] == ["started"]
     assert fake.started[0]["device_id"] == "duid-1"
-    assert fake.started[0]["steps"][0].method == "do_scenes_app_start"
+    assert fake.started[0]["steps"][0].method == "schedule_app_start"
 
 
 def test_tick_does_not_fire_twice_or_when_disabled(tmp_path, monkeypatch):

From 9e6c3efc3c5a0e539d12580f2090f7e58258b232 Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Sun, 27 Sep 2026 11:24:37 -0400
Subject: [PATCH 19/32] Document the admin-optional env vars and the hybrid
 env-var and wizard setup flow

Co-Authored-By: Claude Sonnet 5.5 
---
 docs/installation.md | 33 ++++++++++++++++++++++++++++++---
 1 file changed, 30 insertions(+), 3 deletions(-)

diff --git a/docs/installation.md b/docs/installation.md
index 499b64a..5a5cb99 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -107,6 +107,13 @@ If your model already has certificate notes on the tested-vacuums page, follow t
      uv run roborock-local-server configure
      ```
 
+   You can also combine the two: if `ROBOROCK_SERVER_*` env vars generate `config.toml`'s network/broker/TLS
+   settings but the admin ones (`ROBOROCK_SERVER_ADMIN_PASSWORD`, `ROBOROCK_SERVER_PROTOCOL_LOGIN_EMAIL`,
+   `ROBOROCK_SERVER_PROTOCOL_LOGIN_PIN`) are left unset, the container still boots into `/admin`, but the
+   wizard notices the rest is already configured and only asks for admin credentials. Useful for a
+   reverse-proxy or ACME setup you'd rather express as env vars/IaC, while still picking the admin password
+   in a browser instead of a compose file.
+
    The wizard asks for:
 
    - `stack_fqdn` (must start with `api-`)
@@ -155,15 +162,24 @@ If you don't want to install `uv`/Python on the host just to run `configure`, yo
 Required variables:
 
 - `ROBOROCK_SERVER_STACK_FQDN`
-- `ROBOROCK_SERVER_ADMIN_PASSWORD`
-- `ROBOROCK_SERVER_PROTOCOL_LOGIN_EMAIL`
-- `ROBOROCK_SERVER_PROTOCOL_LOGIN_PIN` (6 digits)
 - Either `ROBOROCK_SERVER_CERT_FILE` + `ROBOROCK_SERVER_KEY_FILE` (bring your own certificate), or `ROBOROCK_SERVER_TLS_MODE=cloudflare_acme` + `ROBOROCK_SERVER_TLS_BASE_DOMAIN` + `ROBOROCK_SERVER_TLS_EMAIL` + `ROBOROCK_SERVER_CLOUDFLARE_TOKEN` (or `_CLOUDFLARE_TOKEN_FILE` for a Docker secret)
 
+The admin credentials are optional as a group:
+
+- Set all three of `ROBOROCK_SERVER_ADMIN_PASSWORD`, `ROBOROCK_SERVER_PROTOCOL_LOGIN_EMAIL`, and
+  `ROBOROCK_SERVER_PROTOCOL_LOGIN_PIN` (6 digits) for a fully headless boot straight into the running stack.
+- Leave all three unset, and the container still generates `config.toml`'s network/broker/TLS settings from
+  the env vars above, then boots into the setup wizard at `/admin` - which notices the rest is already
+  configured and asks only for admin credentials. Handy if you're driving the network/TLS/reverse-proxy side
+  from env vars or IaC, but would still rather pick the admin password in a browser.
+- Setting some but not all three is rejected with a clear error, to avoid a half-set credential.
+
 Commonly-set optional variables: `ROBOROCK_SERVER_HTTPS_PORT`, `ROBOROCK_SERVER_MQTT_TLS_PORT`, `ROBOROCK_SERVER_ADVERTISED_HTTPS_PORT`, `ROBOROCK_SERVER_ADVERTISED_MQTT_TLS_PORT`, `ROBOROCK_SERVER_LISTENER_MODE`, `ROBOROCK_SERVER_BROKER_MODE` + `ROBOROCK_SERVER_BROKER_HOST`. See `env_config.py` for the full list.
 
 **Important:** if you go this route, remove (or comment out) the `./config.toml:/app/config.toml:ro` line from `compose.yaml`. Docker will otherwise bind-mount a nonexistent host path as an empty file, which the container treats as an existing (but invalid) config and never falls through to the env vars. Keep the `./data:/data` and `./secrets:/run/secrets:ro` mounts.
 
+Fully headless (no browser step at all):
+
 ```bash
 export ROBOROCK_SERVER_STACK_FQDN=api-roborock.example.com
 export ROBOROCK_SERVER_ADMIN_PASSWORD=super-secret-password
@@ -176,6 +192,17 @@ export ROBOROCK_SERVER_CLOUDFLARE_TOKEN=your-cloudflare-api-token
 docker compose up -d --build
 ```
 
+Hybrid (network/TLS from env vars, admin credentials in the browser wizard at `/admin`):
+
+```bash
+export ROBOROCK_SERVER_STACK_FQDN=api-roborock.example.com
+export ROBOROCK_SERVER_TLS_MODE=cloudflare_acme
+export ROBOROCK_SERVER_TLS_BASE_DOMAIN=example.com
+export ROBOROCK_SERVER_TLS_EMAIL=acme@example.com
+export ROBOROCK_SERVER_CLOUDFLARE_TOKEN=your-cloudflare-api-token
+docker compose up -d --build
+```
+
 ## Method 2: Home Assistant Add-on
 
 Use [Home Assistant](home_assistant.md) as the installation guide if you want to run the stack as a Home Assistant add-on instead of Docker Compose.

From d62615dde124ff2b29ce501d4d59ccf1d2ee1cf1 Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Sun, 27 Sep 2026 11:51:12 -0400
Subject: [PATCH 20/32] Add a redacted activity-log reader over the HTTP/MQTT
 jsonl logs

decompiled_http.jsonl / decompiled_mqtt.jsonl have no rotation and can
carry sensitive data (auth headers, onboarding localKey/passwords in
HTTP bodies, fully-decrypted device RPC payloads in MQTT entries). This
tails both files (they grow unbounded, so a full read is out) and
returns metadata-only summaries by default - method/path/topic/RPC
method name, sizes, timestamps, never raw headers/bodies/payloads.

ROBOROCK_SERVER_ACTIVITY_RAW=1 switches to complete, unredacted
entries - an explicit deployment-time opt-in, matching how rethink
exposes its own traffic view, rather than a per-view UI toggle.

Co-Authored-By: Claude Sonnet 5 
(cherry picked from commit 9c9943d5b1cbc92368e08066a0b83b24e4ac7133)
---
 src/roborock_local_server/activity_log.py | 133 ++++++++++++++++
 tests/test_activity_log.py                | 181 ++++++++++++++++++++++
 2 files changed, 314 insertions(+)
 create mode 100644 src/roborock_local_server/activity_log.py
 create mode 100644 tests/test_activity_log.py

diff --git a/src/roborock_local_server/activity_log.py b/src/roborock_local_server/activity_log.py
new file mode 100644
index 0000000..e3e22fc
--- /dev/null
+++ b/src/roborock_local_server/activity_log.py
@@ -0,0 +1,133 @@
+"""Redacted summary view over the HTTP/MQTT protocol jsonl logs, for the
+admin dashboard's Activity panel.
+
+decompiled_http.jsonl / decompiled_mqtt.jsonl (see AppPaths in config.py)
+have no rotation or size cap, and can contain sensitive data: HTTP request
+headers and onboarding-adjacent bodies can carry localKey/passwords, and
+MQTT entries carry fully-decrypted device RPC payloads. So by default this
+module only ever returns safe metadata (method/path/topic/RPC method name,
+sizes, timestamps) - never raw headers, bodies, or payloads.
+
+Set ROBOROCK_SERVER_ACTIVITY_RAW=1 to return complete, unredacted entries
+instead. This is an explicit, deployment-time operator opt-in (matching how
+rethink exposes its own traffic view), not a per-view toggle in the UI.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any, Mapping
+
+ENV_ACTIVITY_RAW = "ROBOROCK_SERVER_ACTIVITY_RAW"
+DEFAULT_LIMIT = 200
+MAX_LIMIT = 500
+
+_CHUNK_SIZE = 65536
+_MAX_TAIL_BYTES = 8_000_000
+
+
+def activity_raw_enabled(env: Mapping[str, str]) -> bool:
+    return str(env.get(ENV_ACTIVITY_RAW, "") or "").strip().lower() in {"1", "true", "yes", "on"}
+
+
+def _tail_lines(path: Path, max_lines: int) -> list[str]:
+    """The last `max_lines` lines of `path`, without reading the whole file.
+
+    These jsonl files grow unbounded, so a plain read-then-split is out.
+    """
+    if max_lines <= 0 or not path.exists():
+        return []
+    with path.open("rb") as handle:
+        handle.seek(0, 2)
+        position = handle.tell()
+        buffer = b""
+        bytes_read = 0
+        while position > 0 and buffer.count(b"\n") <= max_lines and bytes_read < _MAX_TAIL_BYTES:
+            read_size = min(_CHUNK_SIZE, position)
+            position -= read_size
+            handle.seek(position)
+            buffer = handle.read(read_size) + buffer
+            bytes_read += read_size
+    lines = buffer.split(b"\n")
+    if position > 0 and lines:
+        # The first entry is a partial line, unless we reached the start of the file.
+        lines = lines[1:]
+    text_lines = [line.decode("utf-8", errors="replace") for line in lines if line.strip()]
+    return text_lines[-max_lines:]
+
+
+def _parse_jsonl_lines(lines: list[str]) -> list[dict[str, Any]]:
+    entries: list[dict[str, Any]] = []
+    for line in lines:
+        try:
+            parsed = json.loads(line)
+        except json.JSONDecodeError:
+            continue
+        if isinstance(parsed, dict):
+            entries.append(parsed)
+    return entries
+
+
+def _summarize_http_entry(raw: dict[str, Any]) -> dict[str, Any]:
+    return {
+        "time": raw.get("time"),
+        "source": "http",
+        "method": raw.get("method"),
+        "path": raw.get("clean_path") or raw.get("raw_path"),
+        "route": raw.get("route"),
+        "did": raw.get("did"),
+        "pid": raw.get("pid"),
+        "remote": raw.get("remote"),
+        "body_len": raw.get("body_len"),
+    }
+
+
+def _summarize_mqtt_entry(raw: dict[str, Any]) -> dict[str, Any]:
+    decoded_messages = raw.get("decoded_messages")
+    rpc_methods: list[str] = []
+    if isinstance(decoded_messages, list):
+        for decoded in decoded_messages:
+            if not isinstance(decoded, dict):
+                continue
+            rpc = decoded.get("rpc")
+            if isinstance(rpc, dict) and rpc.get("method"):
+                rpc_methods.append(str(rpc.get("method")))
+    payload_hex = raw.get("payload_hex")
+    payload_len = len(payload_hex) // 2 if isinstance(payload_hex, str) else None
+    return {
+        "time": raw.get("time"),
+        "source": "mqtt",
+        "direction": raw.get("direction"),
+        "topic": raw.get("topic"),
+        "rpc_methods": rpc_methods,
+        "decoded": bool(decoded_messages),
+        "payload_len": payload_len,
+    }
+
+
+def read_recent_activity(
+    *,
+    http_jsonl_path: Path,
+    mqtt_jsonl_path: Path,
+    limit: int = DEFAULT_LIMIT,
+    raw: bool = False,
+) -> list[dict[str, Any]]:
+    """Most recent `limit` HTTP+MQTT activity entries, newest first.
+
+    `raw=True` returns complete, unredacted entries (see module docstring);
+    the default returns metadata-only summaries with no header/body/payload
+    content at all.
+    """
+    http_entries = _parse_jsonl_lines(_tail_lines(http_jsonl_path, limit))
+    mqtt_entries = _parse_jsonl_lines(_tail_lines(mqtt_jsonl_path, limit))
+
+    if raw:
+        combined = [{"source": "http", **entry} for entry in http_entries]
+        combined += [{"source": "mqtt", **entry} for entry in mqtt_entries]
+    else:
+        combined = [_summarize_http_entry(entry) for entry in http_entries]
+        combined += [_summarize_mqtt_entry(entry) for entry in mqtt_entries]
+
+    combined.sort(key=lambda entry: str(entry.get("time") or ""), reverse=True)
+    return combined[:limit]
diff --git a/tests/test_activity_log.py b/tests/test_activity_log.py
new file mode 100644
index 0000000..9f9d2bb
--- /dev/null
+++ b/tests/test_activity_log.py
@@ -0,0 +1,181 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from roborock_local_server.activity_log import (
+    _tail_lines,
+    activity_raw_enabled,
+    read_recent_activity,
+)
+
+
+def _write_jsonl(path: Path, entries: list[dict]) -> None:
+    path.write_text("\n".join(json.dumps(entry) for entry in entries) + "\n", encoding="utf-8")
+
+
+def test_activity_raw_enabled_default_false() -> None:
+    assert activity_raw_enabled({}) is False
+
+
+def test_activity_raw_enabled_true_values() -> None:
+    for value in ("1", "true", "TRUE", "yes", "on"):
+        assert activity_raw_enabled({"ROBOROCK_SERVER_ACTIVITY_RAW": value}) is True
+
+
+def test_activity_raw_enabled_false_values() -> None:
+    for value in ("0", "false", "no", "off", ""):
+        assert activity_raw_enabled({"ROBOROCK_SERVER_ACTIVITY_RAW": value}) is False
+
+
+def test_tail_lines_missing_file_returns_empty(tmp_path: Path) -> None:
+    assert _tail_lines(tmp_path / "missing.jsonl", 10) == []
+
+
+def test_tail_lines_returns_last_n_in_order(tmp_path: Path) -> None:
+    path = tmp_path / "log.jsonl"
+    path.write_text("\n".join(f"line-{i}" for i in range(1, 21)) + "\n", encoding="utf-8")
+
+    assert _tail_lines(path, 3) == ["line-18", "line-19", "line-20"]
+
+
+def test_tail_lines_handles_chunk_boundary(tmp_path: Path) -> None:
+    # Force multiple internal read chunks by writing a file bigger than _CHUNK_SIZE.
+    path = tmp_path / "big.jsonl"
+    lines = [f"line-{i}-{'x' * 200}" for i in range(1, 2000)]
+    path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+    tailed = _tail_lines(path, 5)
+
+    assert tailed == lines[-5:]
+
+
+def test_tail_lines_zero_or_negative_limit(tmp_path: Path) -> None:
+    path = tmp_path / "log.jsonl"
+    path.write_text("line-1\n", encoding="utf-8")
+
+    assert _tail_lines(path, 0) == []
+
+
+def test_read_recent_activity_redacts_by_default(tmp_path: Path) -> None:
+    http_path = tmp_path / "http.jsonl"
+    mqtt_path = tmp_path / "mqtt.jsonl"
+    _write_jsonl(
+        http_path,
+        [
+            {
+                "time": "2026-01-01T00:00:00Z",
+                "method": "POST",
+                "clean_path": "/api/v1/user/login",
+                "headers": {"authorization": "Bearer super-secret"},
+                "body_json": {"localkey": "abc123", "password": "hunter2"},
+                "body_len": 42,
+                "route": "login",
+                "remote": "10.0.0.5:443",
+            }
+        ],
+    )
+    _write_jsonl(
+        mqtt_path,
+        [
+            {
+                "time": "2026-01-01T00:00:01Z",
+                "direction": "in",
+                "topic": "rr/abc/duid1",
+                "payload_hex": "aabbcc",
+                "decoded_messages": [{"rpc": {"method": "get_status", "params": ["secret-token"]}}],
+            }
+        ],
+    )
+
+    entries = read_recent_activity(http_jsonl_path=http_path, mqtt_jsonl_path=mqtt_path)
+
+    assert len(entries) == 2
+    serialized = json.dumps(entries)
+    assert "super-secret" not in serialized
+    assert "hunter2" not in serialized
+    assert "abc123" not in serialized
+    assert "secret-token" not in serialized
+
+    http_entry = next(e for e in entries if e["source"] == "http")
+    assert http_entry["method"] == "POST"
+    assert http_entry["path"] == "/api/v1/user/login"
+    assert "headers" not in http_entry
+    assert "body_json" not in http_entry
+
+    mqtt_entry = next(e for e in entries if e["source"] == "mqtt")
+    assert mqtt_entry["topic"] == "rr/abc/duid1"
+    assert mqtt_entry["rpc_methods"] == ["get_status"]
+    assert "payload_hex" not in mqtt_entry
+    assert "decoded_messages" not in mqtt_entry
+
+
+def test_read_recent_activity_raw_mode_returns_full_entries(tmp_path: Path) -> None:
+    http_path = tmp_path / "http.jsonl"
+    mqtt_path = tmp_path / "mqtt.jsonl"
+    _write_jsonl(
+        http_path,
+        [
+            {
+                "time": "2026-01-01T00:00:00Z",
+                "method": "POST",
+                "headers": {"authorization": "Bearer super-secret"},
+            }
+        ],
+    )
+    _write_jsonl(mqtt_path, [])
+
+    entries = read_recent_activity(http_jsonl_path=http_path, mqtt_jsonl_path=mqtt_path, raw=True)
+
+    assert len(entries) == 1
+    assert entries[0]["source"] == "http"
+    assert entries[0]["headers"] == {"authorization": "Bearer super-secret"}
+
+
+def test_read_recent_activity_sorts_newest_first_across_sources(tmp_path: Path) -> None:
+    http_path = tmp_path / "http.jsonl"
+    mqtt_path = tmp_path / "mqtt.jsonl"
+    _write_jsonl(http_path, [{"time": "2026-01-01T00:00:00Z", "method": "GET", "clean_path": "/a"}])
+    _write_jsonl(mqtt_path, [{"time": "2026-01-01T00:00:05Z", "topic": "rr/x"}])
+
+    entries = read_recent_activity(http_jsonl_path=http_path, mqtt_jsonl_path=mqtt_path)
+
+    assert [entry["source"] for entry in entries] == ["mqtt", "http"]
+
+
+def test_read_recent_activity_missing_files_returns_empty(tmp_path: Path) -> None:
+    entries = read_recent_activity(
+        http_jsonl_path=tmp_path / "missing_http.jsonl",
+        mqtt_jsonl_path=tmp_path / "missing_mqtt.jsonl",
+    )
+    assert entries == []
+
+
+def test_read_recent_activity_skips_malformed_lines(tmp_path: Path) -> None:
+    http_path = tmp_path / "http.jsonl"
+    mqtt_path = tmp_path / "mqtt.jsonl"
+    http_path.write_text(
+        "not json at all\n" + json.dumps({"time": "2026-01-01T00:00:00Z", "method": "GET"}) + "\n",
+        encoding="utf-8",
+    )
+    _write_jsonl(mqtt_path, [])
+
+    entries = read_recent_activity(http_jsonl_path=http_path, mqtt_jsonl_path=mqtt_path)
+
+    assert len(entries) == 1
+    assert entries[0]["method"] == "GET"
+
+
+def test_read_recent_activity_respects_limit(tmp_path: Path) -> None:
+    http_path = tmp_path / "http.jsonl"
+    mqtt_path = tmp_path / "mqtt.jsonl"
+    _write_jsonl(
+        http_path,
+        [{"time": f"2026-01-01T00:00:{i:02d}Z", "method": "GET", "clean_path": "/a"} for i in range(10)],
+    )
+    _write_jsonl(mqtt_path, [])
+
+    entries = read_recent_activity(http_jsonl_path=http_path, mqtt_jsonl_path=mqtt_path, limit=3)
+
+    assert len(entries) == 3
+    assert entries[0]["time"] == "2026-01-01T00:00:09Z"

From 14ea0dfe4f5db4b763e1713f9277d52ff7974a09 Mon Sep 17 00:00:00 2001
From: Colin Haven <10933733+virtitnerd@users.noreply.github.com>
Date: Sun, 27 Sep 2026 11:51:21 -0400
Subject: [PATCH 21/32] Wire the Activity panel into the admin dashboard

Adds ReleaseSupervisor._activity_payload() and GET /admin/api/activity
(auth-gated like every other admin route, ?limit= clamped to 1-500),
plus an Activity section on the dashboard following the existing
2s-polling pattern - there's no real-time push mechanism in this app
today (websockets/SSE), so this matches how every other panel already
refreshes.

Note: a full-suite run flagged test_admin_onboarding_start_is_blocked_when_new_connections_disabled
as failing once (256 passed/1 failed), but it passes reliably alone,
with just this file plus test_activity_log.py, and on a clean rerun of
the entire suite (257/257). AdminSessionManager (security.py) is
stateless and per-instance with no shared/global auth state for this
change to touch, so this looks like a pre-existing flaky/timing-
sensitive test that more total tests nudged into failing once, not a
regression from this change.

Co-Authored-By: Claude Sonnet 5 
(cherry picked from commit dd825d22f001c7cdfd88f8ae92d30b8997c8f64a)
---
 docs/installation.md                          |   2 +
 src/roborock_local_server/server.py           |  16 ++-
 src/roborock_local_server/standalone_admin.py |  63 +++++++++
 tests/test_admin_api.py                       | 122 ++++++++++++++++++
 4 files changed, 202 insertions(+), 1 deletion(-)

diff --git a/docs/installation.md b/docs/installation.md
index 5a5cb99..2db4f74 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -223,6 +223,8 @@ Use [Home Assistant](home_assistant.md) as the installation guide if you want to
 
 4. For any routines that use zones, re-save them so the server stores the zone data correctly. In the Roborock app, open each routine that has zones, open the zone, tap **Edit**, open any **Zone Cleaning** entry, then tap **Save**. Repeat for each zone in the routine.
 
+5. The dashboard's **Activity** panel shows recent HTTP/MQTT traffic between your vacuum(s)/app/Home Assistant and this server - useful for confirming a device is actually talking to the local stack. It only shows redacted metadata (method/path/topic/RPC method name, sizes, timestamps) by default, since the underlying logs can contain device keys and decrypted command payloads. Set `ROBOROCK_SERVER_ACTIVITY_RAW=1` if you need full unredacted entries for debugging.
+
 ## Next Steps
 
 - [Onboarding](onboarding.md) for pairing a new vacuum
diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py
index a9a2205..aff3b9c 100644
--- a/src/roborock_local_server/server.py
+++ b/src/roborock_local_server/server.py
@@ -24,6 +24,7 @@
 import uvicorn
 from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
 
+from .activity_log import activity_raw_enabled, read_recent_activity
 from .certs import CertificateManager
 from .bundled_backend.shared.constants import DEFAULT_PRODUCT_SCHEMA
 from .bundled_backend.shared.data_helpers import utcnow_iso
@@ -1391,7 +1392,10 @@ async def _handle_roborock_request(self, request: Request) -> Response:
             # /nc just handed the vacuum its localKey; persist now instead of relying on an
             # onboarding client still polling the session (it may have timed out or exited).
             self.persist_active_onboarding_device()
-        append_jsonl(self.context.http_jsonl, entry)
+        if route_name != "catchall":
+            # Truly unmatched requests (favicon probes, health checks, random scans) aren't
+            # meaningful onboarding/protocol activity - keep them out of the Activity feed.
+            append_jsonl(self.context.http_jsonl, entry)
         if key_cache is not None and key_capture_did:
             try:
                 key_cache.maybe_recover_async(key_capture_did)
@@ -1505,6 +1509,16 @@ def _pending_device_mqtt_recovery_payload(self) -> list[dict[str, str]]:
             )
         return devices
 
+    def _activity_payload(self, *, limit: int) -> dict[str, Any]:
+        raw = activity_raw_enabled(os.environ)
+        entries = read_recent_activity(
+            http_jsonl_path=self.paths.http_jsonl_path,
+            mqtt_jsonl_path=self.paths.mqtt_jsonl_path,
+            limit=limit,
+            raw=raw,
+        )
+        return {"raw": raw, "entries": entries}
+
     def _auth_payload(self) -> dict[str, Any]:
         sessions = [
             session
diff --git a/src/roborock_local_server/standalone_admin.py b/src/roborock_local_server/standalone_admin.py
index e1c24dd..32191f5 100644
--- a/src/roborock_local_server/standalone_admin.py
+++ b/src/roborock_local_server/standalone_admin.py
@@ -75,6 +75,11 @@ def _admin_dashboard_html(project_support: dict[str, Any]) -> str:
           
Loading sessions...
+

Activity

+
+
+
+

Health

Vacuums

' + +NAV_HTML = dedent( + """\ + + """ +) + +STYLE_CSS = dedent( + """\ + :root { + --rls-bg: #f3f5f8; + --rls-surface: #ffffff; + --rls-nav: #12263a; + --rls-accent: #2f6fed; + --rls-accent-dark: #1c4fc4; + --rls-text: #1a1f29; + --rls-text-muted: #5a6572; + --rls-border: #e2e6ea; + --rls-danger-bg: #fdeced; + --rls-danger-text: #8a1620; + --rls-danger-border: #f5c2c7; + --rls-success-bg: #e8f8ee; + --rls-success-text: #0f5a33; + --rls-success-border: #b7e4c7; + --rls-warn-bg: #fff7ed; + --rls-warn-text: #7c2d12; + --rls-warn-border: #fdd8ab; + color-scheme: light; + } + + @media (prefers-color-scheme: dark) { + :root { + --rls-bg: #12161d; + --rls-surface: #1a1f28; + --rls-nav: #0c1520; + --rls-accent: #6d9bff; + --rls-accent-dark: #8fb1ff; + --rls-text: #e6e9ef; + --rls-text-muted: #93a0b3; + --rls-border: #2a303c; + --rls-danger-bg: #3a1a1e; + --rls-danger-text: #ff9aa4; + --rls-danger-border: #5c2830; + --rls-success-bg: #16301f; + --rls-success-text: #7fe0a4; + --rls-success-border: #285c3a; + --rls-warn-bg: #3a2a1a; + --rls-warn-text: #ffb066; + --rls-warn-border: #5c4222; + color-scheme: dark; + } + + .modal, .modal .modal-footer, .dropdown-content { background-color: var(--rls-surface); } + .dropdown-content li:hover, .dropdown-content li.active { background-color: var(--rls-border); } + .input-field input[type="text"]:not(.valid), + .input-field input[type="password"]:not(.valid), + .input-field input[type="email"]:not(.valid), + .input-field input[type="number"]:not(.valid) { + border-bottom-color: var(--rls-border); + color: var(--rls-text); + } + .card, .card-panel { background-color: var(--rls-surface); color: var(--rls-text); } + label { color: var(--rls-text-muted); } + } + + body { + background: var(--rls-bg); + color: var(--rls-text); + font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + } + + /* Materialize's nav is a fixed 56px and never grows for a real title - see rethink's own + style.css for the same fix (verified against Materialize 1.0.0's actual CSS). */ + nav { + background: var(--rls-nav) !important; + box-shadow: 0 2px 8px rgba(18, 38, 58, .25); + height: auto; + min-height: 56px; + } + .nav-wrapper { height: auto; min-height: 56px; } + nav .brand-logo { + position: static; left: auto; transform: none; + display: flex; align-items: center; flex-wrap: wrap; gap: .4em; + font-weight: 600; font-size: 1.25rem; letter-spacing: .01em; padding: .6em 0; + } + nav .brand-logo .material-icons { color: var(--rls-accent); } + + .container:not(.nav-wrapper) { + background: var(--rls-surface); + border: 1px solid var(--rls-border); + border-radius: 10px; + padding: 1.25em 1.5em; + margin-top: 1.25em; + margin-bottom: 1.25em; + box-shadow: 0 1px 3px rgba(26, 31, 41, .06); + } + + .header.orange-text, h4.header { + color: var(--rls-accent-dark) !important; + font-weight: 600; + font-size: 1.2rem; + letter-spacing: .01em; + } + + .btn, .btn-large, .btn-small { + background-color: var(--rls-accent); + border-radius: 7px; + box-shadow: none; + text-transform: none; + font-weight: 500; + } + .btn:hover, .btn-large:hover, .btn-small:hover { + background-color: var(--rls-accent-dark); + box-shadow: 0 2px 6px rgba(28, 79, 196, .35); + } + .btn:focus-visible, .btn-large:focus-visible, .btn-small:focus-visible, .btn-flat:focus-visible { + outline: 2px solid var(--rls-accent); + outline-offset: 2px; + } + .btn-flat { color: var(--rls-accent-dark); } + + .input-field input:focus + label, + .input-field input.valid:focus { color: var(--rls-accent-dark) !important; } + .input-field input:focus { + border-bottom: 1px solid var(--rls-accent-dark) !important; + box-shadow: 0 1px 0 0 var(--rls-accent-dark) !important; + } + .switch label input[type="checkbox"]:checked + .lever { background-color: rgba(47, 111, 237, .5); } + .switch label input[type="checkbox"]:checked + .lever:after { background-color: var(--rls-accent-dark); } + + table.highlight { border-collapse: collapse; } + table.highlight thead th { + color: var(--rls-text-muted); font-size: .78rem; text-transform: uppercase; + letter-spacing: .04em; border-bottom: 2px solid var(--rls-border); + } + table.highlight tbody tr { border-bottom: 1px solid var(--rls-border); } + table.highlight tbody tr:hover { background: rgba(47, 111, 237, .06); } + + .alert-banner { + border-radius: 8px; + padding: .7em .9em; + margin-top: .9em; + font-size: .92em; + line-height: 1.5; + white-space: pre-wrap; + display: none; + } + .alert-banner.shown { display: block; } + .alert-banner.error { color: var(--rls-danger-text); background: var(--rls-danger-bg); border: 1px solid var(--rls-danger-border); } + .alert-banner.success { color: var(--rls-success-text); background: var(--rls-success-bg); border: 1px solid var(--rls-success-border); } + + .rls-muted { color: var(--rls-text-muted); } + .rls-card-empty { color: var(--rls-text-muted); } + .rls-badge { + display: inline-block; text-transform: uppercase; font-size: .68rem; font-weight: 600; + letter-spacing: .03em; border-radius: 4px; padding: .15em .5em; + } + .rls-badge.mqtt { background: #e4ecff; color: #2a4d8f; } + .rls-badge.http { background: #eef0f3; color: #3d4a5c; } + .rls-badge.mitm { background: #fdece0; color: #a2540f; } + @media (prefers-color-scheme: dark) { + .rls-badge.mqtt { background: #1c2a4a; color: #9db8f5; } + .rls-badge.http { background: #262c36; color: #b7c0cc; } + .rls-badge.mitm { background: #3a2a1a; color: #ffb066; } + } + + .rls-activity-list { max-height: 26em; overflow-y: auto; } + .rls-activity-entry { + display: flex; align-items: baseline; gap: .6em; padding: .35em 0; + border-bottom: 1px solid var(--rls-border); font-size: .85em; flex-wrap: wrap; + } + .rls-activity-entry:last-child { border-bottom: none; } + .rls-activity-time { color: var(--rls-text-muted); flex-shrink: 0; font-family: monospace; font-size: .92em; } + .rls-activity-detail { word-break: break-word; } + .rls-activity-raw { width: 100%; margin: .3em 0 0; font-family: monospace; font-size: .85em; white-space: pre-wrap; } + + .rls-pre { + background: var(--rls-bg); border: 1px solid var(--rls-border); border-radius: 8px; + padding: .8em 1em; font-family: monospace; font-size: .85em; white-space: pre-wrap; + word-break: break-word; max-height: 22em; overflow: auto; color: var(--rls-text); + } + + .hidden { display: none !important; } + + @media (max-width: 480px) { + .container:not(.nav-wrapper) { padding: 1em; margin-top: .75em; margin-bottom: .75em; } + } + """ +) + + +def register_theme_routes(app: FastAPI) -> None: + @app.get(STYLE_CSS_PATH) + async def admin_style_css() -> PlainTextResponse: + return PlainTextResponse(STYLE_CSS, media_type="text/css") From 0534ef76dade02574cbbac150469e5e575c0f760 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:32:29 -0400 Subject: [PATCH 26/32] Redesign the Setup Wizard with the shared theme Real Materialize form fields/radios/select/buttons instead of hand- built fieldset/input markup, using the same nav/theme as the real dashboard. All required page text and element IDs the wizard's own JS/tests depend on are unchanged; only markup and styling moved. Co-Authored-By: Claude Sonnet 5 (cherry picked from commit 6b1b00b5875d7703bc1a7acaab152219da941c75) --- src/roborock_local_server/management_app.py | 538 ++++++++++++-------- 1 file changed, 318 insertions(+), 220 deletions(-) diff --git a/src/roborock_local_server/management_app.py b/src/roborock_local_server/management_app.py index 421130d..76e0e74 100644 --- a/src/roborock_local_server/management_app.py +++ b/src/roborock_local_server/management_app.py @@ -29,6 +29,7 @@ hash_password, write_config_setup, ) +from .web_theme import HEAD_ASSETS, NAV_HTML, SCRIPT_ASSETS, register_theme_routes DEFAULT_BOOTSTRAP_HTTPS_PORT = 555 _ENV_HTTPS_PORT = "ROBOROCK_SERVER_HTTPS_PORT" @@ -183,239 +184,335 @@ def complete_admin_section( def _status_html() -> str: - return dedent( - """\ - -

Roborock Local Server

-

Setup is complete. The stack is restarting into the full dashboard at this same address - - reload in a few seconds.

- - """ + return ( + dedent( + """\ + + Roborock Local Server + """ + ) + + HEAD_ASSETS + + dedent( + """\ + + """ + ) + + NAV_HTML + + dedent( + """\ +
+

Setup is complete

+

The stack is restarting into the full dashboard at this same address - reload in a few + seconds.

+
+ """ + ) + + SCRIPT_ASSETS + + "\n\n" ) +_WIZARD_SCRIPT_HEAD = dedent( + """\ + + """ +) + + def _setup_wizard_html() -> str: - return dedent( - """\ - - Roborock Local Server Setup - - -

Roborock Local Server Setup

-

This runs once, the first time the stack boots without a config.toml. Fill this in, submit, and the - container will restart into the full HTTPS/MQTT stack.

-
-
- Network - -
-
-
-
-
- -
- MQTT Broker - - - -
- -
- Certificates - - -
- - - - -
- -
- Admin Access - - -
- -
- App / Home Assistant Login - - - -
- - - -

-        
-        
-        
-        """
+
+            """
+        )
+        + _WIZARD_SCRIPT_SUBMIT_COMMON
+        + "\n"
     )
 
 
 def _admin_only_wizard_html() -> str:
-    return dedent(
-        """\
-        
-        Roborock Local Server Setup
-        
-        
-        

Roborock Local Server Setup

-

Network, broker, and certificate settings are already set (from environment variables). - Just add admin credentials to finish setup.

-
-
- Admin Access - - -
- -
- App / Home Assistant Login - - - -
- - -
-

-        
-        
-        
-        """
+    return (
+        dedent(
+            """\
+            
+            Roborock Local Server Setup
+            """
+        )
+        + HEAD_ASSETS
+        + dedent(
+            """\
+            
+            """
+        )
+        + NAV_HTML
+        + dedent(
+            """\
+            
+

Network, broker, and certificate settings are already set (from environment + variables). Just add admin credentials to finish setup.

+
+
Admin Access
+
+
+ + +
+
+ + +
+
+
+ +
App / Home Assistant Login
+
+
+ + +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+ """ + ) + + SCRIPT_ASSETS + + "\n" + + _WIZARD_SCRIPT_HEAD + + _WIZARD_SCRIPT_SUBMIT_COMMON + + "\n" ) @@ -425,6 +522,7 @@ def create_management_app( on_configured: Callable[[], None] | None = None, ) -> FastAPI: app = FastAPI(title="Roborock Local Server Setup", docs_url=None, redoc_url=None, openapi_url=None) + register_theme_routes(app) @app.get("/", response_class=HTMLResponse) @app.get("/admin", response_class=HTMLResponse) From 93f2a8c4a4d1252a03102873278ee4c5afd9b0a5 Mon Sep 17 00:00:00 2001 From: Colin Haven <10933733+virtitnerd@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:32:37 -0400 Subject: [PATCH 27/32] Redesign the admin dashboard with the shared theme Login page and dashboard now use the same Materialize theme as the Setup Wizard - real form fields, buttons, nav, cards - instead of raw inline-styled markup. Every element ID the existing JS (refresh(), renderAuth(), renderActivity(), etc.) depends on is unchanged; only markup/styling moved. Dynamically-created cards (vacuum summary, session list, activity feed) now use theme CSS variables instead of hardcoded light-mode hex colors, so they stay readable in dark mode. Also fixes a real XSS-shaped bug introduced partway through this redesign and caught before commit: the activity feed's per-entry badge was briefly built via innerHTML with server-reported traffic fields (method/path/topic/host) interpolated directly in - the same bug class already found and fixed in rethink's own device table. Rewritten with DOM APIs (createElement/textContent) only; no interpolated HTML anywhere in this file. Co-Authored-By: Claude Sonnet 5 (cherry picked from commit c045dca63de30052845f2d5e6eaa563a72555264) --- src/roborock_local_server/management_app.py | 16 +- src/roborock_local_server/standalone_admin.py | 279 ++++++++++++------ src/roborock_local_server/web_theme.py | 41 ++- 3 files changed, 231 insertions(+), 105 deletions(-) diff --git a/src/roborock_local_server/management_app.py b/src/roborock_local_server/management_app.py index 76e0e74..7c87672 100644 --- a/src/roborock_local_server/management_app.py +++ b/src/roborock_local_server/management_app.py @@ -201,7 +201,7 @@ def _status_html() -> str: + dedent( """\
-

Setup is complete

+

Setup is complete

The stack is restarting into the full dashboard at this same address - reload in a few seconds.

@@ -287,7 +287,7 @@ def _setup_wizard_html() -> str:

This runs once, the first time the stack boots without a config.toml. Fill this in, submit, and the container will restart into the full HTTPS/MQTT stack.

-
Network
+
Network
@@ -306,7 +306,7 @@ def _setup_wizard_html() -> str:
-
MQTT Broker
+
MQTT Broker

@@ -321,7 +321,7 @@ def _setup_wizard_html() -> str:
-
Certificates
+
Certificates

@@ -371,7 +371,7 @@ def _setup_wizard_html() -> str:

-
Admin Access
+
Admin Access
@@ -384,7 +384,7 @@ def _setup_wizard_html() -> str:
-
App / Home Assistant Login
+
App / Home Assistant Login
@@ -468,7 +468,7 @@ def _admin_only_wizard_html() -> str:

Network, broker, and certificate settings are already set (from environment variables). Just add admin credentials to finish setup.

-
Admin Access
+
Admin Access
@@ -481,7 +481,7 @@ def _admin_only_wizard_html() -> str:
-
App / Home Assistant Login
+
App / Home Assistant Login
diff --git a/src/roborock_local_server/standalone_admin.py b/src/roborock_local_server/standalone_admin.py index 17c91cb..cbbd39c 100644 --- a/src/roborock_local_server/standalone_admin.py +++ b/src/roborock_local_server/standalone_admin.py @@ -10,33 +10,63 @@ from fastapi.responses import HTMLResponse, JSONResponse from .security import verify_password +from .web_theme import HEAD_ASSETS, NAV_HTML, SCRIPT_ASSETS, register_theme_routes def _admin_login_html() -> str: - return dedent( - """\ - -

Roborock Local Server

-

Sign in to manage the stack.

- - -

-        
-        """
+    return (
+        dedent(
+            """\
+            
+            Roborock Local Server
+            """
+        )
+        + HEAD_ASSETS
+        + dedent(
+            """\
+            
+            """
+        )
+        + NAV_HTML
+        + dedent(
+            """\
+            
+

Sign in to manage the stack.

+
+
+ + +
+
+ +
+
+ """ + ) + + SCRIPT_ASSETS + + dedent( + """\ + + """ + ) ) @@ -44,44 +74,92 @@ def _admin_dashboard_html(project_support: dict[str, Any]) -> str: support_payload = json.dumps(project_support) return dedent( f"""\ - -
-

Roborock Local Server

-
Loading
+ + Roborock Local Server + {HEAD_ASSETS} + + + +
+

Vacuums

+
Loading vacuums...
+
+ +
+

+

+
-

Vacuums

Loading vacuums...
-

-

Cloud Import

- - - - -
No cloud request yet.
-
-

New Connections

- - -
Loading connection state...
-
+ +
+

Cloud Import

+
+
+ + +
+
+ +
+
+
+
+ + +
+
+ +
+
+
No cloud request yet.
+
+ +
+

New Connections

+

+ +

+ +
Loading connection state...
+
Protocol Sync Secret
-
- - +
+
+ +
+
+ +
-
Use this with mitm_redirect.py --sync-secret ....
+
Use this with mitm_redirect.py --local-api YOUR_SERVER_HOST --sync-secret <secret above> --activity-sync.
-
-
Protocol Sessions
+
+
Protocol Sessions
Loading sessions...
-
+
-

Activity

-
-
-
+
+

Activity

+
+
+
-

Health

-

Vacuums

+
+

Health

+

+        
+
+

Vacuums (raw)

+

+        
+ {SCRIPT_ASSETS} '; + state.roomCatalog.rooms[0].name = ''; + await ready(); + const card = await openSchedule(); + await card.locator(".schedule-details > summary").click(); + assert.equal(await page.locator("#schedulePanel img").count(), 0); + assert.equal(await page.evaluate(() => window.injected), undefined); + for (const width of [320, 390, 768]) { + await page.setViewportSize({width, height: 950}); + await noOverflow(); + } + await page.locator("#schedulePanel").scrollIntoViewIfNeeded(); + await page.screenshot({animations: "disabled", path: path.join(outputDir, "schedule-editor-mobile.png"), fullPage: true}); +}); + +test("header enablement saves immediately while the editor is collapsed and keeps a draft", async () => { + await ready(); + const card = scheduleCard(); + assert.equal(await card.locator(".schedule-dialog").getAttribute("open"), null); + await card.getByLabel("Enable schedule", {exact: true}).uncheck(); + await card.getByText("Schedule disabled.", {exact: true}).waitFor(); + assert.deepEqual(state.requests.find((item) => item.method === "PATCH").body, {revision: "revision-42", enabled: false}); + await openSchedule(); + await card.getByLabel("Start time", {exact: true}).fill("11:45"); + await card.getByLabel("Suction", {exact: true}).selectOption("103"); + await card.getByRole("button", {name: "Close", exact: true}).click(); + await card.getByLabel("Enable schedule", {exact: true}).check(); + await card.getByText("Schedule enabled.", {exact: true}).waitFor(); + assert.equal(await card.getByLabel("Start time", {exact: true}).inputValue(), "11:45"); + assert.equal(await card.getByLabel("Suction", {exact: true}).inputValue(), "103"); + assert.equal(state.schedules.devices[0].schedules[0].settings.fan_power, 102); + await openSchedule(); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + const request = state.requests.filter((item) => item.method === "PATCH").at(-1); + assert.equal(request.body.revision, "revision-42-saved-saved"); + assert.equal(request.body.cron, "45 11 * * 1,2,3,4,5"); + assert.deepEqual(request.body.settings, {fan_power: 103}); +}); + +test("failed enablement restores the checkbox and leaves the time draft intact", async () => { + await ready(); + const card = await openSchedule(); + await card.getByLabel("Start time", {exact: true}).fill("11:45"); + state.fail.add("/admin/api/schedules/sample-downstairs/42"); + await card.getByRole("button", {name: "Close", exact: true}).click(); + await card.getByLabel("Enable schedule", {exact: true}).uncheck(); + await card.locator('[data-field="toggleResult"]').filter({hasText: "failure"}).waitFor(); + assert.equal(await card.getByLabel("Enable schedule", {exact: true}).isChecked(), true); + assert.equal(await card.getByLabel("Enable schedule", {exact: true}).isEnabled(), true); + assert.equal(await card.getByLabel("Start time", {exact: true}).inputValue(), "11:45"); +}); + +test("native toggles wait for verification and show timer detail only inside the editor", async () => { + await ready(); + const card = scheduleCard(); + state.timerDelay = 400; + await card.getByLabel("Enable schedule", {exact: true}).uncheck(); + await card.getByText("Updating and checking schedule…", {exact: true}).waitFor(); + assert.equal(await card.getByLabel("Enable schedule", {exact: true}).isDisabled(), true); + await card.getByText("Schedule disabled.", {exact: true}).waitFor(); + assert.equal(state.requests.filter((item) => item.method === "PATCH").length, 1); + assert.match(await card.locator('[data-field="timerState"]').textContent(), /disabled \(verified when saved\)/); + assert.equal(await card.locator('[data-field="timerState"]').isVisible(), false); +}); + +for (const failure of ["timerFailure", "unverifiedTimerResponse"]) { + test(`native toggle does not report success with ${failure}`, async () => { + await ready(); + state[failure] = true; + const card = scheduleCard(); + await card.getByLabel("Enable schedule", {exact: true}).uncheck(); + await card.locator('[data-field="toggleResult"].error').waitFor(); + assert.equal(await card.getByLabel("Enable schedule", {exact: true}).isChecked(), true); + assert.equal(await card.locator('[data-field="toggleResult"].success').count(), 0); + assert.equal(state.requests.filter((item) => item.method === "PATCH").length, 1); + }); +} + +test("named room and cleaning controls send only chosen settings and keep native extras", async () => { + await ready(); + const card = await openSchedule(); + await card.getByLabel("Kitchen", {exact: true}).waitFor(); + assert.equal(await card.getByLabel("Kitchen", {exact: true}).isChecked(), true); + assert.equal(await card.getByLabel("Hall", {exact: true}).isChecked(), true); + await card.getByLabel("Hall", {exact: true}).uncheck(); + await card.getByLabel("Office", {exact: true}).check(); + await card.getByLabel("Suction", {exact: true}).selectOption({label: "Turbo"}); + await card.getByLabel("Water level", {exact: true}).selectOption({label: "Low"}); + await card.getByLabel("Mopping route", {exact: true}).selectOption({label: "Deep"}); + await card.getByLabel("Cleaning passes", {exact: true}).selectOption({label: "2 passes"}); + await page.evaluate(() => document.getElementById("refreshSchedules").click()); + await page.waitForFunction(() => !document.getElementById("refreshSchedules").disabled); + assert.equal(await card.getByLabel("Office", {exact: true}).isChecked(), true); + assert.equal(await card.getByLabel("Water level", {exact: true}).inputValue(), "201"); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + const request = state.requests.find((item) => item.method === "PATCH"); + assert.deepEqual(request.body, {revision: "revision-42", room_revision: "downstairs-rooms-v1", + settings: {fan_power: 103, water_box_mode: 201, mop_mode: 301, repeat: 2, map_index: 0, segments: "16,18"}}); + assert.equal(state.schedules.devices[0].schedules[0].settings.mop_template_id, 4); + assert.equal(state.schedules.devices[0].schedules[0].settings.clean_order_mode, 1); + assert.equal(await card.locator("pre").count(), 0); +}); + +test("empty room selection is rejected and whole home is explicit", async () => { + await ready(); + const card = await openSchedule(); + await card.getByLabel("Kitchen", {exact: true}).uncheck(); + await card.getByLabel("Hall", {exact: true}).uncheck(); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Choose at least one room or select Whole home.", {exact: true}).waitFor(); + assert.equal(state.requests.some((item) => item.method === "PATCH"), false); + await card.getByLabel("Full", {exact: true}).check(); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + assert.deepEqual(state.requests.find((item) => item.method === "PATCH").body.settings, {map_index: 0, segments: "0"}); +}); + +test("room changes can be reviewed without discarding time and cleaning drafts", async () => { + await ready(); + const card = await openSchedule(); + await card.getByLabel("Start time", {exact: true}).fill("11:15"); + await card.getByLabel("Hall", {exact: true}).uncheck(); + state.roomConflict = true; + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.locator('[data-field="result"]').filter({hasText: "room list changed"}).waitFor(); + state.roomCatalog.revision = "downstairs-rooms-v2"; + state.roomCatalog.rooms[0].name = "Dining room"; + await card.getByRole("button", {name: "Refresh rooms", exact: true}).click(); + await card.getByLabel("Dining room", {exact: true}).waitFor(); + assert.equal(await card.getByRole("button", {name: "Save schedule", exact: true}).isDisabled(), true); + assert.equal(await card.getByLabel("Start time", {exact: true}).inputValue(), "11:15"); + assert.equal(await card.getByLabel("Dining room", {exact: true}).isChecked(), true); + await card.getByRole("button", {name: "Use this room selection", exact: true}).click(); + state.roomConflict = false; + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + const request = state.requests.filter((item) => item.method === "PATCH").at(-1); + assert.equal(request.body.room_revision, "downstairs-rooms-v2"); + assert.equal(request.body.cron, "15 11 * * 1,2,3,4,5"); +}); + +test("map changes clear cross-floor room choices and a failed room read leaves other edits usable", async () => { + state.schedules.devices[0].schedules[0].settings.map_index = 1; + await ready(); + const card = await openSchedule(); + await card.getByText("Map and rooms loaded from the vacuum.", {exact: true}).waitFor(); + assert.equal(await card.getByLabel("Rooms", {exact: true}).isDisabled(), true); + await card.getByLabel("Map", {exact: true}).selectOption("0"); + assert.equal(await card.getByLabel("Kitchen", {exact: true}).isChecked(), false); + assert.equal(await card.getByLabel("Hall", {exact: true}).isChecked(), false); + state.fail.add("/admin/api/schedules/sample-downstairs/rooms"); + await card.getByRole("button", {name: "Refresh rooms", exact: true}).click(); + await card.locator('[data-field="roomStatus"]').filter({hasText: "failure"}).waitFor(); + await card.getByRole("button", {name: "Discard edits and reload", exact: true}).click(); + await card.getByText("Loaded the latest saved values.", {exact: true}).waitFor(); + await card.getByLabel("Suction", {exact: true}).selectOption("104"); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + assert.deepEqual(state.requests.find((item) => item.method === "PATCH").body.settings, {fan_power: 104}); +}); + +test("imported custom mode stays selected and is preserved on other edits", async () => { + state.schedules.devices[0].schedules[0].settings.fan_power = 987; + await ready(); + const card = await openSchedule(); + assert.equal(await card.getByLabel("Suction", {exact: true}).inputValue(), "987"); + await card.getByLabel("Water level", {exact: true}).selectOption("203"); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + assert.deepEqual(state.requests.find((item) => item.method === "PATCH").body.settings, {water_box_mode: 203}); + assert.equal(state.schedules.devices[0].schedules[0].settings.fan_power, 987); +}); + +test("repeat presets cover once, every day, weekdays, weekends and custom days", async () => { + await ready(); + const presets = [ + ["once", "5 8 * * *", false], ["everyday", "5 8 * * *", true], + ["weekdays", "5 8 * * 1,2,3,4,5", true], ["weekends", "5 8 * * 0,6", true], + ]; + for (const [preset, cron, repeated] of presets) { + const card = await openSchedule(); + await card.getByLabel("Start time", {exact: true}).fill("08:05"); + await card.getByLabel("Repeat", {exact: true}).selectOption(preset); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + assert.equal(await card.locator("dialog").isVisible(), false); + assert.equal(state.schedules.devices[0].schedules[0].cron, cron); + assert.equal(state.schedules.devices[0].schedules[0].repeated, repeated); + } + const card = await openSchedule(); + await card.getByLabel("Repeat", {exact: true}).selectOption("custom"); + await card.getByLabel("Sat", {exact: true}).uncheck(); + await card.getByLabel("Sun", {exact: true}).uncheck(); + await card.getByLabel("Mon", {exact: true}).check(); + await card.getByLabel("Thu", {exact: true}).check(); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + assert.equal(state.schedules.devices[0].schedules[0].cron, "5 8 * * 1,4"); +}); + +test("imported dated one-time jobs show their saved start time and Once preset", async () => { + await ready(); + const card = await openSchedule(44); + assert.equal(await card.getByLabel("Start time", {exact: true}).inputValue(), "10:00"); + assert.equal(await card.getByLabel("Repeat", {exact: true}).inputValue(), "once"); + await card.getByLabel("Start time", {exact: true}).fill("11:15"); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + const job = state.schedules.devices[0].schedules[2]; + assert.equal(job.cron, "15 11 * * *"); + assert.equal(job.repeated, false); + assert.equal(job.native_timer_name, "native-once"); +}); + +test("cleaning mode choices translate to vacuum, mop, combined and per-room preferences", async () => { + await ready(); + for (const [mode, fan, water, route] of [["vacuum", 102, 200, 300], ["mop", 105, 202, 300], ["custom", 106, 204, 302], ["vac_mop", 102, 202, 300]]) { + const card = await openSchedule(); + await card.getByLabel("Cleaning mode", {exact: true}).selectOption(mode); + if (mode === "custom") { + assert.equal(await card.getByLabel("Suction", {exact: true}).isVisible(), false); + assert.equal(await card.getByText("Uses the cleaning preferences saved for each room on the vacuum.", {exact: true}).isVisible(), true); + } + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + const settings = state.schedules.devices[0].schedules[0].settings; + assert.deepEqual([settings.fan_power, settings.water_box_mode, settings.mop_mode], [fan, water, route]); + } +}); + +test("full cleaning can target another named map without reusing room IDs", async () => { + await ready(); + const card = await openSchedule(); + await card.getByLabel("Map", {exact: true}).selectOption({label: "Upstairs"}); + assert.equal(await card.getByLabel("Rooms", {exact: true}).isDisabled(), true); + await card.getByLabel("Full", {exact: true}).check(); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + assert.deepEqual(state.requests.find((item) => item.method === "PATCH").body.settings, {map_index: 1, segments: "0"}); + assert.equal(await card.locator('[data-field="taskSummary"]').textContent(), "Upstairs · Full"); +}); + +test("another floor loads only on request and its rooms are then selectable", async () => { + await ready(); + const card = await openSchedule(); + await card.getByLabel("Map", {exact: true}).selectOption({label: "Upstairs"}); + assert.equal(state.requests.some((item) => item.path.endsWith("/rooms") && item.method === "POST"), false); + await card.getByRole("button", {name: "Load map and rooms", exact: true}).click(); + await card.getByLabel("Bedroom", {exact: true}).waitFor(); + await card.getByLabel("Bedroom", {exact: true}).check(); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + const request = state.requests.find((item) => item.method === "PATCH"); + assert.equal(request.body.room_revision, "upstairs-rooms-v1"); + assert.deepEqual(request.body.settings, {map_index: 1, segments: "25"}); +}); + +test("compact list and editor fit mobile and expose keyboard focus without script errors", async () => { + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + await page.setViewportSize({width: 390, height: 844}); + await ready(); + await page.locator("#schedulePanel").scrollIntoViewIfNeeded(); + await page.locator("#scheduleList").screenshot({animations: "disabled", path: path.join(outputDir, "schedule-list-mobile.png")}); + const card = await openSchedule(); + await card.getByLabel("Kitchen", {exact: true}).waitFor(); + for (const width of [320, 390, 768]) { + await page.setViewportSize({width, height: 844}); + await noOverflow(); + assert.equal(await card.locator("dialog").evaluate((dialog) => dialog.scrollWidth > dialog.clientWidth), false); + } + await page.setViewportSize({width: 390, height: 844}); + await card.locator("dialog").screenshot({animations: "disabled", path: path.join(outputDir, "schedule-dialog-mobile.png")}); + await card.getByLabel("Start time", {exact: true}).fill("08:05"); + await page.keyboard.press("Escape"); + assert.equal(await card.locator("dialog").isVisible(), false); + await openSchedule(); + assert.equal(await card.getByLabel("Start time", {exact: true}).inputValue(), "08:05"); + assert.deepEqual(errors, []); +}); + +test("schedule rows sort by earliest clock time, including disabled and multiple-time jobs", async () => { + const [nineThirty, multiple, ten] = state.schedules.devices[0].schedules; + const extra = (id, cron) => ({...structuredClone(nineThirty), id, revision: `revision-${id}`, cron}); + state.schedules.devices[0].schedules = [ten, nineThirty, multiple, extra(45, "5 8 * * *"), + extra(46, "*/15 0-2 * * *"), extra(47, "59 23 * * *"), extra(48, "30 9 * * 0,6"), extra(49, "invalid")]; + const storedOrder = state.schedules.devices[0].schedules.map((job) => job.id); + await ready(); + await page.waitForFunction(() => document.querySelectorAll('.schedule-card[data-device-id="sample-downstairs"]').length === 8); + assert.deepEqual(await visibleScheduleIds(), [46, 43, 45, 42, 48, 44, 47, 49]); + assert.equal(await scheduleCard(43).getByLabel("Enable schedule", {exact: true}).isChecked(), false); + await refresh(); + assert.deepEqual(await visibleScheduleIds(), [46, 43, 45, 42, 48, 44, 47, 49]); + assert.deepEqual(state.schedules.devices[0].schedules.map((job) => job.id), storedOrder); + assert.equal(state.requests.some((request) => request.method === "PATCH"), false); +}); + +test("sorting preserves an open modal and time draft, then reorders immediately after saving", async () => { + await ready(); + const card = await openSchedule(); + await card.getByLabel("Start time", {exact: true}).fill("07:15"); + await card.getByLabel("Start time", {exact: true}).focus(); + state.schedules.devices[0].schedules[1].cron = "0 13 * * *"; + state.schedules.devices[0].schedules[1].revision = "changed-by-app"; + await page.evaluate(() => document.getElementById("refreshSchedules").click()); + await page.waitForFunction(() => document.querySelector('.schedule-card[data-job-id="43"] [data-field="title"]').textContent === "13:00"); + assert.deepEqual(await visibleScheduleIds(), [43, 42, 44]); + assert.equal(await card.locator("dialog").evaluate((dialog) => dialog.matches(":modal")), true); + assert.equal(await card.getByLabel("Start time", {exact: true}).inputValue(), "07:15"); + assert.equal(await page.evaluate(() => document.activeElement.name), "time"); + await card.getByRole("button", {name: "Save schedule", exact: true}).click(); + await card.getByText("Schedule saved.", {exact: true}).waitFor(); + await page.waitForFunction(() => [...document.querySelectorAll('.schedule-card[data-device-id="sample-downstairs"]')].map((card) => card.dataset.jobId).join(",") === "42,44,43"); + assert.deepEqual(await visibleScheduleIds(), [42, 44, 43]); + assert.equal(await card.locator("dialog").isVisible(), false); + assert.equal(await page.evaluate(() => document.activeElement?.closest(".schedule-card")?.dataset.jobId), "42"); +}); + +test("list rows show selected room names or Full and keep names separate for each floor and vacuum", async () => { + const original = state.schedules.devices[0].schedules[0]; + const extra = (id, map, segments) => ({...structuredClone(original), id, revision: `revision-${id}`, + settings: {...original.settings, map_index: map, segments}}); + state.schedules.devices[0].schedules.push(extra(45, 0, "18"), extra(46, 0, "0"), extra(47, 1, "16")); + state.schedules.devices[1].schedules[0].settings = {map_index: 0, segments: "16"}; + await ready(); + await scheduleCard().getByText("Downstairs · Kitchen, Hall", {exact: true}).waitFor(); + assert.equal(await scheduleCard(45).locator('[data-field="taskSummary"]').textContent(), "Downstairs · Office"); + assert.equal(await scheduleCard(46).locator('[data-field="taskSummary"]').textContent(), "Downstairs · Full"); + assert.equal(await scheduleCard(47).locator('[data-field="taskSummary"]').textContent(), "Upstairs · Room 16"); + state.roomCatalog = {...state.roomCatalog, map_index: 1, revision: "upstairs-room-names", + rooms: [{id: 16, room_id: "cloud-bedroom", name: "Bedroom"}]}; + const card = await openSchedule(); + await card.getByRole("button", {name: "Refresh rooms", exact: true}).click(); + await page.waitForFunction(() => document.querySelector('.schedule-card[data-job-id="47"] [data-field="taskSummary"]').textContent === "Upstairs · Bedroom"); + await card.getByRole("button", {name: "Close", exact: true}).click(); + assert.equal(await card.locator('[data-field="taskSummary"]').textContent(), "Downstairs · Kitchen, Hall"); + assert.equal(await scheduleCard(47).locator('[data-field="taskSummary"]').textContent(), "Upstairs · Bedroom"); + await selectVacuum("Upstairs"); + assert.equal(await scheduleCard(42, "sample-upstairs").locator('[data-field="taskSummary"]').textContent(), "Map 1 · Room 16"); +}); + +test("long and untrusted room names wrap completely in compact rows on mobile", async () => { + const longName = '' + "VeryLongRoomName".repeat(12); + state.roomCatalog.rooms[0].name = longName; + await ready(); + const summary = scheduleCard().locator('[data-field="taskSummary"]'); + await scheduleCard().getByText(`Downstairs · ${longName}, Hall`, {exact: true}).waitFor(); + assert.equal(await page.locator("#scheduleList img").count(), 0); + assert.equal(await page.evaluate(() => window.injected), undefined); + for (const width of [320, 390, 768]) { + await page.setViewportSize({width, height: 950}); + await noOverflow(); + assert.equal(await summary.evaluate((element) => element.scrollWidth > element.clientWidth || element.scrollHeight > element.clientHeight), false); + } +}); + +async function selectVacuum(name) { + await page.locator("#deviceTabs").getByRole("button", {name, exact: true}).click(); + await page.waitForFunction((value) => document.getElementById("deviceTitle").textContent === value, name); + await page.waitForFunction(() => !document.getElementById("refreshSchedules").disabled); +} + +test("shared dashboard keeps activity and server controls while tools follow the selected vacuum", async () => { + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + await ready(); + assert.equal(await page.locator("#credentialList article").count(), 1); + assert.equal(await page.locator("#serverPanel").isVisible(), false); + assert.match(await page.locator("#activityList").textContent(), /sample-downstairs/); + await selectVacuum("Upstairs"); + assert.deepEqual(await visibleScheduleIds(), [42]); + assert.equal(await page.getByRole("button", {name: "Clear MQTT credentials for Upstairs", exact: true}).isDisabled(), true); + await page.waitForFunction(() => document.getElementById("activityList").textContent.includes("sample-upstairs")); + await page.locator("#deviceTabs").getByRole("button", {name: "Server", exact: true}).click(); + await page.locator("#serverPanel").waitFor({state: "visible"}); + assert.equal(await page.locator("#schedulePanel").isVisible(), false); + assert.equal(await page.locator("#credentialPanel").isVisible(), false); + assert.equal(await page.locator("#supportLinks a").count(), 3); + assert.equal(await page.locator("#sendCode").isVisible(), true); + assert.equal(await page.locator("#saveConnections").isVisible(), true); + await selectVacuum("Downstairs"); + assert.deepEqual(await visibleScheduleIds(), [43, 42, 44]); + assert.deepEqual(errors, []); +}); + +test("switching vacuums or server view preserves each unsaved editor draft", async () => { + await ready(); + const card = await openSchedule(); + await card.getByLabel("Start time", {exact: true}).fill("07:20"); + // Simulate navigation while the modal is open (a hash link or browser history). + await page.evaluate(() => { location.hash = "device=sample-upstairs"; }); + await page.waitForFunction(() => document.getElementById("deviceTitle").textContent === "Upstairs"); + assert.equal(await card.locator("dialog").isVisible(), false); + assert.equal(await scheduleCard(42, "sample-upstairs").locator('[data-field="title"]').textContent(), "11:00"); + await page.locator("#deviceTabs").getByRole("button", {name: "Server", exact: true}).click(); + await page.locator("#serverPanel").waitFor({state: "visible"}); + await selectVacuum("Downstairs"); + await openSchedule(); + assert.equal(await card.getByLabel("Start time", {exact: true}).inputValue(), "07:20"); + assert.equal(await card.getByRole("button", {name: "Save schedule", exact: true}).isEnabled(), true); + assert.equal(state.requests.some((request) => request.method === "PATCH"), false); +}); + +test("pending credential reset stays bound to its vacuum across navigation", async () => { + state.resetDelay = 800; + state.vacuums[1].mqtt_credentials.saved = true; + await ready(); + page.once("dialog", (dialog) => dialog.accept()); + await page.getByRole("button", {name: "Clear MQTT credentials for Downstairs", exact: true}).click(); + await selectVacuum("Upstairs"); + assert.equal(await page.getByRole("button", {name: "Clear MQTT credentials for Downstairs", exact: true}).isVisible(), false); + await page.waitForTimeout(1000); + assert.equal(await page.getByRole("button", {name: "Clear MQTT credentials for Upstairs", exact: true}).isEnabled(), true); + assert.equal(state.vacuums[1].mqtt_credentials.saved, true); + await selectVacuum("Downstairs"); + assert.equal(await page.getByRole("button", {name: "Clear MQTT credentials for Downstairs", exact: true}).isDisabled(), true); + assert.deepEqual(state.requests.filter((request) => request.method === "DELETE").map((request) => request.path), ["/admin/api/vacuums/sample-downstairs/mqtt-credentials"]); +}); + +test("shared dashboard fits phone, tablet, desktop and dark mode", async () => { + await ready(); + await page.screenshot({animations: "disabled", path: path.join(outputDir, "dashboard-desktop.jpg"), type: "jpeg", quality: 60, fullPage: true}); + for (const width of [320, 390, 768]) { + await page.setViewportSize({width, height: 950}); + await noOverflow(); + } + await page.setViewportSize({width: 390, height: 844}); + await page.screenshot({animations: "disabled", path: path.join(outputDir, "dashboard-mobile.jpg"), type: "jpeg", quality: 60, fullPage: true}); + const card = await openSchedule(); + await card.getByLabel("Kitchen", {exact: true}).waitFor(); + await card.locator("dialog").screenshot({animations: "disabled", path: path.join(outputDir, "editor-mobile.jpg"), type: "jpeg", quality: 60}); + await page.emulateMedia({colorScheme: "dark"}); + await card.locator("dialog").screenshot({animations: "disabled", path: path.join(outputDir, "editor-dark.jpg"), type: "jpeg", quality: 60}); + await page.keyboard.press("Escape"); + await page.setViewportSize({width: 1280, height: 1000}); + await noOverflow(); + await page.screenshot({animations: "disabled", path: path.join(outputDir, "dashboard-dark.jpg"), type: "jpeg", quality: 60, fullPage: true}); +}); + +test("expired schedule sessions return to the existing sign-in page", async () => { + await ready(); + state.loggedIn = false; + await page.locator("#refreshSchedules").click(); + await page.locator("#password").waitFor({state: "visible"}); + assert.equal(await page.locator("#schedulePanel").count(), 0); + assert.equal(await page.locator('link[href="/admin/static/style.css"]').count(), 1); +}); + + +test("visiting Server during a reset cannot enable a duplicate reset", async () => { + state.resetDelay = 1500; + await ready(); + page.once("dialog", (dialog) => dialog.accept()); + await page.getByRole("button", {name: "Clear MQTT credentials for Downstairs", exact: true}).click(); + await page.locator("#deviceTabs").getByRole("button", {name: "Server", exact: true}).click(); + await page.locator("#serverPanel").waitFor({state: "visible"}); + await selectVacuum("Downstairs"); + const button = page.getByRole("button", {name: "Clear MQTT credentials for Downstairs", exact: true}); + assert.equal(await button.isDisabled(), true); + assert.equal(await button.textContent(), "Clearing…"); + await page.waitForFunction(() => document.querySelector("#credentialList").textContent.includes("Credentials cleared for Downstairs")); + assert.equal(await button.isDisabled(), true); + assert.equal(state.requests.filter((request) => request.method === "DELETE").length, 1); +}); + +test("a vacuum snapshot taken before reset cannot restore its old credential state", async () => { + await ready(); + const oldSnapshot = structuredClone(state.vacuums); + let releaseSnapshot, snapshotStarted; + const held = new Promise((resolve) => { releaseSnapshot = resolve; }); + const started = new Promise((resolve) => { snapshotStarted = resolve; }); + let intercept = true; + await page.route("**/admin/api/vacuums", async (route) => { + if (!intercept) return route.continue(); + intercept = false; + snapshotStarted(); + await held; + await route.fulfill({json: {vacuums: oldSnapshot}}); + }); + await page.evaluate(() => window.dispatchEvent(new Event("rls:refresh"))); + await started; + page.once("dialog", (dialog) => dialog.accept()); + const button = page.getByRole("button", {name: "Clear MQTT credentials for Downstairs", exact: true}); + await button.click(); + await page.waitForFunction(() => document.querySelector("#credentialList").textContent.includes("Credentials cleared for Downstairs")); + releaseSnapshot(); + await page.waitForTimeout(250); + assert.equal(await button.isDisabled(), true); + assert.match(await page.locator("#credentialList").textContent(), /Credentials cleared/); +}); diff --git a/tests/browser/render_pages.py b/tests/browser/render_pages.py new file mode 100644 index 0000000..982d1c4 --- /dev/null +++ b/tests/browser/render_pages.py @@ -0,0 +1,32 @@ +"""Render the real dashboard and cache its external styles for isolated browser tests.""" +from pathlib import Path +import re +from urllib.request import urlopen + +from roborock_local_server.standalone_admin import _admin_dashboard_html, _admin_login_html +from roborock_local_server.web_theme import STYLE_CSS, MATERIALIZE_CSS_URL, MATERIALIZE_JS_URL, MATERIAL_ICONS_URL + +output = Path(__file__).parent / "artifacts" / "fixtures" +output.mkdir(parents=True, exist_ok=True) +support = { + "title": "Support This Project", + "text": "Help keep local control open and accessible.", + "links": [ + {"label": "Buy Me a Coffee", "url": "https://buymeacoffee.com/lashl"}, + {"label": "PayPal", "url": "https://paypal.me/LLashley304"}, + {"label": "Roborock Store", "url": "https://us.roborock.com/"}, + ], +} +(output / "dashboard.html").write_text(_admin_dashboard_html(support), encoding="utf-8") +(output / "login.html").write_text(_admin_login_html(), encoding="utf-8") +(output / "style.css").write_text(STYLE_CSS, encoding="utf-8") +with urlopen(MATERIALIZE_CSS_URL, timeout=30) as response: + (output / "materialize.min.css").write_bytes(response.read()) +with urlopen(MATERIALIZE_JS_URL, timeout=30) as response: + (output / "materialize.min.js").write_bytes(response.read()) +with urlopen(MATERIAL_ICONS_URL, timeout=30) as response: + icon_css = response.read().decode("utf-8") +font_url = re.search(r"src:\s*url\((https://fonts\.gstatic\.com/[^)]+)\)", icon_css).group(1) +with urlopen(font_url, timeout=30) as response: + (output / "material-icons.woff2").write_bytes(response.read()) +print("Rendered shared dashboard/login and cached Materialize CSS/JavaScript and icon font.") diff --git a/tests/test_admin_api.py b/tests/test_admin_api.py index f6cf89b..2409df2 100644 --- a/tests/test_admin_api.py +++ b/tests/test_admin_api.py @@ -1724,3 +1724,68 @@ def test_catchall_requests_are_not_logged_as_activity_but_named_routes_are(tmp_p routes = [entry.get("route") for entry in log_entries] assert "catchall" not in routes assert "region" in routes + + +def test_admin_assets_are_local_allowlisted_and_do_not_expose_templates(tmp_path: Path) -> None: + config_file = write_release_config(tmp_path) + config = load_config(config_file) + supervisor = ReleaseSupervisor(config=config, paths=resolve_paths(config_file, config)) + client = TestClient(supervisor.app) + + for name, media_type in (("schedules.css", "text/css"), ("schedules.js", "text/javascript")): + response = client.get(f"/admin/assets/{name}") + assert response.status_code == 200 + assert response.headers["content-type"].startswith(media_type) + assert response.headers["cache-control"] == "no-cache" + assert response.text.strip() + + for name in ("schedule_sections.html", "dashboard.html", "login.html", "config.toml", "missing.js"): + assert client.get(f"/admin/assets/{name}").status_code == 404 + assert client.get("/admin/api/auth").status_code == 401 + + +def test_admin_support_payload_cannot_break_out_of_inline_script() -> None: + from html.parser import HTMLParser + from roborock_local_server.standalone_admin import _admin_dashboard_html + + class Scripts(HTMLParser): + def __init__(self): + super().__init__() + self.scripts = [] + self.in_script = False + + def handle_starttag(self, tag, attrs): + if tag == "script": + self.scripts.append("") + self.in_script = True + + def handle_data(self, data): + if self.in_script: + self.scripts[-1] += data + + def handle_endtag(self, tag): + if tag == "script": + self.in_script = False + + support = {"title": '', "links": []} + parser = Scripts() + parser.feed(_admin_dashboard_html(support)) + inline = [script for script in parser.scripts if script.strip()] + assert len(inline) == 1 + serialized = inline[0].split("const support = ", 1)[1].split(";", 1)[0] + assert json.loads(serialized) == support + assert "" not in inline[0] + + +def test_admin_pages_are_not_cached(tmp_path: Path) -> None: + config_file = write_release_config(tmp_path) + config = load_config(config_file) + supervisor = ReleaseSupervisor(config=config, paths=resolve_paths(config_file, config)) + client = TestClient(supervisor.app) + assert client.get("/admin").headers["cache-control"] == "no-store" + assert client.post("/admin/api/login", json={"password": "correct horse battery staple"}).status_code == 200 + page = client.get("/admin") + assert page.headers["cache-control"] == "no-store" + assert 'id="schedulePanel"' in page.text + assert 'id="credentialPanel"' in page.text + assert 'id="activityList"' in page.text diff --git a/tests/test_admin_schedule_settings.py b/tests/test_admin_schedule_settings.py new file mode 100644 index 0000000..b593a91 --- /dev/null +++ b/tests/test_admin_schedule_settings.py @@ -0,0 +1,114 @@ +"""Room bindings must use segment IDs from the same loaded map, never cloud IDs.""" + +import copy +import json +import unittest + +from roborock_local_server.admin_schedule_settings import ( + RoomCatalogError, build_room_catalog, merge_settings, schedule_param, + segment_ids, setting_choices, validate_rooms, +) + + +class ScheduleSettingsTests(unittest.TestCase): + def setUp(self): + self.inventory = {"home": {"rooms": [{"id": 90000000000000001, "name": "Kitchen"}, {"id": "cloud-b", "name": "Hall"}]}} + self.maps = [{"map_info": [{"mapFlag": 1, "name": "Downstairs"}, {"mapFlag": 2, "name": "Upstairs"}]}] + self.mapping = [[16, "90000000000000001"], [18, "cloud-b", 0], [21, "unknown"]] + self.job = {"param": {"method": "server_scheduled_start", "id": 1, "params": [{ + "name": "native-timer", "map_index": 1, "segments": "16,18", "fan_power": 102, + "water_box_mode": 202, "mop_mode": 300, "repeat": 1, "future": {"keep": True}, + }]}} + + def catalog(self, **kwargs): + return build_room_catalog(**{ + "before": [{"map_status": 7}], "after": {"map_status": 7}, "maps": self.maps, + "mapping": self.mapping, "inventory": self.inventory, **kwargs, + }) + + def test_names_join_cloud_room_ids_without_losing_integer_precision(self): + catalog = self.catalog() + self.assertEqual(catalog["map_index"], 1) + self.assertEqual(catalog["rooms"], [ + {"id": 16, "room_id": "90000000000000001", "name": "Kitchen"}, + {"id": 18, "room_id": "cloud-b", "name": "Hall"}, + {"id": 21, "room_id": "unknown", "name": "Room 21"}, + ]) + self.assertEqual(catalog["revision"], self.catalog(mapping=list(reversed(self.mapping)))["revision"]) + + def test_map_change_no_map_and_unsaved_map_are_rejected(self): + for status in (11, 4, 252, 255, -1, None, True, "7"): + with self.subTest(status=status), self.assertRaises(RoomCatalogError): + self.catalog(after={"map_status": status}) + + def test_ambiguous_and_malformed_room_lists_are_rejected(self): + for mapping in (None, {}, [[16, "a"], [16, "b"]], [[False, "b"]], [[0, "b"]], [[300, "b"]], [[16]]): + with self.subTest(mapping=mapping), self.assertRaises(RoomCatalogError): + self.catalog(mapping=mapping) + + def test_room_rename_or_id_change_invalidates_revision(self): + old = self.catalog() + self.inventory["home"]["rooms"][0]["name"] = "Dining" + new = self.catalog() + self.assertNotEqual(old["revision"], new["revision"]) + with self.assertRaises(RoomCatalogError): + validate_rooms(self.job["param"], new, old["revision"]) + + def test_changed_map_or_missing_room_cannot_be_saved(self): + catalog = self.catalog() + for changes in ({"map_index": 2}, {"segments": "99"}): + param, needs_rooms = merge_settings(self.job, changes) + self.assertTrue(needs_rooms) + with self.assertRaises(RoomCatalogError): + validate_rooms(param, catalog, catalog["revision"]) + validate_rooms(self.job["param"], catalog, catalog["revision"]) + + def test_full_map_does_not_need_room_bindings_but_requires_a_saved_map(self): + catalog = self.catalog() + param, _ = merge_settings(self.job, {"map_index": 2, "segments": "0"}) + validate_rooms(param, catalog, catalog["revision"]) + param["params"][0]["map_index"] = 9 + with self.assertRaises(RoomCatalogError): + validate_rooms(param, catalog, catalog["revision"]) + + def test_edit_preserves_native_identity_unknown_fields_and_original(self): + before = copy.deepcopy(self.job) + param, needs_rooms = merge_settings(self.job, {"segments": [18, 21], "fan_power": 103, "repeat": 2}) + self.assertTrue(needs_rooms) + self.assertEqual(param["params"][0]["segments"], "18,21") + self.assertEqual(param["params"][0]["name"], "native-timer") + self.assertEqual(param["params"][0]["future"], {"keep": True}) + self.assertEqual(self.job, before) + self.assertFalse(merge_settings(self.job, {"water_box_mode": 200})[1]) + + def test_custom_values_are_preserved_without_offering_unrelated_model_modes(self): + self.job["param"]["params"][0]["fan_power"] = 987 + options = setting_choices(self.job["param"]["params"][0])["fan_power"] + self.assertEqual(options[-1], {"value": 987, "label": "Saved custom option (987)"}) + self.assertEqual(merge_settings(self.job, {"fan_power": 987})[0], self.job["param"]) + for changes in ({"fan_power": 108}, {"fan_power": "102"}, {"repeat": True}, {"repeat": 0}, {"repeat": 4}, {"name": "different"}, {}): + with self.subTest(changes=changes), self.assertRaises(ValueError): + merge_settings(self.job, changes) + + def test_whole_home_and_room_selection_validation(self): + self.assertEqual(segment_ids("0"), []) + self.assertEqual(segment_ids("16; 18"), [16, 18]) + for value in ([], "", True, [0, 16], [16, 16], [False], [256], "16,nope"): + with self.subTest(value=value), self.assertRaises(ValueError): + segment_ids(value) + param, _ = merge_settings(self.job, {"segments": "0"}) + catalog = self.catalog() + validate_rooms(param, catalog, catalog["revision"]) + + def test_string_payloads_supported_but_legacy_multi_action_and_unknown_formats_read_only(self): + original = copy.deepcopy(self.job["param"]) + self.job["param"] = json.dumps(original) + self.assertEqual(schedule_param(self.job), original) + original["params"][0].pop("name") + self.assertIsNone(schedule_param({"param": original})) + for param in (None, "invalid", {"method": "other", "params": [{}]}, {"method": "server_scheduled_start", "params": [{}, {}]}): + self.assertIsNone(schedule_param({"param": param})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_admin_schedules.py b/tests/test_admin_schedules.py new file mode 100644 index 0000000..dde7972 --- /dev/null +++ b/tests/test_admin_schedules.py @@ -0,0 +1,617 @@ +"""Dashboard edits preserve native identity and verify room/map bindings.""" + +import copy +import asyncio +from datetime import datetime +import json +from types import SimpleNamespace + +from fastapi.testclient import TestClient +import pytest + +from conftest import write_release_config +from roborock_local_server.config import load_config, resolve_paths +from roborock_local_server.server import ReleaseSupervisor +from roborock_local_server import admin_schedules + + +@pytest.fixture +def timer_robot(monkeypatch): + from shared import routine_runner + + robot = SimpleNamespace( + timers=[["native-test-timer", "on", {"keep": "timer-settings"}]], calls=[], + read_count=0, read_error=None, connect_error=None, write_error=None, + apply_write=True, after_read=None, after_write=None, + ) + + class Client: + def __init__(self, context, device, logger): + assert device["duid"] == "test-vacuum" + + async def connect(self): + robot.calls.append(("connect", None)) + if robot.connect_error: + raise robot.connect_error + + async def send_command(self, command, params): + method = str(command) + robot.calls.append((method, copy.deepcopy(params))) + await asyncio.sleep(0) + if method == "get_server_timer": + robot.read_count += 1 + if robot.after_read: + robot.after_read(robot.read_count) + if robot.read_error: + raise robot.read_error + return copy.deepcopy(robot.timers) + assert method == "upd_server_timer" + if robot.apply_write: + for timer in robot.timers: + if timer[0] == params[0][0]: + timer[1] = params[0][1] + if robot.after_write: + robot.after_write() + if robot.write_error: + raise robot.write_error + return ["ok"] + + async def close(self): + robot.calls.append(("close", None)) + + monkeypatch.setattr(routine_runner, "_RoutineMqttClient", Client) + return robot + + +@pytest.fixture +def schedule_admin(tmp_path, timer_robot): + config_file = write_release_config(tmp_path) + config = load_config(config_file) + paths = resolve_paths(config_file, config) + paths.inventory_path.parent.mkdir(parents=True, exist_ok=True) + native_job = { + "id": 701, "cron": "15 10 * * 1,3,5", "enabled": True, "repeated": True, + "timeZoneId": "America/Los_Angeles", "type": "clean", "future_job_field": "preserve-me", + "param": {"method": "server_scheduled_start", "id": 1, "params": [{ + "name": "native-test-timer", "segments": "16,18", "map_index": 0, + "fan_power": 102, "mop_mode": 300, "mop_template_id": 4, + "water_box_mode": 202, "clean_order_mode": 1, "repeat": 1, + "future_setting": {"preserve": [1, 2, 3]}, "secret": "PRIVATE_SETTING", + }]}, + "opaque": "PRIVATE_JOB_DATA", + } + inventory = { + "devices": [{"duid": "test-vacuum", "name": "Test downstairs", "model": "roborock.vacuum.a15", + "localKey": "PRIVATE_DEVICE_KEY"}], + "schedules": {"test-vacuum": [native_job]}, + "schedule_occurrences": {"test-vacuum": {"701": {"claimed_at": 12345}}}, + } + paths.inventory_path.write_text(json.dumps(inventory), encoding="utf-8") + supervisor = ReleaseSupervisor(config=config, paths=paths) + client = TestClient(supervisor.app) + yield client, supervisor, paths, native_job + client.close() + + +def login(client): + assert client.post("/admin/api/login", json={"password": "correct horse battery staple"}).status_code == 200 + + +def row(client): + response = client.get("/admin/api/schedules") + assert response.status_code == 200 + device = next(device for device in response.json()["devices"] if device["duid"] == "test-vacuum") + return device["schedules"][0] + + +def patch(client, **fields): + return client.patch("/admin/api/schedules/test-vacuum/701", json=fields) + + +def test_schedule_routes_require_admin_session(schedule_admin): + client, _, paths, _ = schedule_admin + before = paths.inventory_path.read_bytes() + assert client.get("/admin/api/schedules").status_code == 401 + assert client.get("/admin/api/schedules/test-vacuum/rooms").status_code == 401 + assert client.post("/admin/api/schedules/test-vacuum/rooms", json={"map_index": 1}).status_code == 401 + assert patch(client, revision="unknown", enabled=False).status_code == 401 + assert paths.inventory_path.read_bytes() == before + + +def test_friendly_cleaning_edits_preserve_other_native_options(schedule_admin, monkeypatch): + client, _, paths, original = schedule_admin + login(client) + + async def no_robot_query(*args): + raise AssertionError("An unrelated edit must not require an online vacuum") + + monkeypatch.setattr(admin_schedules, "read_room_catalog", no_robot_query) + assert row(client)["settings_editable"] is True + response = patch(client, revision=row(client)["revision"], settings={"fan_power": 103, "water_box_mode": 201, "mop_mode": 301, "repeat": 2}) + assert response.status_code == 200 + saved = json.loads(paths.inventory_path.read_text())["schedules"]["test-vacuum"][0] + expected = copy.deepcopy(original) + expected["param"]["params"][0].update(fan_power=103, water_box_mode=201, mop_mode=301, repeat=2) + assert saved == expected + + +def test_room_api_revalidates_loaded_map_and_revision_before_saving(schedule_admin, monkeypatch): + client, _, paths, _ = schedule_admin + login(client) + catalog = {"revision": "map-0-rooms-v1", "map_index": 0, "maps": [{"id": 0, "name": "Downstairs"}], + "rooms": [{"id": 16, "name": "Kitchen"}, {"id": 18, "name": "Hall"}]} + calls = [] + + async def read(supervisor, duid): + calls.append(duid) + return copy.deepcopy(catalog) + + monkeypatch.setattr(admin_schedules, "read_room_catalog", read) + response = client.get("/admin/api/schedules/test-vacuum/rooms") + assert response.status_code == 200 + assert response.headers["cache-control"] == "no-store" + revision = row(client)["revision"] + before = paths.inventory_path.read_bytes() + for room_revision, settings in [(None, {"segments": "16"}), ("old-map", {"segments": "16"}), + (catalog["revision"], {"map_index": 1}), (catalog["revision"], {"segments": "99"})]: + response = patch(client, revision=revision, room_revision=room_revision, settings=settings) + assert response.status_code == 409 + assert response.json()["code"] == "room_catalog_changed" + assert paths.inventory_path.read_bytes() == before + response = patch(client, revision=revision, room_revision=catalog["revision"], settings={"segments": "18", "map_index": 0}) + assert response.status_code == 200 + assert response.json()["schedule"]["settings"]["segments"] == "18" + assert calls == ["test-vacuum"] * 6 + + +def test_read_room_catalog_uses_only_selected_robot_and_read_commands(schedule_admin, monkeypatch): + import asyncio + from shared import routine_runner + from roborock_local_server.admin_schedule_settings import read_room_catalog, RoomCatalogError + + _, supervisor, _, _ = schedule_admin + calls = [] + replies = [[{"map_status": 3}], {"map_info": [{"mapFlag": 0, "name": "Downstairs"}]}, [[16, "cloud-room"]], [{"map_status": 3}]] + + class Client: + def __init__(self, context, device, logger): + assert device["duid"] == "test-vacuum" + + async def connect(self): + calls.append("connect") + + async def send_command(self, command, params): + assert params == [] + calls.append(str(command)) + if not replies: + raise TimeoutError("PRIVATE_CONNECTION_DETAIL") + return replies.pop(0) + + async def close(self): + calls.append("close") + + monkeypatch.setattr(routine_runner, "_RoutineMqttClient", Client) + result = asyncio.run(read_room_catalog(supervisor, "test-vacuum")) + assert result["rooms"][0]["id"] == 16 + assert calls == ["connect", "get_status", "get_multi_maps_list", "get_room_mapping", "get_status", "close"] + with pytest.raises(RoomCatalogError, match="Could not read rooms") as error: + asyncio.run(read_room_catalog(supervisor, "test-vacuum")) + assert "PRIVATE_CONNECTION_DETAIL" not in str(error.value) + assert calls[-1] == "close" + with pytest.raises(KeyError): + asyncio.run(read_room_catalog(supervisor, "other-vacuum")) + + +@pytest.mark.parametrize("state,in_cleaning,allowed", [(3, 0, True), (8, 0, True), (100, 0, True), (5, 0, False), (8, 2, False), (10, 1, False)]) +def test_explicit_map_load_checks_idle_state_and_verifies_the_loaded_floor(schedule_admin, monkeypatch, state, in_cleaning, allowed): + import asyncio + from shared import routine_runner + from roborock_local_server.admin_schedule_settings import read_room_catalog, RoomCatalogError + + _, supervisor, _, _ = schedule_admin + calls = [] + + class Client: + def __init__(self, context, device, logger): + self.loaded = False + + async def connect(self): + pass + + async def send_command(self, command, params): + calls.append((str(command), params)) + if str(command) == "get_status": + return [{"state": state, "in_cleaning": in_cleaning, "map_status": 7 if self.loaded else 3}] + if str(command) == "get_multi_maps_list": + return {"map_info": [{"mapFlag": 0, "name": "Downstairs"}, {"mapFlag": 1, "name": "Upstairs"}]} + if str(command) == "load_multi_map": + assert params == [1] + self.loaded = True + return ["ok"] + if str(command) == "get_room_mapping": + assert self.loaded + return [[25, "bedroom"]] + raise AssertionError("Unexpected robot command") + + async def close(self): + calls.append(("close", [])) + + monkeypatch.setattr(routine_runner, "_RoutineMqttClient", Client) + if allowed: + result = asyncio.run(read_room_catalog(supervisor, "test-vacuum", load_map=1)) + assert result["map_index"] == 1 + assert result["rooms"][0]["id"] == 25 + assert ("load_multi_map", [1]) in calls + else: + with pytest.raises(RoomCatalogError, match="idle or docked"): + asyncio.run(read_room_catalog(supervisor, "test-vacuum", load_map=1)) + assert not any(command == "load_multi_map" for command, _ in calls) + assert calls[-1] == ("close", []) + + +def test_map_load_endpoint_validates_origin_and_shape(schedule_admin, monkeypatch): + client, _, _, _ = schedule_admin + login(client) + calls = [] + + async def load(supervisor, duid, *, load_map): + calls.append((duid, load_map)) + return {"map_index": load_map, "maps": [], "rooms": [], "revision": "fresh"} + + monkeypatch.setattr(admin_schedules, "read_room_catalog", load) + url = "/admin/api/schedules/test-vacuum/rooms" + assert client.post(url, json={"map_index": 1}, headers={"Origin": "https://elsewhere.example"}).status_code == 403 + assert client.post(url, content="{}").status_code == 415 + for body in ({}, {"map_index": True}, {"map_index": -1}, {"map_index": 63}, {"map_index": 1, "start": True}): + assert client.post(url, json=body).status_code == 400 + assert calls == [] + assert client.post(url, json={"map_index": 1}).status_code == 200 + assert calls == [("test-vacuum", 1)] + + +def test_lists_native_imports_and_next_run_without_exposing_inventory(schedule_admin): + client, _, _, _ = schedule_admin + login(client) + response = client.get("/admin/api/schedules") + assert response.headers["cache-control"] == "no-store" + data = row(client) + assert data["id"] == 701 + assert data["enabled"] is True + assert data["native_timer_name"] == "native-test-timer" + assert data["native_timer_state"] == "not_checked" + assert data["editable"] is True + assert datetime.fromisoformat(data["next_run_at"]).utcoffset().total_seconds() == 0 + assert data["settings"]["segments"] == "16,18" + assert data["settings"]["map_index"] == 0 + for secret in ("PRIVATE_SETTING", "PRIVATE_JOB_DATA", "PRIVATE_DEVICE_KEY", "future_setting"): + assert secret not in response.text + + +def test_edit_preserves_native_settings_unknown_fields_and_occurrence_claim(schedule_admin): + client, _, paths, original = schedule_admin + login(client) + revision = row(client)["revision"] + response = patch(client, revision=revision, cron="30 11 * * 0,6", timeZoneId="America/New_York") + assert response.status_code == 200 + assert response.json()["schedule"]["revision"] != revision + stored = json.loads(paths.inventory_path.read_text()) + changed = stored["schedules"]["test-vacuum"][0] + expected = {**original, "cron": "30 11 * * 0,6", "timeZoneId": "America/New_York"} + assert changed == expected + assert stored["schedule_occurrences"]["test-vacuum"]["701"] == {"claimed_at": 12345} + + +def test_disabling_updates_and_verifies_only_the_linked_timer(schedule_admin, timer_robot): + client, _, paths, original = schedule_admin + login(client) + response = patch(client, revision=row(client)["revision"], enabled=False) + assert response.status_code == 200 + updated = response.json()["schedule"] + assert updated["enabled"] is False + assert updated["next_run_at"] is None + assert updated["native_timer_state"] == "off" + assert datetime.fromisoformat(updated["native_timer_checked_at"]).utcoffset().total_seconds() == 0 + assert timer_robot.calls == [ + ("connect", None), ("get_server_timer", []), + ("upd_server_timer", [["native-test-timer", "off"]]), ("get_server_timer", []), ("close", None), + ] + assert timer_robot.timers == [["native-test-timer", "off", {"keep": "timer-settings"}]] + stored = json.loads(paths.inventory_path.read_text())["schedules"]["test-vacuum"][0] + assert stored["param"] == original["param"] + assert stored["cron"] == original["cron"] + + +def test_enabling_repairs_a_server_enabled_job_whose_robot_timer_is_off(schedule_admin, timer_robot): + client, _, paths, original = schedule_admin + timer_robot.timers = [["native-test-timer", "off", {"keep": 1}], ["another-timer", "off"]] + login(client) + response = patch(client, revision=row(client)["revision"], enabled=True) + assert response.status_code == 200 + assert response.json()["schedule"]["native_timer_state"] == "on" + assert timer_robot.timers == [["native-test-timer", "on", {"keep": 1}], ["another-timer", "off"]] + assert json.loads(paths.inventory_path.read_text())["schedules"]["test-vacuum"][0] == original + assert ("upd_server_timer", [["native-test-timer", "on"]]) in timer_robot.calls + # A later listing does not present the earlier verification as a fresh read. + assert row(client)["native_timer_state"] == "not_checked" + + +def test_already_matching_timer_is_read_without_a_duplicate_write(schedule_admin, timer_robot): + client, _, _, _ = schedule_admin + login(client) + response = patch(client, revision=row(client)["revision"], enabled=True) + assert response.status_code == 200 + assert response.json()["schedule"]["native_timer_state"] == "on" + assert timer_robot.calls == [("connect", None), ("get_server_timer", []), ("close", None)] + + +@pytest.mark.parametrize("timers,status", [ + ([], 409), ([["unrelated", "on"]], 409), + ([["native-test-timer", "on"], ["native-test-timer", "off"]], 409), + ([["native-test-timer", "unknown"]], 409), ([["native-test-timer"]], 409), ({"timers": []}, 503), +]) +def test_unusable_native_timer_never_changes_job_or_creates_a_timer(schedule_admin, timer_robot, timers, status): + client, _, paths, _ = schedule_admin + timer_robot.timers = timers + login(client) + before = paths.inventory_path.read_bytes() + response = patch(client, revision=row(client)["revision"], enabled=False) + assert response.status_code == status + assert paths.inventory_path.read_bytes() == before + assert timer_robot.calls == [("connect", None), ("get_server_timer", []), ("close", None)] + + +@pytest.mark.parametrize("name", [None, "", " ", 123]) +def test_invalid_native_reference_is_not_treated_as_a_legacy_schedule(schedule_admin, timer_robot, name): + client, _, paths, _ = schedule_admin + data = json.loads(paths.inventory_path.read_text()) + data["schedules"]["test-vacuum"][0]["param"]["params"][0]["name"] = name + paths.inventory_path.write_text(json.dumps(data)) + login(client) + before = paths.inventory_path.read_bytes() + assert patch(client, revision=row(client)["revision"], enabled=False).status_code == 409 + assert paths.inventory_path.read_bytes() == before + assert timer_robot.calls == [] + + +def test_shared_native_reference_is_rejected_before_contacting_robot(schedule_admin, timer_robot): + client, _, paths, original = schedule_admin + data = json.loads(paths.inventory_path.read_text()) + data["schedules"]["test-vacuum"].append({**original, "id": 702}) + paths.inventory_path.write_text(json.dumps(data)) + login(client) + before = paths.inventory_path.read_bytes() + assert patch(client, revision=row(client)["revision"], enabled=False).status_code == 409 + assert paths.inventory_path.read_bytes() == before + assert timer_robot.calls == [] + + +def test_multiple_native_references_are_not_treated_as_legacy(schedule_admin, timer_robot): + client, _, paths, _ = schedule_admin + data = json.loads(paths.inventory_path.read_text()) + data["schedules"]["test-vacuum"][0]["param"]["params"] = [{"name": "native-test-timer"}, {"name": "another-timer"}] + paths.inventory_path.write_text(json.dumps(data)) + login(client) + before = paths.inventory_path.read_bytes() + assert patch(client, revision=row(client)["revision"], enabled=False).status_code == 409 + assert paths.inventory_path.read_bytes() == before + assert timer_robot.calls == [] + + +@pytest.mark.parametrize("failure", ["connect_error", "read_error"]) +def test_unreachable_robot_keeps_job_and_does_not_expose_connection_details(schedule_admin, timer_robot, failure): + client, _, paths, _ = schedule_admin + setattr(timer_robot, failure, TimeoutError("PRIVATE_CONNECTION_DETAIL")) + login(client) + before = paths.inventory_path.read_bytes() + response = patch(client, revision=row(client)["revision"], enabled=False) + assert response.status_code == 503 + assert "PRIVATE_CONNECTION_DETAIL" not in response.text + assert paths.inventory_path.read_bytes() == before + assert not any(command == "upd_server_timer" for command, _ in timer_robot.calls) + assert timer_robot.calls[-1] == ("close", None) + + +@pytest.mark.parametrize("write_error", [None, RuntimeError("PRIVATE_REFUSAL")]) +def test_acknowledgement_without_changed_timer_is_not_success(schedule_admin, timer_robot, write_error): + client, _, paths, _ = schedule_admin + timer_robot.apply_write = False + timer_robot.write_error = write_error + login(client) + before = paths.inventory_path.read_bytes() + response = patch(client, revision=row(client)["revision"], enabled=False) + assert response.status_code == 503 + assert "PRIVATE_REFUSAL" not in response.text + assert paths.inventory_path.read_bytes() == before + assert timer_robot.read_count == 2 + + +def test_lost_write_acknowledgement_can_be_confirmed_without_resending(schedule_admin, timer_robot): + client, _, _, _ = schedule_admin + timer_robot.write_error = TimeoutError("lost acknowledgement") + login(client) + response = patch(client, revision=row(client)["revision"], enabled=False) + assert response.status_code == 200 + assert response.json()["schedule"]["native_timer_state"] == "off" + assert sum(command == "upd_server_timer" for command, _ in timer_robot.calls) == 1 + assert timer_robot.read_count == 2 + + +def test_failed_verification_reports_uncertainty_without_saving_job(schedule_admin, timer_robot): + client, _, paths, _ = schedule_admin + def fail_readback(count): + if count == 2: + timer_robot.read_error = TimeoutError("PRIVATE_CONNECTION_DETAIL") + timer_robot.after_read = fail_readback + login(client) + before = paths.inventory_path.read_bytes() + response = patch(client, revision=row(client)["revision"], enabled=False) + assert response.status_code == 503 + assert "may have changed" in response.json()["error"] + assert paths.inventory_path.read_bytes() == before + assert timer_robot.timers[0][1] == "off" + assert timer_robot.calls[-1] == ("close", None) + + +@pytest.mark.parametrize("when", ["before_write", "after_write"]) +def test_app_edit_during_timer_operation_is_preserved(schedule_admin, timer_robot, when): + client, _, paths, _ = schedule_admin + def change_job(*args): + data = json.loads(paths.inventory_path.read_text()) + data["schedules"]["test-vacuum"][0]["cron"] = "5 9 * * *" + paths.inventory_path.write_text(json.dumps(data)) + if when == "before_write": + timer_robot.after_read = change_job + else: + timer_robot.after_write = change_job + login(client) + response = patch(client, revision=row(client)["revision"], enabled=False) + assert response.status_code == 409 + stored = json.loads(paths.inventory_path.read_text())["schedules"]["test-vacuum"][0] + assert stored["cron"] == "5 9 * * *" + assert stored["enabled"] is True + writes = [call for call in timer_robot.calls if call[0] == "upd_server_timer"] + assert len(writes) == (0 if when == "before_write" else 1) + + +def test_simultaneous_dashboard_toggles_do_not_interleave_robot_writes(schedule_admin, timer_robot): + import httpx + _, supervisor, _, _ = schedule_admin + async def exercise(): + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=supervisor.app), base_url="http://testserver") as client: + assert (await client.post("/admin/api/login", json={"password": "correct horse battery staple"})).status_code == 200 + listing = (await client.get("/admin/api/schedules")).json() + job = next(d for d in listing["devices"] if d["duid"] == "test-vacuum")["schedules"][0] + results = await asyncio.gather(*[ + client.patch("/admin/api/schedules/test-vacuum/701", json={"revision": job["revision"], "enabled": False}) + for _ in range(2) + ]) + assert sorted(r.status_code for r in results) == [200, 409] + asyncio.run(exercise()) + assert sum(command == "upd_server_timer" for command, _ in timer_robot.calls) == 1 + + +@pytest.mark.parametrize("method", ["app_start", "server_scheduled_start"]) +def test_legacy_enablement_and_unrelated_edits_do_not_contact_native_timer(schedule_admin, timer_robot, method): + client, _, paths, _ = schedule_admin + login(client) + assert patch(client, revision=row(client)["revision"], cron="5 9 * * *").status_code == 200 + assert timer_robot.calls == [] + data = json.loads(paths.inventory_path.read_text()) + del data["schedules"]["test-vacuum"][0]["param"]["params"][0]["name"] + data["schedules"]["test-vacuum"][0]["param"]["method"] = method + paths.inventory_path.write_text(json.dumps(data)) + response = patch(client, revision=row(client)["revision"], enabled=False) + assert response.status_code == 200 + assert response.json()["schedule"]["native_timer_state"] is None + assert timer_robot.calls == [] + + +def test_stale_browser_revision_does_not_overwrite_another_client(schedule_admin): + client, _, paths, _ = schedule_admin + login(client) + revision = row(client)["revision"] + inventory = json.loads(paths.inventory_path.read_text()) + inventory["schedules"]["test-vacuum"][0]["cron"] = "45 14 * * *" + paths.inventory_path.write_text(json.dumps(inventory)) + before = paths.inventory_path.read_bytes() + assert patch(client, revision=revision, enabled=False).status_code == 409 + assert paths.inventory_path.read_bytes() == before + + +def test_change_between_validation_and_write_is_rejected(schedule_admin, monkeypatch): + client, _, paths, _ = schedule_admin + login(client) + revision = row(client)["revision"] + real_upsert = admin_schedules.upsert_job + + def racing_upsert(*args, **kwargs): + inventory = json.loads(paths.inventory_path.read_text()) + inventory["schedules"]["test-vacuum"][0]["cron"] = "5 9 * * *" + paths.inventory_path.write_text(json.dumps(inventory)) + return real_upsert(*args, **kwargs) + + monkeypatch.setattr(admin_schedules, "upsert_job", racing_upsert) + assert patch(client, revision=revision, enabled=False).status_code == 409 + stored = json.loads(paths.inventory_path.read_text())["schedules"]["test-vacuum"][0] + assert stored["cron"] == "5 9 * * *" + assert stored["enabled"] is True + + +@pytest.mark.parametrize("fields", [ + {"enabled": "false"}, {"enabled": 0}, {"cron": "65 8 * * *"}, {"cron": []}, + {"timeZoneId": "Not/A_Zone"}, {"timeZoneId": ""}, {"timeZoneId": None}, + {"param": {"params": []}}, {"id": 800}, {"repeated": "false"}, +]) +def test_invalid_or_out_of_scope_edits_do_not_write(schedule_admin, fields): + client, _, paths, _ = schedule_admin + login(client) + revision = row(client)["revision"] + before = paths.inventory_path.read_bytes() + assert patch(client, revision=revision, **fields).status_code == 400 + assert paths.inventory_path.read_bytes() == before + + +def test_once_and_recurring_schedules_can_be_edited_without_changing_native_identity(schedule_admin): + client, _, paths, _ = schedule_admin + inventory = json.loads(paths.inventory_path.read_text()) + inventory["schedules"]["test-vacuum"][0]["repeated"] = "false" + paths.inventory_path.write_text(json.dumps(inventory)) + login(client) + data = row(client) + assert data["editable"] is True + assert data["repeated"] is False + assert patch(client, revision=data["revision"], enabled=False).status_code == 200 + response = patch(client, revision=row(client)["revision"], repeated=True, cron="30 10 * * 0,6") + assert response.status_code == 200 + assert response.json()["schedule"]["repeated"] is True + response = patch(client, revision=row(client)["revision"], repeated=False, cron="30 10 * * *") + assert response.status_code == 200 + saved = json.loads(paths.inventory_path.read_text())["schedules"]["test-vacuum"][0] + assert saved["repeated"] is False + assert saved["param"] == inventory["schedules"]["test-vacuum"][0]["param"] + + +def test_missing_and_duplicate_jobs_are_not_created_or_arbitrarily_edited(schedule_admin): + client, _, paths, original = schedule_admin + login(client) + assert client.patch("/admin/api/schedules/test-vacuum/999", json={ + "revision": "unknown", "enabled": False, + }).status_code == 404 + inventory = json.loads(paths.inventory_path.read_text()) + inventory["schedules"]["test-vacuum"].append(copy.deepcopy(original)) + paths.inventory_path.write_text(json.dumps(inventory)) + assert patch(client, revision=admin_schedules._revision(original), enabled=False).status_code == 409 + + +def test_write_failure_and_corrupt_inventory_are_not_acknowledged(schedule_admin, monkeypatch): + client, _, paths, _ = schedule_admin + login(client) + revision = row(client)["revision"] + + def cannot_save(*args, **kwargs): + raise OSError("PRIVATE_FILESYSTEM_DETAIL") + + monkeypatch.setattr(admin_schedules, "upsert_job", cannot_save) + response = patch(client, revision=revision, enabled=False) + assert response.status_code == 500 + assert response.json()["code"] == "schedule_save_failed_after_timer_sync" + assert "robot timer was verified off" in response.json()["error"] + assert "PRIVATE_FILESYSTEM_DETAIL" not in response.text + paths.inventory_path.write_text("not valid JSON") + assert client.get("/admin/api/schedules").status_code == 500 + assert patch(client, revision=revision, enabled=False).status_code == 500 + assert paths.inventory_path.read_text() == "not valid JSON" + + +def test_rejects_cross_origin_and_non_json_edits(schedule_admin): + client, _, paths, _ = schedule_admin + login(client) + revision = row(client)["revision"] + before = paths.inventory_path.read_bytes() + response = client.patch("/admin/api/schedules/test-vacuum/701", + json={"revision": revision, "enabled": False}, headers={"Origin": "https://elsewhere.example"}) + assert response.status_code == 403 + assert client.patch("/admin/api/schedules/test-vacuum/701", content="{}").status_code == 415 + assert client.patch("/admin/api/schedules/test-vacuum/701", content="[]", + headers={"Content-Type": "application/json"}).status_code == 400 + assert paths.inventory_path.read_bytes() == before diff --git a/tests/test_existing_compose_update.py b/tests/test_existing_compose_update.py new file mode 100644 index 0000000..44b07a0 --- /dev/null +++ b/tests/test_existing_compose_update.py @@ -0,0 +1,89 @@ +"""Exercise the updater without Docker, a real checkout, or robot credentials.""" + +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +FAKE_COMMAND = r'''#!/usr/bin/env python3 +import json, os, sys +from pathlib import Path +name = Path(sys.argv[0]).name +args = sys.argv[1:] +with open(os.environ['MOCK_TRACE'], 'a') as f: + f.write(json.dumps([name, *args]) + '\n') +if name == 'git': + if 'archive' in args: sys.stdout.buffer.write(b'committed source') + if 'rev-parse' in args: print('a' * 40) + if 'diff' in args and os.environ['MOCK_MODE'] == 'dirty': sys.exit(1) + sys.exit(0) +if 'inspect' in args and '--format' in args: + fmt = args[args.index('--format') + 1] + if 'Labels' in fmt: print(json.loads(os.environ['MOCK_LABELS']).get(fmt.split('"')[1], '')) + elif '.Config.Image' in fmt: print('local/test:schedule-ui') + elif '.State.Health' in fmt: print('healthy') +elif args and args[0] == 'build': + sys.stdin.buffer.read() + if os.environ['MOCK_MODE'] == 'build_failure': sys.exit(4) +elif args and args[0] == 'compose' and 'config' in args: + image = 'other:image' if os.environ['MOCK_MODE'] == 'image_mismatch' else 'local/test:schedule-ui' + print(json.dumps({'services': {'roborock-local-server': {'image': image}}})) +''' + + +class ExistingComposeUpdateTests(unittest.TestCase): + def test_existing_config_is_reused_and_failures_do_not_restart(self): + source = Path(__file__).resolve().parents[1] / "scripts/update-existing-compose.sh" + for mode in ("success", "build_failure", "image_mismatch", "dirty"): + with self.subTest(mode=mode), tempfile.TemporaryDirectory() as directory: + base = Path(directory) + repo = base / "repo" + repo.mkdir() + runtime = base / "runtime" + runtime.mkdir() + (runtime / ".env").write_text("kept settings") + (runtime / "SOURCE_COMMIT").write_text("previous-revision\n") + (runtime / "credentials.json").write_text("keep working credentials") + project = base / "project with spaces" + project.mkdir() + files = [project / "compose.yaml", project / "override.yaml"] + for path in files: + path.write_text("kept configuration") + bindir = base / "bin" + bindir.mkdir() + for command in ("git", "docker"): + path = bindir / command + path.write_text(FAKE_COMMAND) + path.chmod(0o755) + path = bindir / "sudo" + path.write_text('#!/bin/bash\nif [[ "$1" == -v ]]; then exit 0; fi\nexec "$@"\n') + path.chmod(0o755) + trace = base / "trace.jsonl" + env = {**os.environ, "PATH": str(bindir) + ":" + os.environ["PATH"], "MOCK_TRACE": str(trace), + "MOCK_MODE": mode, "ROBOROCK_RUNTIME_DIR": str(runtime), + "MOCK_LABELS": json.dumps({"com.docker.compose.project": "existing-project", + "com.docker.compose.service": "roborock-local-server", + "com.docker.compose.project.working_dir": str(project), + "com.docker.compose.project.config_files": ",".join(map(str, files))})} + result = subprocess.run(["bash", str(source), str(repo)], env=env, text=True, capture_output=True, timeout=15) + commands = [json.loads(line) for line in trace.read_text().splitlines()] + restarts = [item for item in commands if item[:2] == ["docker", "compose"] and "up" in item] + if mode == "success": + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(len(restarts), 1) + for argument in ("--no-deps", "--no-build", "--force-recreate", "never", str(runtime / ".env"), *map(str, files)): + self.assertIn(argument, restarts[0]) + self.assertEqual((runtime / "SOURCE_COMMIT").read_text().strip(), "a" * 40) + else: + self.assertNotEqual(result.returncode, 0) + self.assertFalse(restarts) + self.assertEqual((runtime / "SOURCE_COMMIT").read_text(), "previous-revision\n") + self.assertEqual((runtime / "credentials.json").read_text(), "keep working credentials") + self.assertTrue(all(path.read_text() == "kept configuration" for path in files)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_mqtt_credentials_reset.py b/tests/test_mqtt_credentials_reset.py new file mode 100644 index 0000000..7e74093 --- /dev/null +++ b/tests/test_mqtt_credentials_reset.py @@ -0,0 +1,116 @@ +"""Credential reset exercises persistence, authenticated API and live proxy state.""" + +import json +import logging +import socket + +from fastapi.testclient import TestClient + +from conftest import write_release_config +from roborock_local_server.backend import MqttTlsProxy +from roborock_local_server.config import load_config, resolve_paths +from roborock_local_server.server import ReleaseSupervisor +from shared.runtime_credentials import RuntimeCredentialsStore +from shared.runtime_state import RuntimeState +from test_mqtt_tls_proxy import _build_connect_packet, _build_publish_packet + + +def test_admin_reset_requires_login_and_same_origin_and_preserves_data(tmp_path, monkeypatch): + config_file = write_release_config(tmp_path) + config = load_config(config_file) + paths = resolve_paths(config_file, config) + supervisor = ReleaseSupervisor(config=config, paths=paths) + credentials = supervisor.runtime_credentials + credentials.ensure_device(duid="downstairs", did="123", localkey="keep-key", + device_mqtt_usr="old-user", device_mqtt_pass="old-password") + other = credentials.ensure_device(duid="upstairs", did="456", device_mqtt_usr="other-user", + device_mqtt_pass="other-password") + supervisor.protocol_auth.issue_local_session({"rruid": "test-user", "rriot": { + "u": "app-id", "s": "app-session", "h": "app-hawk", "k": "app-mqtt"}}, source="test") + sessions = supervisor.protocol_auth.persisted_sessions() + paths.inventory_path.write_text(json.dumps({"devices": [{"duid": "downstairs"}], + "server_scheduled_start": {"downstairs": [{"id": "job-1", "enabled": True}]}})) + inventory = paths.inventory_path.read_bytes() + key_path = supervisor.runtime_state.key_state_file + key_path.parent.mkdir(parents=True, exist_ok=True) + key_path.write_text(json.dumps({"devices": {"123": {"modulus": "123456789"}}})) + keys = key_path.read_bytes() + supervisor.runtime_state.start_onboarding_session(target_duid="downstairs", target_did="123") + client = TestClient(supervisor.app) + url = "/admin/api/vacuums/downstairs/mqtt-credentials" + assert client.delete(url).status_code == 401 + assert client.post("/admin/api/login", json={"password": "correct horse battery staple"}).status_code == 200 + assert client.delete(url, headers={"Origin": "https://other.example"}).status_code == 403 + assert client.delete("/admin/api/vacuums/missing/mqtt-credentials").status_code == 404 + response = client.delete(url, headers={"Origin": "http://testserver"}) + assert response.status_code == 200 + assert response.json()["mqtt_credentials"]["saved"] is False + assert "old-password" not in response.text and "keep-key" not in response.text + assert credentials.resolve_device(duid="downstairs")["localkey"] == "keep-key" + assert credentials.resolve_device(duid="upstairs") == other + assert supervisor.protocol_auth.persisted_sessions() == sessions + assert paths.inventory_path.read_bytes() == inventory + assert key_path.read_bytes() == keys + assert not supervisor.runtime_state.onboarding_session_snapshot()["active"] + # A second reset is safe and does not touch another device's pairing. + supervisor.runtime_state.start_onboarding_session(target_duid="upstairs", target_did="456") + assert client.delete(url).status_code == 200 + assert supervisor.runtime_state.onboarding_session_snapshot()["target"]["duid"] == "upstairs" + def fail_save(): + raise OSError("private filesystem detail") + monkeypatch.setattr(credentials, "_save_locked", fail_save) + response = client.delete(url) + assert response.status_code == 500 + assert "private filesystem detail" not in response.text + + +def test_live_reset_disconnects_only_target_and_blocks_queued_or_inflight_old_login(tmp_path): + credentials = RuntimeCredentialsStore(tmp_path / "credentials.json") + credentials.ensure_device(duid="downstairs", did="123", localkey="keep-key", + device_mqtt_usr="old-user", device_mqtt_pass="old-password") + credentials.ensure_device(duid="upstairs", did="456", device_mqtt_usr="other-user", + device_mqtt_pass="other-password") + state = RuntimeState(log_dir=tmp_path, key_state_file=None, runtime_credentials=credentials) + proxy = MqttTlsProxy(cert_file=None, key_file=None, tls_enabled=False, listen_host="127.0.0.1", + listen_port=0, backend_host="127.0.0.1", backend_port=1883, localkey="keep-key", + logger=logging.getLogger("test.reset"), decoded_jsonl=tmp_path / "decoded.jsonl", + runtime_state=state, runtime_credentials=credentials) + old_packet = _build_connect_packet(client_id="robot", username="old-user", password="old-password") + other_packet = _build_connect_packet(client_id="other", username="other-user", password="other-password") + assert proxy._authorize_client_connect("1", old_packet, client_ip="192.0.2.1")[0] + assert proxy._authorize_client_connect("2", other_packet, client_ip="192.0.2.2")[0] + assert proxy._authorize_client_connect("3", old_packet, client_ip="192.0.2.1")[0] + sockets = [sock for _ in range(3) for sock in socket.socketpair()] + try: + assert proxy._register_conn_endpoints("1", sockets[0], sockets[2]) + assert proxy._register_conn_endpoints("2", sockets[4], sockets[5]) + proxy.clear_device_mqtt_credentials(duid="downstairs") + sockets[1].settimeout(1) + sockets[3].settimeout(1) + assert sockets[1].recv(1) == sockets[3].recv(1) == b"" + assert sockets[4].fileno() != -1 and sockets[5].fileno() != -1 + assert not proxy._register_conn_endpoints("3", sockets[1], sockets[3]) + proxy._trace_packet("1", "c2b", _build_publish_packet(topic="rr/d/i/123/old-user")) + assert credentials.resolve_device(duid="downstairs")["device_mqtt_usr"] == "" + assert not proxy._authorize_connect_packet(old_packet)[0] + assert proxy._authorize_connect_packet(other_packet)[0] + assert not (tmp_path / "decoded.jsonl").exists() + finally: + for sock in sockets: + sock.close() + + +def test_reset_status_stays_offline_until_new_credentials_are_confirmed(tmp_path): + config_file = write_release_config(tmp_path) + config = load_config(config_file) + supervisor = ReleaseSupervisor(config=config, paths=resolve_paths(config_file, config)) + supervisor.runtime_credentials.ensure_device(duid="downstairs", did="123", name="Downstairs", + device_mqtt_usr="old-user", device_mqtt_pass="old-password") + supervisor.refresh_inventory_state() + supervisor.clear_device_mqtt_credentials(duid="downstairs") + # An app's request on rr/m is not evidence that a cleared robot has re-paired. + supervisor.runtime_state.record_mqtt_message(conn_id="app", direction="c2b", + topic="rr/m/i/app/user/downstairs", payload_preview="request") + vacuum = next(vac for vac in supervisor._vacuums_payload()["vacuums"] if vac["duid"] == "downstairs") + assert vacuum["connected"] is False + assert vacuum["mqtt_credentials"]["saved"] is False diff --git a/tests/test_mqtt_tls_proxy.py b/tests/test_mqtt_tls_proxy.py index 7c35c1e..c4cbee6 100644 --- a/tests/test_mqtt_tls_proxy.py +++ b/tests/test_mqtt_tls_proxy.py @@ -888,6 +888,7 @@ def test_handle_client_traces_packets_already_buffered_before_relay(tmp_path, mo assert traced == [ ("1", "c2b", connect_packet), ("1", "c2b", b"\xc0\x00"), + ("1", "cleanup", b""), ] diff --git a/tests/test_runtime_credentials.py b/tests/test_runtime_credentials.py index 106f19e..c538c72 100644 --- a/tests/test_runtime_credentials.py +++ b/tests/test_runtime_credentials.py @@ -1,9 +1,75 @@ import json from pathlib import Path +import pytest + from roborock_local_server.bundled_backend.shared.runtime_credentials import RuntimeCredentialsStore +def test_clear_mqtt_credentials_preserves_other_data_and_survives_reload(tmp_path): + path = tmp_path / "credentials.json" + path.write_text(json.dumps({"mqtt_usr": "bootstrap", "mqtt_passwd": "bootstrap-secret", "devices": [ + {"duid": "downstairs", "did": "123", "name": "Downstairs", "model": "a15", "localkey": "keep-key", + "mqtt_usr": "old-user", "mqtt_password": "old-secret"}, + {"duid": "upstairs", "did": "456", "device_mqtt_usr": "other-user", "device_mqtt_pass": "other-secret"}, + ]})) + store = RuntimeCredentialsStore(path) + other = store.resolve_device(duid="upstairs") + cleared = store.clear_device_mqtt_credentials(duid="downstairs") + assert cleared["device_mqtt_usr"] == cleared["device_mqtt_pass"] == "" + assert cleared["localkey"] == "keep-key" + assert cleared["did"] == "123" and cleared["model"] == "a15" + assert store.resolve_device(duid="upstairs") == other + assert store.bootstrap_value("mqtt_passwd") == "bootstrap-secret" + assert not store.verify_device_mqtt_credentials(username="old-user", password="old-secret")[0] + assert list(tmp_path.iterdir()) == [path] # No backup or temporary file remains. + assert "old-secret" not in path.read_text() and "old-user" not in path.read_text() + assert RuntimeCredentialsStore(path).resolve_device(duid="downstairs") == cleared + with pytest.raises(KeyError): + store.clear_device_mqtt_credentials(duid="123") # No DID/model fallback. + + +def test_reset_blocks_old_topics_and_pending_pairing_but_allows_fresh_pairing(tmp_path): + store = RuntimeCredentialsStore(tmp_path / "credentials.json") + store.ensure_device(duid="downstairs", did="123", device_mqtt_usr="old-user", device_mqtt_pass="old-secret") + reset = store.clear_device_mqtt_credentials(duid="downstairs") + store = RuntimeCredentialsStore(store.path) + store.record_mqtt_topic(topic="rr/d/i/123/old-user") + assert store.recover_device_mqtt_password(username="old-user", password="old-secret") is None + assert store.confirm_device_mqtt_credentials(did="123", username="old-user", password="old-secret") is None + learned = store.confirm_device_mqtt_credentials(did="123", username="new-user", password="new-secret", + expected_reset_at=reset["device_mqtt_reset_at"]) + assert learned["device_mqtt_usr"] == "new-user" + store.record_mqtt_topic(topic="rr/d/i/123/old-user") + assert store.verify_device_mqtt_credentials(username="new-user", password="new-secret")[0] + assert not store.verify_device_mqtt_credentials(username="old-user", password="old-secret")[0] + + +def test_reset_is_not_undone_by_merging_a_stale_did_record(tmp_path): + store = RuntimeCredentialsStore(tmp_path / "credentials.json") + store.ensure_device(duid="downstairs", localkey="keep-key") + store.clear_device_mqtt_credentials(duid="downstairs") + store.ensure_device(did="123", device_mqtt_usr="old-user", device_mqtt_pass="old-secret") + merged = store.ensure_device(duid="downstairs", did="123", device_mqtt_usr="old-user") + assert merged["device_mqtt_usr"] == merged["device_mqtt_pass"] == "" + assert merged["localkey"] == "keep-key" + + +def test_failed_reset_preserves_disk_and_live_credentials(tmp_path, monkeypatch): + import os + store = RuntimeCredentialsStore(tmp_path / "credentials.json") + before = store.ensure_device(duid="downstairs", device_mqtt_usr="user", device_mqtt_pass="secret") + before_file = store.path.read_bytes() + def fail_replace(*args): + raise OSError("simulated disk failure") + monkeypatch.setattr(os, "replace", fail_replace) + with pytest.raises(OSError): + store.clear_device_mqtt_credentials(duid="downstairs") + assert store.resolve_device(duid="downstairs") == before + assert store.path.read_bytes() == before_file + assert list(tmp_path.iterdir()) == [store.path] + + def test_ensure_device_merges_split_did_and_duid_records(tmp_path: Path) -> None: credentials_path = tmp_path / "runtime_credentials.json" credentials_path.write_text(