diff --git a/openpilot/starpilot/models/manager.py b/openpilot/starpilot/models/manager.py index 51efaa6eb0..9aa369da32 100644 --- a/openpilot/starpilot/models/manager.py +++ b/openpilot/starpilot/models/manager.py @@ -354,12 +354,14 @@ def resolve_runtime(chestnut_available: bool, *, root: Path = ROOT, randomize: b class ModelManager: def __init__(self, *, root: Path = ROOT, parked: Callable[[], bool] | None = None, - gpu_present: Callable[[], bool] | None = None, opener=urlopen, jetlink=None, refresh_catalog: bool = False): + download_allowed: Callable[[], bool] | None = None, gpu_present: Callable[[], bool] | None = None, + opener=urlopen, jetlink=None, refresh_catalog: bool = False): self.root, self.opener = root, opener self.refresh_catalog = refresh_catalog self.last_refresh_attempt: float | None = None self.jetlink = jetlink self.parked = parked or (lambda: False) + self.download_allowed = download_allowed if gpu_present is None: from openpilot.selfdrive.modeld.helpers import chestnut_present gpu_present = chestnut_present @@ -379,7 +381,7 @@ class ModelManager: self.verify_closed = False def _refresh_if_needed(self) -> None: - if not self.refresh_catalog or not self.parked(): + if not self.refresh_catalog or not self._can_download(): return now = time.monotonic() if self.last_refresh_attempt is not None and now - self.last_refresh_attempt < 300: @@ -614,6 +616,7 @@ class ModelManager: from openpilot.starpilot.models.laboratory import configuration entries, prefs = catalog(self.root), preferences(self.root) parked, gpu = self.parked(), self.gpu_present() + downloads = parked or (self.download_allowed is not None and self.download_allowed()) job = self._job_status() owner = self.jetlink_owner() jetlink = owner.snapshot() @@ -648,14 +651,21 @@ class ModelManager: "downloading": job["downloading"], "refreshing": job["refreshing"], "progress": job.get("progress", ""), "downloadProgress": self._download_progress(job), "isOnroad": not parked, "gpuAvailable": gpu, "jetlink": jetlink, - "capabilities": {"configureLaboratory": not job["downloading"], "select": True, "download": parked, - "downloadAll": parked, "cancel": True, - "jetlink": parked, "refresh": parked, "favorites": True, "delete": parked, "randomizer": True, "exclusions": True}} + "capabilities": {"configureLaboratory": not job["downloading"], "select": True, "download": downloads, + "downloadAll": downloads, "cancel": True, + "jetlink": parked, "refresh": downloads, "favorites": True, "delete": parked, "randomizer": True, "exclusions": True}} def _require_parked(self) -> None: if not self.parked(): raise ModelError("Turn the vehicle off before changing driving models") + def _can_download(self) -> bool: + return (self.download_allowed or self.parked)() + + def _require_download_allowed(self) -> None: + if not self._can_download(): + raise ModelError("Model downloads require confirmed offroad status") + def action(self, action: str, payload: dict) -> dict: if not isinstance(payload, dict): raise ModelError("Invalid model request") @@ -696,9 +706,8 @@ class ModelManager: saved.update(payload) atomic_json(self.root / "preferences.json", saved) return {**self.snapshot(), "message": "Model preferences saved"} - if action != "active": - self._require_parked() if action in ("download", "download_all", "refresh_manifest"): + self._require_download_allowed() if self.worker is not None and self.worker.is_alive(): raise ModelError("A model download is already running") if action == "download" and (set(payload) - {"model", "allowGpuWithoutGpu", "variant"} or @@ -717,7 +726,7 @@ class ModelManager: not self.gpu_present() and not payload.get("allowGpuWithoutGpu")): raise ModelError("Connect Chestnut or choose to download for later") with state_lock(self.root): - self._require_parked() + self._require_download_allowed() lock = (self.root / ".download.lock").open("a") try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) @@ -749,6 +758,8 @@ class ModelManager: self._finish_job(lock, True) raise return {"message": message} + if action != "active": + self._require_parked() if action == "active": job = self._job_status() if job["downloading"] and not job["refreshing"]: @@ -816,6 +827,7 @@ class ModelManager: def _work(self, action: str, payload: dict, lock) -> None: failed = True try: + self._require_download_allowed() self._check_cancelled() self._publish_job(detail={"phase": "catalog"}) self._refresh() @@ -886,7 +898,7 @@ class ModelManager: raise ModelError("Model checksum did not match; download discarded") self._publish_job(detail={"phase": "installing"}) with state_lock(self.root): - self._require_parked() + self._require_download_allowed() self._check_cancelled() os.replace(temp, destination) self.checked.pop(f"{mid}:{variant}", None) diff --git a/openpilot/starpilot/models/tests/test_manager.py b/openpilot/starpilot/models/tests/test_manager.py index a8fb327f9d..d09e2178b2 100644 --- a/openpilot/starpilot/models/tests/test_manager.py +++ b/openpilot/starpilot/models/tests/test_manager.py @@ -92,6 +92,32 @@ class ModelManagerTest(unittest.TestCase): def model_status(self): return next(x for x in self.manager.snapshot()['models'] if x['value'] == 'gwm8223') + def test_bench_can_download_without_unlocking_parked_changes(self): + self.parked = False + self.manager.download_allowed = lambda: True + caps = self.manager.snapshot()['capabilities'] + self.assertTrue(caps['download'] and caps['downloadAll'] and caps['refresh']) + self.assertFalse(caps['delete'] or caps['jetlink']) + with self.assertRaisesRegex(ModelError, "before changing driving models"): + self.manager.action('delete', {'model': 'gwm8223'}) + self.download() + self.assertTrue(self.wait_for_check()['installed']) + + def test_bench_authority_is_rechecked_before_publishing_the_artifact(self): + self.parked = False + offroad = True + self.manager.download_allowed = lambda: offroad + open_fixture = self.manager.opener + def opener(url, timeout): + nonlocal offroad + if url.endswith('chunk02of02'): + offroad = False + return open_fixture(url, timeout) + self.manager.opener = opener + self.download() + self.assertIn("confirmed offroad", self.manager.snapshot()['progress']) + self.assertFalse(self.wait_for_check()['installed']) + def wait_for_check(self): deadline = time.monotonic() + 3 while time.monotonic() < deadline: diff --git a/openpilot/starpilot/parked_evidence.py b/openpilot/starpilot/parked_evidence.py index f1eef7b500..6687235153 100644 --- a/openpilot/starpilot/parked_evidence.py +++ b/openpilot/starpilot/parked_evidence.py @@ -41,14 +41,12 @@ class ParkedEvidence: panda_ignition: tuple[bool, ...] -def fresh_offroad(evidence: ParkedEvidence, *, now_mono_ns: int, now_boot_ns: int) -> bool: +def fresh_offroad(evidence: ParkedEvidence, *, now_mono_ns: int, now_boot_ns: int, allow_bench: bool = False) -> bool: """Confirm effective offroad mode, including Force Offroad with ignition on.""" e = evidence - if (not e.manager_offroad or not all((e.device_seen, e.device_alive, e.device_valid, - e.panda_seen, e.panda_alive, e.panda_valid)) or + if (not e.manager_offroad or not all((e.device_seen, e.device_alive, e.device_valid)) or e.device_started or e.device_boot_minus_mono_at_recv_ns is None or - not e.panda_ignition or - min(e.device_stamp_mono_ns, e.panda_stamp_boot_ns, e.device_recv_mono_ns, e.panda_recv_mono_ns) <= 0 or + min(e.device_stamp_mono_ns, e.device_recv_mono_ns) <= 0 or e.device_stamp_mono_ns <= e.device_after_mono_ns): return False device_mono_age = now_mono_ns - e.device_stamp_mono_ns @@ -56,11 +54,15 @@ def fresh_offroad(evidence: ParkedEvidence, *, now_mono_ns: int, now_boot_ns: in panda_boot_age = now_boot_ns - e.panda_stamp_boot_ns device_receipt_age = now_mono_ns - e.device_recv_mono_ns panda_receipt_age = now_mono_ns - e.panda_recv_mono_ns + fresh_panda = (e.panda_seen and e.panda_alive and e.panda_valid and min(e.panda_stamp_boot_ns, e.panda_recv_mono_ns) > 0 and + 0 <= panda_boot_age <= PANDA_TTL_NS and 0 <= panda_receipt_age <= PANDA_TTL_NS) + has_panda = bool(e.panda_ignition) + # A stale Panda report is not evidence that the device is on a bench. + bench = allow_bench and not has_panda and (not e.panda_seen or fresh_panda) return (0 <= device_mono_age <= DEVICE_TTL_NS and -RESUME_SKEW_NS <= device_boot_age <= DEVICE_TTL_NS and - 0 <= panda_boot_age <= PANDA_TTL_NS and 0 <= device_receipt_age <= DEVICE_TTL_NS and - 0 <= panda_receipt_age <= PANDA_TTL_NS) + (fresh_panda and has_panda or bench)) def fresh_parked(evidence: ParkedEvidence, *, now_mono_ns: int, now_boot_ns: int) -> bool: diff --git a/openpilot/starpilot/ui/models_state.py b/openpilot/starpilot/ui/models_state.py index 640197d03f..03f7d64daf 100644 --- a/openpilot/starpilot/ui/models_state.py +++ b/openpilot/starpilot/ui/models_state.py @@ -88,7 +88,7 @@ def model_action_allowed(data: dict, action: str, model: dict | None = None, pro "exclusion": "exclusions"}.get(action, action) if data.get("capabilities", {}).get(capability) is not True: return False - if data.get("isOnroad") is not False and action not in ("preferences", "cancel", "active"): + if data.get("isOnroad") is not False and action not in ("preferences", "cancel", "active", "download", "download_all", "refresh_manifest"): return False if action == "active": if profile == "big" and data.get("jetlinkBig") and data.get("isOnroad") is not False: @@ -276,7 +276,7 @@ def _catalog_row(data: dict) -> FeatureRow: return FeatureRow("models:downloads", "Catalog", _catalog_summary(data), available=True, actions=tuple((label, model_action_allowed(data, action)) for label, action in model_download_buttons(data)), reason="Downloading" if data.get("downloading") else _plain(data.get("progress", "")) or - ("Check for new models or get every missing one" if data.get("isOnroad") is False else OFFROAD)) + ("Check for new models or get every missing one" if data.get("capabilities", {}).get("refresh") else OFFROAD)) def model_display_text(value: str) -> str: diff --git a/openpilot/starpilot/ui/runtime_app.py b/openpilot/starpilot/ui/runtime_app.py index d042c53f62..57478775eb 100644 --- a/openpilot/starpilot/ui/runtime_app.py +++ b/openpilot/starpilot/ui/runtime_app.py @@ -991,7 +991,7 @@ class StarShellSession(TeslaSpeedActions): def _model_manager(self): if getattr(self, 'model_manager', None) is None: from openpilot.starpilot.models.manager import ModelManager - self.model_manager = ModelManager(parked=self.confirmed_offroad, refresh_catalog=True) + self.model_manager = ModelManager(parked=self.confirmed_offroad, download_allowed=self.adapter.model_download_allowed, refresh_catalog=True) return self.model_manager def model_manager_snapshot(self, fresh: bool = False): diff --git a/openpilot/starpilot/ui/runtime_snapshot.py b/openpilot/starpilot/ui/runtime_snapshot.py index 844098486d..38bb92af50 100644 --- a/openpilot/starpilot/ui/runtime_snapshot.py +++ b/openpilot/starpilot/ui/runtime_snapshot.py @@ -371,7 +371,7 @@ class RuntimeSnapshotAdapter: self._pair_failed = False self._replay_epoch: int | None = None - def _parked(self, ui: Any, pair: tuple[int, int, int] | None) -> bool: + def _parked(self, ui: Any, pair: tuple[int, int, int] | None, *, model_download: bool = False) -> bool: if host_parked(): return not ui.started if pair is None: @@ -400,7 +400,8 @@ class RuntimeSnapshotAdapter: int(sm.logMonoTime["pandaStates"]), int(sm.recv_time["pandaStates"] * 1e9), tuple(bool(p.ignitionLine or p.ignitionCan) for p in pandas), ) - return fresh_offroad(evidence, now_mono_ns=mono_now, now_boot_ns=boot_now) + allow_bench = model_download and not pandas and ui.params.get_bool("IsOffroad") is True + return fresh_offroad(evidence, now_mono_ns=mono_now, now_boot_ns=boot_now, allow_bench=allow_bench) except (AttributeError, KeyError, TypeError, ValueError, OverflowError, OSError, RuntimeError): return False @@ -413,6 +414,11 @@ class RuntimeSnapshotAdapter: return False return self._parked(self.ui_state, _clock_pair(self._mono_clock, self._boot_clock)) + def model_download_allowed(self) -> bool: + if getattr(self.ui_state, "replay_clock", None) is not None: + return False + return self._parked(self.ui_state, _clock_pair(self._mono_clock, self._boot_clock), model_download=True) + def connectivity_allowed(self) -> bool: """Fresh effective offroad admission for connectivity setup, regardless of ignition.""" return self.confirmed_offroad() diff --git a/openpilot/starpilot/ui/tests/test_models.py b/openpilot/starpilot/ui/tests/test_models.py index 196e285d8f..ba7cab5066 100644 --- a/openpilot/starpilot/ui/tests/test_models.py +++ b/openpilot/starpilot/ui/tests/test_models.py @@ -126,7 +126,7 @@ class TestModelManager(unittest.TestCase): self.data = {"schemaVersion": 1, "models": [self.small, self.big, self.pending, self.missing], "isOnroad": False, "activeSmallModel": "small", "activeBigModel": "big", "currentModel": "small", "downloading": False, "capabilities": {"select": True, "download": True, "downloadAll": True, "favorites": True, "delete": True, "cancel": True, - "randomizer": True, "exclusions": True}} + "randomizer": True, "exclusions": True, "refresh": True}} def test_verified_profiles_and_pending_catalog_are_distinct(self): def picks(data, profile): @@ -158,7 +158,8 @@ class TestModelManager(unittest.TestCase): self.assertFalse(model_action_allowed(self.data, "delete", self.big)) self.assertTrue(model_action_allowed({**self.data, "activeBigModel": ""}, "delete", self.big)) self.assertFalse(model_action_allowed({**self.data, "capabilities": {}}, "active", self.small, "small")) - moving = {**self.data, "isOnroad": True, "downloading": False} + moving = {**self.data, "isOnroad": True, "downloading": False, + "capabilities": self.data["capabilities"] | {"download": False, "downloadAll": False, "refresh": False}} self.assertTrue(model_action_allowed(moving, "active", self.small, "small")) self.assertTrue(model_action_allowed(moving, "active", self.big, "big")) self.assertFalse(model_action_allowed(moving | {"jetlinkBig": True}, "active", self.big, "big")) @@ -324,10 +325,18 @@ class TestModelManager(unittest.TestCase): owner._action(page, "download", "missing") session.model_manager_action.assert_not_called() callback = confirm.call_args.args[2] - session.model_manager_snapshot.return_value = {**self.data, "isOnroad": True} + session.model_manager_snapshot.return_value = {**self.data, "isOnroad": True, + "capabilities": self.data["capabilities"] | {"download": False}} callback() session.model_manager_action.assert_not_called() + def test_bench_download_capability_does_not_unlock_parked_model_changes(self): + bench = self.data | {"isOnroad": True} + self.assertTrue(model_action_allowed(bench, "download", self.missing)) + self.assertTrue(model_action_allowed(bench, "download_all")) + self.assertTrue(model_action_allowed(bench, "refresh_manifest")) + self.assertFalse(model_action_allowed(bench, "delete", self.small)) + def test_randomizer_disables_manual_selection_but_keeps_favorites_independent(self): randomized = {**self.data, "randomizer": True} self.assertIsNone(model_request(randomized, "active", "small", "small")) diff --git a/openpilot/starpilot/ui/tests/test_runtime_snapshot.py b/openpilot/starpilot/ui/tests/test_runtime_snapshot.py index 636498508e..1a49964f1d 100644 --- a/openpilot/starpilot/ui/tests/test_runtime_snapshot.py +++ b/openpilot/starpilot/ui/tests/test_runtime_snapshot.py @@ -399,8 +399,39 @@ class TestRuntimeSnapshot(unittest.TestCase): ui.sm.replay_sample = ui.replay_sample adapter = NativeRuntimeSnapshotAdapter(ui) self.assertFalse(adapter.confirmed_offroad()) + self.assertFalse(adapter.model_download_allowed()) self.assertFalse(adapter.build(ShellMode.HOME).device.offroad) + def test_bench_download_requires_fresh_offroad_without_relaxing_other_actions(self): + ui = ui_fake() + ui.started = False + ui.sm['deviceState'].started = False + ui.params.values['IsOffroad'] = '1' + ui.sm.messages['pandaStates'] = [] + ui.sm.seen['pandaStates'] = False + adapter = RuntimeSnapshotAdapter(ui) + self.assertFalse(adapter.confirmed_offroad()) + self.assertTrue(adapter.model_download_allowed()) + ui.params.values['IsOffroad'] = '0' + self.assertFalse(adapter.model_download_allowed()) + ui.params.values['IsOffroad'] = '1' + ui.sm['deviceState'].started = True + self.assertFalse(adapter.model_download_allowed()) + ui.sm['deviceState'].started = False + ui.sm.valid['deviceState'] = False + self.assertFalse(adapter.model_download_allowed()) + ui.sm.valid['deviceState'] = True + ui.sm.put('pandaStates', [], age_ns=400_000_000) + self.assertFalse(adapter.model_download_allowed()) + ui.sm.put('pandaStates', []) + self.assertTrue(adapter.model_download_allowed()) + ui.sm.put('pandaStates', [NS(ignitionLine=False, ignitionCan=False)], age_ns=400_000_000) + self.assertFalse(adapter.model_download_allowed()) + ui.sm.logMonoTime['deviceState'] -= 2_000_000_000 + ui.sm.seen['pandaStates'] = False + ui.sm.messages['pandaStates'] = [] + self.assertFalse(adapter.model_download_allowed()) + def test_replay_epoch_resets_projectors_and_saved_layout_cache(self): from openpilot.tools.replay.display_clock import ClockSample ui = ui_fake() diff --git a/prebuilt.json b/prebuilt.json index 8565b2c2cf..a0e788e5fb 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "d9093e0a0ca6ef2e405bd04180819a1a69bb41fc5283d28db2445f8ba0ac1f8e", "schema_version": 1} +{"protected_inventory_sha256": "54261fc0458a9c34864b113de3ac3c9ec08bebdbbcba6ef3de5458e1377bbc1c", "schema_version": 1}