diff --git a/openpilot/starpilot/galaxy/server.py b/openpilot/starpilot/galaxy/server.py index 4f5cc87241..3261123834 100644 --- a/openpilot/starpilot/galaxy/server.py +++ b/openpilot/starpilot/galaxy/server.py @@ -209,7 +209,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe def context_source(params): from openpilot.starpilot.galaxy.settings import LiveContextSource - return LiveContextSource(params, messages=evidence_source, evidence_wait_ms=0) if evidence_source is not None else LiveContextSource(params) + return LiveContextSource(params, messages=evidence_source) if evidence_source is not None else LiveContextSource(params) if parked is None: from openpilot.common.params import Params @@ -1011,15 +1011,19 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe self.json(400, {'error': 'Invalid map tile'}) return try: - query = parse_qs(urlsplit(self.path).query, keep_blank_values=True, max_num_fields=1) - theme = query.get('theme', ['light'])[0] - if set(query) - {'theme'} or theme not in ('light', 'dark'): + query = parse_qs(urlsplit(self.path).query, keep_blank_values=True, max_num_fields=2) + theme = query.get('theme', ['light']) + provider = query.get('provider', ['mapbox']) + if (set(query) - {'theme', 'provider'} or len(theme) != 1 or theme[0] not in ('light', 'dark') or + len(provider) != 1 or provider[0] not in ('mapbox', 'google')): raise ValueError('Invalid map theme') except ValueError: self.json(400, {'error': 'Invalid map theme'}) return try: - tile = navigation_owner().map_tile(*(int(value) for value in match.groups()), theme) + coords = (int(value) for value in match.groups()) + tile = (navigation_owner().map_tile(*coords, theme[0], provider='google') + if provider[0] == 'google' else navigation_owner().map_tile(*coords, theme[0])) except (OSError, ValueError, RuntimeError): self.json(503, {'error': 'Map tiles are unavailable'}) else: @@ -1888,28 +1892,38 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe raise ValidationError('Enter a destination to search') if 'autocomplete' in payload and payload['autocomplete'] is not True: raise ValidationError('Enter a destination to search') - result = {'results': (navigation_owner().search_places(payload['query'], identity, payload['searchId'], payload['clientId'], - autocomplete='autocomplete' in payload) - if 'searchId' in payload else navigation_owner().search(payload['query']))} + results = (navigation_owner().search_places(payload['query'], identity, payload['searchId'], payload['clientId'], + autocomplete='autocomplete' in payload) + if 'searchId' in payload else navigation_owner().search(payload['query'])) + result = {'results': results, 'provider': getattr(results, 'provider', 'mapbox')} else: fields = {'configure': {'patch'}, 'select': {'destination'}, 'selectPlace': {'id', 'searchId'}, 'cancelSearch': {'searchId'}, 'clear': set(), 'favorite': {'destination'}, 'favoritePlace': {'id', 'searchId'}, 'removeFavorite': {'id'}, 'labelFavorite': {'id', 'label'}, - 'removeRecent': {'id'}, 'clearRecents': set(), 'selectRoute': {'index'}} + 'removeRecent': {'id'}, 'clearRecents': set(), 'selectRoute': {'index'}, 'testGoogleKey': set(), + 'resolveShare': {'text'}, 'share': {'text'}} action = payload.get('action') - optional = {'label'} if action in ('favorite', 'favoritePlace') and 'label' in payload else set() + optional = ({'label'} if action in ('favorite', 'favoritePlace') and 'label' in payload else + {'key'} if action == 'testGoogleKey' and 'key' in payload else + {'intentId'} if action == 'share' and 'intentId' in payload else set()) if type(action) is not str or action not in fields or set(payload) != {'action', 'revision'} | fields[action] | optional: raise ValidationError('Invalid navigation action') - needs_park = action == 'configure' and isinstance(payload['patch'], dict) and 'token' in payload['patch'] + needs_park = action == 'configure' and isinstance(payload['patch'], dict) and bool({'token', 'googleKey'} & payload['patch'].keys()) def authorized(): return self.settings_session() == identity and (not needs_park or configuration_allowed()) - with (nullcontext() if action in ('selectPlace', 'favoritePlace') else effect_lock): + with (nullcontext() if action in ('selectPlace', 'favoritePlace', 'testGoogleKey', 'resolveShare', 'share') else effect_lock): if not authorized(): - raise PermissionError('Park your car before changing the Mapbox key' if needs_park else 'Sign in to Galaxy') + raise PermissionError('Park your car before changing a map key' if needs_park else 'Sign in to Galaxy') nav = navigation_owner() keywords = {'expected_revision': payload['revision'], 'authorized': authorized} if action == 'configure': result = nav.configure(payload['patch'], **keywords) + elif action == 'testGoogleKey': + result = dict(nav.snapshot(), googleKeyTest=nav.test_google_key(payload.get('key'))) + elif action == 'resolveShare': + result = dict(nav.snapshot(), sharedText=nav.resolve_share(payload['text'])) + elif action == 'share': + result = nav.share(payload['text'], intent_id=payload.get('intentId'), **keywords) elif action == 'selectPlace': result = nav.select_place(payload['id'], payload['searchId'], identity, **keywords) elif action == 'cancelSearch': @@ -1939,7 +1953,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe except ConflictError as error: self.json(409, {'error': str(error)}) except ValidationError as error: - self.json(400, {'error': str(error)}) + query = getattr(error, 'query', None) + self.json(400, {'error': str(error), **({'query': query} if query else {})}) except PermissionError as error: if self.require_session(): self.json(409, {'error': str(error)}) diff --git a/openpilot/starpilot/galaxy/settings.py b/openpilot/starpilot/galaxy/settings.py index 9c775ec371..0a621f6ef7 100644 --- a/openpilot/starpilot/galaxy/settings.py +++ b/openpilot/starpilot/galaxy/settings.py @@ -247,7 +247,9 @@ class LiveContextSource: timeout = 0 while True: if sm is None: - return False + sm = self._refreshed_snapshot(deadline) + if sm is None: + return False if hasattr(sm, "after_mono_ns"): self.device_after_mono_ns = max(self.device_after_mono_ns, sm.after_mono_ns) self.device_offset_ns = sm.device_offset_ns @@ -282,10 +284,29 @@ class LiveContextSource: remaining_ms = int((deadline - self.wait_clock()) * 1000) if remaining_ms <= 0: return False + if hasattr(sm, "after_mono_ns"): + # A snapshot never advances by itself; one stale or skewed sample must not read as onroad. + sm = self._refreshed_snapshot(deadline) + if sm is None: + return False + continue timeout = min(50, remaining_ms) except (OSError, RuntimeError, AttributeError, TypeError, ValueError, OverflowError): return False + def _refreshed_snapshot(self, deadline): + """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: + return None + self.lock.release() + try: + refreshed = refresh(remaining_ms) is True + finally: + self.lock.acquire() + return self._messages() if refreshed and not self.closed else None + def configuration_allowed(self) -> bool: """Allow configuration in effective offroad mode or a fresh stationary Park.""" if self.offroad(): diff --git a/openpilot/starpilot/galaxy/tests/browser/navigation-compact.cjs b/openpilot/starpilot/galaxy/tests/browser/navigation-compact.cjs index 34d8d28b8e..1575ec88b5 100644 --- a/openpilot/starpilot/galaxy/tests/browser/navigation-compact.cjs +++ b/openpilot/starpilot/galaxy/tests/browser/navigation-compact.cjs @@ -87,14 +87,14 @@ const status = { enabled: true, hasKey: true, isMetric: true, status: 'noDestina await page.screenshot({ path: `/private/tmp/navigation-offline-${width}.png`, fullPage: true }) } await offlineLink.click() - await page.getByText('Map Overlay Roads', { exact: true }).waitFor() + await page.getByText('Offline Map Management', { exact: true }).waitFor() assert.equal(await page.getByRole('button', { name: 'Offline Maps', exact: true }).getAttribute('aria-pressed'), 'true') await page.getByRole('button', { name: 'Destination', exact: true }).click() status.network = 'unknown' await page.evaluate(() => window.navigation.client.load()) assert.equal(await offlineLink.count(), 0, 'unknown device state must not be presented as offline') await page.goto('http://navigation.test/?shell=1#/navigation/maps') - await page.getByText('Map Overlay Roads', { exact: true }).waitFor() + await page.getByText('Offline Map Management', { exact: true }).waitFor() assert.equal(await page.getByRole('button', { name: 'Offline Maps', exact: true }).getAttribute('aria-pressed'), 'true') await page.getByRole('button', { name: 'Destination', exact: true }).click() await page.waitForURL('**#/navigation') diff --git a/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py b/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py index b2da14254c..ea5947294b 100644 --- a/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py +++ b/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py @@ -280,6 +280,37 @@ def test_refresh_updates_cached_onroad_and_reverse_transition(tmp_path): assert not source.thread.is_alive() and messages.socket_closed +def test_stale_sample_waits_for_next_publishers_instead_of_reading_onroad(tmp_path): + messages, source, _ = refresh_readers(tmp_path) + params = NS(get_param_path=lambda key: str(tmp_path / key)) + authority = LiveContextSource(params, source, mono_clock=time.monotonic_ns, + boot_clock=lambda: time.monotonic_ns() + 1_000_000_000, evidence_wait_ms=750) + try: + assert refresh_with_frames(source, messages, {}) + time.sleep(0.4) # Past the Panda TTL: a parked editor's 5 s poll must not flip on one late frame. + timer = threading.Timer(0.1, messages.queue) + timer.start() + assert authority.parked() + timer.join() + time.sleep(0.4) + started = time.monotonic() + assert not authority.parked() # Silent publishers still fail closed once the wait expires. + assert time.monotonic() - started < 1.5 + # Concurrent requests share one authority; their waits overlap instead of queueing on its lock. + results = [] + waiters = [threading.Thread(target=lambda: results.append(authority.parked())) for _ in range(3)] + started = time.monotonic() + for waiter in waiters: + waiter.start() + for waiter in waiters: + waiter.join(timeout=3) + assert results == [False, False, False] + assert time.monotonic() - started < 1.5 + finally: + authority.close() + source.close() + + @pytest.mark.parametrize('frame', [None, {'services': ('deviceState',)}, {'services': ('pandaStates',)}, {'replay': True}]) def test_refresh_requires_both_post_request_publishers(tmp_path, frame): messages, source, authority = refresh_readers(tmp_path) diff --git a/openpilot/starpilot/galaxy/tests/test_navigation.mjs b/openpilot/starpilot/galaxy/tests/test_navigation.mjs index 9e30757c04..b1212027e5 100644 --- a/openpilot/starpilot/galaxy/tests/test_navigation.mjs +++ b/openpilot/starpilot/galaxy/tests/test_navigation.mjs @@ -257,4 +257,49 @@ console.log("Local HTTP search UUID fallback passed") assert.ok(NavigationPage.template.includes(' body.text.includes("!3d") ? response({ ...snapshot("s"), enabled: true, destination: place, shared: place }) : + body.text === "Atlantis" ? response({ error: "No map location found for Atlantis" }, 400) : + response({ error: "Open StarPilot to search for Starbucks", query: "Starbucks" }, 400), + configure: () => { off = false; return response({ ...snapshot("c"), enabled: true }) } } + const client = new NavigationClient({ publish: (state) => states.push(state), later: () => 0, cancelTimer: () => {}, + fetcher: async (url, options) => { + const body = options.body ? JSON.parse(options.body) : null + sent.push({ url, body }) + if (url.includes("/search")) return response({ results: [place], provider: "google" }) + if (body?.action) return answers[body.action](body) + return response({ ...snapshot(), enabled: !off }) + } }) + await client.start() + const page = { client, query: "" } + await NavigationPage.methods.openShared.call(page, "Starbucks") + assert.deepEqual(sent.slice(1).map(({ url, body }) => body?.action || url), ["share", "configure", "./api/navigation/search"]) + assert.equal(page.query, "Starbucks") + assert.equal(sent.at(-1).body.query, "Starbucks") + const shown = states.at(-1) + assert.deepEqual([shown.results, shown.resultsProvider, shown.error, shown.stale, shown.data.enabled], [[place], "google", "", false, true]) + sent.length = 0 + await NavigationPage.methods.openShared.call(page, "https://www.google.com/maps/place/Library/data=!3d41!4d-88") + assert.deepEqual(sent.map(({ body }) => body?.action), ["share"]) + assert.equal(states.at(-1).data.destination.name, "Library") + sent.length = 0 + page.query = "" + await NavigationPage.methods.openShared.call(page, "Atlantis") + assert.deepEqual([sent.length, page.query, states.at(-1).error], [1, "", "No map location found for Atlantis"]) + assert.equal(client.refusal, null) + client.stop() + assert.equal(NavigationPage.computed.googlePlaces.call({ data: { routeProvider: "google", hasGoogleKey: true } }), true) + assert.equal(NavigationPage.computed.googlePlaces.call({ data: { routeProvider: "mapbox", hasGoogleKey: true } }), false) + const tests = NavigationPage.computed.googleTests.call({ googleTest: { ok: true, message: "map", routes: { ok: false, failure: "disabled", message: "off" }, + places: { ok: false, failure: "budget", message: "used up" } } }) + assert.deepEqual(tests.map((row) => [row.name, row.ok, row.missing, row.link?.href]), [["Map Tiles API", true, false, undefined], + ["Routes API", false, true, "https://console.cloud.google.com/apis/library/routes.googleapis.com"], ["Places API (New)", false, false, undefined]]) + assert.equal(NavigationPage.computed.googleWorking.call({ googleTests: tests }), "2 of 3 APIs working") + assert.ok(NavigationPage.template.includes("Google isn't used until the Mapbox key above is added too.")) + console.log("Shared places: comma lookup, 400 query search, navigation turned on, Google source and key test summary passed") +} await import("./test_navigation_map.mjs") diff --git a/openpilot/starpilot/galaxy/tests/test_navigation_http.py b/openpilot/starpilot/galaxy/tests/test_navigation_http.py index a9fd032a82..705491dbf5 100644 --- a/openpilot/starpilot/galaxy/tests/test_navigation_http.py +++ b/openpilot/starpilot/galaxy/tests/test_navigation_http.py @@ -160,6 +160,84 @@ class NavigationHttpTest(unittest.TestCase): self.assertEqual(self.action('configure', patch={'enabled': True})[0], 200) self.assertEqual(self.action('select', destination=PLACE)[0], 200) + def test_google_key_needs_parked_and_test_key_reports_without_leaking(self): + key = 'AIzaSyFixtureKey_0123456789abcdef' + self.parked = False + self.assertEqual(self.action('configure', patch={'googleKey': key})[0], 409) + self.assertFalse(self.navigation.snapshot()['hasGoogleKey']) + self.parked = True + status, body, _ = self.action('configure', patch={'googleKey': key, 'mapProvider': 'google'}) + self.assertEqual((status, body['hasGoogleKey'], body['mapProvider']), (200, True, 'google')) + self.assertNotIn(key, json.dumps(self.request('/api/navigation/status', cookie=self.local_cookie)[1])) + with (patch('openpilot.starpilot.navigation.google_tiles.test_key', return_value={'ok': False, 'message': 'Billing is off'}) as tested, + patch('openpilot.starpilot.navigation.google_routes.test_routes', return_value={'ok': True, 'failure': None, 'message': 'routes'}), + patch('openpilot.starpilot.navigation.google_places.test_places', return_value={'ok': True, 'failure': None, 'message': 'places'})): + self.parked = False + status, body, _ = self.action('testGoogleKey') + self.assertEqual((status, body['googleKeyTest']['message'], body['hasGoogleKey']), (200, 'Billing is off', True)) + self.assertEqual((body['googleKeyTest']['routes']['ok'], body['googleKeyTest']['places']['message']), (True, 'places')) + self.assertEqual(self.action('testGoogleKey', key='AIzaSyOtherKey_0123456789abcdefgh')[0], 200) + self.assertEqual([call.args[0] for call in tested.call_args_list], [key, 'AIzaSyOtherKey_0123456789abcdefgh']) + self.assertEqual(self.action('testGoogleKey', key='bad key')[0], 400) + self.assertEqual(self.action('testGoogleKey', other=True)[0], 400) + + def test_shared_short_link_is_followed_on_the_comma(self): + with patch.object(type(self.navigation), 'resolve_share', return_value='https://www.google.com/maps/place/X/data=!3d36.1!4d-115.1') as resolved: + status, body, _ = self.action('resolveShare', text='Bellagio https://maps.app.goo.gl/abc123') + self.assertEqual((status, body['sharedText']), (200, 'https://www.google.com/maps/place/X/data=!3d36.1!4d-115.1')) + self.assertIn('revision', body) + resolved.assert_called_once_with('Bellagio https://maps.app.goo.gl/abc123') + self.assertEqual(self.action('resolveShare')[0], 400) + + def test_shared_place_turns_navigation_on_and_starts_the_route(self): + self.assertEqual(self.action('share', text='geo:40.5,-89.5')[1], {'error': 'Add your Mapbox access token first'}) + self.navigation.configure({'token': 'pk.test'}, self.navigation.read()['revision'], True) + self.assertFalse(self.navigation.snapshot()['enabled']) + status, body, _ = self.action('share', remote=True, text='https://www.google.com/maps/place/Bellagio/data=!3d36.1126!4d-115.1767') + self.assertEqual(status, 200) + self.assertEqual(body['shared'], {'name': 'Bellagio', 'latitude': 36.1126, 'longitude': -115.1767}) + self.assertTrue(body['enabled'] and body['hasKey']) + self.assertEqual((body['destination']['latitude'], body['revision']), (36.1126, self.navigation.snapshot()['revision'])) + self.assertNotIn('pk.test', json.dumps(body)) + feature = {'features': [{'properties': {'name': '3600 S Las Vegas Blvd', 'full_address': '3600 S Las Vegas Blvd, Las Vegas, NV'}, + 'geometry': {'coordinates': [-115.17, 36.11]}}]} + with patch('openpilot.starpilot.navigation.owner.response_json', return_value=feature) as geocode: + status, body, _ = self.action('share', text='https://www.google.com/maps/place/Bellagio,+3600+S+Las+Vegas+Blvd,+Las+Vegas,+NV/data=!4m2!3m1!1s0x1:0x2') + self.assertEqual((status, body['shared']), (200, {'name': 'Bellagio', 'latitude': 36.11, 'longitude': -115.17})) + self.assertEqual(geocode.call_args.args[2]['q'], '3600 S Las Vegas Blvd, Las Vegas, NV') + with patch('openpilot.starpilot.navigation.owner.response_json', return_value={'features': []}): + self.assertEqual(self.action('share', text='https://maps.google.com/?q=Nowhere,+Atlantis')[1], + {'error': 'No map location found for Nowhere', 'query': 'Nowhere, Atlantis'}) + self.assertEqual(self.action('share', text='Starbucks')[:2], (400, {'error': 'Open StarPilot to search for Starbucks', 'query': 'Starbucks'})) + revision = self.navigation.read()['revision'] + stale = {'action': 'share', 'revision': '0', 'text': 'geo:40.5,-89.5'} + self.assertEqual(self.request('/api/navigation/action', payload=stale, cookie=self.local_cookie)[0], 409) + self.assertEqual(self.navigation.read()['revision'], revision) + self.assertEqual(self.action('share')[0], 400) + self.assertNotIn('query', self.action('share', text='x' * 8193)[1]) + + def test_shared_intent_retry_after_cancel_does_not_restart_navigation(self): + self.navigation.configure({'token': 'pk.test'}, self.navigation.read()['revision'], True) + request = {'action': 'share', 'revision': self.navigation.read()['revision'], + 'text': 'geo:40.5,-89.5', 'intentId': 'durable-phone-share'} + first = self.request('/api/navigation/action', payload=request, remote=True, cookie=self.remote_cookie) + self.assertEqual(first[0], 200) + self.assertIsNotNone(first[1]['destination']) + cancelled = self.action('clear', remote=True) + replay = self.request('/api/navigation/action', payload=request, remote=True, cookie=self.remote_cookie) + self.assertEqual(replay[0], 200) + self.assertIsNone(replay[1]['destination']) + self.assertEqual(replay[1]['revision'], cancelled[1]['revision']) + 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() @@ -207,6 +285,27 @@ class NavigationHttpTest(unittest.TestCase): self.assertEqual(self.action('clearRecents')[1]['recents'],[]) self.assertEqual(self.action('removeFavorite',id=place)[1]['favorites'],[]) + def test_search_names_the_provider_that_found_the_places(self): + self.action('configure', patch={'token':'pk.synthetic','enabled':True}) + def search(): + return {'query':'bellagio', 'searchId':str(uuid.uuid4()), 'clientId':str(uuid.uuid4())} + suggestion = {'suggestions':[{'mapbox_id':'poi/id','name':'Coffee Shop','feature_type':'poi'}]} + with patch('openpilot.starpilot.navigation.owner.response_json', return_value=suggestion): + self.assertEqual(self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)[1]['provider'], 'mapbox') + key = 'AIzaSyFixtureKey_0123456789abcdef' + self.action('configure', patch={'googleKey':key, 'routeProvider':'google'}) + found = [{'name':'Bellagio','address':'3600 S Las Vegas Blvd','latitude':36.1126,'longitude':-115.1767}] + with patch('openpilot.starpilot.navigation.google_places.text_search', return_value=found) as google: + status, result, _ = self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie) + self.assertEqual((status, result['provider'], result['results'][0]['name']), (200, 'google', 'Bellagio')) + self.assertNotIn('searchId', result['results'][0]) + self.assertEqual(google.call_args.args[1], key) + self.assertNotIn(key, json.dumps(result)) + from openpilot.starpilot.navigation.google_places import GooglePlacesFailed + with (patch('openpilot.starpilot.navigation.google_places.text_search', side_effect=GooglePlacesFailed('budget')), + patch('openpilot.starpilot.navigation.owner.response_json', return_value=suggestion)): + self.assertEqual(self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)[1]['provider'], 'mapbox') + def test_temporary_search_result_cannot_be_saved(self): self.action('configure', patch={'token':'pk.synthetic','enabled':True}) search = {'query':'coffee', 'searchId':str(uuid.uuid4()), 'clientId':str(uuid.uuid4())} diff --git a/openpilot/starpilot/galaxy/tests/test_navigation_map.mjs b/openpilot/starpilot/galaxy/tests/test_navigation_map.mjs index a09c0fdc0b..24f16633ef 100644 --- a/openpilot/starpilot/galaxy/tests/test_navigation_map.mjs +++ b/openpilot/starpilot/galaxy/tests/test_navigation_map.mjs @@ -186,3 +186,33 @@ console.log('Follow, pinch and double-tap zoom passed') globalThis.requestAnimationFrame = originalRaf; globalThis.cancelAnimationFrame = originalCancelRaf } console.log('Live map theme changes: correct requests, cache disposal, late-response isolation, camera preservation and observer cleanup passed') + +{ + // Switching mapProvider between Mapbox and Google clears cached tiles, appends provider=google, and crops 256px parent tiles. + const savedFetch = globalThis.fetch, savedBitmap = globalThis.createImageBitmap + globalThis.requestAnimationFrame = fn => { frames.set(++frameId, fn); return frameId } + globalThis.cancelAnimationFrame = id => frames.delete(id) + const urls = [] + let closed = 0 + globalThis.fetch = async url => { urls.push(url); return { ok: true, blob: async () => ({}) } } + globalThis.createImageBitmap = async () => ({ width: 256, close() { closed++ } }) + const switched = new RasterMap(canvas) + switched.draw = () => {} + switched.update({ mapProvider: 'mapbox', hasGoogleKey: true }, false) + await switched.load('1/0/0') + assert.ok(urls.at(-1).endsWith('1/0/0.png?theme=dark')) + assert.equal(switched.tiles.size, 1) + const crop = switched.placeholder(2, 1, 1) + assert.deepEqual(crop.slice(1), [128, 128, 128], '256px Google/custom tiles crop using their actual bitmap width') + switched.update({ mapProvider: 'google', hasGoogleKey: true }, false) + assert.equal(switched.tiles.size, 0, 'switching map provider clears cached tiles from the previous provider') + assert.equal(closed, 1) + await switched.load('1/0/0') + assert.ok(urls.at(-1).endsWith('1/0/0.png?theme=dark&provider=google')) + switched.update({ mapProvider: 'google', hasGoogleKey: true, googleMap: { failure: 'Quota reached' } }, false) + assert.equal(switched.provider, 'mapbox', 'a Google map failure falls back to Mapbox tiles') + switched.close() + globalThis.fetch = savedFetch; globalThis.createImageBitmap = savedBitmap + globalThis.requestAnimationFrame = originalRaf; globalThis.cancelAnimationFrame = originalCancelRaf +} +console.log('Map provider switching: Google tile URL, cache invalidation, fallback, and 256px placeholder cropping passed') diff --git a/openpilot/starpilot/galaxy/tests/test_share_destination.mjs b/openpilot/starpilot/galaxy/tests/test_share_destination.mjs index 608203ad6c..7095136e38 100644 --- a/openpilot/starpilot/galaxy/tests/test_share_destination.mjs +++ b/openpilot/starpilot/galaxy/tests/test_share_destination.mjs @@ -1,6 +1,6 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { parseSharedDestination as parse } from '../web/js/share-destination.js' +import { isMapLink, parseSharedDestination as parse } from '../web/js/share-destination.js' for (const text of ['https://maps.google.com/@12.3,-45.6,15z', 'https://maps.google.com/?q=12.3,-45.6', 'geo:12.3,-45.6(Home)', 'google.navigation:q=12.3,-45.6', 'https://maps.google.com/?daddr=12.3,-45.6', 'https://maps.google.com/@1,2,15z/data=!3d12.3!4d-45.6']) { @@ -9,3 +9,17 @@ for (const text of ['https://maps.google.com/@12.3,-45.6,15z', 'https://maps.goo test('address search', () => assert.equal(parse('geo:0,0?q=10+Main+Street').query, '10 Main Street')) test('invalid coordinate does not route', () => assert.equal(parse('geo:123,456').destination, undefined)) test('encoded coordinates', () => assert.equal(parse('https://maps.google.com/?q=12.3%2C-45.6').destination.longitude, -45.6)) +test('waze links', () => { + assert.deepEqual(parse('https://waze.com/ul/h9q8yy4').destination, { name: 'Shared destination', latitude: 37.762756, longitude: -122.426147 }) + assert.equal(parse('https://waze.com/live-map/directions?to=ll.37.77%2C-122.41').destination.longitude, -122.41) + assert.equal(parse('https://waze.com/ul?q=Starbucks%20Main%20St&navigate=yes').query, 'Starbucks Main St') + assert.ok(isMapLink('https://waze.com/ul?q=Starbucks&navigate=yes')) +}) +test('pasted map links open their place; words search', () => { + assert.ok(isMapLink('Bellagio Hotel https://maps.app.goo.gl/AbC123')) + assert.ok(isMapLink('https://goo.gl/maps/xyz')) + assert.ok(isMapLink('https://www.google.com/maps/place/X/data=!3d36.1!4d-115.1')) + assert.ok(!isMapLink('Starbucks')) + assert.ok(!isMapLink('10 Main Street')) + assert.ok(!isMapLink('http://maps.app.goo.gl/AbC123')) +}) diff --git a/openpilot/starpilot/galaxy/web/css/galaxy.css b/openpilot/starpilot/galaxy/web/css/galaxy.css index 9436e615d9..d66862475a 100644 --- a/openpilot/starpilot/galaxy/web/css/galaxy.css +++ b/openpilot/starpilot/galaxy/web/css/galaxy.css @@ -1390,7 +1390,7 @@ background: var(--surface-container-high); color: var(--on-surface-variant); bor .gx-starport-pill:has(> i)::before { display: none; } .gx-starport-pill--ready { color: var(--success); border-color: color-mix(in srgb, var(--success) 40%, transparent); background: color-mix(in srgb, var(--success) 12%, transparent); } .gx-starport-pill--soon { color: var(--warning); border-color: color-mix(in srgb, var(--warning) 40%, transparent); background: color-mix(in srgb, var(--warning) 12%, transparent); } -.gx-starport-pill--expired, .gx-starport-pill--broken { color: var(--error); border-color: color-mix(in srgb, var(--error) 40%, transparent); background: color-mix(in srgb, var(--error) 12%, transparent); } +.gx-starport-pill--expired, .gx-starport-pill--broken, .gx-starport-pill--danger, .gx-starport-pill--error { color: var(--error); border-color: color-mix(in srgb, var(--error) 40%, transparent); background: color-mix(in srgb, var(--error) 12%, transparent); } .gx-starport-list { list-style: none; margin: 0; padding: 0; display: grid; border: 1px solid var(--outline); border-radius: var(--radius-md); overflow: hidden; } .gx-starport-list > .gx-starport-row + .gx-starport-row { border-top: 1px solid var(--outline); } .gx-starport-row { display: flex; align-items: center; gap: var(--sp-3); min-width: 0; margin: 0; padding: var(--sp-3) var(--sp-4); } diff --git a/openpilot/starpilot/galaxy/web/css/navigation.css b/openpilot/starpilot/galaxy/web/css/navigation.css index 53609a8b63..9e50eb8fb8 100644 --- a/openpilot/starpilot/galaxy/web/css/navigation.css +++ b/openpilot/starpilot/galaxy/web/css/navigation.css @@ -122,6 +122,72 @@ .gx-navigation__token-link { margin-bottom: var(--sp-4); } -.gx-navigation__gps { scroll-margin-top: 100px; } -.gx-navigation__gps li { margin-block: var(--sp-2); line-height: 1.5; } -.gx-navigation__gps summary { cursor: pointer; min-height: 44px; display: list-item; align-content: center; } +.gx-navigation__gps { scroll-margin-top: 100px; display: grid; gap: var(--sp-3); } +.gx-navigation__gps li { margin-block: var(--sp-1); line-height: 1.45; } +.gx-navigation__gps summary { cursor: pointer; min-height: 44px; display: flex; align-items: center; } +.gx-navigation__gps-status { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); margin: 0; } +.gx-navigation__gps-guides { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: var(--sp-3); margin-top: var(--sp-3); } +.gx-navigation__gps-card { display: grid; gap: var(--sp-2); align-content: start; padding: var(--sp-3) var(--sp-4); border: 1px solid var(--outline); border-radius: var(--radius-md); background: var(--surface-container); } +.gx-navigation__gps-card > strong { display: inline-flex; align-items: center; gap: var(--sp-2); color: var(--on-surface); } +.gx-navigation__gps-card > strong .bi { color: var(--primary); } + +.gx-navigation__prefs { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--sp-3); padding-top: var(--sp-3); margin-top: var(--sp-2); border-top: 1px solid var(--outline); } +.gx-navigation__prefs-head { display: grid; gap: 2px; min-width: 200px; flex: 1 1 220px; } +.gx-navigation__pref-chips { display: flex; flex-wrap: wrap; gap: var(--sp-2); } +.gx-navigation__pref { display: inline-flex; align-items: center; gap: var(--sp-2); min-height: 40px; padding: 0 14px; border-radius: var(--radius-full); border: 1px solid var(--outline); background: var(--surface-container); color: var(--on-surface); font-size: .88rem; font-weight: var(--fw-medium); cursor: pointer; user-select: none; transition: background var(--motion-fast), border-color var(--motion-fast), color var(--motion-fast); } +.gx-navigation__pref > i { font-size: .95rem; color: var(--text-muted); } +.gx-navigation__pref--on { background: color-mix(in srgb, var(--primary) 16%, var(--surface-container)); border-color: var(--primary); color: var(--primary); } +.gx-navigation__pref--on > i { color: var(--primary); } +.gx-navigation__pref:has(input:focus-visible) { outline: 2px solid var(--primary); outline-offset: 3px; } +.gx-navigation__pref--disabled { opacity: .55; cursor: default; } + +.gx-navigation__step-title { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); margin-bottom: var(--sp-1); } +.gx-navigation__step-title h3 { margin: 0; } +.gx-navigation__step-title .gx-starport-pill { padding: 2px 10px; font-size: .75rem; } + +/* Setup choices: compact M3 choice buttons with an expandable info popover. */ +.gx-choice { border: 0; margin: 0; padding: 0; min-width: 0; display: grid; gap: var(--sp-2); } +.gx-choice__head { display: flex; align-items: center; gap: var(--sp-2); } +.gx-choice__legend { font-weight: var(--fw-medium); } +.gx-choice__info-btn { color: var(--text-muted); font-size: .95rem; } +.gx-choice__info-btn:hover, .gx-choice__info-btn[aria-expanded="true"] { background: var(--surface-container-high); color: var(--primary); } +.gx-choice__hint { margin: 0; color: var(--text-muted); font-size: .85rem; } +.gx-choice__grid { display: flex; flex-wrap: wrap; gap: var(--sp-2); } +.gx-choice__card { flex: 1 1 160px; display: flex; align-items: center; min-height: 44px; padding: 8px 14px; border: 1px solid var(--outline); + border-radius: var(--radius-md); background: var(--surface-container); cursor: pointer; min-width: 0; transition: background var(--motion-fast), border-color var(--motion-fast); } +.gx-choice__card--on { border-color: var(--primary); background: color-mix(in srgb, var(--primary) 14%, var(--surface-container)); box-shadow: 0 0 0 1px var(--primary); } +.gx-choice__card--off { opacity: .6; cursor: default; } +.gx-choice__card:has(input:focus-visible) { outline: 2px solid var(--primary); outline-offset: 3px; } +.gx-choice__title { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); width: 100%; min-width: 0; line-height: 1.3; } +.gx-choice__title strong { flex: 1 1 auto; min-width: 0; font-size: .9rem; } +.gx-choice__title .bi { flex: 0 0 auto; color: var(--text-muted); font-size: 1rem; } +.gx-choice__card--on .gx-choice__title .bi { color: var(--primary); } +.gx-choice__title .gx-starport-pill { padding: 2px 8px; font-size: .72rem; margin-left: auto; } +.gx-choice__active-summary { margin: 0; color: var(--text-muted); font-size: .83rem; line-height: 1.4; } +.gx-choice__popover { display: grid; gap: var(--sp-2); padding: var(--sp-3) var(--sp-4); border: 1px solid var(--outline); border-radius: var(--radius-md); background: var(--surface-container-high, var(--surface-container)); font-size: .85rem; } +.gx-choice__popover-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); } +.gx-choice__popover-close { color: var(--text-muted); } +.gx-choice__popover-close:hover { background: var(--glass-active-bg); color: var(--on-surface); } +.gx-choice__popover-list { margin: 0; display: grid; gap: var(--sp-2); } +.gx-choice__popover-item { display: grid; gap: 2px; padding-top: var(--sp-2); border-top: 1px solid var(--outline); } +.gx-choice__popover-item dt { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); } +.gx-choice__popover-item dt .gx-starport-pill { padding: 1px 8px; font-size: .7rem; } +.gx-choice__popover-item dd { margin: 0; color: var(--on-surface-variant, var(--text-muted)); line-height: 1.45; } +.gx-choice__limit { color: var(--text-muted); font-size: .82rem; line-height: 1.4; } +.gx-compare { display: grid; margin-top: var(--sp-3); border: 1px solid var(--outline); border-radius: var(--radius-md); overflow: hidden; } +.gx-compare__row { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) minmax(0, 1fr); gap: var(--sp-3); padding: var(--sp-2) var(--sp-3); font-size: .85rem; } +.gx-compare__row + .gx-compare__row { border-top: 1px solid var(--outline); } +.gx-compare__row--head { font-weight: var(--fw-medium); background: var(--surface-container); } +.gx-compare__row > :first-child { color: var(--text-muted); } +.gx-compare__row--head > :first-child { color: inherit; } +.gx-navigation__sources { display: flex; flex-wrap: wrap; gap: var(--sp-2); list-style: none; margin: 0; padding: 0; } +.gx-navigation__sources .gx-navigation__chip { text-decoration: none; border: 1px solid var(--outline); } +.gx-navigation__power .gx-row__info { display: grid; gap: 2px; } +.gx-navigation .gx-starport-step__body { padding-left: 0; } +@media (min-width: 640px) { .gx-navigation .gx-starport-step__body { padding-left: calc(36px + var(--sp-4)); } } +@media (max-width: 540px) { .gx-compare__row { grid-template-columns: 1fr; gap: 2px; } .gx-compare__row--head { display: none; } .gx-compare__row > :nth-child(2)::before { content: "Mapbox: "; } .gx-compare__row > :nth-child(3)::before { content: "Google: "; } } + +.gx-navigation__guide { border: 1px solid var(--outline); border-radius: var(--radius-sm); padding: var(--sp-3); } +.gx-navigation__guide > summary { font-weight: var(--fw-bold, 700); } +.gx-navigation__guide a { color: var(--primary); font-weight: var(--fw-bold, 700); text-decoration: underline; text-underline-offset: 3px; } +.gx-navigation__guide li strong { color: var(--on-surface); } diff --git a/openpilot/starpilot/galaxy/web/css/offline-road-maps.css b/openpilot/starpilot/galaxy/web/css/offline-road-maps.css index 2c8a748296..2995b39b14 100644 --- a/openpilot/starpilot/galaxy/web/css/offline-road-maps.css +++ b/openpilot/starpilot/galaxy/web/css/offline-road-maps.css @@ -1,26 +1,28 @@ /* Offline road maps for the Android Auto overlay (#/navigation, Offline Maps tab). */ -.gx-navigation__offline { display: grid; gap: 16px; padding: 0 0 96px; } -.gx-offline-roads { padding: 24px; display: grid; gap: 14px; } -/* Keep the section header flush with the card's rounded top like every other Galaxy card. */ -.gx-offline-roads > .gx-section__header { margin: -24px -24px 0; } -.gx-offline-roads__stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; } -.gx-offline-roads__stat { display: grid; gap: 2px; padding: 12px 14px; border-radius: 14px; background: color-mix(in srgb, currentColor 6%, transparent); } -.gx-offline-roads__stat span { font-size: .78rem; opacity: .7; } +.gx-navigation__offline { display: grid; gap: var(--sp-4, 16px); padding: 0 0 96px; } +.gx-offline-roads { padding: var(--panel-padding, 20px); display: grid; gap: var(--sp-4, 16px); min-width: 0; } +.gx-offline-roads__head { display: flex; align-items: flex-start; gap: var(--sp-4, 16px); min-width: 0; } +.gx-offline-roads__head > div { flex: 1; min-width: 0; } +.gx-offline-roads__head .gx-note { margin: 0; line-height: 1.45; } +.gx-offline-roads__stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: var(--sp-3, 12px); } +.gx-offline-roads__stat { display: grid; gap: 2px; padding: var(--sp-3, 12px) var(--sp-4, 16px); border-radius: var(--radius-md, 14px); border: 1px solid var(--outline); background: var(--surface-container); } +.gx-offline-roads__stat span { font-size: .78rem; color: var(--text-muted); } .gx-offline-roads__stat strong { font-size: 1.05rem; } -.gx-offline-roads__stat small { opacity: .7; font-size: .76rem; display: flex; flex-wrap: wrap; gap: 4px 12px; } +.gx-offline-roads__stat small { color: var(--text-muted); font-size: .76rem; display: flex; flex-wrap: wrap; gap: 4px 12px; } .gx-offline-roads__stat--wide { grid-column: 1 / -1; } .gx-offline-roads__bar { display: flex; height: 8px; border-radius: 6px; overflow: hidden; background: color-mix(in srgb, currentColor 12%, transparent); margin: 6px 0 2px; } .gx-offline-roads__bar i { display: block; height: 100%; transition: width .4s ease; } .gx-offline-roads__legend { display: inline-flex; align-items: center; gap: 6px; } .gx-offline-roads__legend b { width: 8px; height: 8px; border-radius: 50%; display: inline-block; } -.gx-offline-roads__picker { display: grid; grid-template-columns: minmax(0, 2fr) minmax(240px, 1fr); gap: 14px; align-items: start; } +.gx-offline-roads__picker { display: grid; grid-template-columns: minmax(0, 1.8fr) minmax(240px, 1fr); gap: var(--sp-3, 12px); align-items: start; } @media (max-width: 760px) { .gx-offline-roads__picker { grid-template-columns: 1fr; } } -.gx-offline-roads__map { position: relative; border-radius: 16px; overflow: hidden; background: #0e0e1a; height: 340px; } +.gx-offline-roads__map { position: relative; border-radius: var(--radius-md, 16px); border: 1px solid var(--outline); overflow: hidden; background: var(--navigation-land, #191a1a); height: clamp(260px, 42svh, 360px); } .gx-offline-roads__map canvas { width: 100%; height: 100%; display: block; cursor: crosshair; touch-action: none; } +.gx-offline-roads__provider { position: absolute; left: 10px; top: 10px; padding: 4px 10px; border-radius: var(--radius-full, 20px); border: 1px solid var(--glass-border); background: var(--glass-bg); color: var(--glass-text); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); font-size: .75rem; font-weight: var(--fw-medium, 500); pointer-events: none; } .gx-offline-roads__map .gx-navigation-map__controls { position: absolute; right: 10px; top: 10px; display: grid; gap: 6px; } -.gx-offline-roads__hint { position: absolute; left: 12px; bottom: 10px; padding: 6px 10px; border-radius: 10px; background: #0e0e1acc; color: #e8e6f5; font-size: .8rem; pointer-events: none; } -.gx-offline-roads__form { display: grid; gap: 8px; } +.gx-offline-roads__hint { position: absolute; left: 10px; right: 10px; bottom: 10px; width: fit-content; max-width: calc(100% - 20px); padding: 6px 12px; border-radius: 10px; border: 1px solid var(--glass-border); background: var(--glass-bg); color: var(--glass-text); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); font-size: .8rem; pointer-events: none; } +.gx-offline-roads__form { display: grid; gap: 8px; padding: var(--sp-3, 12px); border: 1px solid var(--outline); border-radius: var(--radius-md, 14px); background: var(--surface-container); } .gx-offline-roads__areas { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; } -.gx-offline-roads__areas li { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 12px 14px; border-radius: 14px; background: color-mix(in srgb, currentColor 5%, transparent); } -.gx-offline-roads__area { display: grid; gap: 2px; min-width: 0; flex: 1; } -.gx-offline-roads__area small { opacity: .72; } +.gx-offline-roads__areas li { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 12px; padding: 12px 14px; border-radius: var(--radius-md, 14px); border: 1px solid var(--outline); background: var(--surface-container); } +.gx-offline-roads__area { display: grid; gap: 2px; min-width: 160px; flex: 1; } +.gx-offline-roads__area small { color: var(--text-muted); } diff --git a/openpilot/starpilot/galaxy/web/data/catalog.json b/openpilot/starpilot/galaxy/web/data/catalog.json index 7fe322c987..fe3ab8566e 100644 --- a/openpilot/starpilot/galaxy/web/data/catalog.json +++ b/openpilot/starpilot/galaxy/web/data/catalog.json @@ -143,7 +143,7 @@ "name": "Setup", "path": "/navigation/setup", "tab": "setup", - "description": "Configure navigation and Mapbox", + "description": "Keys, map and route sources, and GPS", "icon": "bi-gear" } ] diff --git a/openpilot/starpilot/galaxy/web/js/app.js b/openpilot/starpilot/galaxy/web/js/app.js index fb4c579757..837f47d164 100644 --- a/openpilot/starpilot/galaxy/web/js/app.js +++ b/openpilot/starpilot/galaxy/web/js/app.js @@ -218,7 +218,7 @@ createApp({
-
+
{{ state.error }}
diff --git a/openpilot/starpilot/galaxy/web/js/navigation-map.js b/openpilot/starpilot/galaxy/web/js/navigation-map.js index 52153e2553..713d851be5 100644 --- a/openpilot/starpilot/galaxy/web/js/navigation-map.js +++ b/openpilot/starpilot/galaxy/web/js/navigation-map.js @@ -139,6 +139,11 @@ export class RasterMap { const theme = value === 'light' ? 'light' : 'dark' if (this.closed || this.theme === theme) return this.theme = theme + this.clearTiles() + this.changed('') + this.draw() + } + clearTiles() { for (const controller of this.pending.values()) controller.abort() this.pending.clear() for (const image of this.tiles.values()) image.close() @@ -147,8 +152,6 @@ export class RasterMap { this.failures = 0 clearTimeout(this.retryTimer) this.retryTimer = null - this.changed('') - this.draw() } pause() { if (this.follow) { this.follow = false; this.changed() } @@ -206,6 +209,9 @@ export class RasterMap { if (data?.location && (this.locationFresh || data.location.lastKnown === true && !this.lastLocation)) { this.lastLocation = { ...data.location, bearing: Number.isFinite(data.location.bearing) ? data.location.bearing : this.lastLocation?.bearing } } + const provider = data?.mapProvider === 'google' && data?.hasGoogleKey && !data?.googleMap?.failure ? 'google' : 'mapbox' + if (this.provider && this.provider !== provider) this.clearTiles() + this.provider = provider this.data = data || {} this.stale = stale // A newly chosen route is shown whole once; Recenter returns to following the car. @@ -253,7 +259,7 @@ export class RasterMap { for (let up = 1; up <= 5 && zoom - up >= 0; up++) { const image = this.tiles.get(`${zoom - up}/${x >> up}/${y >> up}`) if (image) { - const span = SIZE / 2 ** up + const span = (image.width || SIZE) / 2 ** up return [image, (x - ((x >> up) << up)) * span, (y - ((y >> up) << up)) * span, span] } } @@ -348,8 +354,9 @@ export class RasterMap { timedOut = true; controller.abort() }, 8000) + const providerQuery = this.provider === 'google' ? '&provider=google' : '' try { - const response = await fetch(`./api/navigation/map/tiles/${key}.png?theme=${this.theme}`, { + const response = await fetch(`./api/navigation/map/tiles/${key}.png?theme=${this.theme}${providerQuery}`, { credentials: 'same-origin', signal: controller.signal }); if (!response.ok) throw new Error('Map tiles unavailable') @@ -359,22 +366,26 @@ export class RasterMap { return } this.tiles.set(key, image); + this.failed.delete(key); this.failures = 0 while (this.tiles.size > TILE_BITMAPS) { const oldest = this.tiles.keys().next().value; this.tiles.get(oldest).close(); this.tiles.delete(oldest) } - if (!this.failed.size) this.changed('') + this.changed('') + if (this.failed.size && !this.retryTimer) { + this.retryTimer = setTimeout(() => { this.retryTimer = null; this.retry() }, 400) + } } catch (error) { if (this.pending.get(key) === controller && (timedOut || !controller.signal.aborted)) { this.failed.add(key); if (this.failed.size > 64) this.failed.delete(this.failed.values().next().value); // A quick refusal (a busy moment) is retried quickly and silently; a hung request or a run of failures is reported. this.failures = (this.failures || 0) + 1 - const persistent = timedOut || this.failures >= 6 + const persistent = timedOut || this.failures >= 8 if (persistent) this.changed('Map tiles unavailable. Check the saved key and connection. Reconnecting automatically…') - this.retryTimer ??= setTimeout(() => { this.retryTimer = null; this.retry() }, persistent ? 5000 : 800) + this.retryTimer ??= setTimeout(() => { this.retryTimer = null; this.retry() }, persistent ? 3000 : 600) } } finally { clearTimeout(timer); @@ -410,6 +421,9 @@ export const NavigationMap = { props: ['data', 'stale'], data: () => ({ error: '', map: null, locationFresh: false, lastLocation: null, following: true }), + computed: { + googleMap() { return this.data?.mapProvider === 'google' && !!this.data?.hasGoogleKey && !this.data?.googleMap?.failure }, + }, mounted() { this.map = markRaw(new RasterMap(this.$refs.canvas, (error) => { if (error !== undefined) this.error = error @@ -447,9 +461,12 @@ export const NavigationMap = {
{{error}} - -
+
+ Google Maps · {{ data?.googleMap?.copyright || 'Map data © Google' }} · Terms +
+ ` diff --git a/openpilot/starpilot/galaxy/web/js/navigation-setup.js b/openpilot/starpilot/galaxy/web/js/navigation-setup.js new file mode 100644 index 0000000000..a59d7491f8 --- /dev/null +++ b/openpilot/starpilot/galaxy/web/js/navigation-setup.js @@ -0,0 +1,81 @@ +// Pieces of the navigation setup page: a compact M3 choice group with an info popover and the Mapbox/Google comparison. +export const ChoiceGroup = { + name: "ChoiceGroup", + props: { label: { type: String, required: true }, hint: { type: String, default: "" }, modelValue: { type: String, default: "" }, + options: { type: Array, required: true }, disabled: { type: Boolean, default: false } }, + emits: ["update:modelValue"], + data() { return { infoOpen: false } }, + computed: { + selectedOption() { return this.options.find((option) => option.value === this.modelValue) || this.options[0] || null }, + }, + methods: { + pick(event, option) { + event.target.checked = this.modelValue === option.value + if (!option.disabled && !this.disabled) this.$emit("update:modelValue", option.value) + }, + }, + template: ` +
+
+ {{ label }} + +
+

{{ hint }}

+
+ +
+

{{ selectedOption.detail }}

+
+
+ {{ label }} options + +
+
+
+
{{ option.label }} {{ option.badge }}
+
{{ option.detail }} {{ option.limit }}
+
+
+
+
`, +} + +// Provider capabilities and limits. +export const COMPARE_ROWS = [ + ["Place search and addresses", "Yes", "Yes, when Google gives directions; Mapbox is the fallback"], + ["Offline road maps", "Yes", "No, Google tiles can't be saved"], + ["Lane arrows on the turn card", "Yes", "No"], + ["Traffic in route times", "Yes", "Yes, with a correction every 7½ minutes"], + ["Map picture", "Road lines", "Street map with traffic colors"], + ["Needs", "Mapbox token", "Google key with billing on"], + ["Free monthly allowance", "Set by Mapbox; counted for this comma", "100,000 map tiles, 10,000 routes, 5,000 traffic routes"], + ["When the allowance runs out", "Typing suggestions, address lookups and offline downloads pause until the 1st", "The comma stops at 99% and uses Mapbox until it resets"], +] + +export const SourceCompare = { + name: "SourceCompare", + data() { return { rows: COMPARE_ROWS } }, + template: ` +
Compare Mapbox and Google +
+
What you getMapboxGoogle
+
+ {{ row[0] }}{{ row[1] }}{{ row[2] }}
+
+

Counts cover this comma only. Mapbox and Google bill everything that uses your key, including other apps.

+
`, +} diff --git a/openpilot/starpilot/galaxy/web/js/navigation.js b/openpilot/starpilot/galaxy/web/js/navigation.js index f70649078a..c129cb986f 100644 --- a/openpilot/starpilot/galaxy/web/js/navigation.js +++ b/openpilot/starpilot/galaxy/web/js/navigation.js @@ -1,4 +1,4 @@ -import { parseSharedDestination } from "./share-destination.js" +import { isMapLink } from "./share-destination.js" import { GxNotice } from "./notice.js" import { BluetoothNotice, bluetoothConnection } from "./bluetooth-notice.js" import { connectionError } from "./polling.js" @@ -7,6 +7,7 @@ import { MapOperationsPanel } from "./map-operations.js" import { OfflineRoadMapsPanel } from "./offline-road-maps.js" import { GalaxySelect } from "./galaxy-select.js" import { reportSave } from "./save-feedback.js" +import { ChoiceGroup, SourceCompare } from "./navigation-setup.js" export function searchUuid() { if (typeof crypto.randomUUID === "function") return crypto.randomUUID() @@ -24,8 +25,10 @@ export function remainingLocationLease(lease, requestStarted, now = performance. const STATUS = new Set(["disabled", "needsKey", "noDestination", "waitingForLocation", "routing", "guiding", "arrived", "routeUnavailable", "stale"]) const ROUTE_AVOIDANCES = [{ key: "avoidTolls", label: "Avoid tolls" }, { key: "avoidHighways", label: "Avoid highways" }, { key: "avoidFerries", label: "Avoid ferries" }] -const GPS_MODES = [{ value: "backup", label: "Phone GPS as backup" }, { value: "comma", label: "Comma and car GPS only" }, - { value: "phone", label: "Prefer phone GPS" }] +const GPS_MODES = [ + { value: "backup", label: "Comma and car, phone as backup", hint: "Uses the comma's or car's GPS. The phone fills in only when neither has a fix." }, + { value: "comma", label: "Comma and car only", hint: "Never uses the phone. Choose this if you don't share phone GPS." }, + { value: "phone", label: "Phone first", hint: "Uses the phone whenever it has a recent fix, otherwise the comma or car." }] const GPS_NAMES = { comma: "Comma", car: "Car", phone: "Phone" } const coordinate = (value) => !!value && Number.isFinite(value.latitude) && Math.abs(value.latitude) <= 90 && Number.isFinite(value.longitude) && Math.abs(value.longitude) <= 180 @@ -94,12 +97,13 @@ export class NavigationClient { this.busy = false this.error = "" this.stale = false + this.refusal = null } emit() { this.publish({ data: this.data, results: this.results, searched: this.searched, busy: this.busy, error: this.error, stale: this.stale, - suggestions: this.suggestions }) } - stop() { - if (this.searchId && this.data) { + suggestions: this.suggestions, resultsProvider: this.resultsProvider, suggestionsProvider: this.suggestionsProvider }) } + stop(keep = false) { + if (!keep && this.searchId && this.data) { this.fetcher("./api/navigation/action", { method: "POST", credentials: "same-origin", cache: "no-store", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "cancelSearch", revision: this.data.revision, searchId: this.searchId }) }).catch(() => {}) @@ -110,15 +114,17 @@ export class NavigationClient { this.controller?.abort() if (this.timer !== null) this.cancelTimer(this.timer) this.controller = this.timer = null - this.data = null - this.results = [] - this.searched = false + if (!keep) { + this.data = null + this.results = [] + this.searched = false + } this.error = "" this.busy = this.stale = false this.endSuggestions(false) this.emit() } - start() { this.stop(); this.active = true; return this.load() } + start(keep = false) { this.stop(keep); this.active = true; return this.load() } load() { return this.run("status") } async search(query) { const text = query.trim() @@ -179,6 +185,7 @@ export class NavigationClient { this.suggestions = [] } else { this.suggestions = payload.results + this.suggestionsProvider = payload.provider this.suggestionResultsQuery = text } this.emit() @@ -205,6 +212,7 @@ export class NavigationClient { } async run(operation, body = null) { + this.refusal = null if (!this.active || this.busy) return null this.controller?.abort() if (this.timer !== null) this.cancelTimer(this.timer) @@ -216,7 +224,8 @@ export class NavigationClient { this.busy = operation !== "status" if (operation !== "status") this.error = "" this.emit() - const deadline = this.later(() => controller.abort(), operation === "search" ? 24000 : operation === "action" && body?.action === "selectPlace" ? 12000 : 4000) + const deadline = this.later(() => controller.abort(), operation === "search" ? 24000 : operation === "action" && body?.action === "selectPlace" ? 12000 : + operation === "action" && body?.action === "testGoogleKey" ? 45000 : operation === "action" && body?.action === "resolveShare" ? 20000 : operation === "action" && body?.action === "share" ? 30000 : 4000) try { // Status polls name the route lines they already hold; the comma then leaves them out. const query = operation === "status" && this.data?.routeKey ? `?routeKey=${this.data.routeKey}` : "" @@ -231,12 +240,17 @@ export class NavigationClient { if (response.status === 401 || response.status === 503 && ["access_unavailable", "setup_required"].includes(payload?.code)) { this.stop(); this.unauthorized(); return null } - if (!response.ok) throw new Error(payload?.error || "Navigation could not complete this request.") + if (!response.ok) { + // A shared place the comma could not pin down comes back with the search to show instead. + if (response.status === 400 && body?.action === "share" && typeof payload?.query === "string") { this.refusal = payload; return null } + throw new Error(payload?.error || "Navigation could not complete this request.") + } this.error = "" if (operation === "search") { if (!Array.isArray(payload.results) || payload.results.length > 20 || !payload.results.every(validSearchResult)) throw new Error("Search results could not be read.") this.results = payload.results + this.resultsProvider = payload.provider this.searched = true } else { if (payload?.routeUnchanged === true) { @@ -259,7 +273,7 @@ export class NavigationClient { } if (!sameSnapshot(payload, this.data)) this.data = payload this.stale = false - if (operation === "action" && ["select", "selectPlace", "clear"].includes(body.action)) { this.results = []; this.searched = false } + if (operation === "action" && ["select", "selectPlace", "clear", "share"].includes(body.action)) { this.results = []; this.searched = false } } return payload } catch (error) { @@ -294,15 +308,33 @@ export const FavoriteChoices = { export const NavigationPage = { name: "NavigationPage", - components: { GxNotice, BluetoothNotice, MapOperationsPanel, NavigationMap, OfflineRoadMapsPanel, FavoriteChoices, GalaxySelect }, + components: { GxNotice, BluetoothNotice, MapOperationsPanel, NavigationMap, OfflineRoadMapsPanel, FavoriteChoices, GalaxySelect, ChoiceGroup, SourceCompare }, props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true }, go: { type: Function, default: null }, initialTab: { type: String, default: "route" }, tabs: { type: Array, required: true } }, - data() { return { bluetooth: bluetoothConnection(), data: null, results: [], busy: false, error: "", stale: false, tab: this.initialTab, gpsGuide: "android", query: "", token: "", searched: false, - suggestions: [], suggestOpen: false, savedSuggestionPlaces: {}, favoritePicker: null, searchPending: false } }, + data() { return { bluetooth: bluetoothConnection(), data: null, results: [], busy: false, error: "", stale: false, tab: this.initialTab, gpsGuide: "android", query: "", token: "", googleKey: "", googleTest: null, mapboxOpen: false, googleOpen: false, searched: false, + suggestions: [], suggestOpen: false, savedSuggestionPlaces: {}, favoritePicker: null, searchPending: false, resultsProvider: null, suggestionsProvider: null } }, watch: { initialTab(value) { this.tab = value } }, computed: { routeAvoidances() { return ROUTE_AVOIDANCES }, gpsModes() { return GPS_MODES }, + googleReady() { return !!this.data?.hasGoogleKey }, + mapChoices() { + return [{ value: "mapbox", label: "Mapbox", detail: "Road lines, drawn from saved or live Mapbox data.", limit: "Works offline once roads are saved." }, + { value: "google", label: "Google", detail: "Google's street map with traffic colors.", disabled: !this.googleReady, badge: !this.data || this.googleReady ? "" : "Needs key", + limit: "Needs internet and the Mapbox key. Google tiles can't be saved offline." }] + }, + routeChoices() { + return [{ value: "mapbox", label: "Mapbox", detail: "Turn-by-turn with lane arrows.", limit: "Counted against your Mapbox allowance." }, + { value: "google", label: "Google", detail: "Routes that follow live traffic, and place search by Google.", disabled: !this.googleReady, badge: !this.data || this.googleReady ? "" : "Needs key", + limit: "Needs the Mapbox key too. No lane arrows. Falls back to Mapbox when its limits run out." }] + }, + gpsChoices() { return GPS_MODES.map((mode) => ({ value: mode.value, label: mode.label, detail: mode.hint })) }, + destinationWays() { + return [{ icon: "bi-search", title: "Search here", detail: "Type an address or place on the Destination page." }, + { icon: "bi-link-45deg", title: "Paste a Google Maps link", detail: "Paste a place link into search, short links included." }, + { icon: "bi-android2", title: "Share from Android", detail: "Google Maps → Share → StarPilot. The route starts on your comma." }, + { icon: "bi-apple", title: "Share from iPhone", detail: "Google Maps or Apple Maps → Share → StarPilot. The route starts on your comma." }] + }, gpsLabel() { if (this.mode !== "local" || !this.ready || this.stale) return "GPS Source" const source = this.data?.location?.lastKnown ? null : GPS_NAMES[this.data?.location?.source] @@ -335,6 +367,33 @@ export const NavigationPage = { return [["searchSessions", "Searches"], ["geocoding", "Address lookups"], ["directions", "Routes"], ["staticTiles", "Map views"]] .filter(([key]) => usage[key]).map(([key, label]) => ({ key, label, ...usage[key] })) }, + // Place search follows the Directions choice, as on the comma. + googlePlaces() { return this.data?.routeProvider === "google" && !!this.data?.hasGoogleKey }, + sources() { + if (!this.data) return [] + const google = (value) => value === "google" && !!this.data.hasGoogleKey ? "Google" : "Mapbox" + return [{ label: "Map", value: google(this.data.mapProvider), icon: "bi-map" }, + { label: "Directions", value: google(this.data.routeProvider), icon: "bi-signpost-split" }, + { label: "Places", value: google(this.data.routeProvider), icon: "bi-geo-alt" }, + { label: "Position", value: this.gpsLabel.replace("GPS: ", ""), icon: "bi-crosshair" }] + }, + googleUsage() { return this.data?.googleMap?.usage || null }, + googleRouteUsage() { return this.data?.googleRoutes?.usage || null }, + googleEssentialUsage() { return this.data?.googleRoutes?.essentials || null }, + googlePlaceUsage() { return this.data?.googlePlaces?.usage || null }, + googleSuggestionUsage() { return this.data?.googlePlaces?.suggestions || null }, + googleTests() { + const test = this.googleTest + if (!test) return [] + return [["Map Tiles API", test, "tile.googleapis.com"], ["Routes API", test.routes, "routes.googleapis.com"], ["Places API (New)", test.places, "places.googleapis.com"]] + .filter(([, result]) => result).map(([name, result, api]) => ({ name, ok: !!result.ok, message: result.message, missing: !result.ok && result.failure !== "budget", + link: result.failure === "billing" ? { href: "https://console.cloud.google.com/billing", label: "Turn on billing" } : + ["key", "disabled"].includes(result.failure) ? { href: `https://console.cloud.google.com/apis/library/${api}`, label: `Open ${name} in Google Cloud` } : null })) + }, + googleWorking() { + const rows = this.googleTests + return rows.length ? `${rows.length - rows.filter((row) => row.missing).length} of ${rows.length} APIs working` : "" + }, path() { return routePath(this.data?.route) }, summary() { const instruction = this.data?.instruction, route = this.data?.alternatives?.[this.data?.selectedRoute || 0] @@ -354,7 +413,7 @@ export const NavigationPage = { created() { this.client = new NavigationClient({ publish: (state) => Object.assign(this.$data, state), unauthorized: this.unauthorized }) }, mounted() { if (this.mode !== "local") return - this.visibilityHandler = () => document.visibilityState === "hidden" ? this.client.stop() : this.client.start() + this.visibilityHandler = () => document.visibilityState === "hidden" ? this.client.stop(true) : this.client.start(true) document.addEventListener("visibilitychange", this.visibilityHandler) if (document.visibilityState !== "hidden") { this.client.start().then(async () => { @@ -363,17 +422,11 @@ export const NavigationPage = { if (!share || !this.client.data || this.client.stale || !this.client.active) return params.delete('share') history.replaceState(history.state, '', `${location.pathname}${params.size ? '?' + params : ''}${location.hash}`) - const parsed = parseSharedDestination(share) - if (parsed.destination) await this.client.action('select', { destination: parsed.destination }) - else { - // Text shares can be ambiguous ("Starbucks"); show the results and let the driver pick. - this.query = parsed.query - await this.client.search(parsed.query) - } + await this.openShared(share) }) } }, - beforeUnmount() { document.removeEventListener("visibilitychange", this.visibilityHandler); clearTimeout(this.suggestTimer); this.client.stop(); this.token = "" }, + beforeUnmount() { document.removeEventListener("visibilitychange", this.visibilityHandler); clearTimeout(this.suggestTimer); this.client.stop(); this.token = ""; this.googleKey = "" }, methods: { reportSave, async openGpsSetup() { @@ -386,6 +439,16 @@ export const NavigationPage = { this.tab = tab this.go?.(tab === 'route' ? '/navigation' : `/navigation/${tab}`) }, + // The comma opens the link, looks the place up, turns navigation on and starts the route. + async openShared(text) { + if (await this.client.action('share', { text: String(text).slice(0, 8192) })) return + const query = this.client.refusal?.query + if (!query) return + // Text shares can be ambiguous ("Starbucks"); show the results and let the driver pick. + if (!this.client.data?.enabled && !await this.client.action('configure', { patch: { enabled: true } })) return + this.query = query + await this.client.search(query) + }, async search() { if (this.searchPending) return clearTimeout(this.suggestTimer) @@ -393,13 +456,13 @@ export const NavigationPage = { this.savedSuggestionPlaces = {} this.favoritePicker = null this.searchPending = true - try { await this.client.search(this.query) } + try { await (isMapLink(this.query) ? this.openShared(this.query) : this.client.search(this.query)) } finally { this.searchPending = false } }, typed() { clearTimeout(this.suggestTimer) this.suggestOpen = true - if (!this.query.trim()) { this.client.endSuggestions(); return } + if (!this.query.trim() || isMapLink(this.query)) { this.client.endSuggestions(); return } this.favoritePicker = null this.suggestTimer = setTimeout(() => this.client.suggest(this.query), 150) }, @@ -459,6 +522,12 @@ export const NavigationPage = { placeName(place) { return LABELS[place.label]?.name || place.name }, placeDetail(place) { return place.label ? place.name : place.address || place.description || "" }, async saveKey(enable = false) { const token = this.token.trim(); this.token = ""; await this.client.action("configure", { patch: enable ? { token, enabled: true } : { token } }) }, + async saveGoogleKey() { const googleKey = this.googleKey.trim(); this.googleKey = ""; this.googleTest = null; await this.client.action("configure", { patch: { googleKey } }) }, + async testGoogleKey() { + const key = this.googleKey.trim() + this.googleTest = null + this.googleTest = (await this.client.action("testGoogleKey", key ? { key } : {}))?.googleKeyTest || null + }, distance(value) { const metric = this.data?.isMetric !== false return metric ? value < 1000 ? `${Math.round(value)} m` : `${(value / 1000).toFixed(1)} km` : @@ -469,87 +538,180 @@ export const NavigationPage = { template: `

Navigation

-

Set a destination, prepare offline maps, and configure navigation and Mapbox.

+

Pick a destination, save maps for offline use, and choose where maps, directions and position come from.

+
-