From 14044e97f00badd31240bef153fb4d40f1c8647f Mon Sep 17 00:00:00 2001 From: Danny Date: Fri, 13 Nov 2026 17:01:12 -0800 Subject: [PATCH] Navigation: Tidy shared route hardening and fix type errors --- openpilot/starpilot/galaxy/settings.py | 5 +--- .../galaxy/tests/test_navigation_http.py | 7 ++++++ .../starpilot/navigation/google_routes.py | 3 +-- .../starpilot/navigation/google_tiles.py | 6 +---- openpilot/starpilot/navigation/owner.py | 10 ++++---- openpilot/starpilot/navigation/runtime.py | 5 ++-- .../starpilot/navigation/tests/test_owner.py | 18 +++++++++++++++ .../system/starport/projection_favorites.py | 2 +- openpilot/starpilot/ui/onroad_google_map.py | 5 +--- openpilot/starpilot/ui/onroad_map.py | 23 +++++-------------- .../ui/onroad_navigation_favorites.py | 2 +- .../ui/tests/test_onroad_navigation.py | 7 +++--- 12 files changed, 47 insertions(+), 46 deletions(-) diff --git a/openpilot/starpilot/galaxy/settings.py b/openpilot/starpilot/galaxy/settings.py index d8b26f3da0..0a621f6ef7 100644 --- a/openpilot/starpilot/galaxy/settings.py +++ b/openpilot/starpilot/galaxy/settings.py @@ -295,10 +295,7 @@ class LiveContextSource: return False def _refreshed_snapshot(self, deadline): - """Wait for the shared collector's next deviceState and pandaStates, then sample it again. - - Called with self.lock held; it is released while waiting so concurrent Galaxy requests wait in parallel. - """ + """Wait for the next deviceState and pandaStates, then sample again; call with self.lock held.""" refresh = getattr(self.messages, "refresh", None) remaining_ms = int((deadline - self.wait_clock()) * 1000) if refresh is None or remaining_ms <= 0: diff --git a/openpilot/starpilot/galaxy/tests/test_navigation_http.py b/openpilot/starpilot/galaxy/tests/test_navigation_http.py index 2c8a0cad03..705491dbf5 100644 --- a/openpilot/starpilot/galaxy/tests/test_navigation_http.py +++ b/openpilot/starpilot/galaxy/tests/test_navigation_http.py @@ -231,6 +231,13 @@ class NavigationHttpTest(unittest.TestCase): changed = dict(request, text='geo:41,-89.5') self.assertEqual(self.request('/api/navigation/action', payload=changed, remote=True, cookie=self.remote_cookie)[0], 400) + def test_invalid_shared_intent_is_rejected(self): + self.navigation.configure({'token': 'pk.test'}, self.navigation.read()['revision'], True) + for intent in ('../bad', '', 'x' * 65, 7): + request = {'action': 'share', 'revision': self.navigation.read()['revision'], 'text': 'geo:40.5,-89.5', 'intentId': intent} + self.assertEqual(self.request('/api/navigation/action', payload=request, remote=True, cookie=self.remote_cookie)[0], 400) + self.assertIsNone(self.navigation.read()['destination']) + def test_stale_or_invalid_actions_never_overwrite_configuration(self): self.action('configure', patch={'enabled': True}) before = self.navigation.path.read_bytes() diff --git a/openpilot/starpilot/navigation/google_routes.py b/openpilot/starpilot/navigation/google_routes.py index 46adb72b97..a623c72719 100644 --- a/openpilot/starpilot/navigation/google_routes.py +++ b/openpilot/starpilot/navigation/google_routes.py @@ -199,8 +199,7 @@ def compute_routes(http, key: str, body: dict, timeout=TIMEOUT) -> list[Navigati class GoogleRouteEngine: - """Traffic-aware (Pro) routes, with the car's heading when it is moving; free Essentials routes once the Pro allowance - or the hourly reroute limit is used up.""" + """Traffic-aware Pro routes, falling back to Essentials once the Pro or hourly reroute limit is used up.""" def __init__(self, session, budget: GoogleBudget, essentials: GoogleBudget, clock=time.monotonic): self.session = session diff --git a/openpilot/starpilot/navigation/google_tiles.py b/openpilot/starpilot/navigation/google_tiles.py index 70708413db..7880b8752d 100644 --- a/openpilot/starpilot/navigation/google_tiles.py +++ b/openpilot/starpilot/navigation/google_tiles.py @@ -1,8 +1,4 @@ -"""Google Map Tiles for the nav map widget, with the user's own key. - -The map widget writes which tiles it is about to show; navtilesd fetches only those, stores each -for as long as Google's Cache-Control allows, and stops at 99% of the free monthly and daily tiles. -""" +"""Google Map Tiles for the nav map widget, fetched only as requested and capped below the free allowance.""" from __future__ import annotations diff --git a/openpilot/starpilot/navigation/owner.py b/openpilot/starpilot/navigation/owner.py index 957cc35e68..382b7c07e5 100644 --- a/openpilot/starpilot/navigation/owner.py +++ b/openpilot/starpilot/navigation/owner.py @@ -51,6 +51,7 @@ GOOGLE_MAP_HOST = re.compile(r'(?:maps\.app\.goo\.gl|goo\.gl|(?:[a-z0-9-]+\.)*go CONFIGURABLE = {'enabled', 'token', 'gpsSource', 'mapProvider', 'routeProvider', 'googleKey'} KEEPS_ACTIVE = {'gpsSource', 'mapProvider', 'routeProvider', 'googleKey'} GOOGLE_KEY_CHARS = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-') +SAFE_ID = re.compile(r'[a-zA-Z0-9_-]{1,64}') def valid_google_key(key: str) -> bool: @@ -211,13 +212,12 @@ class NavigationOwner: if value.get('destination') is not None: value['destination'] = destination(value['destination']) routing_revision = value.setdefault('routingRevision', value['revision']) - if (not isinstance(routing_revision, str) or not 1 <= len(routing_revision) <= 64 or - any(ch not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-' for ch in routing_revision)): + if not isinstance(routing_revision, str) or SAFE_ID.fullmatch(routing_revision) is None: raise ValueError intents = value.setdefault('shareIntents', []) if (not isinstance(intents, list) or len(intents) > 64 or any(not isinstance(row, dict) or set(row) != {'id', 'digest'} or - not isinstance(row['id'], str) or re.fullmatch(r'[a-zA-Z0-9_-]{1,64}', row['id']) is None or + not isinstance(row['id'], str) or SAFE_ID.fullmatch(row['id']) is None or not isinstance(row['digest'], str) or re.fullmatch('[0-9a-f]{64}', row['digest']) is None for row in intents)): raise ValueError if len({row['id'] for row in intents}) != len(intents): @@ -646,7 +646,7 @@ class NavigationOwner: """A place shared from a phone: turns navigation on and starts the route.""" if not isinstance(text, str) or not text.strip() or len(text) > 8192: raise ValidationError('The shared text could not be read') - if intent_id is not None and (not isinstance(intent_id, str) or re.fullmatch(r'[a-zA-Z0-9_-]{1,64}', intent_id) is None): + if intent_id is not None and (not isinstance(intent_id, str) or SAFE_ID.fullmatch(intent_id) is None): raise ValidationError('The shared destination identity could not be read') if not (authorized() if callable(authorized) else authorized is True): raise PermissionError('Navigation changes are not available right now') @@ -662,8 +662,6 @@ class NavigationOwner: raise ValidationError('Add your Mapbox access token first') if not isinstance(expected_revision, str) or current['revision'] != expected_revision: raise ConflictError('Navigation changed; refresh and try again') - if not (authorized() if callable(authorized) else authorized is True): - raise PermissionError('Navigation changes are not available right now') from openpilot.starpilot.navigation.share import map_link_query, search_text, shared_coordinates text = self.resolve_share(text) shared = shared_coordinates(text) diff --git a/openpilot/starpilot/navigation/runtime.py b/openpilot/starpilot/navigation/runtime.py index 81b1f383fe..1ff3650188 100644 --- a/openpilot/starpilot/navigation/runtime.py +++ b/openpilot/starpilot/navigation/runtime.py @@ -190,7 +190,7 @@ class RouteRuntime: self.joined = True if distance(coordinates, (destination['longitude'], destination['latitude'])) < PARKED_RADIUS_M: return False - return self.joined or distance(coordinates, self.route.points[0]) >= UNJOINED_REROUTE_M + return self.joined or (self.route is not None and distance(coordinates, self.route.points[0]) >= UNJOINED_REROUTE_M) def _traffic_eta(self, now_ns: int, key: str, coordinates, speed, bearing, destination, exclusions, instruction: dict) -> None: """The route's own remaining time, scaled by how far off Google's latest traffic said it was.""" @@ -236,8 +236,7 @@ class RouteRuntime: distance(coordinates, (selected['longitude'], selected['latitude'])) < PARKED_RADIUS_M) def _parked_at_destination(self, now_ns: int, position, drive_id: int, settings) -> bool: - """A parking garage loses GPS before the route ends, so the stopped-at-the-end check never fires there. - A drive that ends near the destination arrived, as does one that starts near it (after a reboot, say).""" + """A drive that ends or starts near the destination counts as arrived, even without a final GPS fix.""" fresh = position is not None and 0 < position[0] <= now_ns <= position[0] + GPS_MAX_AGE_NS if not drive_id: if not self.drive: diff --git a/openpilot/starpilot/navigation/tests/test_owner.py b/openpilot/starpilot/navigation/tests/test_owner.py index bead20b497..1fca62a4d9 100644 --- a/openpilot/starpilot/navigation/tests/test_owner.py +++ b/openpilot/starpilot/navigation/tests/test_owner.py @@ -44,6 +44,24 @@ def test_share_intent_retry_after_cancel_or_restart_does_not_restart_route(owner assert restarted.read()['destination'] is not None +def test_settings_saved_before_share_intents_still_load_and_save(owner): + owner.configure({'token': 'pk.test'}, '0', True) + saved = json.loads(owner.path.read_text()) + owner.path.write_text(json.dumps({key: value for key, value in saved.items() if key not in ('routingRevision', 'shareIntents')})) + current = owner.read() + assert current['routingRevision'] == current['revision'] and current['shareIntents'] == [] + owner.favorite(PLACE, current['revision'], True) + assert owner.read()['favorites'][0]['name'] == 'Home' + + +def test_share_intent_history_keeps_the_newest_64(owner): + owner.configure({'token': 'pk.test'}, '0', True) + for index in range(65): + owner.share('geo:40.5,-89.5', owner.read()['revision'], True, intent_id=f'intent-{index}') + intents = owner.read()['shareIntents'] + assert len(intents) == 64 and intents[0]['id'] == 'intent-1' and intents[-1]['id'] == 'intent-64' + + @pytest.mark.parametrize('ledger', [None, [{}], [{'id': '../bad', 'digest': '0' * 64}], [{'id': 'test', 'digest': 'bad'}], [{'id': 'test', 'digest': '0' * 64}] * 2, diff --git a/openpilot/starpilot/system/starport/projection_favorites.py b/openpilot/starpilot/system/starport/projection_favorites.py index 00b0dc63d7..868c9656e1 100644 --- a/openpilot/starpilot/system/starport/projection_favorites.py +++ b/openpilot/starpilot/system/starport/projection_favorites.py @@ -49,7 +49,7 @@ class ProjectionFavorites: return ('bookmark',) doc = self.document if key == MAP_END: - return ('end', doc['revision'], doc['destination']) if self.bounds(key, state) is not None else None + return ('end', doc['revision'], doc['destination']) if doc is not None and self.bounds(key, state) is not None else None if doc is None or key not in FAVORITE_WIDGETS: return None if doc['destination'] is not None: diff --git a/openpilot/starpilot/ui/onroad_google_map.py b/openpilot/starpilot/ui/onroad_google_map.py index 94ab2893d0..d00d9d5891 100644 --- a/openpilot/starpilot/ui/onroad_google_map.py +++ b/openpilot/starpilot/ui/onroad_google_map.py @@ -1,7 +1,4 @@ -"""Google map tiles for the map widget: planned and decoded on a worker thread, uploaded on the render thread. - -navtilesd downloads the tiles this layer asks for; nothing here touches the network. -""" +"""Google map tiles for the map widget: decoded on a worker thread, uploaded on the render thread.""" from __future__ import annotations diff --git a/openpilot/starpilot/ui/onroad_map.py b/openpilot/starpilot/ui/onroad_map.py index 670f4c6e31..68f57691e0 100644 --- a/openpilot/starpilot/ui/onroad_map.py +++ b/openpilot/starpilot/ui/onroad_map.py @@ -117,11 +117,7 @@ def zoom_for_speed(speed_mps: float) -> float: def zoom_target(speed_mps: float, maneuver_m: float | None = None, stopped_s: float = 0.0, guided: bool = False) -> float: - """Meters per screen pixel: closer ahead of a maneuver, wider after sitting still. - - Without a route the zoom follows speed. On a route it holds one steady level and only zooms in for - the next turn, so the map does not breathe in and out with every change of speed. - """ + """Meters per screen pixel: follows speed off-route, holds steady on a route and zooms in for the next turn.""" base = ZOOM_ROUTE_M_PER_PX if guided else zoom_for_speed(speed_mps) near = maneuver_m is not None and maneuver_m <= OVERVIEW_MIN_MANEUVER_M if stopped_s >= OVERVIEW_AFTER_S and not near: @@ -296,8 +292,7 @@ def visible_runs(points: np.ndarray, bounds: tuple[float, float, float, float]) def snap_to_route(route: np.ndarray, position: tuple[float, float], bearing: float | None, max_offset: float, start: int | None = None) -> tuple[tuple[float, float], int, float] | None: - """The nearest point on the route ahead of ``start`` within ``max_offset`` world units (and heading along it): - (point, segment, segment bearing), or None.""" + """(point, segment, bearing) of the nearest route point ahead of ``start`` within ``max_offset``, or None.""" if route is None or len(route) < 2: return None first = 0 if start is None else max(0, start - 1) @@ -328,11 +323,7 @@ def route_lengths(route: np.ndarray) -> np.ndarray: def lookahead_heading(route: np.ndarray, lengths: np.ndarray, segment: int, point: tuple[float, float], ahead: float) -> float | None: - """Bearing from ``point`` (on ``segment``) to the spot ``ahead`` world units farther along the route. - - Facing a point down the line, rather than the segment under the car, keeps the map steady across the - small kinks of a simplified route line and starts a turn's rotation smoothly as the car approaches it. - """ + """Bearing from ``point`` (on ``segment``) to the spot ``ahead`` world units farther along the route.""" segment = min(max(segment, 0), len(route) - 2) a = route[segment] along = float(lengths[segment]) + math.hypot(point[0] - a[0], point[1] - a[1]) + ahead @@ -603,8 +594,7 @@ class MapOverlay: self._bearing = self._heading_target = road_bearing % 360.0 self._has_heading, self._turning = True, False else: - # Smooth the heading first so GPS noise and route kinks never reach the map, then rotate with - # hysteresis: start past the deadband, finish close to the heading instead of parking at the edge. + # Smooth the heading, then rotate with hysteresis past the deadband. self._heading_target = (self._heading_target + angle_delta(road_bearing, self._heading_target) * min(1.0, dt * HEADING_FILTER_RATE)) % 360.0 delta = angle_delta(self._heading_target, self._bearing) @@ -835,8 +825,7 @@ class MapOverlay: try: rl.clear_background(rl.BLANK) rl.begin_blend_mode(rl.BlendMode.BLEND_ALPHA_PREMULTIPLY) - # Render textures have no MSAA: the guidance layer is drawn larger and its bilinear sample in the - # mask shader averages each 2x2 block, so the route line's edges stay smooth at any rotation. + # Drawn at 2x and downsampled in the mask shader, since render textures have no MSAA. rl.rl_push_matrix() if guidance: rl.rl_scalef(GUIDANCE_SUPERSAMPLE, GUIDANCE_SUPERSAMPLE, 1) @@ -997,7 +986,7 @@ class MapOverlay: text = text[:-4] + "..." if text.endswith("...") else text[:-1] + "..." self._attribution_layout = key, text, self.fonts.measure(text, FontRole.NORMAL, size) if text else None _, text, measured = self._attribution_layout - if text: + if measured is not None: self.fonts.draw(text, FontRole.NORMAL, size, rect.x + rect.width - inset - measured.width, bottom - measured.height, rl.Color(214, 218, 230, 255)) diff --git a/openpilot/starpilot/ui/onroad_navigation_favorites.py b/openpilot/starpilot/ui/onroad_navigation_favorites.py index 7a15895c02..2cbe70c7d3 100644 --- a/openpilot/starpilot/ui/onroad_navigation_favorites.py +++ b/openpilot/starpilot/ui/onroad_navigation_favorites.py @@ -29,7 +29,7 @@ class NavigationFavorites: action = self.error or ('End route' if active else 'Navigate' if available else 'Set in Galaxy' if place is None else 'Enable navigation') title = label if bookmark else action detail = 'Save event' if bookmark else label - if active and not (place and doc['destination']['id'] == place['id']): + if active and doc is not None and not (place and doc['destination']['id'] == place['id']): detail = self.fit(doc['destination'].get('name') or 'Route', FontRole.SEMI_BOLD, 34, 290) icons = placed.get('display') == 'icons' rect = rl.Rectangle(placed['x'], placed['y'], 110 if icons else 320, 110) diff --git a/openpilot/starpilot/ui/tests/test_onroad_navigation.py b/openpilot/starpilot/ui/tests/test_onroad_navigation.py index 98d52a4cc1..d51b7cb8bf 100644 --- a/openpilot/starpilot/ui/tests/test_onroad_navigation.py +++ b/openpilot/starpilot/ui/tests/test_onroad_navigation.py @@ -82,12 +82,13 @@ def test_reaching_the_arrive_maneuver_reads_arrived_before_the_car_stops(): 'distanceMeters': 150, 'remainingDistanceMeters': 150, 'remainingDurationSeconds': 20} nav.nextManeuver = {'maneuverType': 'arrive', 'maneuverModifier': 'straight', 'distanceMeters': 150} approaching = navigation_display(nav, now_ns=NOW, drive_id=DRIVE) - assert not approaching.arrived and approaching.text == 'Arrive at your destination' + assert approaching is not None and not approaching.arrived and approaching.text == 'Arrive at your destination' nav.instruction.distanceMeters = nav.instruction.remainingDistanceMeters = 0 there = navigation_display(nav, now_ns=NOW, drive_id=DRIVE) - assert there.arrived and there.text == 'You have arrived' and there.then_type == '', "no '0 ft' while still rolling" + assert there is not None and there.arrived and there.text == 'You have arrived' and there.then_type == '', "no '0 ft' while still rolling" nav.instruction.maneuverType = 'turn' - assert not navigation_display(nav, now_ns=NOW, drive_id=DRIVE).arrived, "only the final maneuver means arrival" + turning = navigation_display(nav, now_ns=NOW, drive_id=DRIVE) + assert turning is not None and not turning.arrived, "only the final maneuver means arrival" @pytest.mark.parametrize('meters,metric,expected', [(120, False, '400 ft'), (120, True, '125 m'),