diff --git a/miniapps/navigation/.claude/scheduled_tasks.lock b/miniapps/navigation/.claude/scheduled_tasks.lock new file mode 100644 index 0000000000000000000000000000000000000000..0520417a63e2a6c2fc69b9c6b26e573590b9cba9 --- /dev/null +++ b/miniapps/navigation/.claude/scheduled_tasks.lock @@ -0,0 +1 @@ +{"sessionId":"cef166da-ea55-4acc-b4b6-cb18eb598d4c","pid":58408,"procStart":"Fri May 29 19:01:33 2026","acquiredAt":1780092380153} \ No newline at end of file diff --git a/miniapps/navigation/miniapp.json b/miniapps/navigation/miniapp.json new file mode 100644 index 0000000000000000000000000000000000000000..d32f847eae34a35381598721675967528ff234eb --- /dev/null +++ b/miniapps/navigation/miniapp.json @@ -0,0 +1,160 @@ +{ + "$schema": "./node_modules/@mentra/miniapp-cli/schema/miniapp.schema.json", + "packageName": "com.mentra.navigation", + "version": "1.1.37", + "name": "Mentra Maps", + "description": "Turn-by-turn navigation with visual or spoken directions.", + "icon": "icon.png", + "type": "standard", + "sdkVersion": "0.3.0", + "minHostVersion": "1.42.0", + "entry": { + "background": "background/index.js", + "ui": "ui/index.html" + }, + "permissions": [ + { + "type": "LOCATION", + "description": "Used for live position, compass heading, and turn-by-turn directions" + }, + { + "type": "BACKGROUND_LOCATION", + "description": "Used for live position, compass heading, and turn-by-turn directions" + } + ], + "hardwareRequirements": [ + { + "type": "DISPLAY", + "level": "OPTIONAL", + "description": "Shows next maneuver and distance on glasses" + }, + { + "type": "SPEAKER", + "level": "OPTIONAL", + "description": "Speaks turn-by-turn directions on audio glasses" + } + ], + "actions": [ + { + "id": "start_navigation", + "description": "Start turn-by-turn navigation to a destination and provide visual or spoken directions on the glasses. Use when the user wants to go somewhere \u2014 e.g. 'navigate to Blue Bottle Coffee', 'directions to the airport', 'take me home'. Give the destination as a place name or address in `query` (it gets looked up near the user's current location); only pass latitude/longitude instead if you already have exact coordinates. Defaults to walking directions.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The destination as a place name or address (e.g. 'Blue Bottle Coffee', '369 Hayes St, San Francisco'). Resolved via place search biased to the user's current location. Provide this OR latitude+longitude." + }, + "latitude": { + "type": "number", + "description": "Destination latitude. Provide latitude+longitude together as an alternative to query, when exact coordinates are known." + }, + "longitude": { + "type": "number", + "description": "Destination longitude. Provide latitude+longitude together as an alternative to query." + }, + "destination_name": { + "type": "string", + "description": "Optional friendly label for the destination, shown in the UI (e.g. 'Home', 'Blue Bottle')." + }, + "travel_mode": { + "type": "string", + "enum": [ + "walking", + "driving", + "cycling", + "two_wheeler" + ], + "description": "How the user is traveling. Defaults to 'walking'." + } + } + }, + "outputSchema": { + "type": "object", + "properties": { + "ok": {"type": "boolean"}, + "error": {"type": "string"}, + "destination": { + "type": "object", + "properties": { + "lat": {"type": "number"}, + "lng": {"type": "number"}, + "name": {"type": "string"}, + "address": {"type": "string"}, + "placeId": {"type": "string"} + } + } + }, + "required": ["ok"] + } + }, + { + "id": "get_saved_addresses", + "description": "Get the user's saved Home and Work addresses. Use before starting navigation when the user refers to Home or Work without giving an address. Returns the configured slots only; missing slots are omitted.", + "parameters": { + "type": "object", + "properties": {} + }, + "outputSchema": { + "type": "object", + "properties": { + "addresses": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "name": {"type": "string"}, + "address": {"type": "string"}, + "latitude": {"type": "number"}, + "longitude": {"type": "number"} + } + } + } + }, + "required": ["addresses"] + } + }, + { + "id": "set_saved_address", + "description": "Save or replace the user's Home or Work address. Use when the user asks to remember, set, or update where Home or Work is. The address is resolved with place search near the user's current location.", + "parameters": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "home", + "work" + ], + "description": "Which saved-address slot to set. Only Home and Work are supported." + }, + "address": { + "type": "string", + "description": "The place name or street address to save (e.g. '369 Hayes St, San Francisco')." + } + }, + "required": [ + "type", + "address" + ] + }, + "outputSchema": { + "type": "object", + "properties": { + "address": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "name": {"type": "string"}, + "address": {"type": "string"}, + "latitude": {"type": "number"}, + "longitude": {"type": "number"} + } + } + }, + "required": ["address"] + } + } + ] +} diff --git a/miniapps/navigation/package.json b/miniapps/navigation/package.json new file mode 100644 index 0000000000000000000000000000000000000000..092ff3371c247fa7311ca479059db8bc0205c8fd --- /dev/null +++ b/miniapps/navigation/package.json @@ -0,0 +1,33 @@ +{ + "name": "navigation-miniapp", + "private": true, + "version": "1.0.6", + "scripts": { + "dev": "mentra-miniapp dev", + "build": "bun run build.ts", + "release": "mentra-miniapp release", + "pack": "mentra-miniapp pack", + "test": "bun test ./src", + "typecheck": "tsc --noEmit -p tsconfig.json" + }, + "dependencies": { + "@mentra/miniapp": "workspace:*", + "@turf/turf": "^7.3.5", + "liquid-glass-react": "^1.1.1", + "lucide-react": "^0.511.0", + "mapbox-gl": "^3.25.0", + "motion": "^12.38.0", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "zustand": "^5.0.13" + }, + "devDependencies": { + "@mentra/miniapp-cli": "workspace:*", + "@types/node": "^25.8.0", + "@types/react": "^19", + "@types/react-dom": "^19", + "bun-plugin-tailwind": "^0.1.2", + "bun-types": "^1.3.14", + "tailwindcss": "^4.2.4" + } +} diff --git a/miniapps/navigation/public/assets/Mentra-Navigation.png b/miniapps/navigation/public/assets/Mentra-Navigation.png new file mode 100644 index 0000000000000000000000000000000000000000..3d3dd985d3e0be373ac8cce8f1024dc040f96814 Binary files /dev/null and b/miniapps/navigation/public/assets/Mentra-Navigation.png differ diff --git a/miniapps/navigation/public/assets/dest.svg b/miniapps/navigation/public/assets/dest.svg new file mode 100644 index 0000000000000000000000000000000000000000..fccd424b384b343a8a646ffc0e5a7594b7f2af50 --- /dev/null +++ b/miniapps/navigation/public/assets/dest.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/miniapps/navigation/src/background/NavigationController.ts b/miniapps/navigation/src/background/NavigationController.ts new file mode 100644 index 0000000000000000000000000000000000000000..1efd601e5e91e462dd1a3029f3db6720bc99804a --- /dev/null +++ b/miniapps/navigation/src/background/NavigationController.ts @@ -0,0 +1,2580 @@ +/** + * NavigationController — the always-on logic for the Mentra Map + * miniapp. Owns MiniappSession subscriptions, trip state, the glasses + * HUD logic, storage reads/writes, and Places REST. Lives for the + * entire session — closing the WebView does NOT stop navigation. + * + * The UI WebView is a thin renderer fed via session.ui.send and the + * UI's mentra.send / mentra.request bus declared in shared/channels.ts. + */ + +import type { + MiniappSession, + NavRoute, + NavUpdate, + Pivot, + StartNavigationOptions, + TravelMode, + UIModule, +} from "@mentra/miniapp/background" + +import type {Channels} from "../shared/channels" +import type { + Coords, + DevSettings, + GlassesCapabilitySnapshot, + LogEntry, + NavSnapshot, + TripState, + UnitSystem, + VoiceGuidanceMode, +} from "../shared/types" +import {deriveManeuverDisplay, liveDistanceToNextTurn} from "../shared/maneuverDisplay" + +import {getSavedAddresses, setSavedAddress} from "./actions/savedAddressActions" +import {renderManeuverArrowBmp} from "./lib/ArrowRenderer" +import {borderTestImageBase64} from "./lib/bmp" +import {readGlassesCapabilities} from "./lib/capabilities" +import {formatDistance, formatDuration} from "./lib/formatDistance" +import { + bearingDeg, + distanceToPolylineMeters, + haversineMeters, + nextSegmentBearing, + remainingRouteMeters, + remainingRoutePoints, + sideOfFinalSegment, + type LatLng, +} from "./lib/geometry" +import {buildOsmLineMap, fetchOsmRoads, renderOsmLineMap} from "./lib/OsmLineMapRenderer" +import type {PlaceDetails} from "./lib/places" +import {TEST_BITMAP_288_B64} from "./lib/testBitmap" +import {AudioGuidanceManager, selectAudioGuidanceDistance} from "./managers/AudioGuidanceManager" +import {CompassManager} from "./managers/CompassManager" +import {DisplayManager} from "./managers/DisplayManager" +import {LocationManager} from "./managers/LocationManager" +import {NavigationManager} from "./managers/NavigationManager" +import {PlacesManager} from "./managers/PlacesManager" +import {SimpleStorageManager} from "./managers/SimpleStorageManager" + +export class NavigationController { + private readonly ui: UIModule + private readonly location: LocationManager + private readonly compass: CompassManager + private readonly display: DisplayManager + private readonly navigation: NavigationManager + private readonly storage: SimpleStorageManager + private readonly places: PlacesManager + private readonly audioGuidance: AudioGuidanceManager + + // PoC OSM map: current view center, mutated by the pan buttons. Starts at + // Hayes Valley, SF. + private osmMapCenter = {lat: 37.7766853, lng: -122.4229361} + private readonly OSM_MAP_SIZE = 88 + private readonly OSM_MAP_RADIUS_M = 133 + + private unsubs: Array<() => void> = [] + private started = false + private logSeq = 0 + private lastHudKey = "" + // Direction key of the last arrow bitmap pushed — re-ENCODE the arrow only + // when the turn direction changes (rasterizing the BMP is the cost; resending + // is free — the host diffs frames and unchanged elements never re-cross BLE). + private lastArrowKey = "" + // Timestamp of the last HUD push, so we can periodically re-push the maneuver + // text even when unchanged (recovers from G2 EvenHub page teardowns). + private lastHudAt = 0 + private lastMinimapPng: string | null = null + // Throttle for the minimap raster: the bitmap is the most expensive HUD + // element to render AND push, and GPS can fire many fixes per second (esp. + // simulated/fast movement). Rendering + sending on every fix wastes CPU and + // can flood the glasses' BLE link (the G2 can't usefully update faster than + // ~200-300ms). So we leading-edge throttle: render immediately, coalesce + // bursts within MINIMAP_MIN_INTERVAL_MS, and schedule ONE trailing render so + // the final position still lands after the burst settles. + private lastMinimapAt = 0 + private minimapTrailingTimer: ReturnType | null = null + // Minimap refresh watchdog. In the field (and esp. in demos) the stream of + // GPS fixes that drives refreshMinimap() can go quiet — the phone stops + // emitting fixes, the route settles, or the G2 swallows a send. When that + // happens the last bitmap is the most recent thing on the glasses, but if the + // page was torn down it may be blank. So: a recurring timer checks whether a + // minimap has been pushed within MINIMAP_WATCHDOG_IDLE_MS; if not, it forces a + // fresh re-render (bypassing the unchanged-png dedup) so the map keeps + // refreshing indefinitely while a trip is running. Runs every + // MINIMAP_WATCHDOG_INTERVAL_MS; started on trip start, stopped on dispose. + private minimapWatchdogTimer: ReturnType | null = null + // Timestamp of the last time a bitmap was ACTUALLY pushed to the glasses + // (showBitmap), as opposed to lastMinimapAt which is set on every render + // ATTEMPT (even ones the png-dedup then drops). The watchdog keys off this so + // it correctly detects "the glasses haven't received a new bitmap in a while" + // even while the HUD pump keeps calling refreshMinimap() with unchanged maps. + private lastMinimapPushAt = 0 + // How long the minimap can go without a push before the watchdog forces one. + private readonly MINIMAP_WATCHDOG_IDLE_MS = 2000 + // How often the watchdog checks for staleness (and the steady re-push cadence + // once updates have gone quiet). + private readonly MINIMAP_WATCHDOG_INTERVAL_MS = 2000 + // Set true for the duration of a watchdog-forced refresh so refreshMinimap() + // bypasses its png-unchanged dedup (line ~1544) — otherwise a quiet, + // unchanged map would never actually re-reach the glasses. + private forceMinimapPush = false + // Watchdog for a stuck "Starting…" HUD. The HUD leaves "Starting…" when a + // maneuver event (or a live pivot) arrives — but in the field the maneuver + // event sometimes never fires (the G2 tears down the EvenHub page mid-start, + // routes recompute back-to-back and reset the cursor, etc.), leaving the user + // stuck on "Starting…" with a perfectly good route on hand. This records when + // "Starting…" first showed; once it's been up past STARTING_WATCHDOG_MS while + // running with route steps available, refreshHUD falls back to the route's + // FIRST step so the HUD recovers instead of hanging. Reset whenever we leave + // the "Starting…" state. + private startingShownAt = 0 + // Glasses minimap bitmap — ON by default. + private showMinimap = true + // Last trip-stats string pushed to the bottom-left label, so we only re-send + // when distance/ETA actually changes (avoids churning the G2 text container). + private lastTripStats = "" + // Timestamp of the last bottom-left trip-stats push, so we can periodically + // re-send even when the content is unchanged (recovers from G2 page teardowns). + private lastTripStatsAt = 0 + // True while the swipe-up large-map view is showing. Suppresses the normal HUD + // pump so it doesn't repaint the minimap/text over the large map. + private largeMapShown = false + // Lock held while a large-map transition (show or dismiss) is mid-flight — + // i.e. between the clear() and the deferred render that follows the settle + // delay. Swipes that arrive during this window are IGNORED. Without it, + // rapid/accidental repeat swipes start overlapping show↔dismiss cycles whose + // clears, deferred renders, and largeMapShown toggles interleave and corrupt + // the display ("swiped a couple times and everything broke"). + private largeMapTransitioning = false + // Re-entrancy guard for nav:start. The Start button (and some upstream + // flows) can dispatch nav:start twice in quick succession; the second + // start()'s internal stop() tears down the sim/trip session the first one + // just spun up, freezing the puck (maneuver + trip distance stuck at one + // value). Held across the async start() so a duplicate start is ignored. + private starting = false + // OSM-roads minimap cache: roads fetched around a center, reused while the + // user stays near it (re-fetch only when they move past a threshold). + private osmRoadsCache: LatLng[][] | null = null + private osmRoadsCenter: LatLng | null = null + private osmFetchInFlight = false + private lastCoordsAt = 0 + private gettingFix = false + // Tracks whether a trip has completed (arrived or stopped) in this + // session. Used to suppress the "Welcome to Mentra Maps!" message + // after the first arrival — the welcome line should only show at + // the very start of the session, not every time the user finishes + // and returns to idle. + private hasCompletedTrip = false + + // Last logged threshold bucket for the off-route diagnostic so we + // only print on crossings, not every coord update. + // 0 = under OFF_ROUTE_ADVISORY_M, 1 = advisory band, 2 = ≥OFF_ROUTE_TRIGGER_M. + private lastOffRouteBucket = 0 + + // True while the user is in the 15–30m advisory band. Drives the + // glasses HUD's "Go back to route" frame between the moment we + // notice the drift and the moment auto-rebuild kicks in at 30m. + // Cleared when we return under 15m or when status flips to + // rerouting (>=30m crossing). + private offRouteAdvisory = false + // Live perpendicular distance to the route while in the advisory + // band. Refreshed on every coord tick (not just bucket transitions) + // so the HUD's "Go back 10m" countdown ticks down as the user + // moves toward the route. Null when not in the band. + private offRouteAdvisoryDistanceM: number | null = null + + // Trip-start anchor: position recorded at trip start, used to gate + // auto-rebuilds. Suppresses the "user is inside a 50m-radius building" + // case where the initial fix is already >30m off-route — until the + // user has moved >REBUILD_MIN_MOVE_M from the start point, we won't + // auto-rebuild. + private tripStartCoords: {lat: number; lng: number} | null = null + // Last StartNavigationOptions so an auto-rebuild can re-fire the same + // mode / simulate / speedMultiplier without the UI having to re-send. + private lastStartOpts: (StartNavigationOptions & {destinationName?: string}) | null = null + // Cooldown: timestamp of the last auto-rebuild. Suppresses back-to- + // back rebuilds while a fresh route is still being computed. + private lastAutoRebuildAt = 0 + // Pending auto-rebuild timer. When we cross >30m we don't rebuild + // immediately — we flip the HUD to "Rebuilding route…" and wait + // REBUILD_DELAY_MS, then re-check distance and either fire or + // cancel. Tracked so we can cancel it on stop/arrived/dispose and + // ignore further bucket-2 transitions while one is already pending. + private pendingRebuildTimer: ReturnType | null = null + + // Canonical state (mirrored to UI). + private coords: Coords | null = null + private heading: number | null = null + + // Movement-vector heading for the minimap "you" arrow. Instead of assuming + // the arrow points along the route, we derive the TRUE direction of travel + // from the user's own displacement: when they move ≥ MOVE_BEARING_MIN_M from + // the last anchor, the bearing anchor→current IS the heading. We hold the + // last computed bearing between moves so the arrow doesn't spin while the + // user stands still (GPS jitter) or snap back to the route direction. + private moveBearingAnchor: LatLng | null = null + private moveBearingDeg: number | null = null + private readonly MOVE_BEARING_MIN_M = 3 + private trip: TripState = { + status: "idle", + running: false, + maneuver: null, + activeDestination: null, + activeDestinationName: null, + routePoints: null, + routeSteps: null, + offRouteAt: null, + arrivalSide: null, + } + private activePivot: Pivot | null = null + private upcomingPivot: Pivot | null = null + private log: LogEntry[] = [] + private devSettings: DevSettings = { + simulate: false, + speedMultiplier: 5, + wrongSidewalk: false, + skipCrossings: false, + useRawInstructions: true, + largeMapEnabled: false, + } + + // User's distance-unit preference. Loaded from storage in start() and + // mirrored into every snapshot. Drives formatDistance() across the + // glasses HUD and (via the snapshot) the UI. Defaults to metric until + // the stored value loads. + private unitSystem: UnitSystem = "metric" + private capabilities: GlassesCapabilitySnapshot = { + modelName: null, + hasDisplay: false, + canPosition: false, + hasSpeaker: false, + hasButton: false, + } + private voiceGuidanceMode: VoiceGuidanceMode = "off" + private voiceGuidancePreferenceLoaded = false + private voiceGuidancePreferenceExplicit = false + private routeRevision = 0 + + // Cached raw Google `navigationInstruction.instructions` strings, in + // step order, from the most recent successful Routes API call. Drives + // the `useRawInstructions` debug toggle — the live SDK doesn't carry + // these through `NavStep`, so we zip the cached array into the live + // step list by index. Refetched on reroute (see onRoute handler) so + // the toggle keeps working after the route changes. + private cachedInstructions: string[] | null = null + // Guards against parallel refetches when the SDK fires multiple + // onRoute events in quick succession during a reroute. + private refetchingInstructions = false + + constructor(private readonly session: MiniappSession) { + this.ui = session.ui as unknown as UIModule + this.location = new LocationManager(session) + this.compass = new CompassManager(session) + this.display = new DisplayManager(session) + this.navigation = new NavigationManager(session) + this.storage = new SimpleStorageManager(session) + // Place search routes through the SDK → host → v2 cloud maps (Mapbox Search + // Box). No Worker, no provider key in this bundle. + this.places = new PlacesManager(session) + this.audioGuidance = new AudioGuidanceManager(session.speaker, (message) => this.appendLog(message)) + } + + start(): void { + if (this.started) return + this.started = true + + this.applyCapabilities(this.session.capabilities) + this.loadVoiceGuidanceMode() + + this.wireSensorSubscriptions() + this.wireCapabilityChanges() + this.wireRpcHandlers() + this.wireUIBroadcasts() + this.registerActions() + this.wireHUDPump() + this.wireTouchGestures() + this.wireRepeatButton() + this.primeNavigationPermission() + this.seedInitialFix() + this.loadUnitSystem() + + this.session.onBeforeDisconnect(() => this.dispose()) + } + + private defaultVoiceGuidanceMode(capabilities = this.capabilities): VoiceGuidanceMode { + if (!capabilities.hasSpeaker) return "off" + return capabilities.hasDisplay ? "essential" : "full" + } + + private applyCapabilities(raw: MiniappSession["capabilities"]): void { + const previous = this.capabilities + this.capabilities = readGlassesCapabilities(raw) + if (this.largeMapShown && !this.display.supportsBitmaps) { + this.exitLargeMap() + this.refreshHUD() + } + this.audioGuidance.setAvailable(this.capabilities.hasSpeaker) + if (!this.voiceGuidancePreferenceExplicit) { + this.voiceGuidanceMode = this.defaultVoiceGuidanceMode() + this.audioGuidance.setMode(this.voiceGuidanceMode) + } + if (!this.capabilities.hasDisplay) { + this.stopMinimapWatchdog() + this.lastMinimapPng = null + } else if (!previous.hasDisplay && this.trip.running) { + this.startMinimapWatchdog() + this.lastHudKey = "" + this.refreshHUD() + } else if (previous.canPosition !== this.capabilities.canPosition && this.trip.running) { + // A glasses swap can change the HUD from a compact text wall to a + // positioned scene (or vice versa) without changing hasDisplay. + if (this.capabilities.canPosition) { + this.startMinimapWatchdog() + } else { + this.stopMinimapWatchdog() + this.lastMinimapPng = null + } + this.lastHudKey = "" + this.refreshHUD() + } + this.broadcastVoiceGuidanceState() + } + + private wireCapabilityChanges(): void { + // registerMiniapp invokes start() before connect(), so the initial read + // above sees null. CONNECT_ACK populates session.capabilities and emits + // "ready" (not a capabilities-change event); refresh from the session once + // that handshake lands so speaker-only glasses work on first launch. + this.unsubs.push(this.session.on("ready", () => this.applyCapabilities(this.session.capabilities))) + this.unsubs.push(this.session.onCapabilitiesChange((capabilities) => this.applyCapabilities(capabilities))) + } + + private broadcastVoiceGuidanceState(): void { + this.ui.send("nav:voice-guidance-update", { + voiceGuidanceMode: this.voiceGuidanceMode, + capabilities: this.capabilities, + }) + } + + private loadVoiceGuidanceMode(): void { + this.storage + .getVoiceGuidanceMode() + .then((stored) => { + // A user choice made while the read was in flight wins over the stale + // stored value that was captured before that choice was persisted. + if (this.voiceGuidancePreferenceLoaded) return + this.voiceGuidancePreferenceLoaded = true + this.voiceGuidancePreferenceExplicit = stored != null + this.voiceGuidanceMode = stored ?? this.defaultVoiceGuidanceMode() + this.audioGuidance.setMode(this.voiceGuidanceMode) + this.broadcastVoiceGuidanceState() + }) + .catch((err) => { + if (this.voiceGuidancePreferenceLoaded) return + this.voiceGuidancePreferenceLoaded = true + this.appendLog(`voice-guidance load failed: ${err instanceof Error ? err.message : String(err)}`) + }) + } + + private wireRepeatButton(): void { + this.unsubs.push( + this.session.input.onButtonPress((data) => { + if (data.pressType !== "short" || !this.trip.running || !this.capabilities.hasButton) return + if (this.audioGuidance.repeatCurrent()) this.appendLog(`VOICE repeat (${data.buttonId})`) + }), + ) + } + + // ── Sensor → state pump ────────────────────────────────────────────── + + private wireSensorSubscriptions(): void { + // Location + this.unsubs.push( + this.location.onUpdate((d) => { + const here: LatLng = {lat: d.lat, lng: d.lng} + // Movement-vector heading: derive the TRUE direction of travel from the + // user's displacement. Seed the anchor on the first fix; thereafter, + // once they've moved ≥ MOVE_BEARING_MIN_M from the anchor, the bearing + // anchor→here is the heading, and we re-anchor. Below that threshold we + // keep the last bearing (so the arrow holds steady through GPS jitter / + // standing still instead of spinning). + if (this.moveBearingAnchor == null) { + this.moveBearingAnchor = here + } else if (haversineMeters(this.moveBearingAnchor, here) >= this.MOVE_BEARING_MIN_M) { + this.moveBearingDeg = bearingDeg(this.moveBearingAnchor, here) + this.moveBearingAnchor = here + } + this.coords = { + lat: d.lat, + lng: d.lng, + accuracy: d.accuracy, + ts: d.timestamp ?? Date.now(), + } + this.lastCoordsAt = Date.now() + this.ui.send("nav:coords", this.coords) + // The maneuver card's "In X m" distance is recomputed LIVE from these + // coords on BOTH surfaces directly — the glasses HUD in refreshHUD() and + // the phone OrientationCard in-component — via the shared + // liveDistanceToNextTurn helper. So there's nothing to freshen here: + // refreshHUD() (called below) picks up the new coords, and the phone + // re-renders off nav:coords. No background→UI re-broadcast needed. + this.logOffRouteThresholds() + this.maybeFireEarlyArrival() + this.refreshHUD() + }), + ) + + // Heading — throttled to ~10Hz so we don't saturate the bus. + const HEADING_MIN_INTERVAL_MS = 100 + let lastHeadingAt = 0 + let pendingHeading: number | null = null + let pendingTimer: ReturnType | null = null + const flushHeading = () => { + pendingTimer = null + if (pendingHeading == null) return + this.heading = pendingHeading + pendingHeading = null + lastHeadingAt = Date.now() + this.ui.send("nav:heading", {degrees: this.heading}) + } + this.unsubs.push( + this.compass.onUpdate((d) => { + const now = Date.now() + const elapsed = now - lastHeadingAt + if (elapsed >= HEADING_MIN_INTERVAL_MS) { + this.heading = d.degrees + lastHeadingAt = now + this.ui.send("nav:heading", {degrees: this.heading}) + } else { + pendingHeading = d.degrees + if (!pendingTimer) pendingTimer = setTimeout(flushHeading, HEADING_MIN_INTERVAL_MS - elapsed) + } + }), + ) + this.unsubs.push(() => { + if (pendingTimer) clearTimeout(pendingTimer) + pendingTimer = null + pendingHeading = null + }) + + // Pivot events + this.unsubs.push( + this.navigation.onPivot(() => { + this.activePivot = this.navigation.getActivePivot() + this.upcomingPivot = this.navigation.getUpcomingPivot() + this.ui.send("nav:pivots", { + active: this.activePivot, + upcoming: this.upcomingPivot, + }) + this.refreshHUD() + }), + ) + + // Navigation updates (maneuver / off_route / rerouting / arrived / error) + this.unsubs.push( + this.navigation.onUpdate((u: NavUpdate) => { + this.appendLog(this.formatUpdate(u)) + switch (u.kind) { + case "maneuver": + // The Nav SDK keeps emitting maneuver events for a beat + // after `arrived` fires (final-leg distance ticking to 0, + // etc). Ignoring them here keeps the "You have arrived" + // card on screen instead of letting it flicker back to + // the live maneuver display. A fresh start() resets + // status away from "arrived" via the synthetic onRoute + // emit path, so this gate doesn't trap a real new trip. + if (this.trip.status === "arrived") break + this.trip = { + ...this.trip, + status: "navigating", + running: true, + maneuver: u, + offRouteAt: null, + } + this.heartbeatLocationIfStale() + break + case "off_route": + this.trip = {...this.trip, offRouteAt: Date.now()} + break + case "rerouting": + // The previous maneuver belongs to the abandoned route. Clear it + // so neither display nor audio can replay stale guidance while the + // replacement route is landing. + this.trip = {...this.trip, status: "rerouting", maneuver: null} + break + case "arrived": { + // Compute side from the current route *before* nulling it, + // so the HUD's "on your left|right" line has data to render + // when the SDK is the trigger (rather than our early ≤7m + // path, which captures side the same way). + const side = sideOfFinalSegment(this.trip.routePoints, this.trip.activeDestination) + this.trip = { + ...this.trip, + status: "arrived", + running: false, + maneuver: null, + activeDestination: null, + routePoints: null, + routeSteps: null, + offRouteAt: null, + arrivalSide: side, + } + this.hasCompletedTrip = true + this.activePivot = null + this.upcomingPivot = null + this.cancelPendingRebuild() + this.tripStartCoords = null + this.lastStartOpts = null + this.lastAutoRebuildAt = 0 + this.lastOffRouteBucket = 0 + this.offRouteAdvisory = false + this.offRouteAdvisoryDistanceM = null + this.cachedInstructions = null + // If the large map is up at arrival, drop out of it so the + // "You have arrived" HUD can actually paint (refreshHUD early- + // returns while largeMapShown). + this.exitLargeMap() + break + } + case "error": + this.trip = {...this.trip, status: "idle", running: false} + this.cancelPendingRebuild() + this.tripStartCoords = null + this.lastStartOpts = null + this.lastAutoRebuildAt = 0 + this.lastOffRouteBucket = 0 + this.offRouteAdvisory = false + this.offRouteAdvisoryDistanceM = null + this.cachedInstructions = null + this.exitLargeMap() + break + } + this.ui.send("nav:trip-state", this.trip) + this.refreshHUD() + }), + ) + + // Route updates (full polyline rebuild) + this.unsubs.push( + this.navigation.onRoute((route: NavRoute) => { + this.routeRevision += 1 + // Mirror NavStep → NavRouteStep, dropping `routeIndex` (UI + // doesn't need it) and widening `maneuver` from the SDK union + // to a plain string for the channel wire (see NavRouteStep). + const steps = + route.steps && route.steps.length > 0 + ? route.steps.map((s, i) => ({ + lat: s.lat, + lng: s.lng, + road: s.road ?? null, + maneuver: s.maneuver, + distanceMeters: s.distanceMeters, + // Zip the cached preview-time Google instructions in by + // index. The SDK strips `instruction` from NavStep, so + // this is the only way the `useRawInstructions` toggle + // can find Google's verbatim text for the current step. + // Mismatched length (cache stale after reroute) is + // handled by the silent refetch below. + instruction: + this.cachedInstructions && i < this.cachedInstructions.length + ? this.cachedInstructions[i] || null + : null, + })) + : null + // A fresh route landing means any in-flight reroute is resolved. + // Clear the "rerouting" status here so the maneuver card / HUD + // drop "Rebuilding route…" the moment the new polyline applies, + // rather than lingering until the next maneuver event. Only + // "rerouting" is rewritten — "navigating" (initial start) and + // "arrived" are left untouched. + const status = this.trip.status === "rerouting" ? "navigating" : this.trip.status + this.trip = {...this.trip, status, routePoints: route.points, routeSteps: steps} + // Fresh route → reset the off-route bucket and re-anchor the + // trip-start point. Otherwise the first coord after the new + // polyline lands could compare against a stale bucket (the + // user might already have been "in" bucket 2 against the old + // route) and skip the threshold transition log. + this.lastOffRouteBucket = 0 + this.offRouteAdvisory = false + this.offRouteAdvisoryDistanceM = null + if (this.coords) { + this.tripStartCoords = {lat: this.coords.lat, lng: this.coords.lng} + } + this.ui.send("nav:route", {points: route.points, steps}) + this.ui.send("nav:trip-state", this.trip) + logLiveRoute(route) + // After a reroute the cached preview instructions no longer line + // up with the new step list (different count or different roads). + // Refetch silently against the current origin so the + // `useRawInstructions` toggle keeps showing fresh Google text + // through reroutes. Gated behind the toggle so we don't burn a + // Routes API call when nobody's watching. + if ( + this.devSettings.useRawInstructions && + steps && + steps.length > 0 && + (this.cachedInstructions == null || this.cachedInstructions.length !== steps.length) + ) { + this.refetchInstructionsForLiveRoute(steps.length) + } + // Push the initial pivot snapshot. The SDK's onPivot only fires + // on approaching/entered/exited transitions — at trip start the + // user can be far from every pivot, so no transition has fired + // yet and the UI would sit on stale (null, null) pivots until + // the user got close. Pull the current pair off the engine and + // ship it explicitly so the maneuver card has something to + // render from the moment the trip begins. + // + // Race window: the SDK's NavigationModule subscribes the pivot + // engine to the SAME onRoute event we're handling here. If the + // engine subscribed AFTER us, getUpcomingPivot() runs before + // the engine has built pivots from this route. Defer one + // microtask + macrotask hop so every subscriber finishes + // processing the event before we snapshot. + setTimeout(() => { + this.activePivot = this.navigation.getActivePivot() + this.upcomingPivot = this.navigation.getUpcomingPivot() + this.ui.send("nav:pivots", {active: this.activePivot, upcoming: this.upcomingPivot}) + this.refreshHUD() + }, 0) + }), + ) + } + + // ── RPC handlers ───────────────────────────────────────────────────── + + private wireRpcHandlers(): void { + this.unsubs.push( + this.ui.handle("nav:compute-route", async (opts) => { + const result = await this.navigation.computeRoute(opts) + // Cache the raw Google instruction strings off the primary route + // so the `useRawInstructions` debug toggle can substitute them + // into the live maneuver card / glasses HUD by step index. + const steps = result.routes?.[0]?.steps + if (steps && steps.length > 0) { + this.cachedInstructions = steps.map((s) => cleanInstruction(s.instruction)) + } + return result + }), + ) + this.unsubs.push(this.ui.handle("nav:request-permission", () => this.navigation.requestPermission())) + this.unsubs.push(this.ui.handle("nav:get-snapshot", () => this.buildSnapshot())) + this.unsubs.push(this.ui.handle("nav:get-pivots", () => this.navigation.getPivots())) + + this.unsubs.push(this.ui.handle("places:autocomplete", ({query, near}) => this.places.autocomplete(query, near))) + this.unsubs.push(this.ui.handle("places:details", ({placeId}) => this.places.details(placeId))) + this.unsubs.push( + this.ui.handle("places:reverse-geocode", ({lat, lng}) => this.navigation.reverseGeocode({lat, lng})), + ) + + this.unsubs.push(this.ui.handle("storage:list-saved", () => this.storage.getAllSavedPlaces())) + this.unsubs.push(this.ui.handle("storage:add-saved", (p) => this.storage.addSavedPlace(p))) + this.unsubs.push(this.ui.handle("storage:remove-saved", ({placeId}) => this.storage.removeSavedPlace(placeId))) + this.unsubs.push(this.ui.handle("storage:list-recent", () => this.storage.getRecentSearches())) + this.unsubs.push(this.ui.handle("storage:add-recent", (p) => this.storage.addRecentSearch(p))) + } + + // ── Trip start (shared by the UI's nav:start and the start_navigation action) ── + + /** + * Begin a turn-by-turn trip. Drives both the UI's `nav:start` broadcast and + * the `start_navigation` action so they share one path: optimistic trip + * state, glasses HUD repaint, then `navigation.start()`, rolling back to idle + * if the native start fails. Resolves `{ok, error?}` for the action; the UI + * listener ignores the return. + */ + private async beginTrip( + opts: StartNavigationOptions & {destinationName?: string}, + ): Promise<{ok: boolean; error?: string}> { + // Re-entrancy guard: ignore a second start while one is already in flight + // (the duplicate's start() would stop() the session the first just created + // and freeze the puck). + if (this.starting) { + this.appendLog("START ignored — already starting") + return {ok: false, error: "A navigation start is already in progress"} + } + this.starting = true + const {destinationName, ...startOpts} = opts + // Clear the previous trip's route polyline immediately so the + // off-route threshold check doesn't run against a stale route + // between nav:start and the new onRoute event landing. Without + // this, the user can be e.g. 500m from the prior route's + // polyline at start, instantly trigger the >30m bucket, flip + // status to "rerouting", and fire a redundant auto-rebuild. + this.trip = { + ...this.trip, + status: "navigating", + running: true, + activeDestination: startOpts.stops?.[startOpts.stops.length - 1] ?? null, + activeDestinationName: destinationName ?? null, + maneuver: null, + routePoints: null, + routeSteps: null, + offRouteAt: null, + arrivalSide: null, + } + // Snapshot the trip-start context so an auto-rebuild can re- + // fire start() with the same shape, and so we can gate + // rebuilds on "user has actually moved away from start". + this.lastStartOpts = opts + this.audioGuidance.beginTrip() + this.startMinimapWatchdog() + this.tripStartCoords = this.coords ? {lat: this.coords.lat, lng: this.coords.lng} : null + // Reset the movement-vector heading so this trip's "you" arrow measures + // direction of travel fresh (anchor re-seeds on the next fix). + this.moveBearingAnchor = this.coords ? {lat: this.coords.lat, lng: this.coords.lng} : null + this.moveBearingDeg = null + this.lastAutoRebuildAt = 0 + this.lastOffRouteBucket = 0 + this.offRouteAdvisory = false + this.offRouteAdvisoryDistanceM = null + // Clear any pivots left over from a previous trip. Without this, a new + // start with stale activePivot/upcomingPivot would make refreshHUD take + // a pivot branch and show the OLD trip's instruction instead of + // "Starting…" — the HUD must read "Starting…" until THIS trip's first + // real maneuver/pivot lands. + this.activePivot = null + this.upcomingPivot = null + // Cancel any in-flight delayed rebuild — a fresh start + // supersedes the old "are we still off-route?" timer. + this.cancelPendingRebuild() + this.appendLog(`START ${destinationName ?? "(unnamed)"}`) + this.ui.send("nav:trip-state", this.trip) + // Repaint the glasses HUD immediately so the left text flips from the + // idle "Welcome to Mentra Maps!" frame to "Starting…" the instant the + // user starts — instead of the welcome frame lingering until the next + // GPS tick / HUD pump (~1s). running is already true above, so refreshHUD + // takes the "Starting…" branch and showManeuver overwrites the welcome + // text in place. + this.refreshHUD() + try { + // start() resolves `{ok:false}` (it never throws) for + // permission, GPS, REST, or native failures — on those the + // native trip never began and no synthetic onRoute will land, + // so we must roll the optimistic "navigating" state set above + // back to idle. Inspecting only `catch` left the UI stuck on a + // routeless trip with no recovery but a manual stop. + const res = await this.navigation.start(withPivotDefaults(startOpts)) + if (!res.ok) { + this.appendLog(`START failed: ${res.error ?? "unknown"}`) + this.rollbackTripToIdle() + } else { + this.audioGuidance.confirmTripStarted(destinationName ?? null) + } + return res + } catch (err) { + const error = err instanceof Error ? err.message : String(err) + this.appendLog(`START error: ${error}`) + this.rollbackTripToIdle() + return {ok: false, error} + } finally { + this.starting = false + } + } + + /** + * Roll the optimistic "navigating" trip state back to idle after a failed + * start. Clears the destination and route fields too — otherwise the phone + * map keeps a pin on a destination we never actually started routing to. + */ + private rollbackTripToIdle(): void { + this.audioGuidance.endTrip() + this.trip = { + ...this.trip, + status: "idle", + running: false, + activeDestination: null, + activeDestinationName: null, + maneuver: null, + routePoints: null, + routeSteps: null, + } + this.ui.send("nav:trip-state", this.trip) + this.refreshHUD() + } + + // ── Actions (cross-miniapp / AI) ───────────────────────────────────── + + /** + * Declared in miniapp.json. A system miniapp (e.g. Mentra AI) invokes + * start_navigation to "navigate to X" — the host headless-wakes us if we're + * stopped, then delivers the call once start() registers the handler. The + * destination may be a place query (looked up via Places, biased to the + * current location) or explicit coordinates. + */ + private registerActions(): void { + try { + this.unsubs.push(this.session.actions.handle("start_navigation", (params) => this.startNavigationAction(params))) + this.unsubs.push(this.session.actions.handle("get_saved_addresses", () => getSavedAddresses(this.storage))) + this.unsubs.push( + this.session.actions.handle("set_saved_address", (params) => + setSavedAddress(params, this.storage, (query) => this.resolveDestination(query)), + ), + ) + } catch (err) { + // actions module unavailable on this host, or already registered — the + // miniapp still runs, but its actions won't be available. + this.appendLog(`actions register failed: ${err instanceof Error ? err.message : String(err)}`) + } + } + + private async startNavigationAction( + params: Record, + ): Promise<{ok: boolean; error?: string; destination?: {lat: number; lng: number; name?: string}}> { + if (!this.navigation.hasPermission) { + return {ok: false, error: "Location permission is required for navigation."} + } + + const mode = MODES.has(params.travel_mode as TravelMode) ? (params.travel_mode as TravelMode) : "walking" + const explicitName = typeof params.destination_name === "string" ? params.destination_name.trim() : "" + + // Resolve the destination. A full coordinate pair wins; otherwise fall back + // to the place query (so a query still works even when a stray/partial + // coordinate is also present); a lone coordinate with no query is an error. + const hasLat = typeof params.latitude === "number" + const hasLng = typeof params.longitude === "number" + const query = typeof params.query === "string" && params.query.trim() ? params.query.trim() : null + + let dest: {lat: number; lng: number; name?: string} | null = null + if (hasLat && hasLng) { + // Validate as finite, in-range coordinates — `typeof NaN === "number"`, so + // a bare typeof check would let NaN/Infinity flow into the native start. + const latitude = params.latitude as number + const longitude = params.longitude as number + if ( + !Number.isFinite(latitude) || + !Number.isFinite(longitude) || + Math.abs(latitude) > 90 || + Math.abs(longitude) > 180 + ) { + return {ok: false, error: "latitude and longitude must be finite coordinates (|lat| ≤ 90, |lng| ≤ 180)."} + } + dest = {lat: latitude, lng: longitude, name: explicitName || undefined} + } else if (query) { + dest = await this.resolveDestination(query) + if (!dest) return {ok: false, error: `Couldn't find a place matching "${query}".`} + } else if (hasLat || hasLng) { + return {ok: false, error: "Provide both latitude and longitude, or a destination query."} + } else { + return {ok: false, error: "Provide a destination query, or latitude and longitude."} + } + + const res = await this.beginTrip({ + stops: [{lat: dest.lat, lng: dest.lng}], + mode, + destinationName: explicitName || dest.name, + }) + if (!res.ok) return {ok: false, error: res.error ?? "Failed to start navigation."} + return {ok: true, destination: dest} + } + + /** + * Geocode a place name/address to coordinates via the Places facade, biased + * to the user's current location. Mirrors the UI's autocomplete → details + * pick. Returns null when there's no match or the lookup fails. + */ + private async resolveDestination(query: string): Promise { + try { + let near = this.coords ? {lat: this.coords.lat, lng: this.coords.lng} : undefined + // A headless start_navigation invoke can be dispatched before the initial + // GPS fix lands (seedInitialFix runs later in start()). Grab a one-shot fix + // so place search is biased to the wearer, per the action contract — and + // seed this.coords so beginTrip has a start position too. + if (!near) { + try { + const d = await this.location.getOnce() + near = {lat: d.lat, lng: d.lng} + if (!this.coords) { + this.coords = {lat: d.lat, lng: d.lng, accuracy: d.accuracy, ts: d.timestamp ?? Date.now()} + this.lastCoordsAt = Date.now() + this.ui.send("nav:coords", this.coords) + } + } catch { + /* no fix yet — fall back to an unbiased search */ + } + } + const suggestions = await this.places.autocomplete(query, near) + if (!suggestions.length) return null + const details = await this.places.details(suggestions[0].placeId) + return details + } catch (err) { + this.appendLog(`resolveDestination failed: ${err instanceof Error ? err.message : String(err)}`) + return null + } + } + + // ── UI broadcast listeners ─────────────────────────────────────────── + + private wireUIBroadcasts(): void { + this.unsubs.push( + this.ui.on("nav:start", async (opts) => { + await this.beginTrip(opts) + }), + ) + this.unsubs.push( + this.ui.on("nav:stop", () => { + this.appendLog("STOP") + this.audioGuidance.endTrip() + try { + this.navigation.stop() + } catch { + /* ignore */ + } + this.cancelPendingRebuild() + this.tripStartCoords = null + this.lastStartOpts = null + this.lastAutoRebuildAt = 0 + this.lastOffRouteBucket = 0 + this.offRouteAdvisory = false + this.offRouteAdvisoryDistanceM = null + this.activePivot = null + this.upcomingPivot = null + this.cachedInstructions = null + this.trip = { + ...this.trip, + status: "idle", + running: false, + maneuver: null, + activeDestination: null, + routePoints: null, + routeSteps: null, + offRouteAt: null, + arrivalSide: null, + } + this.hasCompletedTrip = true + this.stopMinimapWatchdog() + // If the swipe-up large map is showing, drop out of it so the trip's + // end actually clears the glasses — otherwise refreshHUD() early- + // returns (it won't paint over the large map) and the big map lingers + // on screen after the trip is over. + this.exitLargeMap() + this.ui.send("nav:trip-state", this.trip) + this.refreshHUD() + }), + ) + this.unsubs.push( + this.ui.on("nav:deviate", () => { + try { + this.navigation.dev.deviate() + } catch (err) { + this.appendLog(`deviate failed: ${err instanceof Error ? err.message : String(err)}`) + } + }), + ) + this.unsubs.push( + this.ui.on("nav:reset-location", () => { + // Dev: snap the map back to the device's REAL current location. + // After a simulated trip the puck is parked at the sim destination + // (the native sim drove it there); this stops any active trip and + // forces a fresh one-shot fix, then broadcasts it as nav:coords so + // the map re-centers on where the device actually is. + this.appendLog("RESET LOCATION → real fix") + this.audioGuidance.endTrip() + try { + this.navigation.stop() + } catch { + /* ignore */ + } + // Return the page to idle so the map isn't holding a stale trip. + this.cancelPendingRebuild() + this.tripStartCoords = null + this.lastStartOpts = null + this.activePivot = null + this.upcomingPivot = null + this.cachedInstructions = null + this.trip = { + ...this.trip, + status: "idle", + running: false, + maneuver: null, + activeDestination: null, + routePoints: null, + routeSteps: null, + offRouteAt: null, + arrivalSide: null, + } + this.ui.send("nav:trip-state", this.trip) + this.refreshHUD() + // Force-fetch a fresh fix and broadcast it. Unlike seedInitialFix, + // this overwrites existing coords on purpose — the whole point is to + // discard the sim-endpoint position and jump to reality. + this.location + .getOnce() + .then((d) => { + this.coords = {lat: d.lat, lng: d.lng, accuracy: d.accuracy, ts: d.timestamp ?? Date.now()} + this.lastCoordsAt = Date.now() + this.ui.send("nav:coords", this.coords) + this.appendLog(`reset → ${d.lat.toFixed(5)}, ${d.lng.toFixed(5)}`) + }) + .catch((err) => { + this.appendLog(`reset-location fix failed: ${err instanceof Error ? err.message : String(err)}`) + }) + }), + ) + this.unsubs.push( + this.ui.on("nav:set-destination", (place) => { + if (place) this.appendLog(`set-destination ${place.name}`) + }), + ) + this.unsubs.push( + this.ui.on("nav:set-dev-settings", (partial) => { + const next = {...this.devSettings, ...partial} + // Forward changed dev toggles into the navigation SDK's `dev` + // surface so the wrongSidewalk / skipCrossings flags actually + // affect the trip. `simulate` and `speedMultiplier` are passed + // to navigation.start() via the nav:start payload — applying + // them mid-trip would require a stop+restart, which we don't + // do here. + try { + if (partial.wrongSidewalk !== undefined && partial.wrongSidewalk !== this.devSettings.wrongSidewalk) { + this.navigation.dev.setWrongSidewalkOffset(partial.wrongSidewalk) + } + if (partial.skipCrossings !== undefined && partial.skipCrossings !== this.devSettings.skipCrossings) { + this.navigation.dev.setSkipCrossings(partial.skipCrossings) + } + } catch (err) { + this.appendLog(`dev-settings forward failed: ${err instanceof Error ? err.message : String(err)}`) + } + const rawJustEnabled = partial.useRawInstructions === true && !this.devSettings.useRawInstructions + this.devSettings = next + this.ui.send("nav:dev-settings-update", this.devSettings) + // Flipping the toggle changes what the maneuver card / HUD + // render, but neither re-runs until the next pivot / coord + // tick. Force a refresh so the swap is visible immediately. + this.refreshHUD() + // If the toggle was just turned on mid-trip and we have no + // cached instructions (or the cache is stale relative to the + // live route), kick off a silent refetch so the live trip gets + // the strings on the next render. No-op when idle. + if (rawJustEnabled && this.trip.running) { + const liveLen = this.trip.routeSteps?.length ?? 0 + if (liveLen > 0 && (this.cachedInstructions == null || this.cachedInstructions.length !== liveLen)) { + this.refetchInstructionsForLiveRoute(liveLen) + } + } + }), + ) + + this.unsubs.push( + this.ui.on("nav:set-units", ({unitSystem}) => { + if (unitSystem === this.unitSystem) return + this.unitSystem = unitSystem + // Persist (fire-and-forget — the in-memory value is already + // authoritative for this session; storage just survives reloads). + this.storage.setUnitSystem(unitSystem).catch((err) => { + this.appendLog(`unit-system persist failed: ${err instanceof Error ? err.message : String(err)}`) + }) + this.ui.send("nav:units-update", {unitSystem}) + // Re-render the glasses HUD so the distance suffix flips units + // immediately rather than waiting for the next pivot/coord tick. + this.refreshHUD() + }), + ) + + this.unsubs.push( + this.ui.on("nav:set-voice-guidance", ({mode}) => { + if (mode === this.voiceGuidanceMode) return + this.voiceGuidancePreferenceLoaded = true + this.voiceGuidancePreferenceExplicit = true + this.voiceGuidanceMode = mode + this.audioGuidance.setMode(mode) + this.storage.setVoiceGuidanceMode(mode).catch((err) => { + this.appendLog(`voice-guidance persist failed: ${err instanceof Error ? err.message : String(err)}`) + }) + this.broadcastVoiceGuidanceState() + this.refreshHUD() + }), + ) + + this.unsubs.push( + this.ui.on("nav:repeat-direction", () => { + if (!this.audioGuidance.repeatCurrent()) this.appendLog("VOICE repeat ignored — no active direction") + }), + ) + + this.unsubs.push( + this.ui.on("nav:set-show-minimap", (show) => { + if (show === this.showMinimap) return + this.showMinimap = show + if (!show) { + // Drop just the minimap slot — the HUD frame re-renders without it + // (clear() would blank the whole HUD until the next nav tick). + // Reset the dedup cache so toggling back on re-pushes the frame. + if (this.capabilities.hasDisplay) this.display.clearMinimap() + this.lastMinimapPng = null + this.lastHudKey = "" + } else { + // Force the next HUD pump to repush. + this.lastMinimapPng = null + this.refreshHUD() + } + }), + ) + + this.unsubs.push( + this.ui.handle("test:show-text-test", ({text, durationMs}) => { + this.display.showText(text, durationMs) + }), + ) + + this.unsubs.push( + this.ui.handle("test:show-bitmap-test", () => { + this.display.showBitmapTest(TEST_BITMAP_288_B64) + }), + ) + + this.unsubs.push( + this.ui.handle("test:show-bitmap-size", ({size, height}) => { + this.display.showBitmapSize(size, height) + }), + ) + + this.unsubs.push( + this.ui.handle("test:show-osm-map", async () => { + return this.renderOsmMap("draw") + }), + ) + + this.unsubs.push( + this.ui.handle("test:show-large-map", async () => { + if (!this.coords) return {ok: false, error: "no GPS fix yet"} + const me: LatLng = {lat: this.coords.lat, lng: this.coords.lng} + // Fetch roads if we don't have any cached yet, then render the large map. + if (!this.osmRoadsCache) { + try { + this.osmRoadsCache = await fetchOsmRoads(me, this.OSM_MINIMAP_RADIUS_M * 2) + this.osmRoadsCenter = me + } catch (err) { + return {ok: false, error: err instanceof Error ? err.message : String(err)} + } + } + this.renderLargeMap(me) + return {ok: true} + }), + ) + + this.unsubs.push( + this.ui.handle("test:pan-osm-map", async ({dir}) => { + // Small nudge: shift the center by ~1/4 of the visible span. The visible + // span is 2×radius meters, so a quarter is radius/2 meters. + const stepM = this.OSM_MAP_RADIUS_M / 2 + const mPerDegLat = 111_320 + const mPerDegLng = 111_320 * Math.cos((this.osmMapCenter.lat * Math.PI) / 180) + const dLat = stepM / mPerDegLat + const dLng = stepM / mPerDegLng + if (dir === "up") this.osmMapCenter.lat += dLat + else if (dir === "down") this.osmMapCenter.lat -= dLat + else if (dir === "left") this.osmMapCenter.lng -= dLng + else if (dir === "right") this.osmMapCenter.lng += dLng + return this.renderOsmMap(`pan ${dir}`) + }), + ) + + this.unsubs.push( + this.ui.handle("test:count-1-to-10", () => { + for (let i = 1; i <= 10; i++) { + setTimeout(() => this.display.showText(String(i)), (i - 1) * 3000) + } + }), + ) + + this.unsubs.push( + this.ui.handle("test:count-both-boxes", () => { + this.runCountBothBoxesTest() + }), + ) + + // Mid-trip hydration: every fresh WebView open gets a snapshot. + this.unsubs.push(this.ui.onOpen(() => this.ui.send("nav:snapshot", this.buildSnapshot()))) + } + + /** + * Delay probe (dev panel). Shows the minimap bitmap top-right, then counts + * BOTH text containers — top-left maneuver + bottom-left stats — down from + * 100 to 0 on the SAME tick, once per second, through the real + * showManeuver/showTripStats path (so it exercises the production 200ms + * text queue). If the two boxes stay locked together the queue is fine; if + * one trails the other, that's the delay you're seeing. Auto-stops at 0. + * Tapping again while running is ignored (guard) so timers don't stack. + */ + private countBothBoxesTimer: ReturnType | null = null + private runCountBothBoxesTest(): void { + if (this.countBothBoxesTimer != null) return // already running — ignore re-tap + // Top-right minimap bitmap stays up for the whole count. + this.display.showBitmap(borderTestImageBase64(100, 100)) + let n = 100 + const tick = () => { + // Same value, same tick, into both containers via the real queue. + this.display.showManeuver(`Top\n${n}`) + this.display.showTripStats(`Bottom\n${n}`) + if (n <= 0) { + if (this.countBothBoxesTimer != null) { + clearInterval(this.countBothBoxesTimer) + this.countBothBoxesTimer = null + } + return + } + n-- + } + tick() // show 100 immediately + this.countBothBoxesTimer = setInterval(tick, 1000) + } + + // ── OSM line-map PoC ───────────────────────────────────────────────── + /** Fetch + render the OSM road map at the current osmMapCenter and push it. */ + private async renderOsmMap(reason: string): Promise<{ok: boolean; error?: string}> { + const {lat, lng} = this.osmMapCenter + const SIZE = this.OSM_MAP_SIZE + console.log(`[OSM-MAP] 🗺️ ${reason} — fetching roads around ${lat.toFixed(6)},${lng.toFixed(6)} (${SIZE}×${SIZE})`) + const t0 = Date.now() + try { + const base64 = await buildOsmLineMap({ + center: {lat, lng}, + width: SIZE, + height: SIZE, + viewRadiusMeters: this.OSM_MAP_RADIUS_M, + lineWidthPx: 2, + }) + console.log( + `[OSM-MAP] ✅ rendered ${SIZE}×${SIZE} BMP (${(base64.length / 1024).toFixed(1)} KB) in ${Date.now() - t0}ms — sending to glasses`, + ) + this.display.showRawBitmap(base64, SIZE, SIZE) + return {ok: true} + } catch (err) { + const error = err instanceof Error ? err.message : String(err) + console.log(`[OSM-MAP] ❌ failed after ${Date.now() - t0}ms:`, error) + return {ok: false, error} + } + } + + // ── Glasses HUD pump ───────────────────────────────────────────────── + // refreshHUD() is called explicitly at the end of each state mutator + // in wireSensorSubscriptions / wireUIBroadcasts. No monkey-patching of + // ui.send — clearer than reactive auto-refresh. + + private wireHUDPump(): void { + // Prime an initial HUD render once subscriptions warm up so the + // welcome message shows even before the first GPS fix. Stored on + // an unsub so dispose() can cancel before it fires — otherwise a + // session that disconnects within 250ms of start would re-display + // "Welcome" on the glasses after dispose() has already cleared. + const handle = setTimeout(() => { + try { + this.refreshHUD() + } catch { + /* ignore */ + } + }, 250) + this.unsubs.push(() => clearTimeout(handle)) + + // Steady HUD tick while navigating. The distance-to-next-turn and + // total-distance-remaining are recomputed inside refreshHUD() from + // `this.coords`, but refreshHUD() is otherwise only called when a + // GPS fix arrives. On Android the location stream batches/stutters + // (power-save, urban canyon, indoor), so fixes can lag several + // seconds — and the displayed meters freeze in the gap, going stale + // while the user is clearly still moving. Recompute on a fixed ~1s + // cadence so the numbers decrement smoothly regardless of GPS + // jitter. Gated on `trip.running` so we don't repaint when idle, and + // refreshHUD()'s own coalescing (identical-frame + 3s window) + // prevents redundant pushes when nothing actually changed. + const HUD_TICK_MS = 1000 + const tick = setInterval(() => { + if (!this.trip.running) return + try { + this.refreshHUD() + } catch { + /* ignore */ + } + }, HUD_TICK_MS) + this.unsubs.push(() => clearInterval(tick)) + } + + // ── G2 touch gestures ──────────────────────────────────────────────── + // Swipe-up DURING live navigation → clear the HUD (minimap + stats + text) + // and show the large full map. (Swipe-down / tap returns to the HUD.) + private wireTouchGestures(): void { + this.unsubs.push( + this.session.input.onTouch((data) => { + if (!this.capabilities.hasDisplay) return + // `data.kind` carries the gesture (single_tap / double_tap / swipe_up / + // swipe_down / ...); gestureName is a fallback for older host builds. + const d = data as unknown as Record + const gesture = String(d.kind ?? d.gestureName ?? "") + + // system_exit = the glasses tore down our EvenHub page (dashboard etc). + // Do NOT touch largeMapShown here — it fires constantly and would + // repaint the HUD over the user's swipe box immediately. The HUD + // recovers on its own via the periodic re-push in refreshHUD. + if (gesture === "system_exit") return + + // Only react while actually navigating. + if (!this.trip.running) { + console.log(`[TOUCH] ignored — not in live navigation`) + return + } + + const isSwipe = gesture === "swipe_up" || gesture === "swipe_down" + if (!isSwipe) return + + // Large map is a dev-gated WIP feature, OFF by default. When disabled, + // swipes do nothing (no large-map switch). + if (!this.devSettings.largeMapEnabled) { + console.log(`[TOUCH] swipe ignored — large map disabled (dev toggle off)`) + return + } + + // LOCK: ignore swipes while a show/dismiss transition is mid-flight + // (clear() → settle delay → render). Rapid/accidental repeat swipes + // would otherwise overlap and corrupt the display. + if (this.largeMapTransitioning) { + console.log(`[TOUCH] swipe ignored — large-map transition in flight`) + return + } + + // Toggle: any swipe shows the box; any swipe while it's showing dismisses + // it and brings back the original HUD. + if (!this.largeMapShown) { + console.log(`[TOUCH] swipe → showing large route map`) + this.showLargeMap() // sets largeMapShown + transition lock, replaces, draws + } else { + console.log(`[TOUCH] swipe → dismissing large map → HUD`) + this.largeMapShown = false + // Switch large map → HUD by REPLACING containers in place (no + // full-view clear()/teardown / settle delay). The HUD's maneuver text + // spans the FULL canvas, so repainting it overwrites the centered + // large-map bitmap; refreshHUD also re-pushes the top-right minimap. + // Reset the dedup so the repaint isn't swallowed, then repaint now. + this.lastHudKey = "" + this.lastMinimapPng = null + this.refreshHUD() + } + }), + ) + } + + /** + * Drop out of the swipe-up large-map view: clear the big map off the + * glasses and reset large-map state so the normal HUD pump resumes. Safe to + * call when the large map isn't showing (no-op). Used when a trip ends while + * the large map is up — without this, refreshHUD() early-returns on + * `largeMapShown` and the big map lingers after the trip is over. + */ + private exitLargeMap(): void { + // Release the swipe lock (transitions are synchronous now — no deferred + // render to cancel). + this.largeMapTransitioning = false + if (!this.largeMapShown) return + this.largeMapShown = false + // Erase the large map by overwriting its containers in place (no full-view + // clear()): blank the top-right minimap rect, and overwrite the full-canvas + // maneuver region with empty text (which covers the centered large map). + // The caller (trip arrived/stopped) then paints the end-state HUD via + // refreshHUD, which overwrites the same maneuver region. + this.lastHudKey = "" + this.lastMinimapPng = null + this.display.clearMinimap() + this.display.clearLoadingMessage() // blanks the full-canvas maneuver text region + } + + /** + * Clear the current HUD (minimap bitmap + stats text + maneuver text), then + * render the large map. Sets `largeMapShown` so the HUD pump stops repainting + * over it until the user swipes back down. + */ + private showLargeMap(): void { + if (!this.display.supportsBitmaps) return + this.largeMapShown = true + this.largeMapTransitioning = true // lock out swipes until the render lands + // Switch HUD → large map by REPLACING the specific containers in place, not + // a full-view clear(). The HUD pump is gated off by `largeMapShown`, so + // nothing repaints over us. We: + // • erase the top-right minimap rect (clearMinimap overwrites it blank — + // the large map is a different rect so it wouldn't cover the minimap), + // • overwrite the full-canvas maneuver-text region with the loading line, + // • then draw the large map into its own (centered) rect. + // No async full teardown, so no settle delay / race — the draws just + // overwrite their containers. Reset the dedup so swiping back down repaints. + this.lastHudKey = "" + this.lastMinimapPng = null + this.display.clearMinimap() + // Overwrites the maneuver text region; doubles as "loading" feedback. + this.display.showLoadingMessage("Loading large map") + if (!this.coords) { + // No fix to render — release the lock so the view isn't stuck locked. + this.largeMapTransitioning = false + return + } + const me: LatLng = {lat: this.coords.lat, lng: this.coords.lng} + + // Render the large map now (its own centered rect). Blank the loading text + // first so it doesn't linger over the map. No settle delay needed: there's + // no full-view teardown to wait on — each push overwrites its container. + this.display.clearLoadingMessage() + this.renderLargeMap(me) + this.largeMapTransitioning = false // render landed; release the lock + + // 3. The minimap road cache only covers a tight radius around the user, so + // the far end of the route would have no background streets. Fetch roads + // covering the ENTIRE route bounding box, then re-render. + const route = this.trip.routePoints + if (route && route.length >= 2 && !this.osmFetchInFlight) { + const lats = [...route, me].map((p) => p.lat) + const lngs = [...route, me].map((p) => p.lng) + const center: LatLng = { + lat: (Math.min(...lats) + Math.max(...lats)) / 2, + lng: (Math.min(...lngs) + Math.max(...lngs)) / 2, + } + const halfH = + haversineMeters({lat: Math.min(...lats), lng: center.lng}, {lat: Math.max(...lats), lng: center.lng}) / 2 + const halfW = + haversineMeters({lat: center.lat, lng: Math.min(...lngs)}, {lat: center.lat, lng: Math.max(...lngs)}) / 2 + const fetchRadius = Math.max(halfH, halfW) * 1.3 + 50 + this.osmFetchInFlight = true + fetchOsmRoads(center, fetchRadius) + .then((roads) => { + this.osmRoadsCache = roads + this.osmRoadsCenter = center + if (this.largeMapShown && this.coords) { + this.renderLargeMap({lat: this.coords.lat, lng: this.coords.lng}) + } + }) + .catch((err) => console.log("[LARGE-MAP] road fetch failed:", err)) + .finally(() => { + this.osmFetchInFlight = false + }) + } + } + + /** Render + push the large centered map for the current position. */ + private renderLargeMap(me: LatLng): void { + if (!this.display.supportsBitmaps) { + if (this.largeMapShown) { + this.exitLargeMap() + this.refreshHUD() + } + return + } + const {w, h} = this.display.getBitmapSize(this.OSM_LARGE_MAP_W, this.OSM_LARGE_MAP_H) + const route = this.trip.routePoints + + // Zoom to fit the WHOLE route: center on the route's bounding-box midpoint + // and pick a radius that contains every route point (plus the user), with + // some padding. Falls back to the minimap radius around the user if there's + // no usable route yet. + let center = me + let viewRadiusMeters = this.OSM_MINIMAP_RADIUS_M + if (route && route.length >= 2) { + const pts = [...route, me] + const lats = pts.map((p) => p.lat) + const lngs = pts.map((p) => p.lng) + const minLat = Math.min(...lats) + const maxLat = Math.max(...lats) + const minLng = Math.min(...lngs) + const maxLng = Math.max(...lngs) + center = {lat: (minLat + maxLat) / 2, lng: (minLng + maxLng) / 2} + // Half-extent in meters of the larger axis (renderOsmLineMap fits 2×radius + // into the smaller pixel axis), padded 15% so the path isn't edge-to-edge. + const halfH = haversineMeters({lat: minLat, lng: center.lng}, {lat: maxLat, lng: center.lng}) / 2 + const halfW = haversineMeters({lat: center.lat, lng: minLng}, {lat: center.lat, lng: maxLng}) / 2 + viewRadiusMeters = Math.max(80, Math.max(halfH, halfW) * 1.15) + } + + // "You" arrow heading: the TRUE direction of travel from the user's own + // movement vector (anchor→current, updated every ≥3 m). Fall back to the + // route's forward bearing, then the compass, only until we've actually + // moved enough to measure a real heading. + const routeBearing = nextSegmentBearing(me, route) + const markerHeading = this.moveBearingDeg ?? routeBearing ?? this.heading + const png = renderOsmLineMap(this.osmRoadsCache ?? [], { + center, + width: w, + height: h, + viewRadiusMeters, + lineWidthPx: 2, + route, + marker: markerHeading != null ? {at: me, headingDeg: markerHeading} : null, + }) + console.log( + `[LARGE-MAP] render: roads=${this.osmRoadsCache?.length ?? 0} routePts=${route?.length ?? 0} radius=${Math.round(viewRadiusMeters)}m size=${w}x${h} png=${png ? png.length + "b" : "NULL"}`, + ) + if (png) this.display.showLargeBitmap(png, w, h) + } + + private refreshHUD(): void { + const {status, running, activeDestinationName, maneuver, arrivalSide} = this.trip + + // Audio and display consume the same maneuver derivation. Keep this before + // every display guard so displayless glasses still receive guidance and a + // large-map overlay never pauses spoken directions. + const me = this.coords ? {lat: this.coords.lat, lng: this.coords.lng} : null + const liveDist = + maneuver?.maneuverType === "ARRIVE" + ? remainingRouteMeters(me, this.trip.routePoints) + : liveDistanceToNextTurn(me, this.trip.routePoints, this.trip.routeSteps, remainingRouteMeters, haversineMeters) + const md = deriveManeuverDisplay(maneuver, status, liveDist) + this.audioGuidance.observe({ + status, + running, + routeRevision: this.routeRevision, + pivotIndex: this.upcomingPivot?.index ?? null, + maneuverType: md?.kind ?? null, + instruction: md?.instruction ?? null, + // Turn thresholds stay paired with the native event that supplied the + // type/instruction. ARRIVE is different: md carries the live remaining + // route distance, so its spoken destination countdown stays current. + distanceMeters: selectAudioGuidanceDistance(maneuver?.maneuverType, maneuver?.distanceMeters, md?.distanceMeters), + offRoute: this.offRouteAdvisory, + destinationName: activeDestinationName, + arrivalSide, + travelMode: this.lastStartOpts?.mode ?? "walking", + unitSystem: this.unitSystem, + }) + + if (!this.capabilities.hasDisplay || this.largeMapShown) return + + // Minimap runs first so heading-only updates still refresh the map even + // when the text line below is unchanged (and short-circuits). G1/Z100 + // cannot position or display scene images, so skip the work entirely. + if (this.capabilities.canPosition) this.refreshMinimap() + + let next: string | null = null + let durationMs: number | undefined + // Structured maneuver split for the new 4-slot HUD (arrow bitmap + maneuver + // text box). Populated only on the normal next-turn frame; when set (and + // running), refreshHUD sends the split layout instead of the single-container + // text frame used by the welcome/rerouting/arrived/off-route states. + let maneuverArrow: string | null = null + let maneuverBody: string | null = null + + // The next-turn display, derived from the live `maneuver` event via the + // SHARED helper the phone OrientationCard also uses. Computed once here + // so the glasses HUD and the phone card read the identical instruction / + // distance / arrow — single source of truth, no PivotEngine re-derivation. + // + // We pass a LIVE distance recomputed from this.coords (same shared helper + // + same geometry the phone card uses), so the "In X m" line ticks down on + // every location tick instead of only when a new native maneuver event + // fires. For the ARRIVE leg the relevant distance is to the destination. + // Mirrors the phone-side OrientationCard's pickDisplay() — same + // layout, same source, same precedence. If you tweak one, tweak the + // other or they'll diverge. + if (status === "arrived") { + const at = activeDestinationName ? ` at ${activeDestinationName}` : "" + // Side of the destination: "on your left/right" when we know it, else + // "up ahead" (it's straight in front, not to a side). + const side = arrivalSide ? `, on your ${arrivalSide}` : ", up ahead" + next = `You have arrived${at}${side}` + durationMs = 10_000 + } else if (!running && status !== "rerouting" && !this.hasCompletedTrip) { + // FRESH START ONLY: app just opened, no trip has run yet. Show the + // welcome prompt and leave it up INDEFINITELY (no durationMs → sticky) + // until the user picks a destination and a trip starts, at which point + // `running` flips true and the next-turn HUD takes over. The ~3s + // re-push in the coalescer keeps it on screen even if the G2 tears + // down the page. + // + // Gated on !hasCompletedTrip so that ENDING a navigation (nav:stop sets + // hasCompletedTrip=true) clears the glasses and leaves them blank — + // we do NOT bounce back to the welcome prompt after a trip. `next` + // stays null below, which clears the HUD. + next = "Welcome to Mentra Maps!\nPick a destination to get started." + } else if (status === "rerouting") { + // Mapbox detected the user off-route and is fetching a new route. + next = "Rerouting…" + } else if (this.offRouteAdvisory && running) { + // OFF ROUTE (≥ ADVISORY_M, before Mapbox reroutes). Replace the normal + // instruction + stats entirely (GLASSES ONLY) with "Go back in X m", where + // X is the live perpendicular distance to the route and GROWS the further + // the user strays. This persists until either: + // • Mapbox reroutes (status → "rerouting" above takes over the HUD, then + // the new route's instruction/stats), or + // • the user returns within ADVISORY_M (bucket 0 → md branch restores the + // original instruction + stats). + // We set `next` to ONLY the go-back line; `stats` is suppressed below so + // the bottom box doesn't show the (now irrelevant) trip distance/ETA. + const d = this.offRouteAdvisoryDistanceM + next = d != null ? `Go back\nin ${formatDistance(d, this.unitSystem)}` : "Go back\nto route" + } else if (md) { + // Next-turn HUD. The DISTANCE is driven the SAME way the bottom trip-stats + // box is — recomputed live from this.coords against the route polyline + // every location tick (the bottom box proved accurate + low-latency + + // 1:1 with the phone, while the maneuver event's own distance lagged). So + // we compute the top-line distance HERE from the live position, with the + // same fallback chain the bottom box uses, instead of trusting md's + // (possibly frozen) value. The DIRECTIONS box shows the turn instruction; + // distance/ETA now live in the TOP stats box, so we no longer put + // "In X m" / "Arriving in X m" here. + // + // Now ← only at the turn (urgency cue, not distance) + // Turn left onto Market St ← Mapbox's verbatim instruction + if (md.arriving) { + // Final leg: show the arrival directions (distance is in the top stats box). + maneuverArrow = "↑" + maneuverBody = md.instruction || "Arriving" + next = maneuverBody + } else { + // Directions box: NEXT-TURN distance + instruction (mockup: "56 m" / + // "Turn left onto the walkway"). This next-turn distance is distinct from + // the top box's distance-to-destination, so it belongs here. "Now" + // replaces the distance right at the turn. The ARROW and atTurn come from + // `md` (gated on the EVENT distance), so the glyph/cue always match md.kind. + const dTurn = liveDist ?? md.distanceMeters + const distLine = md.atTurn ? "Now" : dTurn != null ? formatDistance(dTurn, this.unitSystem) : null + maneuverArrow = md.arrow || "↑" + maneuverBody = [distLine, md.instruction].filter(Boolean).join("\n") + next = [md.arrow || "↑", distLine, md.instruction].filter(Boolean).join("\n") + } + } else if (running) { + // Running but no maneuver yet — the brief gap right after Start, before + // Mapbox emits the first step. Normally a neutral "Starting…" with NO + // arrow (there's no turn/direction to point at yet). + // + // WATCHDOG: the maneuver event that clears "Starting…" sometimes never + // arrives (G2 page teardown mid-start, back-to-back route recomputes + // resetting the cursor). If we've been stuck on "Starting…" past the + // threshold AND a computed route is on hand, recover by deriving the line + // from the route's first navigable step instead of hanging forever. + const startedAt = this.startingShownAt || Date.now() + if (this.startingShownAt === 0) this.startingShownAt = startedAt + const stuck = Date.now() - startedAt >= STARTING_WATCHDOG_MS + const firstStep = this.firstNavigableStep() + if (stuck && firstStep) { + const arrow = arrowFor(firstStep.maneuver, null) + const onto = isRealRoadName(firstStep.road) + const dist = + firstStep.distanceMeters > 0 ? `In ${formatDistance(firstStep.distanceMeters, this.unitSystem)}` : null + next = [arrow, onto ? `Onto ${onto}` : null, dist].filter(Boolean).join("\n") || `Starting…` + } else { + next = `Starting…` + } + } else { + // Not running — make sure the watchdog clock resets for the next trip. + this.startingShownAt = 0 + } + // Leaving "Starting…" for any real maneuver/pivot frame clears the watchdog + // so the next stuck-start is timed fresh. + if (next !== "Starting…") this.startingShownAt = 0 + + if (next == null) { + // Nothing to display — wipe whatever frame was last on the + // glasses (the SDK's text HUD persists until cleared/replaced). + // Without this, after `nav:stop` the user keeps seeing the last + // "Arriving in Xm" frame indefinitely because the maneuver got + // cleared but no replacement HUD was ever pushed. + if (this.lastHudKey !== "") { + this.lastHudKey = "" + // clear() wipes the glasses AND the DisplayManager's cached frame + // slots; reset the arrow-encode memo so the next frame re-encodes. + this.lastArrowKey = "" + try { + this.display.clear() + } catch { + /* ignore */ + } + } + return + } + // SINGLE-CONTAINER HUD: cram everything (maneuver block + trip stats) into + // the ONE bottom container — the proven-smooth, low-latency, phone-1:1 path. + // The separate top maneuver box lagged/glitched, so we drop it and blank it. + // Suppress the trip stats while the off-route "Go back in X m" advisory is + // showing — the user isn't on the route, so destination distance/ETA are + // irrelevant; the go-back line owns the whole frame until they return or + // Mapbox reroutes. + const showStats = running && !(this.offRouteAdvisory && status !== "rerouting" && status !== "arrived") + const stats = showStats ? this.buildTripStats() : null + + // Wall-clock time-of-day for the top-LEFT slot (the phone's current time). + // Recomputed every refresh; the ~1s HUD tick keeps it fresh, and it's folded + // into the coalescing keys below so a minute rollover forces a re-push. + const clock = this.buildClock() + + // ── New 4-slot HUD ────────────────────────────────────────────────── + // On the normal next-turn frame, send the arrow bitmap (left) + maneuver + // text box (bottom) + trip-stats box (top) as separate canvas components. + // The minimap (right) was pushed by refreshMinimap() above. Special states + // (welcome/rerouting/arrived/off-route) have no arrow/stats split and fall + // through to the single-container text frame below. + if (maneuverBody != null && running && this.capabilities.canPosition) { + const key = `hud|${maneuverArrow}|${maneuverBody}|${stats ?? ""}|${clock}` + const nowHud = Date.now() + const unchanged = key === this.lastHudKey + if (unchanged && nowHud - this.lastHudAt <= 3000) return + const forced = unchanged // unchanged but >3s: periodic re-push (page teardown recovery) + this.lastHudAt = nowHud + this.lastHudKey = key + + // Compose the whole HUD frame in one render() call. The arrow bitmap is + // re-ENCODED only when the direction changes (or on a forced re-push); + // DisplayManager caches it, so it's present in every frame regardless. + const arrowChanged = forced || maneuverArrow !== this.lastArrowKey + if (arrowChanged) this.lastArrowKey = maneuverArrow ?? "" + this.display.showNavHud({ + arrowBmp: arrowChanged ? renderManeuverArrowBmp(maneuverArrow) : undefined, + maneuver: maneuverBody, + stats: stats ?? "", + clock, + }) + return + } + + // Single-container state (welcome / rerouting / arrived / off-route / "Starting…"). + // No HUD bookkeeping needed: render() replaces the frame, and the cached + // arrow/map slots survive in DisplayManager for when turn-by-turn resumes. + + // Stack the maneuver block over the stats line, blank line between, or just + // one if the other is absent. + const combined = [next, stats].filter(Boolean).join("\n\n") + + // Coalesce on the combined frame so we don't re-push identical content. + // Prefixed "msg|" so a message frame never collides with a "hud|" key. + // Non-positioning displays have a five-line text wall. Omitting the clock + // leaves room for the direction (arrow + distance + instruction) before + // optional trip stats; the old degraded positioned scene put clock/stats + // first and clipped the instruction off the bottom on G1. + const displayClock = this.capabilities.canPosition ? clock : null + const key = `msg|${combined}${durationMs ?? 0}|${displayClock ?? ""}` + // Re-push every ~3s even when unchanged: the G2 frequently tears down our + // EvenHub page (system_exit / dashboard), swallowing a one-time send. + const nowHud = Date.now() + if (key === this.lastHudKey && nowHud - this.lastHudAt <= 3000) return + this.lastHudAt = nowHud + this.lastHudKey = key + + // Render as the "message" frame (positioned at the arrow's left x). The + // frame replaces turn-by-turn entirely; returning to turn-by-turn replaces + // it back. Nothing lingers — render() is the whole screen. + if (this.capabilities.canPosition) { + this.display.showNavMessage(combined, displayClock) + } else { + this.display.showCompactNavHud(next, stats) + } + } + + /** + * The first navigable step of the current route — the first turn the user + * should take. Skips the leading DEPART/CONTINUE/STRAIGHT "walk along this + * road" step and returns the first actual turn. Backs the "Starting…" + * watchdog so a stuck start can show a real instruction. Returns null when + * there's no route step list yet. + */ + private firstNavigableStep(): {road: string | null; maneuver: string; distanceMeters: number} | null { + const steps = this.trip.routeSteps + if (!steps || steps.length === 0) return null + const skip = new Set(["DEPART", "CONTINUE", "STRAIGHT", "NAME_CHANGE"]) + const turn = steps.find((s) => !skip.has((s.maneuver ?? "").toUpperCase())) + return turn ?? steps[0] + } + + /** + * Build the trip-stats line: distance remaining + ETA, e.g. + * "273 m · ⊙ 4 min". Returns null when there's no usable distance. + */ + /** + * The phone's current wall-clock time for the top-left HUD slot, e.g. + * "09:41" — 24-hour, zero-padded, no seconds. Formatted manually rather + * than via toLocaleTimeString, whose Intl options are ignored by Hermes + * (it returns a full "hh:mm:ss AM/PM" string regardless). + */ + private buildClock(): string { + const now = new Date() + const hh = String(now.getHours()).padStart(2, "0") + const mm = String(now.getMinutes()).padStart(2, "0") + return `${hh}:${mm}` + } + + private buildTripStats(): string | null { + const me = this.coords ? {lat: this.coords.lat, lng: this.coords.lng} : null + const distM = + this.trip.maneuver?.distanceToDestinationMeters ?? remainingRouteMeters(me, this.trip.routePoints) ?? undefined + if (distM == null || distM < 0) return null + // Top stats slot: total remaining distance + ETA, e.g. "863 m 11 min" + // (matches the HUD mockup). distM also feeds the ETA fallback when the SDK + // hasn't sent a remaining-time value. + const etaS = this.trip.maneuver?.timeToDestinationSeconds ?? distM / this.FALLBACK_WALKING_M_PER_S + const dist = formatDistance(distM, this.unitSystem) + return etaS >= 0 ? `${dist} ${formatDuration(etaS)}` : dist + } + + /** + * Render and push the 100×100 NORTH-UP minimap (north fixed at top; the + * map never rotates to follow heading — only the position arrow rotates + * to show facing direction). Drawn alongside the text HUD (non-overlapping + * regions of the main view). De-duped on the encoded PNG so we don't + * re-send identical frames while idle. + */ + // OSM-roads minimap: street network around the user's live position, with the + // active route drawn on top. Roads are cached and only re-fetched from Overpass + // when the user moves past a threshold (PoC: fetch-on-move, ~1s lag accepted). + private readonly OSM_MINIMAP_SIZE = 100 // matches the top-right container + // Geographic radius shown in the minimap. CALIBRATED to the pixel size so the + // map scale (meters-per-pixel) stays constant — that's what keeps traveled + // distance reading correctly. The renderer fits 2×radius into the pixel size: + // pxPerMeter = SIZE / (2 × RADIUS) = 100 / 266 ≈ 0.376 px/m + // If you change SIZE, scale RADIUS proportionally or the map zooms and the + // traveled distance looks wrong. + private readonly OSM_MINIMAP_RADIUS_M = 133 + // Preferred large-map dimensions. Device image/canvas limits are applied + // before rasterization and shared with placement (e.g. NIMO uses 200×140). + private readonly OSM_LARGE_MAP_W = 288 + private readonly OSM_LARGE_MAP_H = 140 + private readonly OSM_REFETCH_THRESHOLD_M = 120 + // Walking speed for the ETA fallback when the SDK hasn't sent a remaining-time + // value yet. Mirrors the WebView running drawer's FALLBACK_WALKING_M_PER_S. + private readonly FALLBACK_WALKING_M_PER_S = 1.4 + + // Minimum gap between minimap renders/pushes. Roughly the glasses' usable + // display-update rate; faster than this just burns CPU + BLE for frames the + // user can't perceive. + private readonly MINIMAP_MIN_INTERVAL_MS = 300 + + private refreshMinimap(): void { + if (!this.capabilities.hasDisplay || !this.capabilities.canPosition) return + if (this.largeMapShown) return // large map owns the screen; don't overdraw + if (!this.showMinimap) return + if (!this.trip.running || !this.coords) return + + // Leading-edge throttle: if we rendered recently, don't render now — instead + // schedule ONE trailing render for when the window elapses, so the final + // position after a burst of rapid GPS fixes still reaches the glasses. (A + // trailing render already pending is left as-is; it re-reads the latest + // coords/heading when it fires.) + // A watchdog-forced refresh must render+push synchronously here and now — + // it must NOT go down the throttle's trailing-timer path. That path defers + // the render to a setTimeout that fires AFTER the watchdog's `finally` has + // already reset forceMinimapPush=false, so the deferred render gets dedup'd + // and the bitmap never reaches the glasses (the "since last push" counter + // then climbs forever). Skipping the throttle keeps the force flag live + // through the actual push below. The watchdog only fires after ≥2s idle, so + // there's no real throttle to honor anyway. + const now = Date.now() + const sinceLast = now - this.lastMinimapAt + if (!this.forceMinimapPush && sinceLast < this.MINIMAP_MIN_INTERVAL_MS) { + if (this.minimapTrailingTimer == null) { + this.minimapTrailingTimer = setTimeout(() => { + this.minimapTrailingTimer = null + this.refreshMinimap() + }, this.MINIMAP_MIN_INTERVAL_MS - sinceLast) + } + return + } + this.lastMinimapAt = now + + const me: LatLng = {lat: this.coords.lat, lng: this.coords.lng} + + // Re-fetch roads if we have none yet, or the user has wandered far from the + // cached center. Fetch is async + best-effort; we render with whatever roads + // we currently have (possibly empty on the very first tick). + const movedFar = !this.osmRoadsCenter || haversineMeters(me, this.osmRoadsCenter) > this.OSM_REFETCH_THRESHOLD_M + if (movedFar && !this.osmFetchInFlight) { + this.osmFetchInFlight = true + const fetchCenter = me + fetchOsmRoads(fetchCenter, this.OSM_MINIMAP_RADIUS_M * 2) + .then((roads) => { + this.osmRoadsCache = roads + this.osmRoadsCenter = fetchCenter + console.log( + `[OSM-MINIMAP] fetched ${roads.length} roads around ${fetchCenter.lat.toFixed(5)},${fetchCenter.lng.toFixed(5)}`, + ) + this.refreshMinimap() // redraw now that roads are in + }) + .catch((err) => console.log("[OSM-MINIMAP] fetch failed:", err)) + .finally(() => { + this.osmFetchInFlight = false + }) + } + + // "You" arrow heading: the TRUE direction of travel from the user's own + // movement vector (anchor→current, recomputed every ≥3 m of travel) — no + // longer assuming the arrow points along the route. Fall back to the route's + // forward bearing, then the compass, only until we've moved enough to + // measure a real heading. + const routeBearing = nextSegmentBearing(me, this.trip.routePoints) + const markerHeading = this.moveBearingDeg ?? routeBearing ?? this.heading + // Only draw the route AHEAD of the user: trim the part already walked so + // the line behind the position marker disappears as they progress. + const remainingRoute = remainingRoutePoints(me, this.trip.routePoints) + // Destination = the last point of the FULL route (the route's end), drawn + // as a small circle so the user can see where they're headed. + const fullRoute = this.trip.routePoints + const destination = fullRoute && fullRoute.length > 0 ? fullRoute[fullRoute.length - 1] : null + // NORTH-UP: the minimap is kept fixed with north at the top — it does NOT + // rotate to follow heading. Only the position marker rotates to show which + // way the user is facing (marker.headingDeg). `rotationDeg: 0` locks the + // map orientation north-up regardless of travel direction. + const png = renderOsmLineMap(this.osmRoadsCache ?? [], { + center: me, + width: this.OSM_MINIMAP_SIZE, + height: this.OSM_MINIMAP_SIZE, + viewRadiusMeters: this.OSM_MINIMAP_RADIUS_M, + lineWidthPx: 2, + route: remainingRoute, + destination, + rotationDeg: 0, + marker: markerHeading != null ? {at: me, headingDeg: markerHeading} : null, + }) + // Live trip stats in the bottom-left: distance remaining + ETA, both of which + // decrement as we approach the destination. Pushed BEFORE the minimap + // dedup-return below so a heading/position-only tick (where the map bitmap is + // unchanged) still refreshes the numbers — that's what makes it "stream". + // Positioned text uses its own G2 container, so it doesn't fight the bitmaps. + // Falls back to perpendicular route distance when the SDK hasn't populated + // distanceToDestinationMeters yet. Deduped on content. + const distM = + this.trip.maneuver?.distanceToDestinationMeters ?? remainingRouteMeters(me, this.trip.routePoints) ?? undefined + // ETA: prefer the SDK's mode-aware remaining time; fall back to a + // walking-speed estimate from the distance so the time still shows when the + // SDK value isn't in yet. + const etaS = + this.trip.maneuver?.timeToDestinationSeconds ?? + (distM != null ? distM / this.FALLBACK_WALKING_M_PER_S : undefined) + console.log(`[TRIP-STATS] distM=${distM} etaS=${etaS} (will push: ${distM != null && distM >= 0})`) + if (distM != null && distM >= 0) { + const distStr = formatDistance(distM, this.unitSystem) + // U+2299 ⊙ — confirmed to render in the G2 font (the color clock emoji + // don't). Used as the "time" marker next to the ETA. + const etaStr = etaS != null && etaS >= 0 ? `⊙ ${formatDuration(etaS)}` : null + // Distance and time side by side, e.g. "354 m · ⊙ 5 min". + const stats = etaStr ? `${distStr} · ${etaStr}` : distStr + // Re-push when the content changes OR every ~3s even if unchanged. The G2 + // EvenHub page is frequently torn down/rebuilt ("Glasses shutdown our + // EvenHub page"), which can swallow a one-time send — so a change-only + // dedup leaves the stats container blank until the value next changes + // (which, while stationary, can be a long time). Periodic re-push recovers. + const now = Date.now() + const changed = stats !== this.lastTripStats + const stale = now - this.lastTripStatsAt > 3000 + if (changed || stale) { + this.lastTripStats = stats + this.lastTripStatsAt = now + // Bottom-left trip stats disabled — no longer pushed to the glasses. + // this.display.showTripStats(stats) + } + } + + // Normally we dedup on the rendered bytes — but a watchdog-forced refresh + // (no live updates for a while) must re-push even when the map is unchanged, + // to recover from a torn-down G2 page that may have dropped the last send. + if (!png || (png === this.lastMinimapPng && !this.forceMinimapPush)) { + console.log(`[MINIMAP] skip push (png ${png ? "unchanged" : "null"}, force=${this.forceMinimapPush})`) + return + } + this.lastMinimapPng = png + this.lastMinimapPushAt = Date.now() + console.log(`[MINIMAP] push bitmap (${png.length} b64 chars, force=${this.forceMinimapPush})`) + this.display.showBitmap(png) + } + + /** + * Watchdog tick: if no minimap has been pushed within MINIMAP_WATCHDOG_IDLE_MS + * while a trip is running (and the large map isn't owning the screen), force a + * fresh re-render so the glasses keep getting an updated bitmap even when the + * live GPS/update stream has gone quiet. Idempotent + cheap when updates are + * flowing (the idle check short-circuits). + */ + private minimapWatchdogTick(): void { + if (this.largeMapShown || !this.showMinimap) { + console.log(`[MINIMAP-WATCHDOG] tick skipped (largeMap=${this.largeMapShown} showMinimap=${this.showMinimap})`) + return + } + if (!this.trip.running || !this.coords) { + console.log(`[MINIMAP-WATCHDOG] tick skipped (running=${this.trip.running} coords=${!!this.coords})`) + return + } + const idle = Date.now() - this.lastMinimapPushAt + console.log(`[MINIMAP-WATCHDOG] tick: ${idle}ms since last push (threshold ${this.MINIMAP_WATCHDOG_IDLE_MS}ms)`) + if (idle < this.MINIMAP_WATCHDOG_IDLE_MS) return + console.log(`[MINIMAP-WATCHDOG] no push for ${idle}ms — forcing refresh`) + this.forceMinimapPush = true + try { + this.refreshMinimap() + } finally { + this.forceMinimapPush = false + } + } + + /** Start the recurring minimap watchdog (no-op if already running). */ + private startMinimapWatchdog(): void { + if (!this.capabilities.hasDisplay || !this.capabilities.canPosition) return + if (this.minimapWatchdogTimer != null) return + console.log( + `[MINIMAP-WATCHDOG] started (every ${this.MINIMAP_WATCHDOG_INTERVAL_MS}ms, idle threshold ${this.MINIMAP_WATCHDOG_IDLE_MS}ms)`, + ) + this.minimapWatchdogTimer = setInterval(() => this.minimapWatchdogTick(), this.MINIMAP_WATCHDOG_INTERVAL_MS) + } + + /** Stop the minimap watchdog (no-op if not running). */ + private stopMinimapWatchdog(): void { + if (this.minimapWatchdogTimer == null) return + clearInterval(this.minimapWatchdogTimer) + this.minimapWatchdogTimer = null + } + + // ── Permission + initial fix priming ───────────────────────────────── + + private primeNavigationPermission(): void { + this.session + .waitForReady() + .then(() => this.navigation.requestPermission()) + .then((r) => this.appendLog(`requestPermission: ${JSON.stringify(r)}`)) + .catch((err) => { + console.warn("[NavigationController] requestPermission failed", err) + }) + } + + private seedInitialFix(): void { + this.location + .getOnce() + .then((d) => { + if (this.coords) return + this.coords = {lat: d.lat, lng: d.lng, accuracy: d.accuracy, ts: d.timestamp ?? Date.now()} + this.lastCoordsAt = Date.now() + this.ui.send("nav:coords", this.coords) + }) + .catch(() => { + /* streaming updates will arrive when location stabilises */ + }) + } + + // Recovery for the "dot frozen while distance keeps ticking" bug. The Nav + // SDK's onNavManeuver and onNavLocation streams emit independently — when + // the road-snapped location stream goes quiet but maneuvers keep firing, + // the dot freezes on the map even though we're moving. Use the maneuver + // tick as a heartbeat: if our coords haven't refreshed in STALE_MS, force + // a one-shot CoreLocation fix. The existing onUpdate listener handles the + // result; this just primes the pump. + private heartbeatLocationIfStale(): void { + const STALE_MS = 5_000 + if (this.gettingFix) return + if (Date.now() - this.lastCoordsAt < STALE_MS) return + this.gettingFix = true + this.location + .getOnce() + .then((d) => { + this.coords = {lat: d.lat, lng: d.lng, accuracy: d.accuracy, ts: d.timestamp ?? Date.now()} + this.lastCoordsAt = Date.now() + this.ui.send("nav:coords", this.coords) + }) + .catch(() => { + /* next maneuver tick will retry */ + }) + .finally(() => { + this.gettingFix = false + }) + } + + // ── Off-route threshold + auto-rebuild ─────────────────────────────── + + // Compute perpendicular distance from the current fix to the active + // route polyline. Thresholds: + // 15m → log only (advisory: "consider returning to route") + // 30m → trigger an auto-rebuild to the same destination + // + // Bucket-based so a user wandering at 18m doesn't spam logs every + // tick — only bucket transitions emit. Rebuild gated by two filters + // (see triggerAutoRebuild): + // - REBUILD_MIN_MOVE_M: user must have moved away from where the + // trip started. Suppresses the "user is inside a 50m building" + // case where the initial fix is already >30m off but the user + // hasn't actually deviated yet. + // - REBUILD_COOLDOWN_MS: no rebuild within N seconds of the last + // one, so a fresh route can land before we'd consider firing + // another. + private logOffRouteThresholds(): void { + if (!this.coords) return + const route = this.trip.routePoints + if (!route || route.length < 2) { + this.lastOffRouteBucket = 0 + this.offRouteAdvisory = false + this.offRouteAdvisoryDistanceM = null + return + } + const here = {lat: this.coords.lat, lng: this.coords.lng} + const dist = distanceToPolylineMeters(here, route) + if (dist == null) return + // Two states now: 0 = on route (< ADVISORY_M), 1 = OFF route (≥ ADVISORY_M). + // The "Go back in X m" advisory shows for ANY distance ≥ ADVISORY_M and the + // X GROWS the further the user strays — it persists past the old TRIGGER_M + // band until either Mapbox reroutes (status → "rerouting", which takes over + // the HUD) or the user returns to within ADVISORY_M (back to the original + // instruction). TRIGGER_M is kept only for the diagnostic log threshold. + // Use separate enter/exit thresholds so ordinary GPS jitter near 20m + // cannot flip the HUD between its message and turn-by-turn topologies on + // every fix. Each topology change is structural on G2 and requires a page + // rebuild, so threshold chatter presents as a whole-display refresh. + const bucket = classifyOffRouteAdvisory(dist, this.offRouteAdvisory) ? 1 : 0 + // Keep the advisory distance live so the glasses "Go back in X m" line + // tracks the user every fix — growing as they move away, shrinking as they + // return. Null when on route. + const prevDistance = this.offRouteAdvisoryDistanceM + this.offRouteAdvisoryDistanceM = bucket === 1 ? dist : null + if ( + bucket === this.lastOffRouteBucket && + bucket === 1 && + prevDistance != null && + Math.round(prevDistance) !== Math.round(dist) + ) { + // Same state, distance label changed — refresh so the "Go back in X m" + // number follows the user. Coalescing in refreshHUD swallows identical + // frames so this is cheap. + this.refreshHUD() + } + if (bucket === this.lastOffRouteBucket) return + this.lastOffRouteBucket = bucket + // Advisory is active whenever we're off route. refreshHUD() shows the + // "Go back in X m" frame (glasses only) and the off-route toast on the phone + // while we wait for either a return-to-path or Mapbox's reroute. + this.offRouteAdvisory = bucket === 1 + if (bucket === 0) { + // Returned within the route — back to the original maneuver text. + const msg = `back on route (${dist.toFixed(1)}m) — restoring directions` + console.log(`[NavOffRoute] ${msg}`) + this.appendLog(`[NavOffRoute] ${msg}`) + this.refreshHUD() + } else { + // Off route. Mapbox owns the actual reroute (native); this is just the + // advisory HUD. It persists + the distance grows until reroute or return. + const msg = `> ${OFF_ROUTE_ADVISORY_M}m off route (${dist.toFixed(1)}m) — go back / awaiting native reroute` + console.log(`[NavOffRoute] ${msg}`) + this.appendLog(`[NavOffRoute] ${msg}`) + this.refreshHUD() + } + } + + // NOTE: the former `triggerAutoRebuild()` (JS-side off-route → re-fire + // nav:start) was removed in the Mapbox migration. The host Mapbox + // Navigation SDK owns off-route detection + rerouting natively and pushes + // the rerouted route through `onRoute`, with the `rerouting` status + // arriving via the native update stream. A JS-side rebuild would double + // the reroute and fight the native engine. The off-route distance check + // above is now log + advisory-HUD only. `cancelPendingRebuild()` and the + // rebuild-state fields are retained as harmless no-ops (the timer is + // never armed now) to avoid churn across the many lifecycle call sites. + + // ── Early arrival ──────────────────────────────────────────────────── + + // The Nav SDK fires `arrived` based on its own threshold (straight-line to + // the destination pin). We fire earlier on either of two signals: + // + // 1. ALONG-ROUTE: the user has walked nearly the whole route polyline (the + // grey trail reached the pin) — ≤ ARRIVAL_REMAINING_M of route left + // AND physically near the route endpoint, not just projected onto it. + // + // 2. NEAR THE PIN: the straight-line distance to the destination pin is + // small AND we are near the end of the route. This catches the common + // case where the pin is a building entrance set BACK from the walkable + // path: the user is right beside the destination (perpendicular to it) + // with only a few meters of straight-line distance, but the route + // polyline still continues, so the along-route check alone would not + // fire. The "near the route end" gate is what keeps a route that merely + // passes close to the pin mid-trip (e.g. loops back to the real + // entrance) from arriving early. + // + // Mirrors the SDK arrived handler's state mutation so downstream consumers + // (HUD, UI) see the same shape regardless of which trigger fired. Captures + // the side (left/right) of the pin relative to the final route segment + // *before* clearing routePoints so the HUD can render "on your left|right". + private maybeFireEarlyArrival(): void { + // ≤ this much route polyline remaining → arrived (trail reached the pin). + const ARRIVAL_REMAINING_M = 7 + // Projection clamps to the endpoint even for fixes far beyond/beside it. + // Require real proximity before treating zero remaining as arrival. + const ARRIVAL_NEAR_ROUTE_END_M = 15 + // Straight-line distance to the pin that counts as "we're there". + const ARRIVAL_NEAR_PIN_M = 15 + // Only consider the near-pin trigger once we're this close to the route's + // end, so a mid-trip pass beside the destination can't false-arrive. + const ARRIVAL_NEAR_END_M = 40 + if (!this.coords) return + if (this.trip.status === "arrived" || !this.trip.running) return + const route = this.trip.routePoints + const me = {lat: this.coords.lat, lng: this.coords.lng} + if (!Number.isFinite(me.lat) || !Number.isFinite(me.lng)) return + if (!route || route.length < 2 || route.some((p) => !Number.isFinite(p.lat) || !Number.isFinite(p.lng))) return + const remaining = remainingRouteMeters(me, route) + if (remaining == null || !Number.isFinite(remaining)) return + + const dest = this.trip.activeDestination + const straightLineToPin = dest ? haversineMeters(me, dest) : null + const straightLineToRouteEnd = haversineMeters(me, route[route.length - 1]) + + const alongRouteArrived = remaining <= ARRIVAL_REMAINING_M && straightLineToRouteEnd <= ARRIVAL_NEAR_ROUTE_END_M + const nearPinArrived = + straightLineToPin != null && straightLineToPin <= ARRIVAL_NEAR_PIN_M && remaining <= ARRIVAL_NEAR_END_M + if (!alongRouteArrived && !nearPinArrived) return + + const side = sideOfFinalSegment(route, this.trip.activeDestination) + const why = alongRouteArrived + ? `${remaining.toFixed(1)}m of route remaining` + : `${straightLineToPin?.toFixed(1)}m from pin, ${remaining.toFixed(1)}m route left` + this.appendLog(`ARRIVED (early, ${why})`) + this.trip = { + ...this.trip, + status: "arrived", + running: false, + maneuver: null, + activeDestination: null, + routePoints: null, + routeSteps: null, + offRouteAt: null, + arrivalSide: side, + } + this.hasCompletedTrip = true + this.activePivot = null + this.upcomingPivot = null + this.cancelPendingRebuild() + this.tripStartCoords = null + this.lastStartOpts = null + this.lastAutoRebuildAt = 0 + this.lastOffRouteBucket = 0 + this.offRouteAdvisory = false + this.offRouteAdvisoryDistanceM = null + this.cachedInstructions = null + try { + this.navigation.stop() + } catch { + /* ignore */ + } + // If the large map is up at arrival, drop out of it so the "You have + // arrived" HUD can actually paint — refreshHUD() early-returns while + // largeMapShown, and the caller refreshes the HUD right after this returns. + // Mirrors the SDK arrived handler, which also exits the large map here. + this.exitLargeMap() + this.ui.send("nav:trip-state", this.trip) + } + + private cancelPendingRebuild(): void { + if (this.pendingRebuildTimer) { + clearTimeout(this.pendingRebuildTimer) + this.pendingRebuildTimer = null + } + } + + // ── Log + maneuver helpers ─────────────────────────────────────────── + + private appendLog(line: string): void { + const entry: LogEntry = {id: ++this.logSeq, ts: Date.now(), line} + this.log = [entry, ...this.log].slice(0, 100) + this.ui.send("nav:log-append", entry) + } + + /** + * Find the Google `navigationInstruction` string for the live step + * whose start coords match the given pivot, by index match on + * `(lat, lng)`. Returns null when the toggle is off, when no cached + * instructions are available, or when the pivot can't be matched to + * a step (rare — usually means a reroute landed and the silent + * refetch hasn't completed yet). + */ + private lookupRawInstructionForPivot(pivot: Pivot): string | null { + const steps = this.trip.routeSteps + if (!steps || steps.length === 0) return null + // Pivots and steps share lat/lng to ≥5 decimal places (the SDK + // forwards them through unmodified). Match on a small epsilon + // rather than equality to absorb float reformatting. + const EPS = 1e-5 + for (const s of steps) { + if (Math.abs(s.lat - pivot.lat) < EPS && Math.abs(s.lng - pivot.lng) < EPS) { + return s.instruction || null + } + } + return null + } + + /** + * Silent Routes API refetch triggered after a reroute when the + * `useRawInstructions` debug toggle is on. Pulls fresh Google + * `navigationInstruction` strings against the current origin (live + * coords) and the active destination so the maneuver card / glasses + * HUD can keep showing Google's verbatim text through reroutes. + * Re-emits `nav:route` and `nav:trip-state` with the zipped steps so + * the UI picks up the refreshed strings. + */ + private async refetchInstructionsForLiveRoute(expectedStepCount: number): Promise { + if (this.refetchingInstructions) return + const origin = this.coords ? {lat: this.coords.lat, lng: this.coords.lng} : null + const dest = this.trip.activeDestination + if (!origin || !dest) return + this.refetchingInstructions = true + try { + const res = await this.navigation.computeRoute({ + origin, + stops: [dest], + mode: this.lastStartOpts?.mode ?? "walking", + }) + const steps = res.routes?.[0]?.steps + if (!steps || steps.length === 0) return + // Strip the trailing "Destination will be on the left/right" hint, + // same as the onRoute cache path — this refetch path was leaking + // it straight into the HUD instructions. + this.cachedInstructions = steps.map((s) => cleanInstruction(s.instruction)) + // Re-zip into the current live routeSteps so the UI updates. + const live = this.trip.routeSteps + if (live && live.length > 0) { + const merged = live.map((s, i) => ({ + ...s, + instruction: + this.cachedInstructions && i < this.cachedInstructions.length ? this.cachedInstructions[i] || null : null, + })) + this.trip = {...this.trip, routeSteps: merged} + this.ui.send("nav:route", {points: this.trip.routePoints ?? [], steps: merged}) + this.ui.send("nav:trip-state", this.trip) + this.refreshHUD() + } + if (steps.length !== expectedStepCount) { + this.appendLog(`raw-instructions: refetch step count ${steps.length} ≠ live ${expectedStepCount}`) + } + } catch (err) { + this.appendLog(`raw-instructions refetch failed: ${err instanceof Error ? err.message : String(err)}`) + } finally { + this.refetchingInstructions = false + } + } + + private formatUpdate(u: NavUpdate): string { + switch (u.kind) { + case "maneuver": + return `MANEUVER ${u.maneuverType} dist=${u.distanceMeters.toFixed(0)}m` + case "off_route": + return `OFF_ROUTE ${Math.round(u.offRouteDistanceMeters)}m off` + case "rerouting": + return "REROUTING" + case "arrived": + return "ARRIVED" + case "error": + return `ERROR ${u.message}` + default: + return `UPDATE ${(u as {kind?: string}).kind ?? "?"}` + } + } + + // ── Snapshot + dispose ─────────────────────────────────────────────── + + private buildSnapshot(): NavSnapshot { + return { + coords: this.coords, + heading: this.heading, + trip: this.trip, + activePivot: this.activePivot, + upcomingPivot: this.upcomingPivot, + log: [...this.log], + devSettings: this.devSettings, + unitSystem: this.unitSystem, + voiceGuidanceMode: this.voiceGuidanceMode, + capabilities: this.capabilities, + } + } + + /** + * Load the persisted distance-unit preference on startup and, if it + * differs from the metric default, broadcast it so the UI (and the + * glasses HUD on the next refresh) pick it up. Fire-and-forget: the + * snapshot already carries the current value, so a slow storage read + * just means the UI briefly shows metric before the stored choice lands. + */ + private loadUnitSystem(): void { + this.storage + .getUnitSystem() + .then((unit) => { + if (unit === this.unitSystem) return + this.unitSystem = unit + this.ui.send("nav:units-update", {unitSystem: unit}) + this.refreshHUD() + }) + .catch((err) => { + this.appendLog(`unit-system load failed: ${err instanceof Error ? err.message : String(err)}`) + }) + } + + private dispose(): void { + this.audioGuidance.dispose() + this.cancelPendingRebuild() + this.stopMinimapWatchdog() + if (this.minimapTrailingTimer != null) { + clearTimeout(this.minimapTrailingTimer) + this.minimapTrailingTimer = null + } + try { + this.navigation.stop() + } catch { + /* ignore */ + } + if (this.capabilities.hasDisplay) { + try { + this.display.clear() + } catch { + /* ignore */ + } + } + for (const u of this.unsubs) { + try { + u() + } catch { + /* ignore */ + } + } + this.unsubs = [] + } +} + +// ── Module helpers ───────────────────────────────────────────────────── + +function isRealRoadName(s: string | undefined | null): string | null { + if (!s) return null + if (/^Pivot \d+$/i.test(s)) return null + return s +} + +/** + * Glasses HUD direction arrow for a maneuver. Picks a Unicode glyph + * that visually matches the upcoming turn — sharper bends get the + * curved arrows, gentle turns get the diagonals, U-turns get the + * loopback. Falls back to the pivot's `direction` field (left/right) + * when the maneuver string isn't one we recognize, and ultimately to + * a straight-ahead `↑`. + */ +function arrowFor(maneuver: string | null | undefined, direction: "left" | "right" | null | undefined): string { + // Plain arrow glyphs only — the corner-curve variants (↰ ↱) don't + // render on the glasses font. Anything left-ish → ←, right-ish → →, + // straight / continue / depart / unknown → ↑. + const m = (maneuver ?? "").toUpperCase() + if (m.includes("LEFT")) return "←" + if (m.includes("RIGHT")) return "→" + if (direction === "left") return "←" + if (direction === "right") return "→" + return "↑" +} + +/** + * Walking pivot radius (meters). Default SDK walking radius is 7m, + * which is tight enough that crossing to the opposite sidewalk at a + * 4-way puts you outside the at-turn zone and `onPivot.entered` + * never fires. 14m covers all four corners of a typical urban + * intersection without being so wide it misfires on adjacent blocks + * (block length ≈ 80m). Set as a single static value because the SDK + * has no runtime radius setter — same value used for enter and exit. + */ +/** Valid travel modes for the start_navigation action (mirrors TravelMode). */ +const MODES = new Set(["walking", "driving", "cycling", "two_wheeler"]) + +const PIVOT_RADIUS_M_WALKING = 14 + +// Distance at which the HUD's directional arrow flips from ↑ +// (straight ahead) to ←/→ (the actual turn). Locked to the pivot +// radius itself so the arrow never claims "turn now" further out +// than the SDK considers you to be at the turn. Note: in practice +// crossing this threshold also lands the user in the at-pivot +// "Now / Turn right onto X" HUD frame, which doesn't render the +// arrow line — so the ←/→ glyph effectively never shows on screen +// at this setting. ↑ is what the user sees the entire approach. +const ARROW_APPROACH_M_WALKING = PIVOT_RADIUS_M_WALKING + +/** + * Merge the trip-wide pivot radius default into a StartNavigationOptions + * payload. Preserves any caller-supplied `pivots` block so an explicit + * override from the UI still wins. + */ +function withPivotDefaults(opts: T): T { + return { + ...opts, + pivots: { + radiusMeters: PIVOT_RADIUS_M_WALKING, + ...(opts.pivots ?? {}), + }, + } +} + +// Off-route advisory thresholds (meters): how far off the route polyline the +// user must be before the glasses show "Go back in X m". Enter at 20m so +// opposite-sidewalk crossings at typical urban 4-way intersections don't read +// as deviations — walking the far curb across a 4-lane road (~15m wide incl. +// parking) lands ~12-18m from the route polyline, just under this band. Once +// active, require a fix below 15m before clearing it. This hysteresis prevents +// GPS noise around 20m from repeatedly changing the G2 page structure. +const OFF_ROUTE_ADVISORY_M = 20 +const OFF_ROUTE_RECOVERY_M = 15 + +export function classifyOffRouteAdvisory(distanceMeters: number, advisoryActive: boolean): boolean { + return advisoryActive ? distanceMeters >= OFF_ROUTE_RECOVERY_M : distanceMeters >= OFF_ROUTE_ADVISORY_M +} + +// How long the HUD may sit on "Starting…" (running, no maneuver event yet) +// before the watchdog derives the first instruction from the route's steps. +// Long enough that a normal start (maneuver event lands within a second or two) +// never trips it; short enough that a genuinely stuck start recovers quickly. +const STARTING_WATCHDOG_MS = 6000 + +/** + * Strip the trailing arrival-side hint Google's Routes API appends to + * the final step's instruction string (e.g. + * "Turn right onto Octavia St | Destination will be on the left" + * becomes + * "Turn right onto Octavia St" + * ). The pipe is the canonical delimiter, but we also handle the + * occasional period-separated variant. Returns empty string for null + * / undefined so the cache zip stays length-aligned with the SDK's + * live step list. + */ +function cleanInstruction(raw: string | null | undefined): string { + if (!raw) return "" + // Remove "Destination will be on the left/right" (with or without + // a preceding " | " or ". " delimiter). Trim trailing whitespace + // and stray punctuation left behind by the removal. + return raw.replace(/\s*[|.]?\s*(?:your\s+)?destination will be on the (left|right)\s*\.?\s*$/i, "").trim() +} + +/** + * Diagnostic log fired whenever the live trip's onRoute event lands. + * Mirrors the `[NavPreview]` block the miniapp prints during preview, + * so we can eyeball-compare preview vs live for the same destination. + * + * Post-Phase-2 the route this sees should be REST-derived (synthetic + * onRoute from navigation.start). Reroutes still fall through the + * native path until Phase 3 — when those land here, the polyline and + * step shape are the Nav SDK's, which is exactly what we want to + * spot. + */ +function logLiveRoute(route: NavRoute): void { + const steps = route.steps ?? [] + const polyline = route.points ?? [] + const annotated = steps.map((s, i) => ({stepIdx: i, name: s.road ?? null})) + const roads: string[] = [] + for (const a of annotated) { + if (!a.name) continue + if (roads.length > 0 && roads[roads.length - 1].toLowerCase() === a.name.toLowerCase()) continue + roads.push(a.name) + } + console.log(`[NavLive] roads: ${roads.join(" → ")}`) + console.log( + `[NavLive] resolution:\n` + annotated.map((a) => ` step ${a.stepIdx} → ${a.name ?? "(none)"}`).join("\n"), + ) + console.log( + `[NavLive] steps:\n` + + steps + .map((s, i) => ` step ${i}: ${s.road ?? "(unnamed)"} | ${s.maneuver ?? "—"} | ${s.distanceMeters}m`) + .join("\n"), + ) + const stride = Math.max(1, Math.ceil(polyline.length / 30)) + const sampled = polyline.filter((_, i) => i % stride === 0 || i === polyline.length - 1) + console.log( + `[NavLive] polyline (${polyline.length} pts, showing ${sampled.length}):\n` + + sampled.map((p, i) => ` ${i}: ${p.lat.toFixed(5)}, ${p.lng.toFixed(5)}`).join("\n"), + ) + // Turn list derived from road→road transitions, same logic the + // preview block uses minus the polyline-bend filter (we trust the + // SDK's resolved step list at this point). + const turns: string[] = [] + for (let i = 0; i < annotated.length - 1; i++) { + const here = annotated[i] + const next = annotated[i + 1] + if (!here.name || !next.name) continue + if (here.name.toLowerCase() === next.name.toLowerCase()) continue + const junction = steps[here.stepIdx] + turns.push( + ` ${turns.length}: ${here.name} → ${next.name} @ (${junction.lat.toFixed(5)}, ${junction.lng.toFixed(5)})`, + ) + } + console.log(`[NavLive] turns (${turns.length}):\n${turns.join("\n")}`) +} diff --git a/miniapps/navigation/src/background/actions/savedAddressActions.ts b/miniapps/navigation/src/background/actions/savedAddressActions.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf325c190abd86cf2095e325defab9178963cf6b --- /dev/null +++ b/miniapps/navigation/src/background/actions/savedAddressActions.ts @@ -0,0 +1,68 @@ +import type {PlaceDetails, SavedPlace, SavedPlaceType} from "../lib/places" + +const SAVED_ADDRESS_TYPES = ["home", "work"] as const + +type SavedAddressStorage = { + getAllSavedPlaces(): Promise + addSavedPlace(place: SavedPlace): Promise +} + +export type SavedAddress = { + type: SavedPlaceType + name: string + address: string + latitude: number + longitude: number +} + +export type ResolveSavedAddress = (query: string) => Promise + +/** Return only the fixed Home/Work slots, in a stable order for action callers. */ +export async function getSavedAddresses(storage: SavedAddressStorage): Promise<{addresses: SavedAddress[]}> { + const savedPlaces = await storage.getAllSavedPlaces() + const addresses = SAVED_ADDRESS_TYPES.flatMap((type) => { + const place = savedPlaces.find((candidate) => candidate.type === type) + return place ? [toSavedAddress(place, type)] : [] + }) + return {addresses} +} + +/** Resolve and replace one fixed saved-address slot. */ +export async function setSavedAddress( + params: Record, + storage: SavedAddressStorage, + resolveAddress: ResolveSavedAddress, +): Promise<{address: SavedAddress}> { + const type = params.type + if (type !== "home" && type !== "work") { + throw new Error("set_saved_address: 'type' must be 'home' or 'work'") + } + + if (typeof params.address !== "string" || !params.address.trim()) { + throw new Error("set_saved_address: 'address' is required and must be a non-empty string") + } + + const query = params.address.trim() + const place = await resolveAddress(query) + if (!place) { + throw new Error(`set_saved_address: couldn't find a place matching "${query}"`) + } + + const savedPlace: SavedPlace = { + ...place, + type, + savedName: type === "home" ? "Home" : "Work", + } + await storage.addSavedPlace(savedPlace) + return {address: toSavedAddress(savedPlace, type)} +} + +function toSavedAddress(place: SavedPlace, type: SavedPlaceType): SavedAddress { + return { + type, + name: place.name, + address: place.address, + latitude: place.lat, + longitude: place.lng, + } +} diff --git a/miniapps/navigation/src/background/index.ts b/miniapps/navigation/src/background/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..c042e3b4e21e4fc553489330aed2b89b74e0b631 --- /dev/null +++ b/miniapps/navigation/src/background/index.ts @@ -0,0 +1,16 @@ +/** + * Background JSContext entry point — Mentra Map miniapp. + * + * Constructed once by the MentraOS host inside the per-miniapp JSContext. + * `registerMiniapp(...)` wires the handler to fire after CONNECT lands; + * the NavigationController instantiated here lives for the entire + * session, surviving WebView open/close cycles. + */ + +import {registerMiniapp} from "@mentra/miniapp/background" + +import {NavigationController} from "./NavigationController" + +registerMiniapp((session) => { + new NavigationController(session).start() +}) diff --git a/miniapps/navigation/src/background/lib/ArrowRenderer.ts b/miniapps/navigation/src/background/lib/ArrowRenderer.ts new file mode 100644 index 0000000000000000000000000000000000000000..67556632a9e40fb00c34213615a360ea5fe0d97f --- /dev/null +++ b/miniapps/navigation/src/background/lib/ArrowRenderer.ts @@ -0,0 +1,94 @@ +/** + * ArrowRenderer — rasterizes a turn-direction arrow into a 1-bit BMP for the + * glasses HUD's left "arrow" slot. + * + * Dependency-free (runs in the background JSContext). Draws a canonical + * up-pointing arrow (filled shaft + head) and rotates it to the maneuver + * direction by sampling each output pixel in arrow-local space. Polarity + * matches MinimapRenderer: feature = 255 (BOLD), background = 0, so it survives + * the phone's invert + dither the same way the minimap does. + */ + +import {encodeBmpBase64} from "./bmp" + +const BG = 0 +const INK = 255 + +/** + * Clockwise angle (radians, 0 = up) for a maneuver. Accepts either the arrow + * glyph the HUD already computes (↑ ↗ → …) or a Mapbox-style maneuver string + * ("turn-left", "TURN_RIGHT", "uturn", "slight left", …). Unknown → straight up. + */ +export function maneuverAngleRad(maneuver: string | null | undefined): number { + const deg = maneuverAngleDeg(maneuver) + return (deg * Math.PI) / 180 +} + +function maneuverAngleDeg(maneuver: string | null | undefined): number { + if (!maneuver) return 0 + const m = maneuver.toLowerCase() + + // Arrow glyphs the HUD already uses. + if (maneuver.includes("↑")) return 0 + if (maneuver.includes("↗")) return 45 + if (maneuver.includes("→")) return 90 + if (maneuver.includes("↘")) return 135 + if (maneuver.includes("↓")) return 180 + if (maneuver.includes("↙")) return 225 + if (maneuver.includes("←")) return 270 + if (maneuver.includes("↖")) return 315 + if (maneuver.includes("↩") || maneuver.includes("⤵")) return 180 // u-turn + + // Text maneuver descriptors. + if (m.includes("uturn") || m.includes("u-turn")) return 180 + const slight = m.includes("slight") + const sharp = m.includes("sharp") + if (m.includes("left")) return slight ? 315 : sharp ? 225 : 270 + if (m.includes("right")) return slight ? 45 : sharp ? 135 : 90 + return 0 // straight / depart / continue / arrive +} + +/** Is (lx, ly) inside the canonical up-pointing arrow drawn in an S×S box? */ +function insideUpArrow(lx: number, ly: number, s: number): boolean { + const tipY = -0.42 * s // arrowhead tip (up) + const headBaseY = -0.04 * s // where the head meets the shaft + const headHalf = 0.3 * s // half-width of the head at its base + const shaftHalf = 0.11 * s + const shaftTopY = -0.12 * s + const shaftBotY = 0.42 * s + + // Head: triangle tapering from the base up to the tip. + if (ly >= tipY && ly <= headBaseY) { + const t = (ly - tipY) / (headBaseY - tipY) // 0 at tip → 1 at base + if (Math.abs(lx) <= headHalf * t) return true + } + // Shaft: rectangle. + if (ly >= shaftTopY && ly <= shaftBotY && Math.abs(lx) <= shaftHalf) return true + return false +} + +/** + * Render a `size`×`size` arrow BMP pointing in the maneuver's direction. + * Returns a base64 BMP for a `session.display.render()` image element. + */ +export function renderManeuverArrowBmp(maneuver: string | null | undefined, size = 40): string { + const s = Math.max(8, Math.round(size)) + const gray = new Uint8Array(s * s).fill(BG) + const c = (s - 1) / 2 + const theta = maneuverAngleRad(maneuver) + const cosT = Math.cos(theta) + const sinT = Math.sin(theta) + + for (let py = 0; py < s; py++) { + for (let px = 0; px < s; px++) { + const dx = px - c + const dy = py - c + // Rotate the sample point by -theta into arrow-local space (y-down screen + // coords): theta measured clockwise from up, so theta=90 points right. + const lx = dx * cosT + dy * sinT + const ly = -dx * sinT + dy * cosT + if (insideUpArrow(lx, ly, s)) gray[py * s + px] = INK + } + } + return encodeBmpBase64(gray, s, s) +} diff --git a/miniapps/navigation/src/background/lib/MinimapRenderer.ts b/miniapps/navigation/src/background/lib/MinimapRenderer.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c7cebeedf574de5c68eaf044d5ea464e5131e1f --- /dev/null +++ b/miniapps/navigation/src/background/lib/MinimapRenderer.ts @@ -0,0 +1,254 @@ +/** + * MinimapRenderer — rasterizes a small heading-up minimap into an 8-bit + * grayscale BMP for the glasses HUD. Pure JS (no DOM/canvas): we draw into a + * raw 1-byte-per-pixel buffer and hand it to the BMP encoder. + * + * We have no street/tile data in the background JSContext, so the minimap is + * built entirely from what the trip already gives us — the user's position + + * heading, the route polyline, and the upcoming turn. To make that read like + * a map rather than a bare squiggle we add: + * - heading-up orientation (the device-forward axis always points up), + * - concentric distance rings (25 m / 50 m) for a sense of scale, + * - a rotating "N" tick so north is still findable, + * - the route split into traveled (dim) vs. remaining (bold), + * - crosswalk ticks where the route briefly leaves the sidewalk, + * - the upcoming-turn marker and the centered user arrow. + * + * Grays: the encoder is 8-bit, so we use a few levels — BOLD for the live + * route/arrow, DIM for the traveled trail, FAINT for rings/north furniture. + */ + +import {encodeBmpBase64} from "./bmp" +import {detectCrossings, haversineMeters, perpDistanceMeters, type LatLng} from "./geometry" + +export type MinimapInput = { + coords: LatLng | null + heading: number | null // degrees, 0 = North + routePoints: LatLng[] | null + upcomingPivot: LatLng | null +} + +// How many meters from the user the minimap edge represents. The user +// is centered, so the visible square is ~2 * VIEW_RADIUS_M on a side. +export const VIEW_RADIUS_M = 80 + +// Grayscale levels (0 = black background ... 255 = white-hot). +const WHITE = 0 // background +const FAINT = 90 // rings, north furniture +const DIM = 150 // already-traveled route +const BOLD = 255 // live route, arrow, markers + +// Distance rings drawn for scale (meters from the user). +const RING_RADII_M = [25, 50] + +/** Equirectangular projection to local meters, user at origin. */ +function toLocalMeters(p: LatLng, origin: LatLng): {x: number; y: number} { + const mPerDegLat = 111_320 + const mPerDegLng = 111_320 * Math.cos((origin.lat * Math.PI) / 180) + return { + x: (p.lng - origin.lng) * mPerDegLng, // east+ + y: (p.lat - origin.lat) * mPerDegLat, // north+ + } +} + +class Raster { + readonly buf: Uint8Array + constructor(readonly size: number) { + this.buf = new Uint8Array(size * size) // 8-bit grayscale, 1 byte/px + this.buf.fill(WHITE) + } + + set(x: number, y: number, v: number): void { + if (x < 0 || y < 0 || x >= this.size || y >= this.size) return + this.buf[y * this.size + x] = v + } + + /** Filled disc — used as a brush so lines/markers have thickness. */ + disc(cx: number, cy: number, r: number, v: number): void { + const r2 = r * r + for (let dy = -r; dy <= r; dy++) { + for (let dx = -r; dx <= r; dx++) { + if (dx * dx + dy * dy <= r2) this.set(cx + dx, cy + dy, v) + } + } + } + + /** Thick line via a disc brush stepped along the segment (Bresenham). */ + line(x0: number, y0: number, x1: number, y1: number, v: number, thickness: number): void { + x0 = Math.round(x0) + y0 = Math.round(y0) + x1 = Math.round(x1) + y1 = Math.round(y1) + const r = Math.max(0, Math.floor(thickness / 2)) + const dx = Math.abs(x1 - x0) + const dy = -Math.abs(y1 - y0) + const sx = x0 < x1 ? 1 : -1 + const sy = y0 < y1 ? 1 : -1 + let err = dx + dy + for (;;) { + this.disc(x0, y0, r, v) + if (x0 === x1 && y0 === y1) break + const e2 = 2 * err + if (e2 >= dy) { + err += dy + x0 += sx + } + if (e2 <= dx) { + err += dx + y0 += sy + } + } + } + + /** 1px circle outline (midpoint algorithm) — used for the distance rings. */ + circle(cx: number, cy: number, r: number, v: number): void { + if (r < 1) return + let x = r + let y = 0 + let err = 1 - r + const plot8 = (px: number, py: number) => { + this.set(cx + px, cy + py, v) + this.set(cx - px, cy + py, v) + this.set(cx + px, cy - py, v) + this.set(cx - px, cy - py, v) + this.set(cx + py, cy + px, v) + this.set(cx - py, cy + px, v) + this.set(cx + py, cy - px, v) + this.set(cx - py, cy - px, v) + } + while (x >= y) { + plot8(x, y) + y++ + if (err < 0) { + err += 2 * y + 1 + } else { + x-- + err += 2 * (y - x) + 1 + } + } + } + + /** Filled triangle (scanline fill) — the user arrow. */ + triangle( + ax: number, + ay: number, + bx: number, + by: number, + cx: number, + cy: number, + v: number, + ): void { + const minY = Math.floor(Math.min(ay, by, cy)) + const maxY = Math.ceil(Math.max(ay, by, cy)) + const area = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay) + if (area === 0) return + for (let y = minY; y <= maxY; y++) { + for (let x = Math.floor(Math.min(ax, bx, cx)); x <= Math.ceil(Math.max(ax, bx, cx)); x++) { + // Barycentric inside-test. + const w0 = (bx - ax) * (y - ay) - (by - ay) * (x - ax) + const w1 = (cx - bx) * (y - by) - (cy - by) * (x - bx) + const w2 = (ax - cx) * (y - cy) - (ay - cy) * (x - cx) + if ((w0 >= 0 && w1 >= 0 && w2 >= 0) || (w0 <= 0 && w1 <= 0 && w2 <= 0)) { + this.set(x, y, v) + } + } + } + } +} + +/** Index of the route segment whose perpendicular distance to `me` is least. */ +function nearestSegmentIndex(me: LatLng, route: LatLng[]): number { + let bestIdx = 0 + let bestDist = Infinity + for (let i = 0; i < route.length - 1; i++) { + const d = perpDistanceMeters(me, route[i], route[i + 1]) + if (d < bestDist) { + bestDist = d + bestIdx = i + } + } + return bestIdx +} + +/** + * Render the minimap. Returns a base64 BMP, or null when there's no + * position fix yet (nothing meaningful to draw). + */ +export function renderMinimap(input: MinimapInput, size = 100): string | null { + const {coords, heading, routePoints, upcomingPivot} = input + if (!coords) return null + + const r = new Raster(size) + const center = (size - 1) / 2 + const metersPerPx = VIEW_RADIUS_M / center + + // Heading-up: rotate local (east, north) by -heading so the device-forward + // axis maps to screen-up. Screen y grows downward, so forward maps to -y. + const h = ((heading ?? 0) * Math.PI) / 180 + const sinH = Math.sin(h) + const cosH = Math.cos(h) + + const project = (p: LatLng): {x: number; y: number} => { + const m = toLocalMeters(p, coords) + const east = m.x + const north = m.y + const rx = east * cosH - north * sinH + const ry = east * sinH + north * cosH + // rx = right of user, ry = forward of user. Map forward to up (-y). + return { + x: center + rx / metersPerPx, + y: center - ry / metersPerPx, + } + } + + // Corner brackets instead of a full border — short dashes meeting at each + // corner (drawn before the route so the route renders on top). Inset by 1px. + const lo = 1 + const hi = size - 2 + const len = Math.max(4, Math.round(size * 0.18)) // dash length per arm + r.line(lo, lo, lo + len, lo, FAINT, 2) + r.line(lo, lo, lo, lo + len, FAINT, 2) + r.line(hi, lo, hi - len, lo, FAINT, 2) + r.line(hi, lo, hi, lo + len, FAINT, 2) + r.line(lo, hi, lo + len, hi, FAINT, 2) + r.line(lo, hi, lo, hi - len, FAINT, 2) + r.line(hi, hi, hi - len, hi, FAINT, 2) + r.line(hi, hi, hi, hi - len, FAINT, 2) + + // Route polyline, split into traveled (dim) and remaining (bold) at the + // segment closest to the user, so the path ahead stands out. + if (routePoints && routePoints.length >= 2) { + const splitIdx = nearestSegmentIndex(coords, routePoints) + let prev = project(routePoints[0]!) + for (let i = 1; i < routePoints.length; i++) { + const cur = project(routePoints[i]!) + const traveled = i - 1 < splitIdx + r.line(prev.x, prev.y, cur.x, cur.y, traveled ? DIM : BOLD, traveled ? 2 : 3) + prev = cur + } + + // Crosswalk ticks: small bold dots where the route crosses a road. + for (const c of detectCrossings(routePoints)) { + const mid = {lat: (c.start.lat + c.end.lat) / 2, lng: (c.start.lng + c.end.lng) / 2} + const p = project(mid) + r.disc(Math.round(p.x), Math.round(p.y), 1, BOLD) + } + } + + // Upcoming-turn marker (filled disc), only when it's within view. + if (upcomingPivot && haversineMeters(coords, upcomingPivot) <= VIEW_RADIUS_M) { + const p = project(upcomingPivot) + r.disc(Math.round(p.x), Math.round(p.y), 3, BOLD) + } + + // User arrow at center, pointing up (heading-up frame). + const ax = center + const ay = center - 9 // tip + const bx = center - 6 + const by = center + 7 // bottom-left + const cx = center + 6 + const cy = center + 7 // bottom-right + r.triangle(ax, ay, bx, by, cx, cy, BOLD) + + return encodeBmpBase64(r.buf, size, size) +} diff --git a/miniapps/navigation/src/background/lib/OsmLineMapRenderer.ts b/miniapps/navigation/src/background/lib/OsmLineMapRenderer.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf37b2f85831b09dbbb70d748d56edfb761499ca --- /dev/null +++ b/miniapps/navigation/src/background/lib/OsmLineMapRenderer.ts @@ -0,0 +1,407 @@ +/** + * OsmLineMapRenderer — PoC: draw the bare road network around a point as a + * two-tone line map for the glasses. + * + * Pipeline: Overpass (live, DEV ONLY) → highway ways as lat/lng polylines → + * equirectangular projection to pixels → thick Bresenham raster into an 8-bit + * buffer → encodeBmpBase64. Mirrors MinimapRenderer's Raster/projection so the + * two can converge later. + * + * ⚠️ Uses the public Overpass API directly — fine for a dev proof-of-concept, + * NOT for production (OSM fair-use). See issues/barebones-osm-line-map.md for + * the real offline-extract pipeline. + */ + +import {encodeBmpBase64} from "./bmp" +import type {LatLng} from "./geometry" + +const BLACK = 0 // background +const ROAD = 77 // road centerline (70% dimmer ≈ 30% brightness, barely visible so the route dominates) +const ROUTE = 255 // active route overlay (white-hot) +const MARKER = 255 // heading arrow fill (white-hot, drawn on top of everything) +const MARKER_OUTLINE = 0 // heading arrow outline (black halo so it reads over the white route) +const BORDER = 255 // corner-bracket edge marks (white, indicate the bitmap bounds) + +/** Equirectangular projection to local meters, origin-centered. */ +function toLocalMeters(p: LatLng, origin: LatLng): {x: number; y: number} { + const mPerDegLat = 111_320 + const mPerDegLng = 111_320 * Math.cos((origin.lat * Math.PI) / 180) + return { + x: (p.lng - origin.lng) * mPerDegLng, // east+ + y: (p.lat - origin.lat) * mPerDegLat, // north+ + } +} + +class Raster { + readonly buf: Uint8Array + constructor( + readonly w: number, + readonly h: number, + ) { + this.buf = new Uint8Array(w * h) + this.buf.fill(BLACK) + } + private set(x: number, y: number, v: number): void { + if (x < 0 || y < 0 || x >= this.w || y >= this.h) return + this.buf[y * this.w + x] = v + } + private disc(cx: number, cy: number, r: number, v: number): void { + if (r <= 0) { + this.set(cx, cy, v) + return + } + const r2 = r * r + for (let dy = -r; dy <= r; dy++) { + for (let dx = -r; dx <= r; dx++) { + if (dx * dx + dy * dy <= r2) this.set(cx + dx, cy + dy, v) + } + } + } + /** + * Hollow circle outline of radius `r` and `thickness` px, centered at + * (cx, cy). Used for the destination marker on the route. A pixel is "on" + * when its distance from center falls within [r - thickness, r]. + */ + ring(cx: number, cy: number, r: number, v: number, thickness: number): void { + cx = Math.round(cx) + cy = Math.round(cy) + const rOuter = Math.max(1, Math.round(r)) + const rInner = Math.max(0, rOuter - Math.max(1, Math.round(thickness))) + const o2 = rOuter * rOuter + const i2 = rInner * rInner + for (let dy = -rOuter; dy <= rOuter; dy++) { + for (let dx = -rOuter; dx <= rOuter; dx++) { + const d2 = dx * dx + dy * dy + if (d2 <= o2 && d2 >= i2) this.set(cx + dx, cy + dy, v) + } + } + } + + /** Filled triangle via barycentric coverage test (used for the heading arrow). */ + triangle( + ax: number, + ay: number, + bx: number, + by: number, + cx: number, + cy: number, + v: number, + ): void { + const minX = Math.max(0, Math.floor(Math.min(ax, bx, cx))) + const maxX = Math.min(this.w - 1, Math.ceil(Math.max(ax, bx, cx))) + const minY = Math.max(0, Math.floor(Math.min(ay, by, cy))) + const maxY = Math.min(this.h - 1, Math.ceil(Math.max(ay, by, cy))) + const area = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay) + if (area === 0) return // degenerate + for (let y = minY; y <= maxY; y++) { + for (let x = minX; x <= maxX; x++) { + const px = x + 0.5 + const py = y + 0.5 + const w0 = ((bx - px) * (cy - py) - (cx - px) * (by - py)) / area + const w1 = ((cx - px) * (ay - py) - (ax - px) * (cy - py)) / area + const w2 = 1 - w0 - w1 + if (w0 >= 0 && w1 >= 0 && w2 >= 0) this.set(x, y, v) + } + } + } + + /** Thick line via a disc brush stepped along the segment (Bresenham). */ + line(x0: number, y0: number, x1: number, y1: number, v: number, thickness: number): void { + x0 = Math.round(x0) + y0 = Math.round(y0) + x1 = Math.round(x1) + y1 = Math.round(y1) + const r = Math.max(0, Math.floor(thickness / 2)) + const dx = Math.abs(x1 - x0) + const dy = -Math.abs(y1 - y0) + const sx = x0 < x1 ? 1 : -1 + const sy = y0 < y1 ? 1 : -1 + let err = dx + dy + for (;;) { + this.disc(x0, y0, r, v) + if (x0 === x1 && y0 === y1) break + const e2 = 2 * err + if (e2 >= dy) { + err += dy + x0 += sx + } + if (e2 <= dx) { + err += dx + y0 += sy + } + } + } +} + +export type OsmLineMapOptions = { + center: LatLng + width: number + height: number + /** Half-extent of the view in meters (visible area is ~2× this per axis). */ + viewRadiusMeters?: number + lineWidthPx?: number + /** Anti-aliasing: render at this multiple of the target size, then average down. Default 3. */ + supersample?: number + /** Active route polyline, drawn thicker on top of the road network. */ + route?: LatLng[] | null + /** Width of the route overlay line (defaults to lineWidthPx + 2). */ + routeWidthPx?: number + /** + * Destination point — drawn as a small hollow circle at the end of the + * route so the user can see where they're headed. Omit / null for none. + */ + destination?: LatLng | null + /** + * "You are here" heading marker, drawn last (on top) as a filled arrow. + * `at` is projected like any other point; `headingDeg` is a compass bearing + * (0 = north/up, 90 = east/right) — pass the route's forward direction to + * point the arrow the way the user should go next. + */ + marker?: {at: LatLng; headingDeg: number} | null + /** Arrow size in target pixels (tip-to-base length). Default 9. */ + markerSizePx?: number + /** + * Heading-up rotation. When set, the whole map is rotated so this compass + * bearing (0 = north, 90 = east) points UP on the display — i.e. the map + * faces the user's direction of travel. Pass the route's forward bearing to + * keep "the way you're going" always at the top. When omitted/null the map + * is drawn north-up (legacy behaviour). The heading marker is drawn pointing + * straight up in this mode, since the rotation already aligns it with travel. + */ + rotationDeg?: number | null +} + +/** + * Fetch highway geometry around `center` from Overpass (DEV ONLY) and return it + * as lat/lng polylines. One polyline per OSM way. + */ +export async function fetchOsmRoads( + center: LatLng, + viewRadiusMeters: number, +): Promise { + // Keep only real drivable road classes — NOT footways/sidewalks/paths/ + // cycleways/service lanes, which OSM stores as separate parallel ways and + // would draw as a mess of extra lines next to each street. This whitelist + // gives one centerline per street. `out geom` returns inline node geometry. + const ROAD_CLASSES = + "motorway|trunk|primary|secondary|tertiary|unclassified|residential|" + + "living_street|motorway_link|trunk_link|primary_link|secondary_link|tertiary_link" + const query = + `[out:json][timeout:25];` + + `way["highway"~"^(${ROAD_CLASSES})$"](around:${viewRadiusMeters},${center.lat},${center.lng});` + + `out geom;` + + const res = await fetch("https://overpass-api.de/api/interpreter", { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + Accept: "application/json", + // Overpass rejects requests with no/blank UA (HTTP 406). Identify the app. + "User-Agent": "MentraOS-Navigation-PoC/0.1 (OSM line map dev test)", + }, + body: `data=${encodeURIComponent(query)}`, + }) + if (!res.ok) { + throw new Error(`Overpass HTTP ${res.status}`) + } + const json = (await res.json()) as { + elements?: Array<{type: string; geometry?: Array<{lat: number; lon: number}>}> + } + + const polylines: LatLng[][] = [] + for (const el of json.elements ?? []) { + if (el.type !== "way" || !el.geometry) continue + const pts = el.geometry.map((g) => ({lat: g.lat, lng: g.lon})) + if (pts.length >= 2) polylines.push(pts) + } + return polylines +} + +/** + * Rasterize road polylines into a base64 grayscale BMP centered on `center`. + * Pure function — no network. North-up, aspect-ratio preserved, Y flipped. + */ +export function renderOsmLineMap(roads: LatLng[][], opts: OsmLineMapOptions): string { + const {center, width, height} = opts + const viewRadius = opts.viewRadiusMeters ?? 400 + const lineWidth = opts.lineWidthPx ?? 1 + // Supersample: draw at SS× resolution with hard pixels, then box-average down + // to the target size. The averaging turns staircased diagonal edges into gray + // pixels (anti-aliasing) — and the G2 keeps 16 gray levels, so the smoothing + // survives instead of being thresholded back to jaggies. + const ss = Math.max(1, Math.round(opts.supersample ?? 3)) + + const hiW = width * ss + const hiH = height * ss + const raster = new Raster(hiW, hiH) + + // meters → pixels at the hi-res scale; fit 2×viewRadius into the smaller axis + // so aspect ratio is preserved (no stretching). + const pxPerMeter = Math.min(hiW, hiH) / (viewRadius * 2) + const cx = hiW / 2 + const cy = hiH / 2 + + // Heading-up rotation. Rotate the local-meter frame so the given compass + // bearing points up. A bearing θ has world vector (sinθ, cosθ) in (east, + // north); to bring it onto +north we rotate every point by −θ. cos/sin are + // hoisted out of the per-point hot path. rot==null → identity (north-up). + const rotDeg = opts.rotationDeg ?? null + const rotRad = rotDeg != null ? (-rotDeg * Math.PI) / 180 : 0 + const rCos = Math.cos(rotRad) + const rSin = Math.sin(rotRad) + + const project = (p: LatLng): {x: number; y: number} => { + const m = toLocalMeters(p, center) + // Rotate the (east, north) meter vector before projecting to pixels so the + // chosen bearing ends up pointing up. + const ex = m.x * rCos - m.y * rSin + const ny = m.x * rSin + m.y * rCos + return { + x: cx + ex * pxPerMeter, + y: cy - ny * pxPerMeter, // Y flipped: north(-of-rotated-frame) is up + } + } + + for (const way of roads) { + for (let i = 0; i < way.length - 1; i++) { + const a = project(way[i]!) + const b = project(way[i + 1]!) + raster.line(a.x, a.y, b.x, b.y, ROAD, lineWidth * ss) + } + } + + // Route overlay: drawn on top, thicker, so it stands out over the network. + const route = opts.route + if (route && route.length >= 2) { + const routeWidth = opts.routeWidthPx ?? lineWidth + 2 + for (let i = 0; i < route.length - 1; i++) { + const a = project(route[i]!) + const b = project(route[i + 1]!) + raster.line(a.x, a.y, b.x, b.y, ROUTE, routeWidth * ss) + } + } + + // Destination: a small hollow circle at the route's end so the user can see + // where they're headed. Drawn after the route, before the heading marker. + // Kept small + thin so it's "barely visible" — just enough to read as a + // target without dominating the tiny minimap. + const destination = opts.destination + if (destination) { + const d = project(destination) + const ringR = 3.9 * ss // ~3.9px target radius (30% larger than the prior 3px) + const ringT = Math.max(1, Math.round(ss)) // ~1px stroke + raster.ring(d.x, d.y, ringR, ROUTE, ringT) + } + + // Heading marker: a filled arrowhead at the user's position, rotated to the + // route's forward bearing. Drawn last so it sits on top of roads + route. + const marker = opts.marker + if (marker) { + const c = project(marker.at) + const size = (opts.markerSizePx ?? 14) * ss + // Bearing 0 = north = up (−y). Rotate the arrow's local geometry by it. + // In heading-up mode the map is already rotated to travel direction, so the + // arrow points straight up (effective bearing = headingDeg − rotationDeg, + // which is ~0 when the marker uses the same bearing the map is rotated to). + const effHeading = rotDeg != null ? marker.headingDeg - rotDeg : marker.headingDeg + const rad = (effHeading * Math.PI) / 180 + const sin = Math.sin(rad) + const cos = Math.cos(rad) + // Local arrow (pointing up): tip ahead, two base corners behind. + const tip = {x: 0, y: -size * 0.6} + const left = {x: -size * 0.45, y: size * 0.4} + const right = {x: size * 0.45, y: size * 0.4} + const rot = (p: {x: number; y: number}) => ({ + x: c.x + (p.x * cos - p.y * sin), + y: c.y + (p.x * sin + p.y * cos), + }) + // Outline thickness in hi-res px (scales with supersample so it survives the + // downsample). Expand each vertex outward from the local centroid to grow the + // black halo triangle, then fill the white arrow inside it. + const outline = Math.max(1, Math.round(1.5 * ss)) + const ctr = {x: 0, y: (tip.y + left.y + right.y) / 3} + const grow = (p: {x: number; y: number}) => { + const dx = p.x - ctr.x + const dy = p.y - ctr.y + const len = Math.hypot(dx, dy) || 1 + return {x: p.x + (dx / len) * outline, y: p.y + (dy / len) * outline} + } + // Black outline first (enlarged), white fill on top. + const ot = rot(grow(tip)) + const ol = rot(grow(left)) + const or = rot(grow(right)) + raster.triangle(ot.x, ot.y, ol.x, ol.y, or.x, or.y, MARKER_OUTLINE) + const t = rot(tip) + const l = rot(left) + const r = rot(right) + raster.triangle(t.x, t.y, l.x, l.y, r.x, r.y, MARKER) + } + + // Corner brackets: short rounded L-shaped marks at each corner (not a full + // border). A small quarter-circle arc rounds the turn, with two straight arms + // running out along each edge. Drawn in hi-res so it survives the downsample. + { + const armLen = Math.round(width * 0.066) * ss // length of each bracket arm (70% shorter) + const r = Math.max(1, Math.round(2 * ss)) // corner radius (~2px) + const thick = Math.max(1, ss) // stroke thickness + const W = hiW - 1 + const H = hiH - 1 + const hLine = (x0: number, x1: number, y: number) => raster.line(x0, y, x1, y, BORDER, thick) + const vLine = (y0: number, y1: number, x: number) => raster.line(x, y0, x, y1, BORDER, thick) + // Quarter arc of radius r, centered (cx,cy), sweeping from a→b radians. + const arc = (cx: number, cy: number, a0: number, a1: number) => { + const steps = Math.max(4, Math.round(r * 2)) + for (let i = 0; i <= steps; i++) { + const a = a0 + ((a1 - a0) * i) / steps + raster.line(cx + Math.cos(a) * r, cy + Math.sin(a) * r, cx + Math.cos(a) * r, cy + Math.sin(a) * r, BORDER, thick) + } + } + // Each corner: arc tangent to both edges (center r in from the corner), + // then straight arms from the arc's edge-tangent points outward. + // top-left — arc center (r,r), sweeps 180°→270° + arc(r, r, Math.PI, 1.5 * Math.PI) + hLine(r, r + armLen, 0) + vLine(r, r + armLen, 0) + // top-right — center (W-r,r), sweeps 270°→360° + arc(W - r, r, 1.5 * Math.PI, 2 * Math.PI) + hLine(W - r - armLen, W - r, 0) + vLine(r, r + armLen, W) + // bottom-left — center (r,H-r), sweeps 90°→180° + arc(r, H - r, 0.5 * Math.PI, Math.PI) + hLine(r, r + armLen, H) + vLine(H - r - armLen, H - r, 0) + // bottom-right — center (W-r,H-r), sweeps 0°→90° + arc(W - r, H - r, 0, 0.5 * Math.PI) + hLine(W - r - armLen, W - r, H) + vLine(H - r - armLen, H - r, W) + } + + // Box-downsample hi-res → target: each output pixel is the average of its + // ss×ss source block, producing smooth grayscale edges. + const out = new Uint8Array(width * height) + if (ss === 1) { + out.set(raster.buf) + } else { + const area = ss * ss + for (let oy = 0; oy < height; oy++) { + for (let ox = 0; ox < width; ox++) { + let sum = 0 + for (let sy = 0; sy < ss; sy++) { + const row = (oy * ss + sy) * hiW + ox * ss + for (let sx = 0; sx < ss; sx++) sum += raster.buf[row + sx]! + } + out[oy * width + ox] = Math.round(sum / area) + } + } + } + + return encodeBmpBase64(out, width, height) +} + +/** Convenience: fetch + render in one call. */ +export async function buildOsmLineMap(opts: OsmLineMapOptions): Promise { + const viewRadius = opts.viewRadiusMeters ?? 400 + const roads = await fetchOsmRoads(opts.center, viewRadius) + console.log(`[OSM-MAP] fetched ${roads.length} road ways around ${opts.center.lat},${opts.center.lng}`) + return renderOsmLineMap(roads, opts) +} diff --git a/miniapps/navigation/src/background/lib/bmp.ts b/miniapps/navigation/src/background/lib/bmp.ts new file mode 100644 index 0000000000000000000000000000000000000000..bad633c504c1422c61602d94c2cc8c60a2676505 --- /dev/null +++ b/miniapps/navigation/src/background/lib/bmp.ts @@ -0,0 +1,242 @@ +/** + * Minimal, dependency-free 1-bit BMP encoder for the background JSContext. + * + * The glasses render in 1-bit monochrome, and the phone decodes the + * bitmap via iOS `UIImage(data:)` / Android BitmapFactory. A hand-rolled + * stored-DEFLATE PNG is rejected by ImageIO ("could not decode image"), + * and 24-bit is wasteful, so we emit an uncompressed 1-bit BMP — the same + * shape the cloud SDK's bitmap-utils produces, which both platforms decode. + * + * BMP is bottom-up. 1-bit pixels are packed MSB-first, 8 px/byte, with a + * 2-entry color table (index 0 = black, index 1 = white) and each row + * padded to a 4-byte boundary. + */ + +const FILE_HEADER = 14 +const DIB_HEADER = 40 +const COLOR_TABLE = 8 // 2 colors * 4 bytes +const PIXEL_OFFSET = FILE_HEADER + DIB_HEADER + COLOR_TABLE // 62 + +function setU16LE(buf: Uint8Array, off: number, v: number): void { + buf[off] = v & 0xff + buf[off + 1] = (v >>> 8) & 0xff +} + +function setU32LE(buf: Uint8Array, off: number, v: number): void { + buf[off] = v & 0xff + buf[off + 1] = (v >>> 8) & 0xff + buf[off + 2] = (v >>> 16) & 0xff + buf[off + 3] = (v >>> 24) & 0xff +} + +function base64(bytes: Uint8Array): string { + let binary = "" + const CHUNK = 0x8000 + for (let i = 0; i < bytes.length; i += CHUNK) { + const slice = bytes.subarray(i, i + CHUNK) + binary += String.fromCharCode.apply(null, slice as unknown as number[]) + } + return btoa(binary) +} + +/** + * Encode an 8-bit grayscale pixel buffer (row-major, top-down, 1 byte/px) + * as a base64 8-bit BMP string. Uses a 256-entry grayscale palette so each + * pixel byte indexes its own gray level (0 = black, 255 = white). + */ +export function encodeBmpBase64(gray: Uint8Array, width: number, height: number): string { + if (gray.length !== width * height) { + throw new Error(`encodeBmpBase64: expected ${width * height} bytes, got ${gray.length}`) + } + + const GRAY_COLOR_TABLE = 256 * 4 // 256 colors * 4 bytes + const grayPixelOffset = FILE_HEADER + DIB_HEADER + GRAY_COLOR_TABLE // 1078 + const rowSize = Math.ceil(width / 4) * 4 // 1 byte/px, 4-byte aligned + const pixelDataSize = rowSize * height + const fileSize = grayPixelOffset + pixelDataSize + + const buf = new Uint8Array(fileSize) + + // BMP file header (14 bytes) + buf[0] = 0x42 // 'B' + buf[1] = 0x4d // 'M' + setU32LE(buf, 2, fileSize) + setU32LE(buf, 6, 0) // reserved + setU32LE(buf, 10, grayPixelOffset) + + // DIB header (BITMAPINFOHEADER, 40 bytes) + setU32LE(buf, 14, DIB_HEADER) + setU32LE(buf, 18, width) + setU32LE(buf, 22, height) // positive = bottom-up + setU16LE(buf, 26, 1) // planes + setU16LE(buf, 28, 8) // bits per pixel + setU32LE(buf, 30, 0) // compression: BI_RGB (none) + setU32LE(buf, 34, pixelDataSize) + setU32LE(buf, 38, 2835) // X px/meter (~72 DPI) + setU32LE(buf, 42, 2835) // Y px/meter + setU32LE(buf, 46, 256) // colors used + setU32LE(buf, 50, 256) // important colors + + // Grayscale palette (1024 bytes): entry i = gray level i (BGRA). + for (let i = 0; i < 256; i++) { + const off = FILE_HEADER + DIB_HEADER + i * 4 + buf[off] = i // B + buf[off + 1] = i // G + buf[off + 2] = i // R + buf[off + 3] = 0x00 // reserved + } + + // Pixel data — bottom-up rows, 1 byte/px. + for (let y = 0; y < height; y++) { + const srcRow = y * width // source is top-down + const destRow = grayPixelOffset + (height - 1 - y) * rowSize // write bottom-up + for (let x = 0; x < width; x++) { + buf[destRow + x] = gray[srcRow + x]! + } + } + return base64(buf) +} + +/** + * Build an 8-bit grayscale gradient test image as a base64 BMP. The width is + * split into 17 equal vertical bars whose gray level steps 0 → 16 left to + * right — handy for verifying the glasses' grayscale rendering. + */ +export function gradientTestImageBase64(width: number, height: number): string { + const BARS = 255 // levels 0..16 + const gray = new Uint8Array(width * height) + for (let x = 0; x < width; x++) { + const level = Math.min(BARS - 1, Math.floor((x / width) * BARS)) + for (let y = 0; y < height; y++) { + gray[y * width + x] = level + } + } + return encodeBmpBase64(gray, width, height) +} + +/** + * Build an 8-bit grayscale test image of just the rectangle BORDER (outline) + * as a base64 BMP — a white frame `thickness` px wide on a black background. + * Handy for seeing the exact bounds/size of a bitmap container on the glasses. + */ +export function borderTestImageBase64(width: number, height: number, thickness = 2): string { + const t = Math.max(1, Math.min(thickness, Math.floor(Math.min(width, height) / 2))) + const gray = new Uint8Array(width * height) // 0 = black fill + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const onBorder = x < t || x >= width - t || y < t || y >= height - t + if (onBorder) gray[y * width + x] = 255 // white edge + } + } + return encodeBmpBase64(gray, width, height) +} + +/* -------------------------------------------------------------------------- */ +/* Minimal 5×7 bitmap font — enough to draw short uppercase test labels into a */ +/* bitmap. Each glyph is 7 rows × 5 bits (MSB = leftmost column). */ + +const GLYPH_W = 5 +const GLYPH_H = 7 +const GLYPH_GAP = 1 // blank column between glyphs + +// Bit rows per glyph, top→bottom. 1 = on (white). Only the chars we need. +const FONT: Record = { + " ": [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + A: [0x0e, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11], + B: [0x1e, 0x11, 0x11, 0x1e, 0x11, 0x11, 0x1e], + C: [0x0e, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0e], + D: [0x1e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1e], + E: [0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x1f], + F: [0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x10], + G: [0x0e, 0x11, 0x10, 0x17, 0x11, 0x11, 0x0e], + H: [0x11, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11], + I: [0x0e, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0e], + L: [0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1f], + M: [0x11, 0x1b, 0x15, 0x15, 0x11, 0x11, 0x11], + N: [0x11, 0x19, 0x15, 0x13, 0x11, 0x11, 0x11], + O: [0x0e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e], + P: [0x1e, 0x11, 0x11, 0x1e, 0x10, 0x10, 0x10], + R: [0x1e, 0x11, 0x11, 0x1e, 0x14, 0x12, 0x11], + S: [0x0f, 0x10, 0x10, 0x0e, 0x01, 0x01, 0x1e], + T: [0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04], + U: [0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e], + W: [0x11, 0x11, 0x11, 0x15, 0x15, 0x1b, 0x11], + "0": [0x0e, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0e], + "1": [0x04, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x0e], + "2": [0x0e, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1f], + "3": [0x1f, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0e], +} + +/** Width in px of a string rendered at `scale` (incl. inter-glyph gaps). */ +function measureText(text: string, scale: number): number { + const n = text.length + if (n === 0) return 0 + return (n * GLYPH_W + (n - 1) * GLYPH_GAP) * scale +} + +/** Blit a string into `gray` (8-bit, row-major) at top-left (ox, oy), `scale`×. */ +function drawText( + gray: Uint8Array, + imgW: number, + imgH: number, + text: string, + ox: number, + oy: number, + scale: number, + value = 255, +): void { + let penX = ox + for (const ch of text.toUpperCase()) { + const glyph = FONT[ch] ?? FONT[" "]! + for (let row = 0; row < GLYPH_H; row++) { + const bits = glyph[row]! + for (let col = 0; col < GLYPH_W; col++) { + if ((bits >> (GLYPH_W - 1 - col)) & 1) { + // Scale up each lit cell into a scale×scale block. + for (let dy = 0; dy < scale; dy++) { + for (let dx = 0; dx < scale; dx++) { + const px = penX + col * scale + dx + const py = oy + row * scale + dy + if (px >= 0 && px < imgW && py >= 0 && py < imgH) gray[py * imgW + px] = value + } + } + } + } + } + penX += (GLYPH_W + GLYPH_GAP) * scale + } +} + +/** + * Bordered box with `text` drawn centered inside it, as a base64 BMP. Same + * white-frame-on-black look as [borderTestImageBase64], but with a label baked + * into the bitmap (no separate positioned-text layout needed). + */ +export function labeledBoxImageBase64( + width: number, + height: number, + text: string, + thickness = 2, +): string { + const t = Math.max(1, Math.min(thickness, Math.floor(Math.min(width, height) / 2))) + const gray = new Uint8Array(width * height) // 0 = black fill + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const onBorder = x < t || x >= width - t || y < t || y >= height - t + if (onBorder) gray[y * width + x] = 255 + } + } + // Pick the largest integer scale that fits the text inside the border padding. + const padX = t + 2 + const padY = t + 2 + const maxW = width - padX * 2 + const maxH = height - padY * 2 + let scale = Math.max(1, Math.floor(maxH / GLYPH_H)) + while (scale > 1 && measureText(text, scale) > maxW) scale-- + const tw = measureText(text, scale) + const th = GLYPH_H * scale + const ox = Math.round((width - tw) / 2) + const oy = Math.round((height - th) / 2) + drawText(gray, width, height, text, ox, oy, scale, 255) + return encodeBmpBase64(gray, width, height) +} diff --git a/miniapps/navigation/src/background/lib/capabilities.ts b/miniapps/navigation/src/background/lib/capabilities.ts new file mode 100644 index 0000000000000000000000000000000000000000..bb601734a7f1ce76f6b95eed552069aa0b8a790b --- /dev/null +++ b/miniapps/navigation/src/background/lib/capabilities.ts @@ -0,0 +1,25 @@ +import type {GlassesCapabilitySnapshot} from "../../shared/types" + +/** + * Normalize the host's glasses capability payload for navigation. + * + * Display capability fields are optional because older hosts do not send all + * of them. Absence means "unknown", so preserve Navigation's established + * positioned HUD unless the host explicitly says positioning is unsupported. + * Current G1 and Z100 profiles send `canPosition: false` and take the compact + * text fallback; current G2 and Mentra Display profiles send `true`. + */ +export function readGlassesCapabilities(capabilities: unknown): GlassesCapabilitySnapshot { + const record = (capabilities ?? {}) as Record + const display = + record.display && typeof record.display === "object" ? (record.display as Record) : null + const modelName = typeof record.modelName === "string" ? record.modelName : null + + return { + modelName, + hasDisplay: record.hasDisplay === true || !!display, + canPosition: display != null && display.canPosition !== false, + hasSpeaker: record.hasSpeaker === true, + hasButton: record.hasButton === true, + } +} diff --git a/miniapps/navigation/src/background/lib/formatDistance.ts b/miniapps/navigation/src/background/lib/formatDistance.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3c440dedc9ae22d2c3d889c9f004f1c3bd11403 --- /dev/null +++ b/miniapps/navigation/src/background/lib/formatDistance.ts @@ -0,0 +1,40 @@ +import type {UnitSystem} from "../../shared/types" + +const FEET_PER_METER = 3.28084 +const FEET_PER_MILE = 5280 + +/** + * Compact distance string in the requested unit system. + * + * metric → "750 m", "1.2 km" (m below 1000 m, then km) + * imperial → "820 ft", "0.8 mi" (ft below 0.1 mi ≈ 528 ft, then mi) + * + * "—" for unknown (negative) input. Clamps very-small values to the + * smallest whole unit ("1 m" / "1 ft") so we never display "0 m". The + * `unit` param defaults to "metric" so legacy call sites stay valid. + */ +export function formatDistance(meters: number, unit: UnitSystem = "metric"): string { + if (meters < 0) return "—" + if (unit === "imperial") { + const feet = meters * FEET_PER_METER + // Switch to miles once we're past ~0.1 mi so short distances stay + // legible in feet rather than rounding to "0.0 mi". + if (feet < FEET_PER_MILE * 0.1) return `${Math.max(1, Math.round(feet))} ft` + const miles = feet / FEET_PER_MILE + return `${miles.toFixed(miles < 10 ? 1 : 0)} mi` + } + if (meters < 1000) return `${Math.max(1, Math.round(meters))} m` + const km = meters / 1000 + return `${km.toFixed(km < 10 ? 1 : 0)} km` +} + +/** Compact duration string ("45 sec", "14 min", "1 h 5 min", "—" for unknown). */ +export function formatDuration(seconds: number): string { + if (seconds < 0) return "—" + if (seconds < 60) return `${seconds} sec` + const minutes = Math.round(seconds / 60) + if (minutes < 60) return `${minutes} min` + const hours = Math.floor(minutes / 60) + const remMin = minutes % 60 + return remMin === 0 ? `${hours} h` : `${hours} h ${remMin} min` +} diff --git a/miniapps/navigation/src/background/lib/geometry.ts b/miniapps/navigation/src/background/lib/geometry.ts new file mode 100644 index 0000000000000000000000000000000000000000..718c4a950269fc462b49e1065e206aa54744b301 --- /dev/null +++ b/miniapps/navigation/src/background/lib/geometry.ts @@ -0,0 +1,297 @@ +/** + * Lightweight geo helpers used by the map and orientation logic. + * Small-angle approximations are fine for the segment lengths we deal + * with (10s–100s of meters within a single trip). + */ + +export type LatLng = {lat: number; lng: number} + +/** Great-circle distance in meters (haversine). */ +export function haversineMeters(a: LatLng, b: LatLng): number { + const R = 6_371_000 + const toRad = (d: number) => (d * Math.PI) / 180 + const dLat = toRad(b.lat - a.lat) + const dLng = toRad(b.lng - a.lng) + const lat1 = toRad(a.lat) + const lat2 = toRad(b.lat) + const x = Math.sin(dLat / 2) ** 2 + Math.sin(dLng / 2) ** 2 * Math.cos(lat1) * Math.cos(lat2) + return 2 * R * Math.asin(Math.sqrt(x)) +} + +/** Compass bearing from `a` to `b`, in degrees [0, 360). */ +export function bearingDeg(a: LatLng, b: LatLng): number { + const toRad = (d: number) => (d * Math.PI) / 180 + const toDeg = (r: number) => (r * 180) / Math.PI + const lat1 = toRad(a.lat) + const lat2 = toRad(b.lat) + const dLng = toRad(b.lng - a.lng) + const y = Math.sin(dLng) * Math.cos(lat2) + const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLng) + return (toDeg(Math.atan2(y, x)) + 360) % 360 +} + +/** Smallest signed difference: target - actual, in [-180, 180]. */ +export function signedAngleDiff(target: number, actual: number): number { + return ((target - actual + 540) % 360) - 180 +} + +/** Eight-point cardinal name from a degree heading. */ +export function cardinal(deg: number): string { + const names = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] + const idx = Math.round((((deg % 360) + 360) % 360) / 45) % 8 + return names[idx] +} + +/** + * Approximate perpendicular distance from `p` to segment `a→b`, in meters. + * Good enough for picking the closest segment of a polyline. + */ +export function perpDistanceMeters(p: LatLng, a: LatLng, b: LatLng): number { + const mPerDegLat = 111_320 + const mPerDegLng = 111_320 * Math.cos((a.lat * Math.PI) / 180) + const ax = 0 + const ay = 0 + const bx = (b.lng - a.lng) * mPerDegLng + const by = (b.lat - a.lat) * mPerDegLat + const px = (p.lng - a.lng) * mPerDegLng + const py = (p.lat - a.lat) * mPerDegLat + const dx = bx - ax + const dy = by - ay + const len2 = dx * dx + dy * dy + if (len2 === 0) return Math.sqrt(px * px + py * py) + let t = (px * dx + py * dy) / len2 + t = Math.max(0, Math.min(1, t)) + const projx = ax + t * dx + const projy = ay + t * dy + return Math.sqrt((px - projx) * (px - projx) + (py - projy) * (py - projy)) +} + +/** + * Distance in meters from `p` to the nearest point on a polyline. + * Returns null for empty / single-point polylines. Walks every segment; + * fine for the segment counts we deal with (tens to low hundreds). + */ +export function distanceToPolylineMeters(p: LatLng, points: LatLng[] | null): number | null { + if (!points || points.length < 2) return null + let best = Infinity + for (let i = 0; i < points.length - 1; i++) { + const d = perpDistanceMeters(p, points[i], points[i + 1]) + if (d < best) best = d + } + return best === Infinity ? null : best +} + +/** + * Bearing of the route at the user's current position. We find the + * polyline segment closest to `me` and return its endpoint bearing — + * i.e. which way the route wants you to face right now. + */ +export function nextSegmentBearing(me: LatLng | null, route: LatLng[] | null): number | null { + if (!me || !route || route.length < 2) return null + let bestIdx = 0 + let bestDist = Infinity + for (let i = 0; i < route.length - 1; i++) { + const d = perpDistanceMeters(me, route[i], route[i + 1]) + if (d < bestDist) { + bestDist = d + bestIdx = i + } + } + return bearingDeg(route[bestIdx], route[bestIdx + 1]) +} + +/** + * Remaining route distance in meters: from the user's projection onto + * the route polyline to the route's endpoint. Walks the polyline from + * the closest segment forward, summing the rest of that segment plus + * every segment after it. Returns null for empty / single-point routes. + * + * Used to fire arrival when the user is within N meters of the route's + * end *along the route*, rather than straight-line to the destination + * pin (the pin can sit a few meters off the walkable polyline). + */ +/** + * The portion of the route the user has NOT walked yet: the user's projected + * point onto the closest segment, followed by every route point after it. + * Used to draw only the route AHEAD on the minimap (the part behind the user + * is trimmed as they pass it). Returns the full route if `me` is null, and + * null for empty / single-point routes. + */ +export function remainingRoutePoints(me: LatLng | null, route: LatLng[] | null): LatLng[] | null { + if (!route || route.length < 2) return route ?? null + if (!me) return route + // Closest segment (same scan as remainingRouteMeters / nextSegmentBearing). + let bestIdx = 0 + let bestDist = Infinity + for (let i = 0; i < route.length - 1; i++) { + const d = perpDistanceMeters(me, route[i], route[i + 1]) + if (d < bestDist) { + bestDist = d + bestIdx = i + } + } + // Project `me` onto that segment to get the exact "where I am on the route" + // point, so the trimmed line starts right at the user, not at the segment's + // start vertex (which could be several meters behind). + const seg = route[bestIdx] + const next = route[bestIdx + 1] + const mPerDegLat = 111_320 + const mPerDegLng = 111_320 * Math.cos((seg.lat * Math.PI) / 180) + const bx = (next.lng - seg.lng) * mPerDegLng + const by = (next.lat - seg.lat) * mPerDegLat + const px = (me.lng - seg.lng) * mPerDegLng + const py = (me.lat - seg.lat) * mPerDegLat + const len2 = bx * bx + by * by + let t = len2 > 0 ? (px * bx + py * by) / len2 : 0 + t = Math.max(0, Math.min(1, t)) + const projected: LatLng = { + lat: seg.lat + (next.lat - seg.lat) * t, + lng: seg.lng + (next.lng - seg.lng) * t, + } + // projected point + the rest of the route ahead. + return [projected, ...route.slice(bestIdx + 1)] +} + +export function remainingRouteMeters(me: LatLng | null, route: LatLng[] | null): number | null { + if (!me || !route || route.length < 2) return null + let bestIdx = 0 + let bestDist = Infinity + for (let i = 0; i < route.length - 1; i++) { + const d = perpDistanceMeters(me, route[i], route[i + 1]) + if (d < bestDist) { + bestDist = d + bestIdx = i + } + } + const mPerDegLat = 111_320 + const seg = route[bestIdx] + const next = route[bestIdx + 1] + const mPerDegLng = 111_320 * Math.cos((seg.lat * Math.PI) / 180) + const ax = 0 + const ay = 0 + const bx = (next.lng - seg.lng) * mPerDegLng + const by = (next.lat - seg.lat) * mPerDegLat + const px = (me.lng - seg.lng) * mPerDegLng + const py = (me.lat - seg.lat) * mPerDegLat + const dx = bx - ax + const dy = by - ay + const len2 = dx * dx + dy * dy + let t = len2 > 0 ? (px * dx + py * dy) / len2 : 0 + t = Math.max(0, Math.min(1, t)) + const projx = ax + t * dx + const projy = ay + t * dy + let remaining = Math.sqrt((bx - projx) * (bx - projx) + (by - projy) * (by - projy)) + for (let i = bestIdx + 1; i < route.length - 1; i++) { + remaining += haversineMeters(route[i], route[i + 1]) + } + return remaining +} + +/** + * "left" or "right": which side of the final route segment the + * destination pin sits on, from the perspective of a walker facing + * along that segment. Used at arrival to tell the user which way to + * turn their head to see the destination. + * + * Returns null when the route is too short or the pin sits exactly on + * the segment's bearing line (rare; cross-product is zero). + */ +export function sideOfFinalSegment(route: LatLng[] | null, pin: LatLng | null): "left" | "right" | null { + if (!route || route.length < 2 || !pin) return null + const b = route[route.length - 1] + // Find the last DISTINCT point before the endpoint. Mapbox routes often end + // with duplicate trailing coordinates (b === route[length-2]); using one of + // those would make `segBearing` a meaningless bearing-between-identical- + // points (≈0/North), which flips left/right at random. Walk back until we + // find a point at least ~0.5 m from b so the segment has a real direction. + let a: LatLng | null = null + for (let i = route.length - 2; i >= 0; i--) { + if (haversineMeters(route[i], b) > 0.5) { + a = route[i] + break + } + } + if (!a) return null // whole tail collapses onto b — no usable bearing + const segBearing = bearingDeg(a, b) + const pinBearing = bearingDeg(b, pin) + const diff = signedAngleDiff(pinBearing, segBearing) + if (diff === 0) return null + // Compass bearings increase CLOCKWISE, so a destination to the walker's + // RIGHT has a larger bearing than the travel direction → positive diff. + return diff > 0 ? "right" : "left" +} + +export type Crossing = { + /** Start of the crossing leg (curb on the user's current sidewalk). */ + start: LatLng + /** End of the crossing leg (curb on the other sidewalk). */ + end: LatLng +} + +/** + * Detect crossing micro-steps in a route polyline. A "crossing" is a + * short polyline leg (minBendDeg) + * away from the previous leg and then turns sharply back to roughly + * the original direction on the leg after — characteristic of a + * crosswalk where the planned route briefly leaves the sidewalk to + * traverse the road, then resumes along the opposite curb. + * + * Heuristic-based; tweakable via `maxLegMeters` and `minBendDeg`. + * Mirrors the same algorithm as the Android NavigationManager's + * stripCrossings() so the dev-panel visualization and the simulator + * walker agree on what counts as a crossing. + */ +export function detectCrossings( + points: LatLng[], + opts: {maxLegMeters?: number; minBendDeg?: number; minSidewalkSwitchMeters?: number} = {}, +): Crossing[] { + const maxLeg = opts.maxLegMeters ?? 25 + const minBend = opts.minBendDeg ?? 60 + // Reject pass-through crosswalk traces at intersections where the + // user stays on the same sidewalk. A real sidewalk-switch leaves the + // post-crossing polyline ≥4m perpendicular from the pre-crossing line. + const minSwitch = opts.minSidewalkSwitchMeters ?? 4 + const sampleMeters = 10 + const out: Crossing[] = [] + if (points.length < 4) return out + for (let i = 1; i < points.length - 2; i++) { + const prev = points[i - 1] + const here = points[i] + const next = points[i + 1] + const afterNext = points[i + 2] + const legOut = haversineMeters(here, next) + if (legOut >= maxLeg) continue + const bearIn = bearingDeg(prev, here) + const bearOut = bearingDeg(here, next) + const bend = Math.abs(((bearIn - bearOut + 540) % 360) - 180) + if (bend <= minBend) continue + const bearAfter = bearingDeg(next, afterNext) + const bendBack = Math.abs(((bearOut - bearAfter + 540) % 360) - 180) + const inOutDelta = Math.abs(((bearIn - bearAfter + 540) % 360) - 180) + if (!(bendBack > minBend && inOutDelta < minBend)) continue + const sample = walkAlongPolyline(points, i + 1, sampleMeters) + if (!sample) continue + const displacement = perpDistanceMeters(sample, prev, here) + if (displacement < minSwitch) continue + out.push({start: here, end: next}) + } + return out +} + +function walkAlongPolyline(points: LatLng[], startIdx: number, meters: number): LatLng | null { + if (startIdx >= points.length - 1) return null + let remaining = meters + let idx = startIdx + while (idx < points.length - 1) { + const a = points[idx] + const b = points[idx + 1] + const segLen = haversineMeters(a, b) + if (remaining <= segLen) { + const t = segLen > 0 ? remaining / segLen : 0 + return {lat: a.lat + (b.lat - a.lat) * t, lng: a.lng + (b.lng - a.lng) * t} + } + remaining -= segLen + idx++ + } + return null +} diff --git a/miniapps/navigation/src/background/lib/places.ts b/miniapps/navigation/src/background/lib/places.ts new file mode 100644 index 0000000000000000000000000000000000000000..93a70eb02a449d01325e8224b4cb175241fd4623 --- /dev/null +++ b/miniapps/navigation/src/background/lib/places.ts @@ -0,0 +1,103 @@ +/** + * Places client — type-ahead autocomplete + details for the search box. + * + * Routes entirely through the miniapp SDK (`session.navigation.place*`), which + * the host bridges to the v2 cloud maps service (Mapbox Search Box today). There + * is NO backend Worker and no provider key in this bundle — the cloud holds the + * token, caches, and bills. This replaced the old Google-Places secret-proxy + * Worker. + * + * One PlacesSession represents one autocomplete-then-details flow. The provider + * bills the autocomplete keystrokes + the final details call as a single search + * session when the same `sessionToken` is sent on all of them, so callers should + * create a session per "search box opening" and `reset()` it after the user + * picks a result. + */ + +import type {MiniappSession} from "@mentra/miniapp" + +export type PlaceSuggestion = { + placeId: string + mainText: string + secondaryText: string +} + +export type PlaceDetails = { + placeId: string + lat: number + lng: number + name: string + address: string + /** User-defined label when saved as a favorite or custom place */ + savedName?: string + /** + * True while a reverse-geocode is in flight for a dropped pin. The + * `name` / `address` fields are placeholders (raw lat/lng) until this + * flips back to false. UI consumers render a skeleton while this is + * true so the user doesn't see the bare coordinates flash on screen + * before the real address lands. + */ + isGeocoding?: boolean +} + +/** + * A place saved by the user. Optionally tagged as `"home"` or `"work"` + * so the IdleDrawer can surface those two as fixed quick-access slots. + * Anything else is just an untagged saved place — there is no + * favorite/custom distinction anymore. + */ +export type SavedPlaceType = "home" | "work" + +export type SavedPlace = PlaceDetails & { + type?: SavedPlaceType +} + +export class PlacesSession { + private token: string + + constructor(private readonly session: MiniappSession) { + this.token = newToken() + } + + /** + * Type-ahead suggestions for `input`, optionally biased toward `near`. Goes + * through the SDK → host → v2 cloud maps (Mapbox Search Box). The same + * `token` is sent on every keystroke + the final `details()` so the cloud + * bills one search session. + */ + async autocomplete(input: string, near?: {lat: number; lng: number}): Promise { + if (!input.trim()) return [] + const res = await this.session.navigation.placeAutocomplete({ + query: input, + near, + sessionToken: this.token, + }) + if (!res.ok) throw new Error(res.error || "autocomplete failed") + return res.suggestions ?? [] + } + + /** Resolve a picked suggestion to coordinates. Uses the same session token. */ + async details(placeId: string): Promise { + const res = await this.session.navigation.placeDetails({ + placeId, + sessionToken: this.token, + }) + if (!res.ok || !res.place) throw new Error(res.error || "details failed") + const {placeId: id, name, address, lat, lng} = res.place + return {placeId: id, name, address, lat, lng} + } + + /** Rotate the token after a completed pick so the next search is a new + * billing session. */ + reset(): void { + this.token = newToken() + } +} + +function newToken(): string { + if (typeof crypto !== "undefined" && "randomUUID" in crypto) { + return crypto.randomUUID() + } + return Math.random().toString(36).slice(2) + Date.now().toString(36) +} + diff --git a/miniapps/navigation/src/background/lib/rdpSmooth.ts b/miniapps/navigation/src/background/lib/rdpSmooth.ts new file mode 100644 index 0000000000000000000000000000000000000000..b26f5739604713da789839d2ba47f829ae39005e --- /dev/null +++ b/miniapps/navigation/src/background/lib/rdpSmooth.ts @@ -0,0 +1,65 @@ +/** + * Ramer-Douglas-Peucker polyline simplification for visual rendering. + * + * The pivot-detection variant of RDP moved into `@mentra/miniapp`'s + * internal geometry helpers when pivot tracking was lifted into the + * SDK. This file is the small leftover that NavMap uses to smooth + * the visible route polyline before drawing it on the map — pure + * presentation, no semantics. + */ + +import type {LatLng} from "./geometry" + +/** + * Return a simplified copy of `points` for rendering. Drops vertices + * whose perpendicular distance to the line through their neighbors + * is below `epsilonMeters`. Default 6m — slightly looser than the + * pivot extractor's 5m because the map only needs visual fidelity. + */ +export function rdpSmooth(points: LatLng[], epsilonMeters: number = 6): LatLng[] { + if (points.length < 3) return points.slice() + const kept = rdpSimplify(points, epsilonMeters) + return kept.map((i) => points[i]) +} + +function rdpSimplify(points: LatLng[], epsilonMeters: number): number[] { + if (points.length < 3) return points.map((_, i) => i) + + const keep = new Array(points.length).fill(false) + keep[0] = true + keep[points.length - 1] = true + + const stack: Array<[number, number]> = [[0, points.length - 1]] + while (stack.length) { + const [lo, hi] = stack.pop()! + let maxDist = 0 + let maxIdx = -1 + for (let i = lo + 1; i < hi; i++) { + const d = perpDistMeters(points[i], points[lo], points[hi]) + if (d > maxDist) { + maxDist = d + maxIdx = i + } + } + if (maxIdx !== -1 && maxDist > epsilonMeters) { + keep[maxIdx] = true + stack.push([lo, maxIdx], [maxIdx, hi]) + } + } + + const out: number[] = [] + for (let i = 0; i < keep.length; i++) if (keep[i]) out.push(i) + return out +} + +function perpDistMeters(p: LatLng, a: LatLng, b: LatLng): number { + const mPerDegLat = 111_320 + const mPerDegLng = 111_320 * Math.cos((a.lat * Math.PI) / 180) + const bx = (b.lng - a.lng) * mPerDegLng + const by = (b.lat - a.lat) * mPerDegLat + const px = (p.lng - a.lng) * mPerDegLng + const py = (p.lat - a.lat) * mPerDegLat + const len = Math.sqrt(bx * bx + by * by) + if (len === 0) return Math.sqrt(px * px + py * py) + return Math.abs(bx * -py - -px * by) / len +} diff --git a/miniapps/navigation/src/background/lib/testBitmap.ts b/miniapps/navigation/src/background/lib/testBitmap.ts new file mode 100644 index 0000000000000000000000000000000000000000..a994e3aad12316f1a0fe32cc534bb17d431f8e03 --- /dev/null +++ b/miniapps/navigation/src/background/lib/testBitmap.ts @@ -0,0 +1,7 @@ +// AUTO-GENERATED test bitmap used by the dev panel's "Send test bitmap" +// button. Generated from /Users/aryan/Documents/test.png at 288x288, encoded +// as an 8-bit grayscale BMP (matches the shape produced by encodeBmpBase64()). +// Kept in its own file so the ~112 KB literal does not clutter caller code. + +export const TEST_BITMAP_288_B64 = + "Qk02SAEAAAAAADYEAAAoAAAAIAEAACABAAABAAgAAAAAAABEAQATCwAAEwsAAAABAAAAAQAAAAAAAAEBAQACAgIAAwMDAAQEBAAFBQUABgYGAAcHBwAICAgACQkJAAoKCgALCwsADAwMAA0NDQAODg4ADw8PABAQEAAREREAEhISABMTEwAUFBQAFRUVABYWFgAXFxcAGBgYABkZGQAaGhoAGxsbABwcHAAdHR0AHh4eAB8fHwAgICAAISEhACIiIgAjIyMAJCQkACUlJQAmJiYAJycnACgoKAApKSkAKioqACsrKwAsLCwALS0tAC4uLgAvLy8AMDAwADExMQAyMjIAMzMzADQ0NAA1NTUANjY2ADc3NwA4ODgAOTk5ADo6OgA7OzsAPDw8AD09PQA+Pj4APz8/AEBAQABBQUEAQkJCAENDQwBEREQARUVFAEZGRgBHR0cASEhIAElJSQBKSkoAS0tLAExMTABNTU0ATk5OAE9PTwBQUFAAUVFRAFJSUgBTU1MAVFRUAFVVVQBWVlYAV1dXAFhYWABZWVkAWlpaAFtbWwBcXFwAXV1dAF5eXgBfX18AYGBgAGFhYQBiYmIAY2NjAGRkZABlZWUAZmZmAGdnZwBoaGgAaWlpAGpqagBra2sAbGxsAG1tbQBubm4Ab29vAHBwcABxcXEAcnJyAHNzcwB0dHQAdXV1AHZ2dgB3d3cAeHh4AHl5eQB6enoAe3t7AHx8fAB9fX0Afn5+AH9/fwCAgIAAgYGBAIKCggCDg4MAhISEAIWFhQCGhoYAh4eHAIiIiACJiYkAioqKAIuLiwCMjIwAjY2NAI6OjgCPj48AkJCQAJGRkQCSkpIAk5OTAJSUlACVlZUAlpaWAJeXlwCYmJgAmZmZAJqamgCbm5sAnJycAJ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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" diff --git a/miniapps/navigation/src/background/managers/AudioGuidanceManager.ts b/miniapps/navigation/src/background/managers/AudioGuidanceManager.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e29d9db1ed6ac62af6f383f0d2adabd7034c045 --- /dev/null +++ b/miniapps/navigation/src/background/managers/AudioGuidanceManager.ts @@ -0,0 +1,565 @@ +import type {NavStatus, UnitSystem, VoiceGuidanceMode} from "../../shared/types" + +export type AudioTravelMode = "walking" | "driving" | "cycling" | "two_wheeler" + +type SpeakerPort = { + speak( + text: string, + options?: {stopOtherAudio?: boolean; voice_settings?: Record}, + ): Promise<{completed: boolean}> + stop(): void +} + +export type AudioGuidanceInput = { + status: NavStatus + running: boolean + routeRevision: number + pivotIndex: number | null + maneuverType: string | null + instruction: string | null + distanceMeters: number | null + offRoute: boolean + destinationName: string | null + arrivalSide: "left" | "right" | null + travelMode: AudioTravelMode + unitSystem: UnitSystem +} + +type Prompt = { + text: string + priority: number + expiresAt: number + maneuverKey?: string +} + +type Thresholds = {prepareMeters: number; nowMeters: number} + +const THRESHOLDS: Record = { + walking: {prepareMeters: 60, nowMeters: 10}, + cycling: {prepareMeters: 200, nowMeters: 25}, + driving: {prepareMeters: 500, nowMeters: 60}, + two_wheeler: {prepareMeters: 350, nowMeters: 50}, +} + +const MIN_AUTOMATIC_PROMPT_GAP_MS = 3_500 +const STARTUP_OFF_ROUTE_GRACE_MS = 15_000 +const TURN_TYPES = new Set([ + "TURN_LEFT", + "TURN_RIGHT", + "SLIGHT_LEFT", + "SLIGHT_RIGHT", + "SHARP_LEFT", + "SHARP_RIGHT", + "U_TURN", + "CROSS_STREET", +]) + +/** + * Converts the navigation engine's ~1 Hz/per-metre progress stream into a + * deliberately sparse spoken experience: one preparation prompt and one + * action prompt per maneuver, plus deduplicated lifecycle alerts. + */ +export class AudioGuidanceManager { + private available = false + private mode: VoiceGuidanceMode = "off" + private tripActive = false + private tripConfirmed = false + private tripStartedAt: number | null = null + private startupOffRouteSuppressed = false + private startupRerouteSuppressed = false + private allowImplicitResume = true + private latestUnconfirmedInput: AudioGuidanceInput | null = null + private lastStatus: NavStatus = "idle" + private lastOffRoute = false + private currentManeuverKey: string | null = null + private currentPivotIndex: number | null = null + private currentRepeatPhrase: string | null = null + private lastSignature = "" + private lastDistance: number | null = null + private syntheticSequence = 0 + private spokenStages = new Set() + private speakingGeneration = 0 + private speaking = false + private speakingPriority = 0 + private speakingManeuverKey: string | null = null + private pending: Prompt | null = null + private pendingTimer: ReturnType | null = null + private lastPromptStartedAt = 0 + private disposed = false + + constructor( + private readonly speaker: SpeakerPort, + private readonly log: (message: string) => void = () => {}, + ) {} + + setAvailable(available: boolean): void { + this.available = available + if (!available) this.stopSpeech() + } + + setMode(mode: VoiceGuidanceMode): void { + this.mode = mode + if (mode === "off") this.stopSpeech() + } + + beginTrip(): void { + this.stopSpeech() + this.tripActive = true + this.tripConfirmed = false + this.tripStartedAt = null + this.startupOffRouteSuppressed = false + this.startupRerouteSuppressed = false + this.allowImplicitResume = false + this.latestUnconfirmedInput = null + this.lastStatus = "navigating" + this.lastOffRoute = false + this.resetManeuverState() + } + + confirmTripStarted(destinationName: string | null): void { + if (!this.tripActive) return + this.tripConfirmed = true + this.tripStartedAt = Date.now() + if (this.canSpeak()) { + const destination = cleanSpokenText(destinationName) + this.enqueue({ + text: destination ? `Navigation started to ${destination}.` : "Navigation started.", + // Lead the first maneuver cue, but still allow arrival to interrupt. + priority: 100, + expiresAt: Date.now() + 12_000, + }) + } + const latest = this.latestUnconfirmedInput + this.latestUnconfirmedInput = null + if (latest) this.observe(latest) + } + + observe(input: AudioGuidanceInput): void { + if (this.disposed) return + + if (!input.running && input.status === "idle") { + if (this.tripActive) this.endTrip() + this.lastStatus = input.status + return + } + + // Keep the manager usable for an already-running session restored by the + // host, where beginTrip()/confirmTripStarted() did not occur in this JS + // lifetime. Explicit new trips still enter the unconfirmed path below. + if (this.allowImplicitResume && !this.tripActive && input.running && input.status === "navigating") { + this.tripActive = true + this.tripConfirmed = true + this.tripStartedAt = null + this.allowImplicitResume = false + } + if (!this.tripActive) { + this.lastStatus = input.status + return + } + + // The native engine can emit its first maneuver before navigation.start() + // resolves. Keep only the freshest update and replay it after the start + // confirmation so spoken guidance never leads with a turn instruction. + if (this.tripActive && !this.tripConfirmed) { + this.latestUnconfirmedInput = input + return + } + + const startupOffRouteGraceActive = this.isStartupOffRouteGraceActive() + const enteredRerouting = input.status === "rerouting" && this.lastStatus !== "rerouting" + const deferredStartupReroute = + input.status === "rerouting" && this.startupRerouteSuppressed && !startupOffRouteGraceActive + if (enteredRerouting || deferredStartupReroute) { + this.discardStaleManeuverPrompts() + this.currentManeuverKey = null + this.currentRepeatPhrase = "Rerouting." + if (startupOffRouteGraceActive) { + this.startupRerouteSuppressed = true + } else { + this.startupRerouteSuppressed = false + this.enqueue({text: "Off route. Rerouting.", priority: 100, expiresAt: Date.now() + 10_000}) + } + } else if (input.status !== "rerouting") { + this.startupRerouteSuppressed = false + } + + if (input.status === "arrived" && this.lastStatus !== "arrived") { + const destination = cleanSpokenText(input.destinationName) + const side = input.arrivalSide ? `, on your ${input.arrivalSide}` : "" + const phrase = destination ? `You have arrived at ${destination}${side}.` : `You have arrived${side}.` + this.currentManeuverKey = null + this.currentRepeatPhrase = phrase + this.enqueue({text: phrase, priority: 110, expiresAt: Date.now() + 20_000}) + this.tripActive = false + this.allowImplicitResume = false + this.lastOffRoute = false + } + + this.lastStatus = input.status + if (!input.running || input.status !== "navigating") return + this.tripActive = true + + // A route can initially snap to a walkable road tens of metres from an + // indoor or noisy GPS fix. Keep real rerouting active, but do not speak + // either an off-route warning or maneuver guidance derived from that + // unstable fix. A stable on-route update resumes the current maneuver + // afresh; if the condition persists past the grace period, the normal + // one-shot warning becomes eligible. + if (input.offRoute && startupOffRouteGraceActive) { + if (!this.startupOffRouteSuppressed) { + this.discardStaleManeuverPrompts() + this.currentManeuverKey = null + this.currentPivotIndex = null + this.currentRepeatPhrase = null + } + this.startupOffRouteSuppressed = true + return + } + if (input.offRoute) { + this.startupOffRouteSuppressed = false + if (!this.lastOffRoute) { + const phrase = "You are off route. Go back to the route." + this.discardStaleManeuverPrompts() + this.currentManeuverKey = null + this.currentRepeatPhrase = phrase + this.enqueue({text: phrase, priority: 100, expiresAt: Date.now() + 12_000}) + } + this.lastOffRoute = true + return + } + if (this.lastOffRoute || this.startupOffRouteSuppressed) { + // Returning to the route should evaluate the current maneuver afresh; + // stages spoken before the deviation no longer describe the live spot. + this.currentManeuverKey = null + this.currentPivotIndex = null + } + this.startupOffRouteSuppressed = false + this.lastOffRoute = false + + const instruction = cleanSpokenText(input.instruction) + const maneuverType = input.maneuverType?.toUpperCase() ?? null + const distance = validDistance(input.distanceMeters) + if (!instruction || !maneuverType) return + + const signature = `${input.routeRevision}|${maneuverType}|${instruction.toLowerCase()}` + const thresholds = THRESHOLDS[input.travelMode] + // Consecutive identical turns without pivot metadata advance by jumping + // from a near-zero distance to the next turn's much larger distance. + const previousNowSpoken = + this.currentManeuverKey != null && this.spokenStages.has(`${this.currentManeuverKey}|now`) + const distanceRebounded = + input.pivotIndex == null && + signature === this.lastSignature && + distance != null && + this.lastDistance != null && + (distance > this.lastDistance + Math.max(25, thresholds.prepareMeters / 2) || + (previousNowSpoken && + distance > thresholds.nowMeters && + distance > this.lastDistance + Math.max(10, thresholds.nowMeters / 2))) + + const pivotChanged = + this.currentPivotIndex != null && input.pivotIndex != null && input.pivotIndex !== this.currentPivotIndex + const newSemanticManeuver = + this.currentManeuverKey == null || signature !== this.lastSignature || pivotChanged || distanceRebounded + if (newSemanticManeuver) { + this.discardStaleManeuverPrompts() + this.syntheticSequence += 1 + this.currentManeuverKey = `${signature}|semantic-${this.syntheticSequence}` + this.currentPivotIndex = input.pivotIndex + } else if (this.currentPivotIndex == null && input.pivotIndex != null) { + // The same maneuver first arrived before PivotEngine bound metadata. + // Attach the pivot without changing its identity or replaying stages. + this.currentPivotIndex = input.pivotIndex + } + this.lastSignature = signature + this.lastDistance = distance + const maneuverKey = this.currentManeuverKey + if (!maneuverKey) return + + const preparePhrase = buildPreparationPhrase(instruction, distance, input.unitSystem) + const nowPhrase = buildNowPhrase(instruction, maneuverType) + + if (maneuverType === "ARRIVE") { + const approachPhrase = + distance == null ? "Approaching your destination." : `Destination in ${formatSpokenDistance(distance, input.unitSystem)}.` + this.currentRepeatPhrase = approachPhrase + const approachStage = `${maneuverKey}|prepare` + if ( + this.canSpeak() && + this.mode === "full" && + distance != null && + distance <= thresholds.prepareMeters && + !this.spokenStages.has(approachStage) + ) { + this.spokenStages.add(approachStage) + this.enqueue({ + text: approachPhrase, + priority: 30, + expiresAt: Date.now() + 15_000, + maneuverKey, + }) + } + return + } + + this.currentRepeatPhrase = + distance != null && distance <= thresholds.nowMeters && TURN_TYPES.has(maneuverType) ? nowPhrase : preparePhrase + + if (!this.canSpeak()) return + + const nowStage = `${maneuverKey}|now` + if ( + TURN_TYPES.has(maneuverType) && + distance != null && + distance <= thresholds.nowMeters && + !this.spokenStages.has(nowStage) + ) { + this.spokenStages.add(nowStage) + this.enqueue({ + text: nowPhrase, + priority: 90, + expiresAt: Date.now() + 7_000, + maneuverKey, + }) + return + } + + const prepareStage = `${maneuverKey}|prepare` + if ( + this.mode === "full" && + distance != null && + distance <= thresholds.prepareMeters && + distance > thresholds.nowMeters && + !this.spokenStages.has(nowStage) && + !this.spokenStages.has(prepareStage) + ) { + this.spokenStages.add(prepareStage) + this.enqueue({ + text: preparePhrase, + priority: 30, + expiresAt: Date.now() + 15_000, + maneuverKey, + }) + } + } + + repeatCurrent(): boolean { + if (!this.canSpeak() || !this.tripActive || !this.currentRepeatPhrase) return false + this.enqueue({ + text: this.currentRepeatPhrase, + priority: 95, + expiresAt: Date.now() + 8_000, + maneuverKey: this.currentManeuverKey ?? undefined, + }) + return true + } + + endTrip(): void { + this.tripActive = false + this.tripConfirmed = false + this.tripStartedAt = null + this.startupOffRouteSuppressed = false + this.startupRerouteSuppressed = false + this.allowImplicitResume = false + this.latestUnconfirmedInput = null + this.lastStatus = "idle" + this.lastOffRoute = false + this.currentRepeatPhrase = null + this.resetManeuverState() + this.stopSpeech() + } + + dispose(): void { + this.disposed = true + this.endTrip() + } + + private canSpeak(): boolean { + return !this.disposed && this.available && this.mode !== "off" + } + + private isStartupOffRouteGraceActive(): boolean { + return this.tripStartedAt != null && Date.now() - this.tripStartedAt < STARTUP_OFF_ROUTE_GRACE_MS + } + + private resetManeuverState(): void { + this.currentManeuverKey = null + this.currentPivotIndex = null + this.currentRepeatPhrase = null + this.lastSignature = "" + this.lastDistance = null + this.syntheticSequence = 0 + this.spokenStages.clear() + this.pending = null + this.clearPendingTimer() + } + + private enqueue(prompt: Prompt): void { + if (!this.canSpeak() || !prompt.text) return + if (prompt.priority >= 90) { + // An action/repeat/lifecycle cue supersedes deferred advance notice. + // Otherwise a prepare prompt waiting out the automatic gap can fire + // after "turn now", when it is both stale and actively confusing. + this.pending = null + this.clearPendingTimer() + if (this.speaking && prompt.priority >= this.speakingPriority) { + this.speaker.stop() + this.startPrompt(prompt) + return + } + } + + if (this.speaking) { + if (!this.pending || prompt.priority >= this.pending.priority) this.pending = prompt + return + } + + const gap = prompt.priority >= 90 ? 0 : MIN_AUTOMATIC_PROMPT_GAP_MS + const wait = Math.max(0, this.lastPromptStartedAt + gap - Date.now()) + if (wait > 0) { + if (!this.pending || prompt.priority >= this.pending.priority) this.pending = prompt + if (!this.pendingTimer) { + this.pendingTimer = setTimeout(() => { + this.pendingTimer = null + this.drainPending() + }, wait) + } + return + } + this.startPrompt(prompt) + } + + private startPrompt(prompt: Prompt): void { + if (!this.isPromptValid(prompt)) return + const generation = ++this.speakingGeneration + this.speaking = true + this.speakingPriority = prompt.priority + this.speakingManeuverKey = prompt.maneuverKey ?? null + this.lastPromptStartedAt = Date.now() + this.log(`VOICE ${prompt.text}`) + void this.speaker + .speak(prompt.text, { + // The host's playback session ducks external media. Do not abort other + // miniapp streams merely to deliver a short navigation cue. + stopOtherAudio: false, + voice_settings: {speed: 1.05}, + }) + .catch((err) => { + this.log(`VOICE failed: ${err instanceof Error ? err.message : String(err)}`) + }) + .finally(() => { + if (generation !== this.speakingGeneration) return + this.speaking = false + this.speakingPriority = 0 + this.speakingManeuverKey = null + this.drainPending() + }) + } + + private drainPending(): void { + if (this.speaking) return + const next = this.pending + this.pending = null + if (!next || !this.isPromptValid(next)) return + this.enqueue(next) + } + + private isPromptValid(prompt: Prompt): boolean { + if (!this.canSpeak() || Date.now() > prompt.expiresAt) return false + return !prompt.maneuverKey || prompt.maneuverKey === this.currentManeuverKey + } + + private discardStaleManeuverPrompts(): void { + if (this.pending?.maneuverKey) { + this.pending = null + this.clearPendingTimer() + } + if (!this.speaking || !this.speakingManeuverKey) return + + // A route/pivot change invalidates even an utterance that has already + // started. Interrupt only maneuver-bound speech; lifecycle cues such as + // "Navigation started" deliberately have no maneuver key and continue. + this.speakingGeneration += 1 + this.speaker.stop() + this.speaking = false + this.speakingPriority = 0 + this.speakingManeuverKey = null + } + + private stopSpeech(): void { + this.pending = null + this.clearPendingTimer() + this.speakingGeneration += 1 + if (this.speaking) this.speaker.stop() + this.speaking = false + this.speakingPriority = 0 + this.speakingManeuverKey = null + } + + private clearPendingTimer(): void { + if (!this.pendingTimer) return + clearTimeout(this.pendingTimer) + this.pendingTimer = null + } +} + +/** + * Arrival guidance follows the live destination countdown, while turn cues + * stay paired with the native event that supplied their type and instruction. + */ +export function selectAudioGuidanceDistance( + maneuverType: string | null | undefined, + eventDistanceMeters: number | null | undefined, + liveDisplayDistanceMeters: number | null | undefined, +): number | null { + const eventDistance = validDistance(eventDistanceMeters ?? null) + if (maneuverType?.toUpperCase() !== "ARRIVE") return eventDistance + return validDistance(liveDisplayDistanceMeters ?? null) ?? eventDistance +} + +function validDistance(value: number | null): number | null { + return value != null && Number.isFinite(value) && value >= 0 ? value : null +} + +function cleanSpokenText(value: string | null | undefined): string { + return (value ?? "") + .replace(/[\n\r]+/g, " ") + .replace(/[←→↑↺↰↱↖↗⤴⤵●⇆]/g, "") + .replace(/\s+/g, " ") + .replace(/[.\s]+$/, "") + .trim() +} + +function buildPreparationPhrase(instruction: string, distanceMeters: number | null, unit: UnitSystem): string { + if (distanceMeters == null) return `${capitalize(instruction)}.` + return `In ${formatSpokenDistance(distanceMeters, unit)}, ${lowercaseFirst(instruction)}.` +} + +function buildNowPhrase(instruction: string, maneuverType: string): string { + if (maneuverType === "CROSS_STREET") return "Cross the street now." + if (maneuverType === "U_TURN") return "Turn around now." + return `${capitalize(instruction)} now.` +} + +function formatSpokenDistance(meters: number, unit: UnitSystem): string { + if (unit === "imperial") { + const feet = meters * 3.28084 + if (feet < 528) return `${Math.max(10, Math.round(feet / 10) * 10)} feet` + const miles = feet / 5280 + return `${miles.toFixed(1)} ${miles >= 0.95 && miles < 1.05 ? "mile" : "miles"}` + } + if (meters < 1000) { + const rounded = meters < 100 ? Math.max(5, Math.round(meters / 5) * 5) : Math.round(meters / 10) * 10 + return `${rounded} meters` + } + const kilometers = meters / 1000 + return `${kilometers.toFixed(1)} ${kilometers >= 0.95 && kilometers < 1.05 ? "kilometer" : "kilometers"}` +} + +function capitalize(value: string): string { + return value ? value.charAt(0).toUpperCase() + value.slice(1) : value +} + +function lowercaseFirst(value: string): string { + return value ? value.charAt(0).toLowerCase() + value.slice(1) : value +} diff --git a/miniapps/navigation/src/background/managers/CompassManager.ts b/miniapps/navigation/src/background/managers/CompassManager.ts new file mode 100644 index 0000000000000000000000000000000000000000..528342b4ecb9e6389fd06d9f9eb18dd28ec673cc --- /dev/null +++ b/miniapps/navigation/src/background/managers/CompassManager.ts @@ -0,0 +1,21 @@ +/** + * CompassManager + * + * Thin wrapper over `session.heading.onUpdate`. Same shape as the SDK's + * heading module — callers do `user.compass.onUpdate(handler)` and own + * their state. + */ + +import type {HeadingData, MiniappSession} from "@mentra/miniapp" + +export type CompassListener = (data: HeadingData) => void +export type Unsubscribe = () => void + +export class CompassManager { + constructor(private readonly session: MiniappSession) {} + + /** Subscribe to continuous compass-heading updates. */ + onUpdate(handler: CompassListener): Unsubscribe { + return this.session.heading.onUpdate(handler) + } +} diff --git a/miniapps/navigation/src/background/managers/DisplayManager.ts b/miniapps/navigation/src/background/managers/DisplayManager.ts new file mode 100644 index 0000000000000000000000000000000000000000..77f00dd34f4a4b2f8013f95a5e2d2ebf67af17ca --- /dev/null +++ b/miniapps/navigation/src/background/managers/DisplayManager.ts @@ -0,0 +1,372 @@ +/** + * DisplayManager + * + * Thin imperative wrapper over `session.display.*`. Mirrors the SDK + * module shape — short verbs that delegate to the underlying + * DisplayManager. Callers decide when to push. + */ + +import type {MiniappSession, RenderElement} from "@mentra/miniapp" +import {borderTestImageBase64} from "../lib/bmp" +import {readGlassesCapabilities} from "../lib/capabilities" + +export class DisplayManager { + constructor(private readonly session: MiniappSession) {} + + private get bitmapLimits() { + const display = this.session.capabilities?.display + const dimension = (value: unknown, fallback: number) => + typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback + const width = dimension(display?.width, 576) + const height = dimension(display?.height, 288) + return { + width, + height, + maxWidth: display?.maxImageElements === 0 ? 0 : Math.min(width, dimension(display?.maxImagePx?.width, width)), + maxHeight: display?.maxImageElements === 0 ? 0 : Math.min(height, dimension(display?.maxImagePx?.height, height)), + } + } + + /** Whether the selected display can show a positioned bitmap. */ + get supportsBitmaps(): boolean { + const {maxWidth, maxHeight} = this.bitmapLimits + return this.session.capabilities?.display?.canPosition !== false && maxWidth > 0 && maxHeight > 0 + } + + /** Choose raster dimensions before encoding, using the same limits as placement. */ + getBitmapSize(width = 288, height = 140): {w: number; h: number} { + const {maxWidth, maxHeight} = this.bitmapLimits + const w = Math.min(width, maxWidth) + const h = Math.min(height, maxHeight) + this.bitmapBox(w, h) + return {w, h} + } + + private bitmapBox(w: number, h: number): {x: number; y: number; w: number; h: number} { + const {width, height, maxWidth, maxHeight} = this.bitmapLimits + if (!Number.isInteger(w) || !Number.isInteger(h) || w <= 0 || h <= 0 || w > maxWidth || h > maxHeight) { + throw new RangeError(`Bitmap ${w}x${h} is unsupported; maximum image size is ${maxWidth}x${maxHeight}`) + } + return {x: Math.round((width - w) / 2), y: Math.round((height - h) / 2), w, h} + } + + // ── Navigation HUD layout ──────────────────────────────────────────── + // Boxes on the 500×220 Mentra canvas, from the nav HUD mockup: a map bitmap + // on the right, a turn-arrow bitmap on the left, trip stats along the top, + // and the maneuver instruction below the arrow. The firmware draws the outer + // rounded frame itself, so we only send these content slots. `message` shares + // the arrow's left x and spans the content area (staying clear of the map). + static readonly HUD = { + // Keep the map below the two-line stats region. Both regions meet at y=80 + // without overlapping and still fit the 220px-tall HUD canvas exactly. + map: {x: 340, y: 80, w: 140, h: 140}, + arrow: {x: 0, y: 182, w: 38, h: 38}, + // Wall-clock current time, top-LEFT (the phone's clock, sent each refresh). + // The widest 24-hour clock is 52px in the G2 font, and native adds 4px of + // padding on each side. Keep a little extra headroom so it never wraps into + // a clipped second line. + clock: {x: 0, y: 0, w: 64, h: 40}, + // Long distance + ETA strings can wrap. Give the top-right stats region + // two full calibrated G2 lines instead of letting a second line overflow a + // 28px box. The wider box also keeps the common case on one line. + stats: {x: 280, y: 0, w: 200, h: 80}, + // The body contains a distance line plus an instruction that may itself + // wrap (for example, "Turn right onto Gough Street"). G2 clips by + // floor(height / 40px), so reserve three complete lines; the old 52px box + // admitted only the distance and silently removed the instruction. + maneuver: {x: 40, y: 100, w: 270, h: 120}, + message: {x: 12, y: 54, w: 310, h: 156}, + } + + // ── HUD frame state ────────────────────────────────────────────────── + // render() replaces the whole frame, so this class caches the CONTENT of + // each slot (the arrow/map bitmaps are expensive to produce, not to resend — + // the host diffs frames and unchanged elements never re-cross BLE) and + // composes the full scene on every push. No element lifecycle, no removes: + // what's on screen is exactly what buildFrame() returns. + private mode: "hud" | "message" | null = null + private arrowBmp: string | null = null + private mapBmp: string | null = null + private clock: string | null = null + private stats: string | null = null + private maneuver: string | null = null + private message: string | null = null + + private buildFrame(): RenderElement[] { + const els: RenderElement[] = [] + if (this.mode === "hud") { + if (this.arrowBmp) els.push({type: "image", id: "arrow", box: DisplayManager.HUD.arrow, data: this.arrowBmp}) + if (this.maneuver != null) + els.push({type: "text", id: "maneuver", box: DisplayManager.HUD.maneuver, text: this.maneuver}) + if (this.stats != null) els.push({type: "text", id: "stats", box: DisplayManager.HUD.stats, text: this.stats}) + } else if (this.mode === "message" && this.message != null) { + els.push({ + type: "text", + id: "message", + box: DisplayManager.HUD.message, + text: this.message, + ...(readGlassesCapabilities(this.session.capabilities).canPosition + ? {style: {breakMode: "word" as const}} + : {}), + }) + } + // The clock (top-left) and minimap ride along in both modes. + if (this.clock != null) els.push({type: "text", id: "clock", box: DisplayManager.HUD.clock, text: this.clock}) + if (this.mapBmp) els.push({type: "image", id: "map", box: DisplayManager.HUD.map, data: this.mapBmp}) + return els + } + + private pushFrame(): void { + this.safeCall(() => void this.session.display.render(this.buildFrame())) + } + + /** + * Turn-by-turn HUD frame: arrow bitmap (left), maneuver text (bottom), trip + * stats (top) — plus the cached minimap. Fields set to a value (including + * null) overwrite that slot; omitted fields keep their cached content, so the + * caller only re-encodes the arrow BMP when the direction changes. + */ + showNavHud(frame: {arrowBmp?: string; stats?: string | null; maneuver?: string | null; clock?: string | null}): void { + this.mode = "hud" + if (frame.arrowBmp !== undefined) this.arrowBmp = frame.arrowBmp + if (frame.stats !== undefined) this.stats = frame.stats + if (frame.maneuver !== undefined) this.maneuver = frame.maneuver + if (frame.clock !== undefined) this.clock = frame.clock + this.pushFrame() + } + + /** + * Single-message state (welcome / "Starting…" / rerouting / arrived): the + * whole frame becomes the message (plus minimap). Turn-by-turn slots simply + * stop being rendered — render() replaces the frame, nothing to remove. + */ + showNavMessage(text: string, clock?: string | null): void { + this.mode = "message" + this.message = text + if (clock !== undefined) this.clock = clock + this.pushFrame() + } + + /** + * Navigation frame for non-positioning displays such as Even Realities G1. + * Keep the maneuver first and emit one text element: host-side scene + * degradation otherwise inserts blank lines between the positioned clock, + * stats, and maneuver elements, pushing the instruction past G1's five-line + * limit. Images and clock are deliberately cleared because these displays + * cannot render them through the scene API. + */ + showCompactNavHud(maneuver: string, stats: string | null): void { + this.mode = "message" + this.message = [maneuver, stats].filter(Boolean).join("\n\n") + this.clock = null + this.mapBmp = null + this.pushFrame() + } + + // ── Display sends ──────────────────────────────────────────────────── + // Sends are INSTANT — each show fires immediately, no spacing/throttle. + // (We previously serialized text through a 200ms queue, but that's removed: + // `enqueue` now just fires the thunk right away. The `box` key is kept in + // the signature only so call sites read clearly and so a future throttle + // could be reintroduced without touching them.) + private enqueue(_box: string, fn: () => void): void { + this.safeCall(fn) + } + + /** + * Single line filling the glasses display. + * `durationMs` is forwarded to the SDK; if set, the message auto-clears + * after that long. Omit for a sticky message that persists until replaced. + */ + showText(text: string, durationMs?: number): void { + const {width: w, height: h} = this.bitmapLimits + this.enqueue( + "wall", + () => + void this.session.display.render( + [{type: "text", id: "wall", box: {x: 0, y: 0, w, h}, text}], + durationMs != null ? {durationMs} : undefined, + ), + ) + } + + showTextTest(): void { + this.showText( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec venenatis vulputate lorem. Maecenas vestibulum mollis diam. Pellentesque ut neque. Sed lectus. Donec sodales sagittis magna.", + ) + } + + // showTwoLines(top: string, bottom: string): void { + // this.showText(`${top} / ${bottom}`) + // } + + // /** Title + body card. */ + // showCard(title: string, body: string): void { + // this.showText(`${title} — ${body}`) + // } + + /** + * Show a bitmap on the glasses. `base64Bmp` is a base64-encoded 1-bit + * BMP (see MinimapRenderer/bmp.ts). `width`/`height` size the target + * container on the glasses canvas. + */ + showBitmap(base64Bmp: string): void { + // The minimap is the "map" slot of the HUD frame — refreshMinimap runs on + // its own async cadence, so it updates the cache and re-pushes whatever + // frame is current (host diff keeps unchanged slots off BLE). + this.mapBmp = base64Bmp + this.pushFrame() + } + + /** + * Drop the minimap slot (e.g. when switching to the swipe-up large map, which + * renders at a different rect). + */ + clearMinimap(): void { + this.mapBmp = null + this.pushFrame() + } + + /** + * Swipe test box centered on the advertised canvas. Reject unsupported + * sizes before clearing, so a diagnostic cannot silently blank the display. + */ + showTestBox(width: number, height: number): void { + const {w, h} = this.bitmapBox(width, height) + const base64Bmp = borderTestImageBase64(w, h) + // Clear first, wait 1s so old containers tear down, THEN draw the box. + this.safeCall(() => void this.session.display.render([])) + setTimeout(() => { + this.renderCenteredBitmap(base64Bmp, w, h) + }, 1000) + } + + /** One centered image element as the whole frame (test/large-map paths). */ + private renderCenteredBitmap(data: string, w: number, h: number): void { + const box = this.bitmapBox(w, h) + this.safeCall(() => void this.session.display.render([{type: "image", id: "bmp", box, data}])) + } + + /** + * Large map shown on swipe-up. Call getBitmapSize before rasterizing; + * silently clamping only the box would disagree with the encoded image. + */ + showLargeBitmap(base64Bmp: string, width = 288, height = 140): void { + this.renderCenteredBitmap(base64Bmp, width, height) + } + + // ── Two stacked text containers ────────────────────────────────────── + // The G2's single full-screen (576×288) text wall only fits ~5 lines. To get + // more usable vertical text we split into two stacked positioned-text + // containers: maneuver/directions on top, trip stats below. + // SINGLE-CONTAINER HUD: the whole frame (maneuver block + trip stats) is now + // crammed into THIS one container, spanning the full canvas so all the lines + // fit. There is no longer a separate stats box below it. + // Full 500×220 Mentra canvas — used by the single-container states + // (welcome / rerouting / arrived / off-route), which don't use the 4-slot split. + private static readonly MANEUVER_REGION = {x: 0, y: 0, width: 500, height: 220} + + /** + * Single full-canvas message element shared by the single-container states + * (maneuver text, loading messages, trip stats). One stable id + one + * geometry means every push is a content-only update — the same last-wins + * behavior as the positioned_text sends it replaces. Replaces the whole + * frame; these states never coexist with the 4-slot HUD. + */ + private renderRegionText(text: string): void { + const r = DisplayManager.MANEUVER_REGION + void this.session.display.render([{type: "text", id: "msg", box: {x: r.x, y: r.y, w: r.width, h: r.height}, text}]) + } + + /** + * Maneuver / direction text in the TOP region of the canvas (its own G2 text + * container), leaving the bottom region free for the stats container. + */ + showManeuver(text: string): void { + // Queued under "maneuver" — drains after "minimap", before "stats". + this.enqueue("maneuver", () => this.renderRegionText(text)) + } + + /** + * Transition status text in the TOP-LEFT maneuver region, shown IMMEDIATELY + * (bypasses the 200ms text queue) — used for "Loading large map" / "Loading + * main menu" while a swipe transition settles, so the user sees feedback in + * the gap rather than a blank/stale screen. Bypasses the queue because it + * must appear right at the swipe, before any HUD text, and the transition + * clear() has just purged the queue anyway. + */ + showLoadingMessage(text: string): void { + this.safeCall(() => this.renderRegionText(text)) + } + + /** Blank the top-left loading message (overwrite its region with empty text). */ + clearLoadingMessage(): void { + this.safeCall(() => this.renderRegionText("")) + } + + /** + * Live trip-stats (distance + ETA) in the BOTTOM region, in its own G2 text + * container stacked under the maneuver box. + */ + showTripStats(text: string): void { + // Queued under "stats" — drains last, after "minimap" and "maneuver". + // STATS_REGION === MANEUVER_REGION (single-container HUD), so this rides + // the same shared message element. + this.enqueue("stats", () => this.renderRegionText(text)) + } + + /** + * Fixed 288x288 diagnostic asset. Reports an unsupported size on displays + * whose image or canvas limits cannot accommodate it; it is not resized. + */ + showBitmapTest(base64Bmp: string): void { + // render() replaces the whole frame — no separate clear needed. + this.renderCenteredBitmap(base64Bmp, 288, 288) + } + + /** + * Test-only: render a bordered bitmap at the exact requested size, centered + * on the device canvas. Unsupported probes fail before clearing the frame. + */ + showBitmapSize(size: number, height?: number): void { + const {w, h} = this.bitmapBox(size, height ?? size) + const base64Bmp = borderTestImageBase64(w, h) + // Clear first, wait 3s so the old container fully tears down, THEN draw the + // new bitmap — avoids the G2 reusing/overlapping a stale image container. + this.safeCall(() => void this.session.display.render([])) + setTimeout(() => { + this.renderCenteredBitmap(base64Bmp, w, h) + }, 3000) + } + + /** + * Test-only: show a pre-rendered base64 BMP at a given container size, + * centered within device limits. Used by the OSM line-map PoC. + */ + showRawBitmap(base64Bmp: string, width: number, height: number): void { + // Stable id + unchanged rect ⇒ the differ marks this a content-only update + // and the G2 swaps the bitmap into the existing container in place — the + // same no-flicker behavior the old rect-keyed container reuse gave. + this.renderCenteredBitmap(base64Bmp, width, height) + } + + /** Wipe whatever's on the glasses (and forget the cached frame slots). */ + clear(): void { + this.mode = null + this.arrowBmp = null + this.mapBmp = null + this.clock = null + this.stats = null + this.maneuver = null + this.message = null + this.safeCall(() => void this.session.display.render([])) + } + + private safeCall(fn: () => void): void { + try { + fn() + } catch (err) { + console.log("[NAV-MINI] display call ignored:", err) + } + } +} diff --git a/miniapps/navigation/src/background/managers/LocationManager.ts b/miniapps/navigation/src/background/managers/LocationManager.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3603c70c15ce079cc8f50ef4d9b40f84599f6bc --- /dev/null +++ b/miniapps/navigation/src/background/managers/LocationManager.ts @@ -0,0 +1,29 @@ +/** + * LocationManager + * + * Thin wrapper over `session.location.onUpdate`. Mirrors the shape of the + * SDK's `LocationModule` (sdk/miniapp/src/modules/location.ts) — the User + * holds an instance, callers do `user.location.onUpdate(handler)` and + * manage their own state. + */ + +import type {LocationData, MiniappSession} from "@mentra/miniapp" + +export type Coords = {lat: number; lng: number; accuracy?: number; ts: number} + +export type LocationListener = (data: LocationData) => void +export type Unsubscribe = () => void + +export class LocationManager { + constructor(private readonly session: MiniappSession) {} + + /** Subscribe to continuous location updates. */ + onUpdate(handler: LocationListener): Unsubscribe { + return this.session.location.onUpdate(handler) + } + + /** Request a single location fix. Useful at app load to seed UI. */ + getOnce(): Promise { + return this.session.location.getOnce() + } +} diff --git a/miniapps/navigation/src/background/managers/ManeuverFormatter.ts b/miniapps/navigation/src/background/managers/ManeuverFormatter.ts new file mode 100644 index 0000000000000000000000000000000000000000..beb2c6041e42539d7f44d0f8988bc60a9310a5de --- /dev/null +++ b/miniapps/navigation/src/background/managers/ManeuverFormatter.ts @@ -0,0 +1,192 @@ +/** + * ManeuverFormatter + * + * Pure presentation helpers for `NavManeuver` data — glyphs, arrows, + * human verbs, headlines, and the glasses NOW/NEXT line pair. Lives + * under `user.navigation.format` so anything maneuver-related has a + * single entry point. + * + * Stateless: every method is a pure function of its inputs. The class + * shape exists only so callers can reach the helpers via the + * NavigationManager (`user.navigation.format.headline(m)`). + */ + +import type {NavManeuver} from "@mentra/miniapp" + +import type {UnitSystem} from "../../shared/types" +import {formatDistance, formatDuration} from "../lib/formatDistance" + +/** Distance threshold below which a turn becomes the active instruction. */ +const IMMINENT_M = 30 + +export class ManeuverFormatter { + /** A "go straight" continuation rather than a turn. */ + isStraight(m: NavManeuver | null): boolean { + return !!m && (m.maneuverType === "STRAIGHT" || m.maneuverType === "CONTINUE") + } + + /** Capitalize first letter. */ + cap(s: string): string { + return s.charAt(0).toUpperCase() + s.slice(1) + } + + /** Big glyph for the OrientationCard / pill. */ + glyph(type: string): string { + switch (type.toUpperCase()) { + case "TURN_LEFT": + return "↰" + case "TURN_RIGHT": + return "↱" + case "SLIGHT_LEFT": + return "↖" + case "SLIGHT_RIGHT": + return "↗" + case "SHARP_LEFT": + return "⤴" + case "SHARP_RIGHT": + return "⤵" + case "U_TURN": + return "↶" + case "STRAIGHT": + case "CONTINUE": + return "↑" + case "ARRIVE": + return "●" + case "CROSS_STREET": + return "⇆" + default: + return "↑" + } + } + + /** Compact arrow for short text lines (←/→/↑). */ + arrow(type: string): string { + const t = type.toUpperCase() + if (t === "CROSS_STREET") return "⇆" + if (t.includes("LEFT")) return "←" + if (t.includes("RIGHT")) return "→" + if (t === "U_TURN") return "↺" + return "↑" + } + + /** Human-readable verb. */ + humanize(type: string): string { + switch (type.toUpperCase()) { + case "TURN_LEFT": + return "turn left" + case "TURN_RIGHT": + return "turn right" + case "SLIGHT_LEFT": + return "slight left" + case "SLIGHT_RIGHT": + return "slight right" + case "SHARP_LEFT": + return "sharp left" + case "SHARP_RIGHT": + return "sharp right" + case "U_TURN": + return "turn around" + case "STRAIGHT": + case "CONTINUE": + return "continue straight" + case "ARRIVE": + return "arrive" + case "CROSS_STREET": + return "cross the road" + default: + return type.toLowerCase().replace(/_/g, " ") + } + } + + /** + * One-line headline for the maneuver pill. Built from the categorical + * type + distance — no road names. + * + * "In 200 m, turn right" + * "Continue straight" + * "Arriving in 35 m" + */ + headline(m: NavManeuver, unit: UnitSystem = "metric"): string { + const verb = this.humanize(m.maneuverType) + if (m.maneuverType === "ARRIVE") { + return m.distanceMeters > 0 ? `Arriving in ${formatDistance(m.distanceMeters, unit)}` : "Arriving" + } + if (m.maneuverType === "STRAIGHT") { + return "Continue straight" + } + if (m.distanceMeters > 0) { + return `In ${formatDistance(m.distanceMeters, unit)}, ${verb}` + } + return this.cap(verb) + } + + /** + * Two short lines for the glasses HUD — NOW (top) + NEXT (bottom). + * Returns `next: null` when the imminent turn IS the active instruction + * (≤ IMMINENT_M), in which case the caller falls back to a single line. + */ + glassesLines(m: NavManeuver, unit: UnitSystem = "metric"): {now: string; next: string | null} { + const dist = m.distanceMeters + const isStraightT = this.isStraight(m) + const arrowed = (verb: string) => `${this.arrow(m.maneuverType)} ${verb}` + const toRoad = this.cleanRoad(m.toRoad, m.maneuverType) + + if (!isStraightT && dist >= 0 && dist <= IMMINENT_M) { + const verb = this.humanize(m.maneuverType) + // CROSS_STREET keeps the same road on both sides — never append + // "onto X". The verb already reads as a complete instruction. + const onto = m.maneuverType === "CROSS_STREET" || !toRoad ? "" : ` onto ${toRoad}` + return {now: arrowed(`${this.cap(verb)}${onto}`), next: null} + } + + const road = this.cleanRoad(m.fromRoad, m.maneuverType) + const distStr = dist > 0 ? formatDistance(dist, unit) : null + const nowLine = + road && distStr + ? `↑ ${road} • ${distStr}` + : road + ? `↑ ${road}` + : distStr + ? `↑ Continue ${distStr}` + : "↑ Continue" + + if (isStraightT) { + return {now: nowLine, next: null} + } + const verb = this.humanize(m.maneuverType) + const onto = m.maneuverType === "CROSS_STREET" || !toRoad ? "" : ` onto ${toRoad}` + return {now: nowLine, next: arrowed(`Then ${verb}${onto}`)} + } + + /** + * Third HUD line: "1.2 km to destination · 14 min". Returns null when + * the engine hasn't supplied trip totals yet (-1 sentinels), so the UI + * can hide the line instead of rendering em-dashes. + */ + glassesProgressLine(m: NavManeuver, unit: UnitSystem = "metric"): string | null { + const dist = m.distanceToDestinationMeters + const time = m.timeToDestinationSeconds + const haveDist = typeof dist === "number" && dist >= 0 + const haveTime = typeof time === "number" && time >= 0 + if (!haveDist && !haveTime) return null + const distStr = haveDist ? `${formatDistance(dist!, unit)} to destination` : null + const timeStr = haveTime ? formatDuration(time!) : null + return [distStr, timeStr].filter(Boolean).join(" · ") + } + + /** + * Drop a "road name" that's actually the maneuver instruction. The + * Google Nav SDK falls back to its instruction text (e.g. "Turn left") + * when the underlying road has no name, and that bubbles all the way + * here — concatenated naively, you'd render "Turn left onto Turn left". + * Returns null when the road string is empty or duplicates the verb. + */ + private cleanRoad(road: string | null | undefined, maneuverType: string): string | null { + const trimmed = road?.trim() + if (!trimmed) return null + const verb = this.humanize(maneuverType).toLowerCase() + const lower = trimmed.toLowerCase() + if (lower === verb || lower.startsWith(verb)) return null + return trimmed + } +} diff --git a/miniapps/navigation/src/background/managers/NavigationManager.ts b/miniapps/navigation/src/background/managers/NavigationManager.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0e8082f4ccd2f17985f2cc8d87d287d338c5c9f --- /dev/null +++ b/miniapps/navigation/src/background/managers/NavigationManager.ts @@ -0,0 +1,131 @@ +/** + * NavigationManager + * + * Thin wrapper over `session.navigation.*`. Mirrors the SDK module shape: + * imperative methods (start/stop/deviate) and subscribe-style listeners + * (onUpdate/onRoute). Callers manage their own state. + */ + +import type { + ComputeRouteOptions, + ComputeRouteResult, + MiniappSession, + NavigationDev, + NavRoute, + NavState, + NavUpdate, + Pivot, + PivotEvent, + StartNavigationOptions, +} from "@mentra/miniapp/background" + +import {ManeuverFormatter} from "./ManeuverFormatter" + +export type NavUpdateListener = (update: NavUpdate) => void +export type NavRouteListener = (route: NavRoute) => void +export type PivotListener = (event: PivotEvent) => void +export type Unsubscribe = () => void + +export class NavigationManager { + /** + * Presentation helpers for `NavManeuver` data — glyphs, arrows, human + * verbs, headlines, glasses lines. Lives here so all maneuver-related + * stuff is reachable via `user.navigation.format.*`. + */ + readonly format = new ManeuverFormatter() + + constructor(private readonly session: MiniappSession) {} + + /** True iff `LOCATION` is declared in the miniapp's manifest. */ + get hasPermission(): boolean { + return this.session.navigation.hasPermission + } + + /** + * Trigger the Google Nav SDK Terms & Conditions dialog. Idempotent and + * intended to be called eagerly on mount so `start()` is friction-free. + */ + requestPermission(): Promise<{ok: boolean; accepted: boolean; error?: string}> { + return this.session.navigation.requestPermission() + } + + /** Begin a turn-by-turn trip. */ + start(opts: StartNavigationOptions): Promise<{ok: boolean; error?: string}> { + return this.session.navigation.start(opts) + } + + /** Stop the active trip (if any). Fire-and-forget. */ + stop(): void { + this.session.navigation.stop() + } + + /** + * Dev-only helpers (simulator deviation, wrong-sidewalk lock, + * skip-crossings). Throws in production builds — gate all calls + * behind `if (process.env.NODE_ENV !== "production")`. See + * `NavigationModule.dev` for the underlying API. + */ + get dev(): NavigationDev { + return this.session.navigation.dev + } + + /** Subscribe to maneuver / rerouting / arrived / error events. */ + onUpdate(handler: NavUpdateListener): Unsubscribe { + return this.session.navigation.onUpdate(handler) + } + + /** Subscribe to the route polyline (full path each time it's rebuilt). */ + onRoute(handler: NavRouteListener): Unsubscribe { + return this.session.navigation.onRoute(handler) + } + + /** + * Snapshot of the active trip; null when no trip is running. Use on + * mount to hydrate state for a miniapp opening mid-trip. + */ + getState(): Promise { + return this.session.navigation.getState() + } + + /** Compute one or more routes without starting a trip. */ + computeRoute(opts: ComputeRouteOptions): Promise { + return this.session.navigation.computeRoute(opts) + } + + /** + * Reverse-geocode a coordinate to a road name + full address via the SDK, + * which routes through the v2 cloud maps service (the WebView never calls a + * maps provider directly). Normalizes the SDK's `{ok, road?, address?}` into a + * plain `{road, address}` for the RPC channel — a failed lookup surfaces as + * `{road: null, address: null}` rather than throwing, so dropped-pin / POI UI + * just falls back to coordinates. + */ + async reverseGeocode(coord: {lat: number; lng: number}): Promise<{ + road: string | null + address: string | null + }> { + const result = await this.session.navigation.reverseGeocodeRoad(coord) + if (!result.ok) return {road: null, address: null} + return {road: result.road ?? null, address: result.address ?? null} + } + + /** Subscribe to pivot events (approaching / entered / exited). */ + onPivot(handler: PivotListener): Unsubscribe { + return this.session.navigation.onPivot(handler) + } + + /** Full pivot list for the active route. */ + getPivots(): Pivot[] { + return this.session.navigation.getPivots() + } + + /** Pivot the user is currently inside the radius of, or null. */ + getActivePivot(): Pivot | null { + return this.session.navigation.getActivePivot() + } + + /** Next pivot ahead, or null when past the final pivot. */ + getUpcomingPivot(): Pivot | null { + return this.session.navigation.getUpcomingPivot() + } +} diff --git a/miniapps/navigation/src/background/managers/PlacesManager.ts b/miniapps/navigation/src/background/managers/PlacesManager.ts new file mode 100644 index 0000000000000000000000000000000000000000..318e19f39e77b4d16f25d0c50ec940955d287633 --- /dev/null +++ b/miniapps/navigation/src/background/managers/PlacesManager.ts @@ -0,0 +1,42 @@ +/** + * PlacesManager + * + * Background-side Places facade. Wraps `PlacesSession` so the + * `NavigationController` can expose `places:autocomplete` and + * `places:details` as RPC channels. The underlying session token is + * reset after every successful `details()` so the next autocomplete + * begins a fresh billing session. + * + * Place search goes through the miniapp SDK → host → v2 cloud maps service + * (Mapbox Search Box). There is no backend Worker. The request/response SDK + * bridge has no mid-flight cancellation, so a superseded keystroke can't abort + * an in-flight call — the UI's debounce limits wasted calls and the cloud + * coalesces identical prefixes, so this is fine. + */ + +import {PlacesSession} from "../lib/places" +import type {PlaceDetails, PlaceSuggestion} from "../lib/places" +import type {MiniappSession} from "@mentra/miniapp" + +export class PlacesManager { + private session: PlacesSession + + constructor(session: MiniappSession) { + this.session = new PlacesSession(session) + } + + autocomplete( + query: string, + near: {lat: number; lng: number} | undefined, + ): Promise { + return this.session.autocomplete(query, near) + } + + async details(placeId: string): Promise { + const result = await this.session.details(placeId) + // Rotate the session token after a successful pick so the next + // autocomplete is billed as a new session. + this.session.reset() + return result + } +} diff --git a/miniapps/navigation/src/background/managers/SimpleStorageManager.ts b/miniapps/navigation/src/background/managers/SimpleStorageManager.ts new file mode 100644 index 0000000000000000000000000000000000000000..79fb50e773d2f2c1461f8055ef5a8c93d4a81db4 --- /dev/null +++ b/miniapps/navigation/src/background/managers/SimpleStorageManager.ts @@ -0,0 +1,133 @@ +/** + * SimpleStorageManager + * + * Thin wrapper over `session.storage` for persistent phone-local key-value + * storage scoped to this miniapp. Values are always strings — callers + * JSON.stringify / JSON.parse structured data themselves. + * + * const storage = new SimpleStorageManager(session) + * await storage.set("recentDestinations", JSON.stringify([...])) + * const raw = await storage.get("recentDestinations") + */ + +import type {MiniappSession} from "@mentra/miniapp" +import type {PlaceDetails, SavedPlace} from "../lib/places" +import type {UnitSystem, VoiceGuidanceMode} from "../../shared/types" + +export class SimpleStorageManager { + constructor(private readonly session: MiniappSession) {} + + /** Retrieve a value by key. Returns null if the key does not exist. */ + get(key: string): Promise { + return this.session.storage.get(key) + } + + /** Store a string value. Overwrites any existing value for the key. */ + set(key: string, value: string): Promise { + return this.session.storage.set(key, value) + } + + /** Remove a key. No-op if the key does not exist. */ + delete(key: string): Promise { + return this.session.storage.delete(key) + } + + /** List all keys currently stored for this miniapp. */ + list(): Promise { + return this.session.storage.list() + } + + /** Convenience: get and JSON.parse in one call. Returns null on miss or parse error. */ + async getJSON(key: string): Promise { + const raw = await this.session.storage.get(key) + if (raw === null) return null + try { + return JSON.parse(raw) as T + } catch { + return null + } + } + + /** Convenience: JSON.stringify and set in one call. */ + setJSON(key: string, value: T): Promise { + return this.session.storage.set(key, JSON.stringify(value)) + } + + private static readonly RECENT_SEARCHES_KEY = "recentSearches" + private static readonly RECENT_SEARCHES_MAX = 10 + + /** Returns the saved list of recent searches, most recent first. */ + async getRecentSearches(): Promise { + return (await this.getJSON(SimpleStorageManager.RECENT_SEARCHES_KEY)) ?? [] + } + + /** Prepends a place to the recent searches list, deduplicates by placeId, and caps at 10. */ + async addRecentSearch(place: PlaceDetails): Promise { + const current = await this.getRecentSearches() + const next = [place, ...current.filter((p) => p.placeId !== place.placeId)].slice(0, SimpleStorageManager.RECENT_SEARCHES_MAX) + await this.setJSON(SimpleStorageManager.RECENT_SEARCHES_KEY, next) + } + + private static readonly SAVED_PLACES_KEY = "savedPlaces" + private static readonly SAVED_MAX = 20 + + /** Returns all saved places, most recently added first. */ + async getAllSavedPlaces(): Promise { + return (await this.getJSON(SimpleStorageManager.SAVED_PLACES_KEY)) ?? [] + } + + /** + * Adds or replaces a saved place (caps at 20). + * + * Dedup rules: + * - If the incoming place has `type: "home"` or `"work"`, any existing + * entry with the same type is replaced (a user only ever has one + * Home and one Work). + * - Otherwise dedup by `placeId` so re-saving the same untagged place + * moves it to the top instead of duplicating it. + */ + async addSavedPlace(place: SavedPlace): Promise { + const current = await this.getAllSavedPlaces() + const filtered = current.filter((p) => { + if (place.type && p.type === place.type) return false + if (p.placeId === place.placeId) return false + return true + }) + const next = [place, ...filtered].slice(0, SimpleStorageManager.SAVED_MAX) + await this.setJSON(SimpleStorageManager.SAVED_PLACES_KEY, next) + } + + /** Removes a saved place by placeId. No-op if it isn't saved. */ + async removeSavedPlace(placeId: string): Promise { + const current = await this.getAllSavedPlaces() + const next = current.filter((p) => p.placeId !== placeId) + if (next.length !== current.length) { + await this.setJSON(SimpleStorageManager.SAVED_PLACES_KEY, next) + } + } + + private static readonly UNIT_SYSTEM_KEY = "unitSystem" + + /** Returns the saved distance-unit preference, defaulting to "metric". */ + async getUnitSystem(): Promise { + const raw = await this.get(SimpleStorageManager.UNIT_SYSTEM_KEY) + return raw === "imperial" ? "imperial" : "metric" + } + + /** Persists the distance-unit preference. */ + async setUnitSystem(unit: UnitSystem): Promise { + await this.set(SimpleStorageManager.UNIT_SYSTEM_KEY, unit) + } + + private static readonly VOICE_GUIDANCE_MODE_KEY = "voiceGuidanceMode" + + /** Null means the user has never chosen, so hardware-aware defaults may apply. */ + async getVoiceGuidanceMode(): Promise { + const raw = await this.get(SimpleStorageManager.VOICE_GUIDANCE_MODE_KEY) + return raw === "off" || raw === "essential" || raw === "full" ? raw : null + } + + async setVoiceGuidanceMode(mode: VoiceGuidanceMode): Promise { + await this.set(SimpleStorageManager.VOICE_GUIDANCE_MODE_KEY, mode) + } +} diff --git a/miniapps/navigation/src/shared/channels.ts b/miniapps/navigation/src/shared/channels.ts new file mode 100644 index 0000000000000000000000000000000000000000..be7cacb7e3b6aa4d5f6212301f10537747edf312 --- /dev/null +++ b/miniapps/navigation/src/shared/channels.ts @@ -0,0 +1,111 @@ +/** + * Typed channel registry — the single source of truth for every name + * that flows between this miniapp's background JSContext and its UI + * WebView. Both halves import this file at build time; the bundler + * inlines the declarations so there's no runtime cross-boundary I/O. + * + * Channels wrapped in `Rpc` are RPC (call via mentra.request / + * session.ui.handle). Everything else is broadcast (mentra.send / + * session.ui.on / session.ui.send). + */ + +import type {Rpc} from "@mentra/miniapp/ui" +import type { + ComputeRouteOptions, + ComputeRouteResult, + NavPermissionResult, + Pivot, + StartNavigationOptions, +} from "@mentra/miniapp" + +import type { + Coords, + DevSettings, + LogEntry, + NavRouteStep, + NavSnapshot, + PlaceDetails, + PlaceSuggestion, + SavedPlace, + TripState, + UnitSystem, + VoiceGuidanceMode, +} from "./types" + +export interface Channels { + // ── background → UI broadcasts ───────────────────────────────────────── + "nav:snapshot": NavSnapshot // on ui.onOpen + "nav:coords": Coords // hot + "nav:heading": {degrees: number} // hot, 10Hz throttled + "nav:trip-state": TripState // on transitions + "nav:route": {points: {lat: number; lng: number}[]; steps: NavRouteStep[] | null} // on onRoute + "nav:pivots": {active: Pivot | null; upcoming: Pivot | null} + "nav:log-append": LogEntry + "nav:log-clear": Record + "nav:dev-settings-update": DevSettings + "nav:units-update": {unitSystem: UnitSystem} + "nav:voice-guidance-update": Pick + + // ── UI → background broadcasts (fire-and-forget) ─────────────────────── + "nav:start": StartNavigationOptions & {destinationName?: string} + "nav:stop": Record + "nav:deviate": Record + /** Dev: stop any active trip/sim and snap the map back to the device's + * real current location (forces a fresh one-shot fix). */ + "nav:reset-location": Record + "nav:set-destination": PlaceDetails | null + "nav:set-dev-settings": Partial + "nav:set-show-minimap": boolean + "nav:set-units": {unitSystem: UnitSystem} + "nav:set-voice-guidance": {mode: VoiceGuidanceMode} + "nav:repeat-direction": Record + + // ── UI → background RPC ──────────────────────────────────────────────── + "nav:compute-route": Rpc + "nav:request-permission": Rpc + "nav:get-snapshot": Rpc + "nav:get-pivots": Rpc // full turn list for dev debug dots + + "places:autocomplete": Rpc<{query: string; near?: {lat: number; lng: number}}, PlaceSuggestion[]> + "places:details": Rpc<{placeId: string}, PlaceDetails> + /** + * Reverse-geocode a coordinate to a road name + full address. Proxies through + * the background's SDK session into the v2 cloud maps service (auth + cache + + * rate-limit point) — the WebView never calls a maps provider directly. Each + * field is null when none of that kind is found near the coordinate. + */ + "places:reverse-geocode": Rpc<{lat: number; lng: number}, {road: string | null; address: string | null}> + + "storage:list-saved": Rpc + "storage:add-saved": Rpc + "storage:remove-saved": Rpc<{placeId: string}, void> + "storage:list-recent": Rpc + "storage:add-recent": Rpc + + // test channels + "test:show-text-test": Rpc<{text: string; durationMs?: number}, void> + "test:show-bitmap-test": Rpc + /** Render a gradient test bitmap. `size` is the width; `height` defaults to `size` (square). */ + "test:show-bitmap-size": Rpc<{size: number; height?: number}, void> + /** PoC: fetch OSM roads around the test center and draw the bare network on the glasses. */ + "test:show-osm-map": Rpc + /** PoC: pan the OSM map view by a small nudge in a direction, then redraw. */ + "test:pan-osm-map": Rpc<{dir: "up" | "down" | "left" | "right"}, {ok: boolean; error?: string}> + "test:count-1-to-10": Rpc + /** + * Delay-probe: show the minimap bitmap top-right, then count BOTH text + * containers (top-left maneuver + bottom-left stats) down from 100 to 0 on + * the same tick, through the real showManeuver/showTripStats queue. Lets + * you eyeball whether the two boxes stay in sync or one lags. + */ + "test:count-both-boxes": Rpc + "test:reset-nav-permission": Rpc + /** Test: render the large centered map bitmap at a given size on demand. */ + "test:show-large-map": Rpc<{size?: number}, {ok: boolean; error?: string}> +} + +// Convenience: the typed shape of `window.mentra` for this miniapp. +declare global { + // eslint-disable-next-line no-var + var mentra: import("@mentra/miniapp/ui").MentraTyped +} diff --git a/miniapps/navigation/src/shared/maneuverDisplay.ts b/miniapps/navigation/src/shared/maneuverDisplay.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e9b43fb0d4d59358d13278c56867d5a15c83c7d --- /dev/null +++ b/miniapps/navigation/src/shared/maneuverDisplay.ts @@ -0,0 +1,240 @@ +/** + * Shared maneuver → display derivation. + * + * SINGLE SOURCE OF TRUTH for what the next-turn UI says. Both the phone + * OrientationCard and the glasses HUD consume this so they can never drift + * apart on instruction text, distance, or turn direction — they read the + * exact same Mapbox `maneuver` event through the exact same logic. + * + * It returns the raw PIECES (instruction string, distance in meters, arrow + * glyph, an "at turn / arriving" mode) rather than a finished string, so + * each surface can lay them out its own way (the card is two lines; the + * glasses HUD prepends a directional arrow) while still agreeing on every + * value. Distance formatting is left to the caller so each side applies its + * own unit system. + */ + +import type {NavManeuver} from "@mentra/miniapp" +import type {NavStatus} from "./types" + +/** Distance (m) at/under which we say "Now" instead of "In X m". */ +const AT_TURN_M = 10 + +export type ManeuverDisplay = { + /** Big instruction line — Mapbox's verbatim text, or a reconstructed verb+road. */ + instruction: string + /** Maneuver kind (drives icon on the card, arrow glyph on the HUD). */ + kind: string + /** Directional arrow glyph for the glasses HUD (←/→/↑). */ + arrow: string + /** + * Distance to the maneuver in meters, or null when unknown. Callers + * format this with their own unit system (e.g. `In ${formatDistance(...)}`). + */ + distanceMeters: number | null + /** True within AT_TURN_M of the maneuver — show "Now" instead of distance. */ + atTurn: boolean + /** Final-leg arrival mode: show "Arriving in " not "In X m, ". */ + arriving: boolean +} + +/** + * Derive the shared display fields from the live `maneuver` event (Mapbox's + * own current-step tracking, delivered natively from RouteProgress). + * Returns null when there's nothing to show (no maneuver / arrived) — the + * caller decides the empty/arrival framing. + * + * `liveDistanceMeters` (optional): a freshly-computed distance to the next + * maneuver, derived from the user's LIVE position against the route polyline by + * the caller (see liveDistanceToNextTurn). When provided it OVERRIDES the + * maneuver event's own `distanceMeters`, so the "In X m" / "Arriving in X m" + * line ticks down on every location update instead of only when a new native + * RouteProgress maneuver event arrives. Both the phone card and the glasses HUD + * pass it, so they recompute identically and stay in lockstep — without waiting + * on a background→UI re-broadcast. Omit it to use the event's own distance. + */ +export function deriveManeuverDisplay( + maneuver: NavManeuver | null, + status: NavStatus | undefined, + liveDistanceMeters?: number | null, +): ManeuverDisplay | null { + if (status === "arrived" || !maneuver) return null + + const kind = maneuver.maneuverType + const instructionRaw = maneuver.instruction?.trim() || null + + // Prefer the live position-derived distance when the caller supplies one; + // fall back to the maneuver event's own (slower-updating) distance. + const liveDist = + liveDistanceMeters != null && liveDistanceMeters >= 0 ? liveDistanceMeters : null + const eventDist = + maneuver.distanceMeters != null && maneuver.distanceMeters >= 0 ? maneuver.distanceMeters : null + // DISPLAYED distance: live (smooth) when available, else the event's. + const distanceMeters = liveDist ?? eventDist + + // "At turn" (and therefore whether to show a DIRECTIONAL arrow) must be gated + // on the EVENT's own distance — NOT the live distance. Reason: `kind` (the + // turn direction) comes from the maneuver EVENT, while `liveDist` is derived + // from the live position against the route STEPS and can already be measuring + // the turn AFTER the one `kind` describes. If we let liveDist decide atTurn, + // there's a brief window right as you pass a turn where liveDist says "now" + // but `kind` still points at the wrong/next turn — that's the flash of the + // wrong arrow (right turn shows, then a left arrow blips before it settles). + // Gating atTurn on eventDist keeps the arrow and its direction from the SAME + // turn, so the glyph can never disagree with the distance that triggered it. + const atTurn = eventDist != null && eventDist <= AT_TURN_M + + // Arrival leg (the LAST step) — show ONLY the destination countdown + // ("Arriving in X m") and drop the turn instruction entirely: there are no + // more turns, just the destination ahead. Fires for ANY ARRIVE maneuver, + // even when Mapbox supplies an instruction string ("Your destination is on + // the right.") — we deliberately replace that with the clean countdown. + if (kind === "ARRIVE") { + // On the arrival leg the relevant distance is to the destination. Prefer + // the live distance (caller passes distance-to-destination here), else the + // event's own toDest. + const toDest = liveDist ?? maneuver.distanceToDestinationMeters + return { + instruction: "Arriving", + kind: "ARRIVE", + arrow: "↑", + distanceMeters: toDest != null && toDest >= 0 ? toDest : null, + atTurn: false, + arriving: true, + } + } + + // Bottom/instruction line: Mapbox's verbatim instruction, falling back to + // a reconstructed " onto " only when none is present. + let instruction = instructionRaw + if (!instruction) { + const verb = verbForManeuver(kind) + const onto = realRoadName(maneuver.nextStepRoad) + instruction = onto ? `${verb} onto ${onto}` : verb + } + + return { + instruction, + kind, + // Directional arrow (←/→) ONLY once we're AT the turn (atTurn / "Now"). + // While still approaching ("In 90 m, turn left") the arrow stays ↑ — + // straight ahead — so it doesn't claim "turn now" the whole walk in. + // Applies to both the glasses HUD and the phone card (shared source). + arrow: atTurn ? arrowForKind(kind) : "↑", + distanceMeters, + atTurn, + arriving: false, + } +} + +/** + * Live distance (m) from the user's current position to the NEXT maneuver, + * measured ALONG the route — the value that should drive the "In X m" line so + * it ticks down on every location update (not only when a native maneuver event + * fires). SHARED by the phone card and the glasses HUD so both recompute the + * same number from the same live coords. + * + * `remaining` is the caller's `remainingRouteMeters(point, route)` implementation + * (injected so this shared module stays free of a geometry import / cross-layer + * dependency). Returns null when it can't be computed — caller then falls back + * to the maneuver event's own distance. + * + * Algorithm: the next turn is the closest route step still AHEAD of the user. + * Each step's remaining-along-route distance is measured the same way as the + * user's, so `userRemaining - stepRemaining` is the live gap to that step. + * + * Robustness: some routes (e.g. a ferry leg) contain a huge coordinate + * discontinuity that corrupts the along-route arithmetic, making every gap + * negative or null. In that case we fall back to the STRAIGHT-LINE (haversine) + * distance to the nearest step ahead, so the line never freezes. `straightLine` + * is injected (like `remaining`) to keep this module dependency-free. + */ +export function liveDistanceToNextTurn( + me: {lat: number; lng: number} | null, + route: Array<{lat: number; lng: number}> | null, + steps: Array<{lat: number; lng: number}> | null, + remaining: ( + p: {lat: number; lng: number} | null, + r: Array<{lat: number; lng: number}> | null, + ) => number | null, + straightLine?: (a: {lat: number; lng: number}, b: {lat: number; lng: number}) => number, +): number | null { + if (!me || !route || route.length < 2 || !steps || steps.length === 0) return null + + // Primary: along-route gap to the closest step ahead of the user. + const meRemaining = remaining(me, route) + if (meRemaining != null) { + let bestGap: number | null = null + for (const s of steps) { + const stepRemaining = remaining({lat: s.lat, lng: s.lng}, route) + if (stepRemaining == null) continue + const gap = meRemaining - stepRemaining + if (gap <= 1) continue // behind us or essentially here — skip + if (bestGap == null || gap < bestGap) bestGap = gap + } + if (bestGap != null) return bestGap + } + + // Fallback: straight-line distance to the nearest step (when the along-route + // math degenerates). Better a slightly-off live number than a frozen one. + if (straightLine) { + let best: number | null = null + for (const s of steps) { + const d = straightLine(me, {lat: s.lat, lng: s.lng}) + if (d <= 1) continue + if (best == null || d < best) best = d + } + if (best != null) return best + } + + return null +} + +/** Plain arrow glyph for the glasses HUD (corner-curve variants don't render). */ +export function arrowForKind(kind: string | null | undefined): string { + const m = (kind ?? "").toUpperCase() + if (m.includes("LEFT")) return "←" + if (m.includes("RIGHT")) return "→" + return "↑" +} + +/** Map a ManeuverKind to a verb (fallback when no verbatim instruction). */ +export function verbForManeuver(kind: string): string { + switch (kind) { + case "TURN_LEFT": + case "SLIGHT_LEFT": + case "SHARP_LEFT": + return kind === "SLIGHT_LEFT" ? "Slight left" : kind === "SHARP_LEFT" ? "Sharp left" : "Turn left" + case "TURN_RIGHT": + case "SLIGHT_RIGHT": + case "SHARP_RIGHT": + return kind === "SLIGHT_RIGHT" ? "Slight right" : kind === "SHARP_RIGHT" ? "Sharp right" : "Turn right" + case "U_TURN": + return "Turn around" + case "CONTINUE": + case "STRAIGHT": + return "Continue" + case "NAME_CHANGE": + return "Continue" + case "DEPART": + return "Head out" + case "CROSS_STREET": + return "Cross the street" + default: + return "Continue" + } +} + +/** Drop instruction-like strings masquerading as road names; trim the rest. */ +export function realRoadName(raw: string | null | undefined): string | null { + if (!raw) return null + const trimmed = raw.trim() + if (trimmed.length === 0) return null + if ( + /^(toward|turn|continue|destination|head|cross|slight|sharp|keep|merge|fork|exit|take|roundabout|u[\s-]?turn|arrive|arriving|depart|enter|leave|stay)\b/i.test( + trimmed, + ) + ) + return null + return trimmed +} diff --git a/miniapps/navigation/src/shared/types.ts b/miniapps/navigation/src/shared/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c19a48e3e4efbea6e7821541d8dc04aeb44744f --- /dev/null +++ b/miniapps/navigation/src/shared/types.ts @@ -0,0 +1,146 @@ +/** + * Shared domain types referenced by both the background JSContext and + * the UI WebView. Both bundlers inline this file at build time, so + * there's no runtime resolution across the boundary. + */ + +import type {NavManeuver, Pivot} from "@mentra/miniapp" + +export type Coords = {lat: number; lng: number; accuracy?: number; ts: number} +export type LatLng = {lat: number; lng: number} +export type NavStatus = "idle" | "navigating" | "rerouting" | "arrived" + +/** + * Distance unit preference. "metric" → m / km, "imperial" → ft / mi. + * A real user preference (not a dev toggle): persisted in background + * storage and mirrored to the UI via the snapshot so every distance + * string — on the map, in drawers, and on the glasses HUD — renders in + * the chosen system. Defaults to "metric". + */ +export type UnitSystem = "metric" | "imperial" +export type VoiceGuidanceMode = "off" | "essential" | "full" +export type GlassesCapabilitySnapshot = { + modelName: string | null + hasDisplay: boolean + /** True when the glasses can render positioned scene elements. */ + canPosition: boolean + hasSpeaker: boolean + hasButton: boolean +} +export type LogEntry = {id: number; ts: number; line: string} + +export type PlaceSuggestion = {placeId: string; mainText: string; secondaryText?: string} +export type PlaceDetails = { + placeId: string + name: string + address: string + lat: number + lng: number + /** User-defined label when saved as a favorite or custom place */ + savedName?: string + /** + * True while a reverse-geocode is in flight for a dropped pin. The + * `name` / `address` fields are placeholders (raw lat/lng) until this + * flips back to false. UI consumers render a skeleton while this is + * true so the user doesn't see the bare coordinates flash on screen + * before the real address lands. + */ + isGeocoding?: boolean +} +export type SavedPlace = PlaceDetails & { + type?: "home" | "work" +} + +/** + * Trip state mirrored from background to UI. Kept dual `status` + + * `running` for parity with the existing NavigationPage state machine — + * `running` is true while `status` ∈ {"navigating","rerouting"}, false + * otherwise. Collapsing into a single field is a separate refactor. + */ +/** + * One step in the active trip's route, mirrored from the SDK's + * `NavStep` minus internal fields the UI doesn't need (`routeIndex`). + * Carries the resolved road name (host-side hybrid resolver) so the + * UI can build live turn dots from road→road transitions, matching + * the preview path. `maneuver` is the SDK's `ManeuverKind` string — + * widened to `string` here to avoid pulling the union into the + * shared types boundary (the channel layer doesn't gain anything + * from the narrower type). + */ +export type NavRouteStep = { + lat: number + lng: number + road: string | null + maneuver: string + distanceMeters: number + /** + * Google's verbatim turn-by-turn text for this step (e.g. "Head west + * on Hayes St toward Gough St"). Populated from the preview-time + * Routes API response and refetched on reroute. Null when no cached + * preview is available — consumers fall back to the constructed + * "Turn left onto Octavia St" rendering. + */ + instruction: string | null +} + +export type TripState = { + status: NavStatus + running: boolean + maneuver: NavManeuver | null + activeDestination: LatLng | null + activeDestinationName: string | null + routePoints: LatLng[] | null + /** + * Step list for the active route, populated alongside `routePoints` + * from the SDK's onRoute event. Null until the first route lands. + * Used by NavigationPage to build live turn dots that mirror the + * preview from→to/direction labels — preview reads steps directly + * from `computeRoute`, live reads them from here. + */ + routeSteps: NavRouteStep[] | null + offRouteAt: number | null + /** + * Side of the final route segment the destination pin sits on, from + * the walker's perspective. Captured at the moment we fire arrival + * (either from the early ≤7m-remaining trigger or the SDK's own + * arrived event) and held alongside `status === "arrived"` so the + * HUD can render "You have arrived at X, on your left|right". + * Null while not arrived, or when the route was too short to derive + * a side. + */ + arrivalSide: "left" | "right" | null +} + +export type DevSettings = { + simulate: boolean + speedMultiplier: number + wrongSidewalk: boolean + skipCrossings: boolean + /** + * Debug toggle. When on, the maneuver card and glasses HUD swap their + * constructed "Turn right onto Octavia St" phrasing for Google's raw + * navigationInstruction string (e.g. "Head west on Hayes St toward + * Gough St"). The distance suffix ("in 198 m") is preserved. + */ + useRawInstructions: boolean + /** + * Dev toggle for the swipe-up large map (WIP). When OFF (default), swipe + * gestures do nothing — the large map feature is disabled. When ON, swiping + * toggles the full-screen route map on/off as usual. + */ + largeMapEnabled: boolean +} + +export type NavSnapshot = { + coords: Coords | null + heading: number | null + trip: TripState + activePivot: Pivot | null + upcomingPivot: Pivot | null + log: LogEntry[] + devSettings: DevSettings + /** User's distance-unit preference. Defaults to "metric". */ + unitSystem: UnitSystem + voiceGuidanceMode: VoiceGuidanceMode + capabilities: GlassesCapabilitySnapshot +} diff --git a/miniapps/navigation/src/test/audio-guidance.test.ts b/miniapps/navigation/src/test/audio-guidance.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a86a314cac73e4071baaa4e6d0cbaa3459d5805b --- /dev/null +++ b/miniapps/navigation/src/test/audio-guidance.test.ts @@ -0,0 +1,421 @@ +/// + +import {afterEach, describe, expect, jest, test} from "bun:test" + +import { + AudioGuidanceManager, + selectAudioGuidanceDistance, + type AudioGuidanceInput, +} from "../background/managers/AudioGuidanceManager" + +function createHarness() { + const spoken: string[] = [] + let stops = 0 + const manager = new AudioGuidanceManager({ + speak: async (text) => { + spoken.push(text) + return {completed: true} + }, + stop: () => { + stops += 1 + }, + }) + manager.setAvailable(true) + return { + manager, + spoken, + get stops() { + return stops + }, + } +} + +function input(partial: Partial = {}): AudioGuidanceInput { + return { + status: "navigating", + running: true, + routeRevision: 1, + pivotIndex: 0, + maneuverType: "TURN_LEFT", + instruction: "Turn left onto Market Street", + distanceMeters: 100, + offRoute: false, + destinationName: "Blue Bottle", + arrivalSide: null, + travelMode: "walking", + unitSystem: "metric", + ...partial, + } +} + +async function settleSpeech(): Promise { + for (let i = 0; i < 6; i += 1) await Promise.resolve() +} + +afterEach(() => { + if (jest.isFakeTimers()) jest.useRealTimers() +}) + +describe("AudioGuidanceManager", () => { + test("full guidance speaks at most one preparation and one now prompt per turn", async () => { + const {manager, spoken} = createHarness() + manager.setMode("full") + + manager.observe(input({distanceMeters: 59})) + await settleSpeech() + manager.observe(input({distanceMeters: 48})) + await settleSpeech() + manager.observe(input({distanceMeters: 9})) + await settleSpeech() + manager.observe(input({distanceMeters: 4})) + await settleSpeech() + + expect(spoken).toEqual(["In 60 meters, turn left onto Market Street.", "Turn left onto Market Street now."]) + }) + + test("essential guidance skips advance notice but still announces the turn", async () => { + const {manager, spoken} = createHarness() + manager.setMode("essential") + + manager.observe(input({distanceMeters: 55})) + await settleSpeech() + manager.observe(input({distanceMeters: 10})) + await settleSpeech() + + expect(spoken).toEqual(["Turn left onto Market Street now."]) + }) + + test("route revision and pivot index create fresh maneuver identities", async () => { + const {manager, spoken} = createHarness() + manager.setMode("full") + + manager.observe(input({distanceMeters: 9, pivotIndex: 0})) + await settleSpeech() + manager.observe(input({distanceMeters: 9, pivotIndex: 1})) + await settleSpeech() + manager.observe(input({distanceMeters: 9, pivotIndex: 1, routeRevision: 2})) + await settleSpeech() + + expect(spoken).toHaveLength(3) + }) + + test("binding a late pivot does not replay the same maneuver", async () => { + const {manager, spoken} = createHarness() + manager.setMode("full") + + manager.observe(input({distanceMeters: 50, pivotIndex: null})) + await settleSpeech() + manager.observe(input({distanceMeters: 48, pivotIndex: 0})) + await settleSpeech() + + expect(spoken).toEqual(["In 50 meters, turn left onto Market Street."]) + }) + + test("pivotless identical short turns receive distinct action cues", async () => { + const {manager, spoken} = createHarness() + manager.setMode("essential") + + manager.observe(input({distanceMeters: 9, pivotIndex: null})) + await settleSpeech() + manager.observe(input({distanceMeters: 20, pivotIndex: null})) + await settleSpeech() + manager.observe(input({distanceMeters: 9, pivotIndex: null})) + await settleSpeech() + + expect(spoken).toEqual(["Turn left onto Market Street now.", "Turn left onto Market Street now."]) + }) + + test("full guidance announces the final approach once", async () => { + const {manager, spoken} = createHarness() + manager.setMode("full") + + manager.observe( + input({maneuverType: "ARRIVE", instruction: "Arriving", distanceMeters: 50, pivotIndex: null}), + ) + await settleSpeech() + manager.observe( + input({maneuverType: "ARRIVE", instruction: "Arriving", distanceMeters: 30, pivotIndex: null}), + ) + await settleSpeech() + + expect(spoken).toEqual(["Destination in 50 meters."]) + }) + + test("arrival guidance uses live distance without detaching turn cues from their event", () => { + expect(selectAudioGuidanceDistance("ARRIVE", 120, 35)).toBe(35) + expect(selectAudioGuidanceDistance("ARRIVE", 120, null)).toBe(120) + expect(selectAudioGuidanceDistance("TURN_LEFT", 12, 80)).toBe(12) + }) + + test("a new semantic maneuver stops an in-progress maneuver prompt", async () => { + const spoken: string[] = [] + let stops = 0 + const manager = new AudioGuidanceManager({ + speak: (text) => { + spoken.push(text) + return new Promise(() => {}) + }, + stop: () => { + stops += 1 + }, + }) + manager.setAvailable(true) + manager.setMode("full") + + manager.observe(input({distanceMeters: 50, pivotIndex: 0})) + manager.observe( + input({ + maneuverType: "TURN_RIGHT", + instruction: "Turn right onto Valencia Street", + distanceMeters: 45, + pivotIndex: 1, + }), + ) + await settleSpeech() + + expect(spoken).toEqual(["In 50 meters, turn left onto Market Street."]) + expect(stops).toBe(1) + }) + + test("off-route guidance replaces stale turn cues until the route is regained", async () => { + const {manager, spoken} = createHarness() + manager.setMode("essential") + + manager.observe(input({distanceMeters: 9, offRoute: true})) + await settleSpeech() + manager.observe(input({distanceMeters: 7, offRoute: true})) + await settleSpeech() + manager.observe(input({distanceMeters: 7, offRoute: false})) + await settleSpeech() + + expect(spoken).toEqual(["You are off route. Go back to the route.", "Turn left onto Market Street now."]) + }) + + test("startup grace resumes maneuver guidance when an off-route fix stabilizes", async () => { + jest.useFakeTimers({now: 100_000}) + const {manager, spoken} = createHarness() + manager.setMode("essential") + manager.beginTrip() + manager.confirmTripStarted("Blue Bottle") + await settleSpeech() + + manager.observe(input({distanceMeters: 9, offRoute: true})) + await settleSpeech() + + expect(spoken).toEqual(["Navigation started to Blue Bottle."]) + + manager.observe(input({distanceMeters: 9, offRoute: false})) + await settleSpeech() + + expect(spoken).toEqual(["Navigation started to Blue Bottle.", "Turn left onto Market Street now."]) + }) + + test("startup off-route warning becomes eligible if the condition outlasts the grace period", async () => { + jest.useFakeTimers({now: 100_000}) + const {manager, spoken} = createHarness() + manager.setMode("essential") + manager.beginTrip() + manager.confirmTripStarted("Blue Bottle") + await settleSpeech() + + manager.observe(input({distanceMeters: 9, offRoute: true})) + await settleSpeech() + jest.advanceTimersByTime(15_000) + manager.observe(input({distanceMeters: 7, offRoute: true})) + await settleSpeech() + + expect(spoken).toEqual(["Navigation started to Blue Bottle.", "You are off route. Go back to the route."]) + }) + + test("startup reroute becomes eligible if it is still active after the grace period", async () => { + jest.useFakeTimers({now: 100_000}) + const {manager, spoken} = createHarness() + manager.setMode("essential") + manager.beginTrip() + manager.confirmTripStarted("Blue Bottle") + await settleSpeech() + + manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null})) + await settleSpeech() + jest.advanceTimersByTime(14_999) + manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null})) + await settleSpeech() + + expect(spoken).toEqual(["Navigation started to Blue Bottle."]) + + jest.advanceTimersByTime(1) + manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null})) + await settleSpeech() + manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null})) + await settleSpeech() + + expect(spoken).toEqual(["Navigation started to Blue Bottle.", "Off route. Rerouting."]) + }) + + test("a suppressed startup reroute cancels stale maneuver speech", async () => { + jest.useFakeTimers({now: 100_000}) + const spoken: string[] = [] + let stops = 0 + const manager = new AudioGuidanceManager({ + speak: (text) => { + spoken.push(text) + if (text.startsWith("Turn left")) return new Promise(() => {}) + return Promise.resolve({completed: true}) + }, + stop: () => { + stops += 1 + }, + }) + manager.setAvailable(true) + manager.setMode("essential") + manager.beginTrip() + manager.confirmTripStarted("Blue Bottle") + await settleSpeech() + manager.observe(input({distanceMeters: 9})) + await settleSpeech() + + manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null})) + await settleSpeech() + + expect(spoken).toEqual(["Navigation started to Blue Bottle.", "Turn left onto Market Street now."]) + expect(stops).toBe(1) + }) + + test("late navigation updates cannot revive guidance after stop or arrival", async () => { + const stopped = createHarness() + stopped.manager.setMode("essential") + stopped.manager.beginTrip() + stopped.manager.endTrip() + stopped.manager.observe(input({distanceMeters: 9})) + await settleSpeech() + expect(stopped.spoken).toEqual([]) + + const arrived = createHarness() + arrived.manager.setMode("essential") + arrived.manager.beginTrip() + arrived.manager.confirmTripStarted("Blue Bottle") + await settleSpeech() + arrived.manager.observe( + input({status: "arrived", running: false, maneuverType: null, instruction: null, distanceMeters: null}), + ) + await settleSpeech() + arrived.manager.observe(input({distanceMeters: 9})) + await settleSpeech() + expect(arrived.spoken).toEqual(["Navigation started to Blue Bottle.", "You have arrived at Blue Bottle."]) + }) + + test("distance jitter after a now cue cannot backtrack into preparation", async () => { + const {manager, spoken} = createHarness() + manager.setMode("full") + + manager.observe(input({distanceMeters: 9, pivotIndex: null})) + await settleSpeech() + manager.observe(input({distanceMeters: 16, pivotIndex: null})) + await settleSpeech() + + expect(spoken).toEqual(["Turn left onto Market Street now."]) + }) + + test("start confirmation leads a maneuver received during startup", async () => { + jest.useFakeTimers({now: 100_000}) + const {manager, spoken} = createHarness() + manager.setMode("full") + manager.beginTrip() + + manager.observe(input({distanceMeters: 50})) + expect(spoken).toEqual([]) + manager.confirmTripStarted(null) + await settleSpeech() + jest.advanceTimersByTime(4_000) + await settleSpeech() + + expect(spoken).toEqual(["Navigation started.", "In 50 meters, turn left onto Market Street."]) + }) + + test("rerouting and arrival are each announced once", async () => { + jest.useFakeTimers({now: 100_000}) + const {manager, spoken} = createHarness() + manager.setMode("essential") + manager.beginTrip() + manager.confirmTripStarted("Blue Bottle") + await settleSpeech() + jest.advanceTimersByTime(15_000) + + manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null})) + await settleSpeech() + manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null})) + await settleSpeech() + manager.observe( + input({ + status: "arrived", + running: false, + maneuverType: null, + instruction: null, + distanceMeters: null, + arrivalSide: "right", + }), + ) + await settleSpeech() + + expect(spoken).toEqual([ + "Navigation started to Blue Bottle.", + "Off route. Rerouting.", + "You have arrived at Blue Bottle, on your right.", + ]) + }) + + test("repeat speaks the latest live instruction and off stops all speech", async () => { + const harness = createHarness() + harness.manager.setMode("full") + harness.manager.beginTrip() + harness.manager.confirmTripStarted(null) + await settleSpeech() + harness.manager.observe(input({distanceMeters: 42})) + await settleSpeech() + + expect(harness.manager.repeatCurrent()).toBe(true) + await settleSpeech() + harness.manager.setMode("off") + expect(harness.manager.repeatCurrent()).toBe(false) + expect(harness.spoken.at(-1)).toBe("In 40 meters, turn left onto Market Street.") + }) + + test("urgent turn cue cancels deferred advance notice", async () => { + jest.useFakeTimers({now: 100_000}) + const {manager, spoken} = createHarness() + manager.setMode("full") + manager.beginTrip() + manager.confirmTripStarted(null) + await settleSpeech() + + // This preparation prompt waits for the automatic gap after the start + // announcement. The urgent action cue must supersede it completely. + manager.observe(input({distanceMeters: 50})) + manager.observe(input({distanceMeters: 9})) + await settleSpeech() + jest.advanceTimersByTime(4_000) + await settleSpeech() + + expect(spoken).toEqual(["Navigation started.", "Turn left onto Market Street now."]) + }) + + test("new trip clears the previous arrival repeat phrase", async () => { + const {manager} = createHarness() + manager.setMode("essential") + manager.beginTrip() + manager.observe( + input({ + status: "arrived", + running: false, + maneuverType: null, + instruction: null, + distanceMeters: null, + }), + ) + await settleSpeech() + + manager.beginTrip() + + expect(manager.repeatCurrent()).toBe(false) + }) +}) diff --git a/miniapps/navigation/src/test/bitmaps/fetch-static-maps.ts b/miniapps/navigation/src/test/bitmaps/fetch-static-maps.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc1081ee9b0b1b4f952e6b07a2ed39eef8edd3b9 --- /dev/null +++ b/miniapps/navigation/src/test/bitmaps/fetch-static-maps.ts @@ -0,0 +1,88 @@ +/** + * Fetch Google Static Maps images and save them next to this file, so we can + * eyeball what kind of picture the glasses bitmap pipeline could render from a + * real map tile (different zooms / sizes / map types). + * + * The API key is read from PUBLIC_MAP_NAV_VIEWER (the navigation miniapp's + * map key — Bun auto-loads it from .env). NOTE: that key is normally restricted + * to the Maps JavaScript API + an HTTP-referrer; the Static Maps API is a + * different endpoint, so if it's restricted you'll get a 403 / "API key not + * authorized" PNG back. In that case enable "Maps Static API" for the key + * (or use an unrestricted key) — see the console URL in .env.example. + * + * Run: bun run src/test/bitmaps/fetch-static-maps.ts + */ + +const API_KEY = process.env.PUBLIC_MAP_NAV_VIEWER + +if (!API_KEY || API_KEY.startsWith("your_") || API_KEY.startsWith("YOUR_")) { + console.error( + "✗ PUBLIC_MAP_NAV_VIEWER is not set (or is a placeholder). Add it to .env.", + ) + process.exit(1) +} + +const BASE = "https://maps.googleapis.com/maps/api/staticmap" + +// Center used in the examples (Lower Manhattan). +const CENTER = "40.714728,-73.998672" + +// A spread of variations so we can compare what reads well on a 1-bit-ish +// glasses display: zoom levels, output sizes, and map types. +type MapRequest = {name: string; params: Record} + +const REQUESTS: MapRequest[] = [ + {name: "z12-400x400", params: {center: CENTER, zoom: "12", size: "400x400"}}, + {name: "z14-400x400", params: {center: CENTER, zoom: "14", size: "400x400"}}, + {name: "z16-400x400", params: {center: CENTER, zoom: "16", size: "400x400"}}, + // Match the glasses container shapes we've been testing. + {name: "z14-200x88", params: {center: CENTER, zoom: "14", size: "200x88"}}, + {name: "z14-200x100", params: {center: CENTER, zoom: "14", size: "200x100"}}, + // Map type variations — roadmap vs high-contrast options. + {name: "z14-roadmap", params: {center: CENTER, zoom: "14", size: "400x400", maptype: "roadmap"}}, + {name: "z14-terrain", params: {center: CENTER, zoom: "14", size: "400x400", maptype: "terrain"}}, + {name: "z14-satellite", params: {center: CENTER, zoom: "14", size: "400x400", maptype: "satellite"}}, +] + +function buildUrl(params: Record): string { + const q = new URLSearchParams({...params, key: API_KEY!}) + return `${BASE}?${q.toString()}` +} + +// The key is HTTP-referrer-restricted, but a CLI fetch sends no referrer and +// gets rejected. We forge a Referer header matching one of the key's allowed +// referrer patterns so the request is accepted WITHOUT loosening the key. +// Override via STATIC_MAPS_REFERER if the key allows a different domain. +const REFERER = process.env.STATIC_MAPS_REFERER ?? "https://console.mentra.glass/" + +const outDir = new URL(".", import.meta.url).pathname + +async function fetchOne(req: MapRequest): Promise { + const url = buildUrl(req.params) + // Log the URL with the key redacted so it's safe to paste. + console.log(`→ ${req.name}: ${url.replace(API_KEY!, "***")}`) + + const res = await fetch(url, {headers: {Referer: REFERER}}) + const buf = new Uint8Array(await res.arrayBuffer()) + + if (!res.ok) { + console.error(` ✗ HTTP ${res.status} — saving body for inspection`) + } + + const file = `${outDir}${req.name}.png` + await Bun.write(file, buf) + console.log(` ✓ saved ${file} (${(buf.length / 1024).toFixed(1)} KB)`) +} + +export {} + +console.log(`Fetching ${REQUESTS.length} static maps → ${outDir}`) +console.log(`Referer: ${REFERER}\n`) +for (const req of REQUESTS) { + try { + await fetchOne(req) + } catch (err) { + console.error(` ✗ ${req.name} failed:`, err) + } +} +console.log("\nDone.") diff --git a/miniapps/navigation/src/test/bitmaps/png-to-bmp.ts b/miniapps/navigation/src/test/bitmaps/png-to-bmp.ts new file mode 100644 index 0000000000000000000000000000000000000000..7008f3c77a2d34fc934248f3e6b76d5cc1058253 --- /dev/null +++ b/miniapps/navigation/src/test/bitmaps/png-to-bmp.ts @@ -0,0 +1,105 @@ +/** + * PNG → glasses-BMP converter (build-time util). + * + * Pipeline: PNG --sips--> 88×88 24-bit BMP --> 8-bit grayscale pixels + * --> encodeBmpBase64() --> base64 BMP string the glasses display. + * + * PNG is the right SOURCE: it's lossless, so downscaling + graying doesn't + * fight JPEG artifacts. BMP is the right TARGET: it's what the phone SGC / + * G2 native side decode (see bmp.ts / convertToG2Bmp). + * + * We shell out to macOS `sips` for decode+resize (no npm image deps). It + * emits a 24-bit, top-down (negative-height) uncompressed BMP with a 54-byte + * header — easy to parse by hand. + * + * Usage: + * bun run src/test/bitmaps/png-to-bmp.ts [size] + * # → writes .bmp.ts exporting the base64 BMP string + dims. + * + * Default size is 88 (→ 88×88). + */ + +import {$} from "bun" +import {encodeBmpBase64} from "../../background/lib/bmp" + +const DEFAULT_SIZE = 88 + +/** + * Convert a PNG file to a base64 grayscale BMP at `size`×`size`, ready for + * a `session.display.render()` image element. Returns the base64 string. + */ +export async function pngToGlassesBmp(pngPath: string, size = DEFAULT_SIZE): Promise { + const tmpBmp = `/tmp/png-to-bmp-${size}.bmp` + + // Resize to size×size and emit a 24-bit BMP. `-z H W` forces exact dims + // (not aspect-preserving) — caller asked for a fixed square. + await $`sips -z ${size} ${size} -s format bmp ${pngPath} --out ${tmpBmp}`.quiet() + + const bmp = new Uint8Array(await Bun.file(tmpBmp).arrayBuffer()) + + // --- Parse the BMP sips produced (BITMAPINFOHEADER, 24-bit, uncompressed) --- + const readU32 = (o: number) => bmp[o] | (bmp[o + 1] << 8) | (bmp[o + 2] << 16) | (bmp[o + 3] << 24) + const readI32 = (o: number) => readU32(o) | 0 + + const pixelOffset = readU32(10) + const width = readI32(18) + const rawHeight = readI32(22) + const topDown = rawHeight < 0 + const height = Math.abs(rawHeight) + const bpp = bmp[28] | (bmp[29] << 8) + + if (bpp !== 24) throw new Error(`expected 24-bit BMP from sips, got ${bpp}-bit`) + + // 24-bit rows are padded to a 4-byte boundary; pixels are stored B,G,R. + const rowSize = ((width * 3 + 3) >> 2) << 2 + + // Build the 8-bit grayscale buffer encodeBmpBase64 wants: row-major, TOP-DOWN. + const gray = new Uint8Array(width * height) + for (let y = 0; y < height; y++) { + // Map our top-down output row `y` to the source row in the BMP. + const srcRow = topDown ? y : height - 1 - y + const rowStart = pixelOffset + srcRow * rowSize + for (let x = 0; x < width; x++) { + const p = rowStart + x * 3 + const b = bmp[p]! + const g = bmp[p + 1]! + const r = bmp[p + 2]! + // ITU-R 601 luma — same weights the G2 native converter uses. + gray[y * width + x] = (r * 299 + g * 587 + b * 114) / 1000 + } + } + + return encodeBmpBase64(gray, width, height) +} + +// ── CLI ────────────────────────────────────────────────────────────────── +if (import.meta.main) { + const input = process.argv[2] + const size = process.argv[3] ? parseInt(process.argv[3], 10) : DEFAULT_SIZE + if (!input) { + console.error("usage: bun run png-to-bmp.ts [size]") + process.exit(1) + } + + const base64 = await pngToGlassesBmp(input, size) + + const outTs = input.replace(/\.png$/i, "") + `.bmp.ts` + const constName = + "MAP_BMP_" + + input + .split("/") + .pop()! + .replace(/\.png$/i, "") + .replace(/[^a-zA-Z0-9]/g, "_") + .toUpperCase() + + const contents = + `// AUTO-GENERATED by png-to-bmp.ts from ${input} at ${size}×${size}.\n` + + `// Base64 8-bit grayscale BMP — data for a session.display.render() image element.\n` + + `export const ${constName} = "${base64}"\n` + + `export const ${constName}_SIZE = ${size}\n` + + await Bun.write(outTs, contents) + console.log(`✓ ${input} → ${outTs}`) + console.log(` const: ${constName} (${size}×${size}, ${(base64.length / 1024).toFixed(1)} KB base64)`) +} diff --git a/miniapps/navigation/src/test/bitmaps/preview-osm-map.ts b/miniapps/navigation/src/test/bitmaps/preview-osm-map.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a18807fc674217d6486f2d0d33a0851bdf791cc --- /dev/null +++ b/miniapps/navigation/src/test/bitmaps/preview-osm-map.ts @@ -0,0 +1,56 @@ +/** + * Desktop preview for the OSM line-map renderer — no glasses needed. + * + * Fetches roads, renders the exact same base64 BMP the glasses get, decodes it + * back to a PNG, upscales it so it's visible, saves to disk, and (on macOS) + * opens it. Use this to iterate on zoom / line width / center quickly. + * + * Usage: + * bun run src/test/bitmaps/preview-osm-map.ts # defaults + * bun run src/test/bitmaps/preview-osm-map.ts + * + * Example (zoomed in on Manhattan, 8× upscale): + * bun run src/test/bitmaps/preview-osm-map.ts 40.714728 -73.998672 133 88 1 8 + */ + +import {$} from "bun" +import {buildOsmLineMap} from "../../background/lib/OsmLineMapRenderer" + +const lat = Number(process.argv[2] ?? 40.714728) +const lng = Number(process.argv[3] ?? -73.998672) +const radius = Number(process.argv[4] ?? 133) +const size = Number(process.argv[5] ?? 88) +const lineW = Number(process.argv[6] ?? 1) +const upscale = Number(process.argv[7] ?? 4) + +console.log(`Rendering OSM map: center=${lat},${lng} radius=${radius}m size=${size}×${size} lineW=${lineW}`) + +const base64 = await buildOsmLineMap({ + center: {lat, lng}, + width: size, + height: size, + viewRadiusMeters: radius, + lineWidthPx: lineW, +}) + +// Decode the base64 BMP (exactly what the glasses receive) and save it. +const bmpBytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)) +const outDir = new URL(".", import.meta.url).pathname +const bmpPath = `${outDir}preview-osm.bmp` +const pngPath = `${outDir}preview-osm.png` +await Bun.write(bmpPath, bmpBytes) + +// Convert BMP → PNG and upscale (nearest-neighbour stays crisp for line art) +// so the tiny 88px image is actually viewable on a desktop monitor. +const upPx = size * upscale +await $`sips -s format png ${bmpPath} -z ${upPx} ${upPx} --out ${pngPath}`.quiet() + +console.log(`✓ saved ${pngPath} (${size}×${size} upscaled ${upscale}× → ${upPx}px)`) + +// Open it on macOS so you see it immediately. +try { + await $`open ${pngPath}`.quiet() + console.log("→ opened in Preview") +} catch { + console.log("(could not auto-open; open the PNG manually)") +} diff --git a/miniapps/navigation/src/test/bitmaps/preview-osm.bmp b/miniapps/navigation/src/test/bitmaps/preview-osm.bmp new file mode 100644 index 0000000000000000000000000000000000000000..ed2c44f01e1b16ded0556e3982b353f3a7b40494 Binary files /dev/null and b/miniapps/navigation/src/test/bitmaps/preview-osm.bmp differ diff --git a/miniapps/navigation/src/test/bitmaps/preview-osm.png b/miniapps/navigation/src/test/bitmaps/preview-osm.png new file mode 100644 index 0000000000000000000000000000000000000000..5281be2d7579879384553ea1f35b1c25f0847cd2 Binary files /dev/null and b/miniapps/navigation/src/test/bitmaps/preview-osm.png differ diff --git a/miniapps/navigation/src/test/bitmaps/z12-400x400.png b/miniapps/navigation/src/test/bitmaps/z12-400x400.png new file mode 100644 index 0000000000000000000000000000000000000000..4b2dfdc83835695e5b6f44beff7469ace044b299 Binary files /dev/null and b/miniapps/navigation/src/test/bitmaps/z12-400x400.png differ diff --git a/miniapps/navigation/src/test/bitmaps/z14-200x100.png b/miniapps/navigation/src/test/bitmaps/z14-200x100.png new file mode 100644 index 0000000000000000000000000000000000000000..17bfdbd068d31c2f2058ce12a68b9dec6a0f9282 Binary files /dev/null and b/miniapps/navigation/src/test/bitmaps/z14-200x100.png differ diff --git a/miniapps/navigation/src/test/bitmaps/z14-200x88.png b/miniapps/navigation/src/test/bitmaps/z14-200x88.png new file mode 100644 index 0000000000000000000000000000000000000000..17644158c114d64a98443e6c730a1aaca271379c Binary files /dev/null and b/miniapps/navigation/src/test/bitmaps/z14-200x88.png differ diff --git a/miniapps/navigation/src/test/bitmaps/z14-400x400.png b/miniapps/navigation/src/test/bitmaps/z14-400x400.png new file mode 100644 index 0000000000000000000000000000000000000000..863f431175c6fe899f55fd57bda7323354c721cc Binary files /dev/null and b/miniapps/navigation/src/test/bitmaps/z14-400x400.png differ diff --git a/miniapps/navigation/src/test/bitmaps/z14-88x88-scale2.bmp.ts b/miniapps/navigation/src/test/bitmaps/z14-88x88-scale2.bmp.ts new file mode 100644 index 0000000000000000000000000000000000000000..062f7341c48db4b2f1d3a88ec2b92e98d54b3a5d --- /dev/null +++ b/miniapps/navigation/src/test/bitmaps/z14-88x88-scale2.bmp.ts @@ -0,0 +1,4 @@ +// AUTO-GENERATED by png-to-bmp.ts from src/test/bitmaps/z14-88x88-scale2.png at 88×88. +// Base64 8-bit grayscale BMP — data for a session.display.render() image element. +export const MAP_BMP_Z14_88X88_SCALE2 = "Qk12IgAAAAAAADYEAAAoAAAAWAAAAFgAAAABAAgAAAAAAEAeAAATCwAAEwsAAAABAAAAAQAAAAAAAAEBAQACAgIAAwMDAAQEBAAFBQUABgYGAAcHBwAICAgACQkJAAoKCgALCwsADAwMAA0NDQAODg4ADw8PABAQEAAREREAEhISABMTEwAUFBQAFRUVABYWFgAXFxcAGBgYABkZGQAaGhoAGxsbABwcHAAdHR0AHh4eAB8fHwAgICAAISEhACIiIgAjIyMAJCQkACUlJQAmJiYAJycnACgoKAApKSkAKioqAC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8/Pz9O7j4uza3d7e2On08/Pz8/Pd3N7e2ezo3Nnc3dnb5t7c3t7d2Oj08/P06uPz8/Pz8/Pz8/P05ef08/Pz8/Pz8/Pk6PT08erh4ujv39ve3t7b4fHw8/Pz8ujg6PL06tje3tza8PPz8/P069ne3tzX2d3d2N3p8eDb3t7d2Oj08/Pz8/Hg7PTz8/Pz8/Pz8+7g8fPz8/Pz8/P07OHw6uHi6/Ly8enY3t7e3tnu8PPz8ePf7fPz8/Tg297e2eH08/Pz8/Pd3d7e3t7Z2erz9OHY3t7e1+b08/Pz8/P05+Tz8/Pz8/Pz8/Pz4+r08/Pz8/Pz8/Li3+Dr8/Tz8/Hw2t3e3t7Y5/E=" +export const MAP_BMP_Z14_88X88_SCALE2_SIZE = 88 diff --git a/miniapps/navigation/src/test/bitmaps/z14-88x88-scale2.png b/miniapps/navigation/src/test/bitmaps/z14-88x88-scale2.png new file mode 100644 index 0000000000000000000000000000000000000000..1b38976dab2fe80a2295c759c33fd6954bfb7581 Binary files /dev/null and b/miniapps/navigation/src/test/bitmaps/z14-88x88-scale2.png differ diff --git a/miniapps/navigation/src/test/bitmaps/z14-roadmap.png b/miniapps/navigation/src/test/bitmaps/z14-roadmap.png new file mode 100644 index 0000000000000000000000000000000000000000..863f431175c6fe899f55fd57bda7323354c721cc Binary files /dev/null and b/miniapps/navigation/src/test/bitmaps/z14-roadmap.png differ diff --git a/miniapps/navigation/src/test/bitmaps/z14-terrain.png b/miniapps/navigation/src/test/bitmaps/z14-terrain.png new file mode 100644 index 0000000000000000000000000000000000000000..d2643650442c6aa4bc09ccc9bc425aeea7cea20c Binary files /dev/null and b/miniapps/navigation/src/test/bitmaps/z14-terrain.png differ diff --git a/miniapps/navigation/src/test/bitmaps/z16-400x400.png b/miniapps/navigation/src/test/bitmaps/z16-400x400.png new file mode 100644 index 0000000000000000000000000000000000000000..55de636f3d4ca8dd907debb70bcb94a559b61feb Binary files /dev/null and b/miniapps/navigation/src/test/bitmaps/z16-400x400.png differ diff --git a/miniapps/navigation/src/test/buildConfig.test.ts b/miniapps/navigation/src/test/buildConfig.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f30da4975ccbcc93b6791399b60b3cf8edc21561 --- /dev/null +++ b/miniapps/navigation/src/test/buildConfig.test.ts @@ -0,0 +1,41 @@ +import {describe, expect, test} from "bun:test" + +import {resolveMapboxBuildToken} from "../../buildConfig" + +describe("navigation build configuration", () => { + test("uses the standalone miniapp token when configured", () => { + expect( + resolveMapboxBuildToken({ + NODE_ENV: "production", + PUBLIC_MAPBOX_TOKEN: "pk.miniapp-token", + EXPO_PUBLIC_MAPBOX_ACCESS_TOKEN: "pk.mobile-token", + }), + ).toBe("pk.miniapp-token") + }) + + test("falls back to the Mentra App token for bundled builds", () => { + expect( + resolveMapboxBuildToken({ + NODE_ENV: "production", + PUBLIC_MAPBOX_TOKEN: " ", + EXPO_PUBLIC_MAPBOX_ACCESS_TOKEN: "pk.mobile-token", + }), + ).toBe("pk.mobile-token") + }) + + test.each([undefined, "", "ci-dummy-mapbox-pk-token"])( + "rejects a missing or invalid token in production (%s)", + (token) => { + expect(() => + resolveMapboxBuildToken({ + NODE_ENV: "production", + PUBLIC_MAPBOX_TOKEN: token, + }), + ).toThrow("A valid public Mapbox token is required") + }, + ) + + test("allows the dev server to provide the token at runtime", () => { + expect(resolveMapboxBuildToken({NODE_ENV: "development"})).toBe("") + }) +}) diff --git a/miniapps/navigation/src/test/capabilities.test.ts b/miniapps/navigation/src/test/capabilities.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8935cb829dff112b7190a25c518a10a3ce03b0bc --- /dev/null +++ b/miniapps/navigation/src/test/capabilities.test.ts @@ -0,0 +1,49 @@ +import {describe, expect, test} from "bun:test" + +import {readGlassesCapabilities} from "../background/lib/capabilities" + +describe("navigation glasses capabilities", () => { + test("preserves the positioned HUD when the host omits canPosition", () => { + expect( + readGlassesCapabilities({ + modelName: "Even Realities G2", + hasDisplay: true, + display: {canDisplayBitmap: true}, + }).canPosition, + ).toBe(true) + }) + + test("does not infer positioning support from a device model", () => { + expect( + readGlassesCapabilities({ + modelName: "Even Realities G2", + hasDisplay: true, + display: {canPosition: false}, + }).canPosition, + ).toBe(false) + }) + + test("uses the compact text HUD only when positioning is explicitly unsupported", () => { + expect( + readGlassesCapabilities({ + modelName: "Even Realities G1", + hasDisplay: true, + display: {canPosition: false}, + }).canPosition, + ).toBe(false) + }) + + test("honors explicit positioned-scene support", () => { + expect( + readGlassesCapabilities({ + modelName: "Mentra Display", + hasDisplay: true, + display: {canPosition: true}, + }).canPosition, + ).toBe(true) + }) + + test("does not claim positioning support without a display", () => { + expect(readGlassesCapabilities({modelName: "Mentra Live", hasDisplay: false}).canPosition).toBe(false) + }) +}) diff --git a/miniapps/navigation/src/test/display-manager.test.ts b/miniapps/navigation/src/test/display-manager.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0aad2ae617bacc29071293993d06a22387c315c --- /dev/null +++ b/miniapps/navigation/src/test/display-manager.test.ts @@ -0,0 +1,216 @@ +import {afterEach, describe, expect, test} from "bun:test" +import type {MiniappSession, RenderElement} from "@mentra/miniapp" + +import {DisplayManager} from "../background/managers/DisplayManager" +import {NavigationController} from "../background/NavigationController" +import {borderTestImageBase64} from "../background/lib/bmp" + +// Rendered widths from the calibrated G2 font profile. All digits except 1 +// occupy 12px; 1 occupies 8px; the colon occupies 4px. +const G2_DIGIT_WIDTH_PX = 12 +const G2_COLON_WIDTH_PX = 4 +const G2_NATIVE_HORIZONTAL_PADDING_PX = 8 +const G2_LINE_HEIGHT_PX = 40 + +function makeNimoDisplay() { + const frames: RenderElement[][] = [] + const session = { + capabilities: { + modelName: "NIMO", + display: {width: 500, height: 220, canPosition: true, maxImagePx: {width: 200, height: 200}}, + }, + display: {render: (elements: RenderElement[]) => frames.push(elements)}, + } as unknown as MiniappSession + return {frames, session, display: new DisplayManager(session)} +} + +describe("navigation capability-bounded bitmaps", () => { + const setTimeoutOriginal = globalThis.setTimeout + afterEach(() => { + globalThis.setTimeout = setTimeoutOriginal + }) + + test("ignores large-map requests on text-only displays without taking over the HUD", () => { + const {frames, session} = makeNimoDisplay() + session.capabilities = {display: {width: 576, height: 288, canPosition: false, maxImageElements: 0}} + const controller = new NavigationController(session) as unknown as { + showLargeMap(): void + renderLargeMap(position: {lat: number; lng: number}): void + largeMapShown: boolean + largeMapTransitioning: boolean + } + expect(() => controller.showLargeMap()).not.toThrow() + expect(() => controller.renderLargeMap({lat: 37.77, lng: -122.42})).not.toThrow() + expect(controller.largeMapShown).toBe(false) + expect(controller.largeMapTransitioning).toBe(false) + expect(frames).toEqual([]) + }) + + test("repaints the HUD when only bitmap capability disappears", () => { + const {frames, session} = makeNimoDisplay() + const controller = new NavigationController(session) as unknown as { + applyCapabilities(raw: MiniappSession["capabilities"]): void + largeMapShown: boolean + broadcastVoiceGuidanceState(): void + } + controller.broadcastVoiceGuidanceState = () => {} + session.capabilities = {...session.capabilities, hasDisplay: true} + controller.applyCapabilities(session.capabilities) + controller.largeMapShown = true + session.capabilities = {...session.capabilities, display: {...session.capabilities?.display, maxImageElements: 0}} + controller.applyCapabilities(session.capabilities) + expect(controller.largeMapShown).toBe(false) + expect(frames.at(-1)?.some((el) => el.type === "text" && el.text.includes("Welcome to Mentra Maps"))).toBe(true) + }) + + test("renders the real large-map raster and matching placement inside NIMO limits", () => { + const {frames, session} = makeNimoDisplay() + const controller = new NavigationController(session) as unknown as { + renderLargeMap: (position: {lat: number; lng: number}) => void + } + controller.renderLargeMap({lat: 37.77, lng: -122.42}) + const image = frames.at(-1)?.[0] + expect(image?.type).toBe("image") + if (image?.type !== "image") throw new Error("large map did not render an image") + expect(image.box).toEqual({x: 150, y: 40, w: 200, h: 140}) + const bmp = Buffer.from(image.data, "base64") + expect(bmp.readUInt32LE(18)).toBe(image.box.w) + expect(bmp.readUInt32LE(22)).toBe(image.box.h) + }) + + test("centers existing raw images without changing their declared raster size", () => { + const {frames, display} = makeNimoDisplay() + display.showRawBitmap(borderTestImageBase64(100, 80), 100, 80) + expect(frames.at(-1)?.[0]?.box).toEqual({x: 200, y: 70, w: 100, h: 80}) + }) + + test("generates diagnostics at the same dimensions as their device-centered box", () => { + const callbacks: Array<() => void> = [] + globalThis.setTimeout = ((cb: () => void) => { + callbacks.push(cb) + return 1 + }) as unknown as typeof setTimeout + const {frames, display} = makeNimoDisplay() + for (const render of [() => display.showTestBox(200, 100), () => display.showBitmapSize(200, 100)]) { + render() + callbacks.shift()?.() + const image = frames.at(-1)?.[0] + expect(image?.type).toBe("image") + if (image?.type !== "image") throw new Error("diagnostic did not render an image") + expect(image.box).toEqual({x: 150, y: 60, w: 200, h: 100}) + const bmp = Buffer.from(image.data, "base64") + expect(bmp.readUInt32LE(18)).toBe(200) + expect(bmp.readUInt32LE(22)).toBe(100) + } + }) + + test("rejects invalid and oversized diagnostics before clearing or sending a frame", () => { + globalThis.setTimeout = (() => 1) as unknown as typeof setTimeout + const {frames, display} = makeNimoDisplay() + for (const [w, h] of [ + [288, 140], + [100, 221], + [NaN, 100], + [100, Infinity], + [0, 100], + [-1, 100], + [8.5, 100], + ]) { + expect(() => display.showLargeBitmap("bmp", w, h)).toThrow() + expect(() => display.showRawBitmap("bmp", w, h)).toThrow() + expect(() => display.showTestBox(w, h)).toThrow() + expect(() => display.showBitmapSize(w, h)).toThrow() + } + expect(() => display.showBitmapTest("288-square-bmp")).toThrow() + expect(frames).toEqual([]) + }) + + test("uses live capabilities and preserves the older-host canvas fallback", () => { + const {frames, session, display} = makeNimoDisplay() + display.showText("NIMO") + expect(frames.at(-1)?.[0]?.box).toEqual({x: 0, y: 0, w: 500, h: 220}) + session.capabilities = {display: {width: 576, height: 288}} + display.showLargeBitmap("bmp", 288, 140) + expect(frames.at(-1)?.[0]?.box).toEqual({x: 144, y: 74, w: 288, h: 140}) + session.capabilities = null + display.showLargeBitmap("bmp", 288, 140) + expect(frames.at(-1)?.[0]?.box).toEqual({x: 144, y: 74, w: 288, h: 140}) + }) +}) + +describe("navigation display layout", () => { + test("keeps arrival words intact in the positioned message box", () => { + const {frames, display} = makeNimoDisplay() + + display.showNavMessage("You have arrived at Union Square, on your left", "15:55") + + expect(frames.at(-1)?.find((element) => element.id === "message")).toEqual({ + type: "text", + id: "message", + box: DisplayManager.HUD.message, + text: "You have arrived at Union Square, on your left", + style: {breakMode: "word"}, + }) + }) + + test("uses word wrapping for older positioned hosts that omit canPosition", () => { + const {frames, session, display} = makeNimoDisplay() + session.capabilities = {display: {width: 500, height: 220}} + + display.showNavMessage("You have arrived at Union Square, on your left") + + expect(frames.at(-1)?.find((element) => element.id === "message")).toMatchObject({ + style: {breakMode: "word"}, + }) + }) + + test("keeps every 24-hour clock value on one G2 text line", () => { + const widestClockWidth = G2_DIGIT_WIDTH_PX * 4 + G2_COLON_WIDTH_PX + const availableTextWidth = DisplayManager.HUD.clock.w - G2_NATIVE_HORIZONTAL_PADDING_PX + + expect(availableTextWidth).toBeGreaterThanOrEqual(widestClockWidth) + expect(DisplayManager.HUD.clock.h).toBeGreaterThanOrEqual(G2_LINE_HEIGHT_PX) + }) + + test("reserves complete G2 lines for wrapped stats and maneuver instructions", () => { + const {maneuver, map, stats} = DisplayManager.HUD + + expect(stats.w).toBeGreaterThanOrEqual(200) + expect(stats.h).toBeGreaterThanOrEqual(G2_LINE_HEIGHT_PX * 2) + expect(stats.y + stats.h).toBeLessThanOrEqual(map.y) + + // One distance line plus up to two wrapped instruction lines. + expect(maneuver.h).toBeGreaterThanOrEqual(G2_LINE_HEIGHT_PX * 3) + expect(maneuver.y + maneuver.h).toBeLessThanOrEqual(220) + expect(maneuver.x + maneuver.w).toBeLessThanOrEqual(map.x) + }) + + test("keeps the maneuver instruction inside G1's five-line text budget", () => { + const frames: RenderElement[][] = [] + const session = { + capabilities: {display: {canPosition: false}}, + display: { + render: (elements: RenderElement[]) => { + frames.push(elements) + }, + }, + } as unknown as MiniappSession + const display = new DisplayManager(session) + + // Prime the positioning-only slots. The compact frame must drop them so + // scene degradation cannot consume G1's line budget before the instruction. + display.showBitmap("map-bitmap") + display.showNavMessage("Starting…", "10:51") + display.showCompactNavHud("→\n56 m\nTurn right onto Gough Street", "1.2 km · 14 min") + + expect(frames.at(-1)).toEqual([ + { + type: "text", + id: "message", + box: DisplayManager.HUD.message, + text: "→\n56 m\nTurn right onto Gough Street\n\n1.2 km · 14 min", + }, + ]) + expect((frames.at(-1)?.[0] as {text: string}).text.split("\n")).toHaveLength(5) + }) +}) diff --git a/miniapps/navigation/src/test/early-arrival.test.ts b/miniapps/navigation/src/test/early-arrival.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..98d077ba8bbe7b66e05ad611f3c97207464c40dc --- /dev/null +++ b/miniapps/navigation/src/test/early-arrival.test.ts @@ -0,0 +1,107 @@ +import {describe, expect, mock, test} from "bun:test" + +import {NavigationController} from "../background/NavigationController" +import type {LatLng} from "../background/lib/geometry" +import type {Coords, TripState} from "../shared/types" + +// Exercise the controller's arrival transition without constructing device, +// network, UI, or timer-owning managers. +type ArrivalHarness = { + coords: Coords | null + trip: TripState + maybeFireEarlyArrival(): void +} + +const point = (eastMeters: number, northMeters = 0): LatLng => ({ + lat: northMeters / 111_320, + lng: eastMeters / 111_320, +}) +const route = [point(0), point(372)] + +function checkArrival(me: LatLng, points: LatLng[] | null = route, destination: LatLng = point(372)) { + const stop = mock(() => {}) + const controller: ArrivalHarness = Object.create(NavigationController.prototype) + Object.assign(controller, { + coords: {...me, ts: 0}, + trip: { + status: "navigating", + running: true, + maneuver: null, + activeDestination: destination, + activeDestinationName: null, + routePoints: points, + routeSteps: null, + offRouteAt: null, + arrivalSide: null, + } satisfies TripState, + appendLog: () => {}, + cancelPendingRebuild: () => {}, + exitLargeMap: () => {}, + navigation: {stop}, + ui: {send: () => {}}, + }) + controller.maybeFireEarlyArrival() + return {controller, stop} +} + +describe("early arrival requires actual proximity", () => { + test("does not stop a trip when a fix projects beyond the route tail from 64.4m away", () => { + const {controller, stop} = checkArrival(point(436.4)) + expect(controller.trip.status).toBe("navigating") + expect(stop).not.toHaveBeenCalled() + }) + + test("does not arrive 64.4m lateral to the endpoint despite zero projected distance", () => { + const {controller, stop} = checkArrival(point(372, 64.4)) + expect(controller.trip.status).toBe("navigating") + expect(stop).not.toHaveBeenCalled() + }) + + test("still arrives five meters before the route endpoint", () => { + const {controller, stop} = checkArrival(point(367)) + expect(controller.trip.status).toBe("arrived") + expect(stop).toHaveBeenCalledTimes(1) + }) + + test("still arrives at the walkable route endpoint when the destination pin is set back", () => { + const {controller, stop} = checkArrival(point(372), route, point(372, 30)) + expect(controller.trip.status).toBe("arrived") + expect(stop).toHaveBeenCalledTimes(1) + }) + + test("preserves near-pin arrival within the last forty meters", () => { + const {controller, stop} = checkArrival(point(350), route, point(350, 10)) + expect(controller.trip.status).toBe("arrived") + expect(stop).toHaveBeenCalledTimes(1) + }) + + test("does not arrive at the beginning of a 372m route", () => { + const {controller, stop} = checkArrival(point(0)) + expect(controller.trip.status).toBe("navigating") + expect(stop).not.toHaveBeenCalled() + }) + + test("leaves arrival to the native stream when route geometry is unavailable", () => { + for (const points of [null, [], [point(372)]]) { + const {controller, stop} = checkArrival(point(372), points) + expect(controller.trip.status).toBe("navigating") + expect(stop).not.toHaveBeenCalled() + } + }) + + test("does not infer arrival from a route containing nonfinite points", () => { + for (const invalid of [NaN, Infinity, -Infinity]) { + const {controller, stop} = checkArrival(point(372), [{lat: invalid, lng: 0}, ...route]) + expect(controller.trip.status).toBe("navigating") + expect(stop).not.toHaveBeenCalled() + } + }) + + test("does not infer arrival from a nonfinite location fix", () => { + for (const invalid of [NaN, Infinity, -Infinity]) { + const {controller, stop} = checkArrival({lat: invalid, lng: route[1].lng}) + expect(controller.trip.status).toBe("navigating") + expect(stop).not.toHaveBeenCalled() + } + }) +}) diff --git a/miniapps/navigation/src/test/navigation/computeRoute/computeRoute.test.ts b/miniapps/navigation/src/test/navigation/computeRoute/computeRoute.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..120ebdf13cb2ae4560f8f40a741a67a9c6b1acfa --- /dev/null +++ b/miniapps/navigation/src/test/navigation/computeRoute/computeRoute.test.ts @@ -0,0 +1,53 @@ +/// +import {describe, expect, test} from "bun:test" + +import {ackLatest, connectedSession, lastOutbound} from "../helpers" + +import defaultsInput from "./fixtures/defaults.input.json" +import defaultsExpected from "./fixtures/defaults.expected.json" +import passthroughInput from "./fixtures/passthrough.input.json" +import passthroughExpected from "./fixtures/passthrough.expected.json" +import primaryPlusAlts from "./fixtures/primary-plus-alternates.response.json" +import engineFailure from "./fixtures/engine-failure.response.json" + +describe("navigation.computeRoute", () => { + test("resolves with {ok: false, error: ...} when LOCATION not declared", async () => { + const {session} = await connectedSession({location: false}) + const result = await session.navigation.computeRoute({origin: {lat: 0, lng: 0}, stops: [{lat: 1, lng: 1}]}) + expect(result.ok).toBe(false) + expect((result as {error?: string}).error).toMatch(/LOCATION permission not declared/) + }) + + test("defaults mode to driving and alternatives to 1", async () => { + const {session, transport} = await connectedSession({location: true}) + void session.navigation.computeRoute(defaultsInput as never) + expect(lastOutbound(transport)).toMatchObject(defaultsExpected) + }) + + test("origin / stops / alternatives / mode pass through verbatim", async () => { + const {session, transport} = await connectedSession({location: true}) + void session.navigation.computeRoute(passthroughInput as never) + expect(lastOutbound(transport)).toMatchObject(passthroughExpected) + }) + + test("resolves with primary + alternates", async () => { + const {session, transport} = await connectedSession({location: true}) + const promise = session.navigation.computeRoute({ + origin: {lat: 0, lng: 0}, + stops: [{lat: 1, lng: 1}], + alternatives: 2, + }) + ackLatest(transport, primaryPlusAlts) + await expect(promise).resolves.toEqual(primaryPlusAlts) + }) + + test("forwards engine failure as ComputeRouteResult.ok=false", async () => { + const {session, transport} = await connectedSession({location: true}) + const promise = session.navigation.computeRoute({ + origin: {lat: 0, lng: 0}, + stops: [{lat: 1, lng: 1}], + }) + ackLatest(transport, engineFailure) + await expect(promise).resolves.toEqual(engineFailure) + }) +}) diff --git a/miniapps/navigation/src/test/navigation/computeRoute/fixtures/defaults.expected.json b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/defaults.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..b168c32d1f79c87053c21bdec057b648fc600a62 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/defaults.expected.json @@ -0,0 +1,5 @@ +{ + "type": "miniapp_navigation_compute_route", + "mode": "driving", + "alternatives": 1 +} diff --git a/miniapps/navigation/src/test/navigation/computeRoute/fixtures/defaults.input.json b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/defaults.input.json new file mode 100644 index 0000000000000000000000000000000000000000..577a2cc558e37239e1a4d7e145b1d70bb5345f43 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/defaults.input.json @@ -0,0 +1,4 @@ +{ + "origin": {"lat": 0, "lng": 0}, + "stops": [{"lat": 1, "lng": 1}] +} diff --git a/miniapps/navigation/src/test/navigation/computeRoute/fixtures/engine-failure.response.json b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/engine-failure.response.json new file mode 100644 index 0000000000000000000000000000000000000000..b3da84113ae317642e4335f6091f1a453f653805 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/engine-failure.response.json @@ -0,0 +1,4 @@ +{ + "ok": false, + "error": "no route" +} diff --git a/miniapps/navigation/src/test/navigation/computeRoute/fixtures/passthrough.expected.json b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/passthrough.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..3bcdd9fb9c8763e62ae919f4ec81f38c5eb3c3b3 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/passthrough.expected.json @@ -0,0 +1,10 @@ +{ + "type": "miniapp_navigation_compute_route", + "origin": {"lat": 1, "lng": 2}, + "stops": [ + {"lat": 3, "lng": 4}, + {"lat": 5, "lng": 6} + ], + "alternatives": 3, + "mode": "cycling" +} diff --git a/miniapps/navigation/src/test/navigation/computeRoute/fixtures/passthrough.input.json b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/passthrough.input.json new file mode 100644 index 0000000000000000000000000000000000000000..7d2760e5a129c94923fe03b78c5c02857c812928 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/passthrough.input.json @@ -0,0 +1,9 @@ +{ + "origin": {"lat": 1, "lng": 2}, + "stops": [ + {"lat": 3, "lng": 4}, + {"lat": 5, "lng": 6} + ], + "alternatives": 3, + "mode": "cycling" +} diff --git a/miniapps/navigation/src/test/navigation/computeRoute/fixtures/primary-plus-alternates.response.json b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/primary-plus-alternates.response.json new file mode 100644 index 0000000000000000000000000000000000000000..8791712573db82264d20c0101ceeaed5f9316d6c --- /dev/null +++ b/miniapps/navigation/src/test/navigation/computeRoute/fixtures/primary-plus-alternates.response.json @@ -0,0 +1,17 @@ +{ + "ok": true, + "routes": [ + { + "points": [{"lat": 0, "lng": 0}], + "totalDistanceMeters": 1000, + "totalDurationSeconds": 300, + "summary": "via A St" + }, + { + "points": [{"lat": 0, "lng": 0}], + "totalDistanceMeters": 1100, + "totalDurationSeconds": 320, + "summary": "via B St" + } + ] +} diff --git a/miniapps/navigation/src/test/navigation/deviate/deviate.test.ts b/miniapps/navigation/src/test/navigation/deviate/deviate.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..124617a3d0c162ef53d1310030b1d00e7f2e11d9 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/deviate/deviate.test.ts @@ -0,0 +1,23 @@ +/// +import {describe, expect, test} from "bun:test" + +import {connectedSession, lastEnvelope} from "../helpers" + +import defaultOffset from "./fixtures/default-offset.expected.json" +import customOffset from "./fixtures/custom-offset.expected.json" + +describe("navigation.dev.deviate", () => { + test("defaults offsetMeters to 20", async () => { + const {session, transport} = await connectedSession({location: true}) + session.navigation.dev.deviate() + expect(lastEnvelope(transport).payload).toEqual(defaultOffset) + }) + + test("forwards custom offset and is a one-shot (no requestId)", async () => { + const {session, transport} = await connectedSession({location: true}) + session.navigation.dev.deviate(75) + const env = lastEnvelope(transport) + expect(env.payload).toEqual(customOffset) + expect(env.requestId).toBeUndefined() + }) +}) diff --git a/miniapps/navigation/src/test/navigation/deviate/fixtures/custom-offset.expected.json b/miniapps/navigation/src/test/navigation/deviate/fixtures/custom-offset.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6fcb8083a1011c840d09db2d08d9e9b6cb527407 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/deviate/fixtures/custom-offset.expected.json @@ -0,0 +1,4 @@ +{ + "type": "miniapp_navigation_deviate", + "offsetMeters": 75 +} diff --git a/miniapps/navigation/src/test/navigation/deviate/fixtures/default-offset.expected.json b/miniapps/navigation/src/test/navigation/deviate/fixtures/default-offset.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..e8615c3732bd991d93821cfcdcb232c9112d3bff --- /dev/null +++ b/miniapps/navigation/src/test/navigation/deviate/fixtures/default-offset.expected.json @@ -0,0 +1,4 @@ +{ + "type": "miniapp_navigation_deviate", + "offsetMeters": 20 +} diff --git a/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/duplicates.event.json b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/duplicates.event.json new file mode 100644 index 0000000000000000000000000000000000000000..2a3d8f5602c1f32db21505534597030ec86b0ef4 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/duplicates.event.json @@ -0,0 +1,13 @@ +{ + "points": [ + {"lat": 0, "lng": 0}, + {"lat": 0, "lng": 1}, + {"lat": 0, "lng": 2}, + {"lat": 1, "lng": 2} + ], + "steps": [ + {"lat": 0, "lng": 0, "routeIndex": 0, "road": "Market St", "maneuver": "DEPART", "distanceMeters": 100}, + {"lat": 0, "lng": 1, "routeIndex": 1, "road": "Market St", "maneuver": "STRAIGHT", "distanceMeters": 100}, + {"lat": 0, "lng": 2, "routeIndex": 2, "road": "Castro St", "maneuver": "TURN_LEFT", "distanceMeters": 150} + ] +} diff --git a/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/duplicates.expected.json b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/duplicates.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..55e070867e1da19fcb784e47913cdf078cc8f335 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/duplicates.expected.json @@ -0,0 +1,3 @@ +{ + "roadNames": ["Market St", "Market St", "Castro St"] +} diff --git a/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/empty-steps.event.json b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/empty-steps.event.json new file mode 100644 index 0000000000000000000000000000000000000000..5c4133106d483e41efbfbd8063a528fc9343d18d --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/empty-steps.event.json @@ -0,0 +1,4 @@ +{ + "points": [{"lat": 0, "lng": 0}], + "steps": [] +} diff --git a/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/empty-steps.expected.json b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/empty-steps.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..fba7974e2fa8a826eeeff65a892ad8fc195ce095 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/empty-steps.expected.json @@ -0,0 +1,3 @@ +{ + "roadNames": [] +} diff --git a/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/simple-route.event.json b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/simple-route.event.json new file mode 100644 index 0000000000000000000000000000000000000000..1785de3db4b9c7728c6998d87b519288db595c6c --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/simple-route.event.json @@ -0,0 +1,13 @@ +{ + "points": [ + {"lat": 0, "lng": 0}, + {"lat": 0, "lng": 1}, + {"lat": 1, "lng": 1}, + {"lat": 1, "lng": 2} + ], + "steps": [ + {"lat": 0, "lng": 0, "routeIndex": 0, "road": "Fell St", "maneuver": "DEPART", "distanceMeters": 100}, + {"lat": 0, "lng": 1, "routeIndex": 1, "road": "Divisadero St", "maneuver": "TURN_LEFT", "distanceMeters": 200}, + {"lat": 1, "lng": 1, "routeIndex": 2, "road": "Geary Blvd", "maneuver": "TURN_RIGHT", "distanceMeters": 150} + ] +} diff --git a/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/simple-route.expected.json b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/simple-route.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..8ca4fc4b30bcb11c3255e55a4593b50781ab9051 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/simple-route.expected.json @@ -0,0 +1,3 @@ +{ + "roadNames": ["Fell St", "Divisadero St", "Geary Blvd"] +} diff --git a/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/with-nulls.event.json b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/with-nulls.event.json new file mode 100644 index 0000000000000000000000000000000000000000..1309c94892e74cdb71f01d024b9f9e359dfb1f25 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/with-nulls.event.json @@ -0,0 +1,14 @@ +{ + "points": [ + {"lat": 0, "lng": 0}, + {"lat": 0, "lng": 1}, + {"lat": 1, "lng": 1}, + {"lat": 1, "lng": 2} + ], + "steps": [ + {"lat": 0, "lng": 0, "routeIndex": 0, "road": "Fell St", "maneuver": "DEPART", "distanceMeters": 100}, + {"lat": 0, "lng": 1, "routeIndex": 1, "road": null, "maneuver": "STRAIGHT", "distanceMeters": 50}, + {"lat": 1, "lng": 1, "routeIndex": 2, "maneuver": "TURN_RIGHT", "distanceMeters": 200}, + {"lat": 1, "lng": 2, "routeIndex": 3, "road": "Geary Blvd", "maneuver": "ARRIVE", "distanceMeters": 100} + ] +} diff --git a/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/with-nulls.expected.json b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/with-nulls.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..f5e09311435d219103d8d72a05109cdf33a67b0a --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getRoadNames/fixtures/with-nulls.expected.json @@ -0,0 +1,3 @@ +{ + "roadNames": ["Fell St", "Geary Blvd"] +} diff --git a/miniapps/navigation/src/test/navigation/getRoadNames/getRoadNames.test.ts b/miniapps/navigation/src/test/navigation/getRoadNames/getRoadNames.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1066b5c8802ace61e3be5c8511cfb4a1b1dbd65f --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getRoadNames/getRoadNames.test.ts @@ -0,0 +1,75 @@ +/// +/** + * Asserts road names survive the bridge end-to-end: when the host emits a + * NavRoute with step metadata, an onRoute subscriber sees every `step.road` + * in order. Drops nulls (unnamed paths), keeps consecutive duplicates. + */ +import {describe, expect, test} from "bun:test" + +import {MiniappStreamType} from "@mentra/miniapp" +import type {NavRoute, NavStep} from "@mentra/miniapp" + +import {connectedSession, pushEvent} from "../helpers" + +import simpleRoute from "./fixtures/simple-route.event.json" +import simpleExpected from "./fixtures/simple-route.expected.json" +import withNullsRoute from "./fixtures/with-nulls.event.json" +import withNullsExpected from "./fixtures/with-nulls.expected.json" +import duplicatesRoute from "./fixtures/duplicates.event.json" +import duplicatesExpected from "./fixtures/duplicates.expected.json" +import emptyStepsRoute from "./fixtures/empty-steps.event.json" +import emptyStepsExpected from "./fixtures/empty-steps.expected.json" + +function getRoadNames(route: NavRoute): string[] { + const steps: NavStep[] = route.steps ?? [] + return steps + .map((s) => s.road) + .filter((r): r is string => typeof r === "string" && r.length > 0) +} + +describe("road names from a NavRoute", () => { + test("extracts every named road in order", async () => { + const {session, transport} = await connectedSession({location: true}) + let received: NavRoute | null = null + session.navigation.onRoute((r) => { + received = r + }) + + pushEvent(transport, MiniappStreamType.NAVIGATION_ROUTE, simpleRoute) + expect(received).not.toBeNull() + expect(getRoadNames(received!)).toEqual(simpleExpected.roadNames) + }) + + test("drops null / missing road names (unnamed paths)", async () => { + const {session, transport} = await connectedSession({location: true}) + let received: NavRoute | null = null + session.navigation.onRoute((r) => { + received = r + }) + + pushEvent(transport, MiniappStreamType.NAVIGATION_ROUTE, withNullsRoute) + expect(getRoadNames(received!)).toEqual(withNullsExpected.roadNames) + }) + + test("keeps consecutive duplicates (same road across steps)", async () => { + const {session, transport} = await connectedSession({location: true}) + let received: NavRoute | null = null + session.navigation.onRoute((r) => { + received = r + }) + + pushEvent(transport, MiniappStreamType.NAVIGATION_ROUTE, duplicatesRoute) + expect(getRoadNames(received!)).toEqual(duplicatesExpected.roadNames) + }) + + test("returns empty array when the route has no steps", async () => { + const {session, transport} = await connectedSession({location: true}) + let received: NavRoute | null = null + session.navigation.onRoute((r) => { + received = r + }) + + pushEvent(transport, MiniappStreamType.NAVIGATION_ROUTE, emptyStepsRoute) + expect(getRoadNames(received!)).toEqual(emptyStepsExpected.roadNames) + }) +}) diff --git a/miniapps/navigation/src/test/navigation/getState/fixtures/active-trip.response.json b/miniapps/navigation/src/test/navigation/getState/fixtures/active-trip.response.json new file mode 100644 index 0000000000000000000000000000000000000000..2beda942e14872042d7c11be7005155d58764f9a --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getState/fixtures/active-trip.response.json @@ -0,0 +1,13 @@ +{ + "ok": true, + "state": { + "active": true, + "mode": "walking", + "stops": [{"lat": 1, "lng": 2}], + "currentStopIndex": 0, + "distanceToDestinationMeters": 1200, + "timeToDestinationSeconds": 600, + "currentSpeedMps": 1.4, + "speedLimitMps": null + } +} diff --git a/miniapps/navigation/src/test/navigation/getState/fixtures/missing-state.response.json b/miniapps/navigation/src/test/navigation/getState/fixtures/missing-state.response.json new file mode 100644 index 0000000000000000000000000000000000000000..a9f53b383d35416073a43ea718e876fb14dd6fed --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getState/fixtures/missing-state.response.json @@ -0,0 +1,3 @@ +{ + "ok": true +} diff --git a/miniapps/navigation/src/test/navigation/getState/fixtures/no-trip.response.json b/miniapps/navigation/src/test/navigation/getState/fixtures/no-trip.response.json new file mode 100644 index 0000000000000000000000000000000000000000..4276ff886ffe08579c967eb21ceccbcb300ac9a8 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getState/fixtures/no-trip.response.json @@ -0,0 +1,3 @@ +{ + "ok": false +} diff --git a/miniapps/navigation/src/test/navigation/getState/fixtures/request.expected.json b/miniapps/navigation/src/test/navigation/getState/fixtures/request.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d54fc1083ac2ea6f50d0d80c7cfe7add1d03b465 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getState/fixtures/request.expected.json @@ -0,0 +1,3 @@ +{ + "type": "miniapp_navigation_get_state" +} diff --git a/miniapps/navigation/src/test/navigation/getState/getState.test.ts b/miniapps/navigation/src/test/navigation/getState/getState.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d028c388efd3889e0198432d8b0de58958a77a9b --- /dev/null +++ b/miniapps/navigation/src/test/navigation/getState/getState.test.ts @@ -0,0 +1,42 @@ +/// +import {describe, expect, test} from "bun:test" + +import type {NavState} from "@mentra/miniapp" + +import {ackLatest, connectedSession, lastEnvelope} from "../helpers" + +import requestShape from "./fixtures/request.expected.json" +import noTrip from "./fixtures/no-trip.response.json" +import missingState from "./fixtures/missing-state.response.json" +import activeTripJson from "./fixtures/active-trip.response.json" + +const activeTrip = activeTripJson as {ok: boolean; state: NavState} + +describe("navigation.getState", () => { + test("emits NAVIGATION_GET_STATE request", async () => { + const {session, transport} = await connectedSession({location: true}) + void session.navigation.getState() + expect(lastEnvelope(transport).payload).toMatchObject(requestShape) + }) + + test("returns null when host responds with ok: false", async () => { + const {session, transport} = await connectedSession({location: true}) + const promise = session.navigation.getState() + ackLatest(transport, noTrip) + await expect(promise).resolves.toBeNull() + }) + + test("returns null when host returns ok but no state field", async () => { + const {session, transport} = await connectedSession({location: true}) + const promise = session.navigation.getState() + ackLatest(transport, missingState) + await expect(promise).resolves.toBeNull() + }) + + test("hydrates the full NavState snapshot when active", async () => { + const {session, transport} = await connectedSession({location: true}) + const promise = session.navigation.getState() + ackLatest(transport, activeTrip) + await expect(promise).resolves.toEqual(activeTrip.state) + }) +}) diff --git a/miniapps/navigation/src/test/navigation/hasPermission/fixtures/denied.expected.json b/miniapps/navigation/src/test/navigation/hasPermission/fixtures/denied.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d5c03d80e03ad45316d196434dd899574e80ebe6 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/hasPermission/fixtures/denied.expected.json @@ -0,0 +1,3 @@ +{ + "hasPermission": false +} diff --git a/miniapps/navigation/src/test/navigation/hasPermission/fixtures/granted.expected.json b/miniapps/navigation/src/test/navigation/hasPermission/fixtures/granted.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..ddfef3d67da9fb2914e4f3d46852414b17a17c8d --- /dev/null +++ b/miniapps/navigation/src/test/navigation/hasPermission/fixtures/granted.expected.json @@ -0,0 +1,3 @@ +{ + "hasPermission": true +} diff --git a/miniapps/navigation/src/test/navigation/hasPermission/hasPermission.test.ts b/miniapps/navigation/src/test/navigation/hasPermission/hasPermission.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a36ab2155523b82b5b1724e7d0ee3c49a2f5e21e --- /dev/null +++ b/miniapps/navigation/src/test/navigation/hasPermission/hasPermission.test.ts @@ -0,0 +1,19 @@ +/// +import {describe, expect, test} from "bun:test" + +import {connectedSession} from "../helpers" + +import granted from "./fixtures/granted.expected.json" +import denied from "./fixtures/denied.expected.json" + +describe("navigation.hasPermission", () => { + test("returns true when LOCATION is in the manifest", async () => { + const {session} = await connectedSession({location: true}) + expect(session.navigation.hasPermission).toBe(granted.hasPermission) + }) + + test("returns false when LOCATION is absent", async () => { + const {session} = await connectedSession({location: false}) + expect(session.navigation.hasPermission).toBe(denied.hasPermission) + }) +}) diff --git a/miniapps/navigation/src/test/navigation/helpers.ts b/miniapps/navigation/src/test/navigation/helpers.ts new file mode 100644 index 0000000000000000000000000000000000000000..dcf327f4677f3d934d012d9f968d5db9b96e4d19 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/helpers.ts @@ -0,0 +1,102 @@ +/// +/** + * Shared test harness for navigation suites. + * + * Every test under src/test/navigation/* uses this. The split is by method + * — one folder per `session.navigation.*` surface, each with its own + * fixtures/ dir of {case}.input.json / {case}.expected.json / {case}.response.json + * files. + */ +import {expect} from "bun:test" + +import { + MiniappResponseType, + MiniappSession, + parseEnvelope, + serializeEnvelope, +} from "@mentra/miniapp" +import type {Transport, TransportDisconnectHandler, TransportMessageHandler} from "@mentra/miniapp" + +export class FakeTransport implements Transport { + sent: string[] = [] + private messageHandler: TransportMessageHandler | null = null + private disconnectHandler: TransportDisconnectHandler | null = null + private open_ = false + + async open(): Promise { + this.open_ = true + } + send(raw: string): void { + this.sent.push(raw) + } + onMessage(handler: TransportMessageHandler): void { + this.messageHandler = handler + } + onDisconnect(handler: TransportDisconnectHandler): void { + this.disconnectHandler = handler + } + close(): void { + this.open_ = false + } + isOpen(): boolean { + return this.open_ + } + + deliverFromPhone(payload: object, requestId?: string): void { + const env = {payload, ...(requestId ? {requestId} : {})} + this.messageHandler?.(serializeEnvelope(env as never)) + } +} + +export async function connectedSession(opts: {location: boolean}): Promise<{session: MiniappSession; transport: FakeTransport}> { + const transport = new FakeTransport() + const session = new MiniappSession({transport, packageName: "com.mentra.navigation"}) + const connectPromise = session.connect() + transport.deliverFromPhone({ + type: MiniappResponseType.CONNECT_ACK, + userId: "u", + packageName: "com.mentra.navigation", + capabilities: null, + permissions: { + location: opts.location, + microphone: false, + camera: false, + notifications: false, + calendar: false, + }, + }) + await connectPromise + return {session, transport} +} + +/** Latest payload the SDK pushed to the transport. */ +export function lastOutbound(transport: FakeTransport): Record { + const env = parseEnvelope(transport.sent[transport.sent.length - 1]!) + expect(env).not.toBeNull() + return env!.payload as Record +} + +/** Envelope (payload + requestId) of the latest outbound message. */ +export function lastEnvelope(transport: FakeTransport): {payload: Record; requestId?: string} { + const env = parseEnvelope(transport.sent[transport.sent.length - 1]!) + expect(env).not.toBeNull() + return {payload: env!.payload as Record, requestId: env!.requestId} +} + +/** Deliver a REQUEST_RESULT keyed to the most recent outbound request. */ +export function ackLatest(transport: FakeTransport, data: unknown, ok = true): void { + const env = parseEnvelope(transport.sent[transport.sent.length - 1]!) + transport.deliverFromPhone( + {type: MiniappResponseType.REQUEST_RESULT, ok, data}, + env!.requestId!, + ) +} + +/** Deliver an EVENT push on the given stream type. */ +export function pushEvent(transport: FakeTransport, streamType: string, data: unknown): void { + transport.deliverFromPhone({ + type: MiniappResponseType.EVENT, + streamType, + data, + }) +} diff --git a/miniapps/navigation/src/test/navigation/onRoute/fixtures/full-route.event.json b/miniapps/navigation/src/test/navigation/onRoute/fixtures/full-route.event.json new file mode 100644 index 0000000000000000000000000000000000000000..457f19ab574b6e26db3c5cfcc7981a7d88e9cc85 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/onRoute/fixtures/full-route.event.json @@ -0,0 +1,11 @@ +{ + "points": [ + {"lat": 1, "lng": 2}, + {"lat": 3, "lng": 4} + ], + "totalDistanceMeters": 500, + "totalDurationSeconds": 120, + "steps": [ + {"lat": 1, "lng": 2, "routeIndex": 0, "road": "A St", "maneuver": "DEPART", "distanceMeters": 100} + ] +} diff --git a/miniapps/navigation/src/test/navigation/onRoute/fixtures/reroute.events.json b/miniapps/navigation/src/test/navigation/onRoute/fixtures/reroute.events.json new file mode 100644 index 0000000000000000000000000000000000000000..005ca7ef9478cee19ecdc1388c4ba80bc170abf8 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/onRoute/fixtures/reroute.events.json @@ -0,0 +1,4 @@ +[ + {"points": [{"lat": 1, "lng": 1}]}, + {"points": [{"lat": 2, "lng": 2}, {"lat": 3, "lng": 3}]} +] diff --git a/miniapps/navigation/src/test/navigation/onRoute/onRoute.test.ts b/miniapps/navigation/src/test/navigation/onRoute/onRoute.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef828e5ce825cfb1c65fe578c895c50b1725bdc8 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/onRoute/onRoute.test.ts @@ -0,0 +1,49 @@ +/// +import {describe, expect, test} from "bun:test" + +import {MiniappStreamType} from "@mentra/miniapp" + +import {connectedSession, pushEvent} from "../helpers" + +import fullRoute from "./fixtures/full-route.event.json" +import reroute from "./fixtures/reroute.events.json" + +describe("navigation.onRoute", () => { + test("delivers the full NavRoute payload to subscribers", async () => { + const {session, transport} = await connectedSession({location: true}) + const received: Record[] = [] + session.navigation.onRoute((r) => { + received.push(r as Record) + }) + + pushEvent(transport, MiniappStreamType.NAVIGATION_ROUTE, fullRoute) + expect(received[0]).toEqual(fullRoute) + }) + + test("a reroute fires onRoute again with the full new polyline", async () => { + const {session, transport} = await connectedSession({location: true}) + const received: Array<{points: unknown}> = [] + session.navigation.onRoute((r) => received.push(r as {points: unknown})) + + for (const event of reroute) { + pushEvent(transport, MiniappStreamType.NAVIGATION_ROUTE, event) + } + + expect(received).toHaveLength(reroute.length) + expect((received[1]!.points as unknown[]).length).toBe((reroute[1]!.points as unknown[]).length) + }) + + test("unsubscribe stops further deliveries", async () => { + const {session, transport} = await connectedSession({location: true}) + let count = 0 + const unsub = session.navigation.onRoute(() => { + count++ + }) + + pushEvent(transport, MiniappStreamType.NAVIGATION_ROUTE, {points: []}) + unsub() + pushEvent(transport, MiniappStreamType.NAVIGATION_ROUTE, {points: []}) + + expect(count).toBe(1) + }) +}) diff --git a/miniapps/navigation/src/test/navigation/onUpdate/fixtures/all-kinds.events.json b/miniapps/navigation/src/test/navigation/onUpdate/fixtures/all-kinds.events.json new file mode 100644 index 0000000000000000000000000000000000000000..ca8c8153281f2a9d97f06a2ed17a1eca67fa9350 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/onUpdate/fixtures/all-kinds.events.json @@ -0,0 +1,7 @@ +[ + {"kind": "maneuver", "maneuverType": "TURN_LEFT", "distanceMeters": 50}, + {"kind": "off_route", "offRouteDistanceMeters": 18}, + {"kind": "rerouting"}, + {"kind": "arrived"}, + {"kind": "error", "message": "GPS lost"} +] diff --git a/miniapps/navigation/src/test/navigation/onUpdate/fixtures/maneuver-payload.events.json b/miniapps/navigation/src/test/navigation/onUpdate/fixtures/maneuver-payload.events.json new file mode 100644 index 0000000000000000000000000000000000000000..d829fe5b090f74c17135faede9adc84cc90b00a7 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/onUpdate/fixtures/maneuver-payload.events.json @@ -0,0 +1,12 @@ +{ + "kind": "maneuver", + "maneuverType": "SHARP_RIGHT", + "distanceMeters": 12, + "fromRoad": "Fell St", + "nextStepRoad": "Divisadero St", + "distanceToDestinationMeters": 1240, + "timeToDestinationSeconds": 360, + "currentSpeedMps": 4.2, + "speedLimitMps": null, + "routeHeadingDeg": 87 +} diff --git a/miniapps/navigation/src/test/navigation/onUpdate/onUpdate.test.ts b/miniapps/navigation/src/test/navigation/onUpdate/onUpdate.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d4f5e006b503b210200295d5d7c5e76b47fcc36 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/onUpdate/onUpdate.test.ts @@ -0,0 +1,47 @@ +/// +import {describe, expect, test} from "bun:test" + +import {MiniappStreamType} from "@mentra/miniapp" + +import {connectedSession, pushEvent} from "../helpers" + +import allKinds from "./fixtures/all-kinds.events.json" +import maneuverPayload from "./fixtures/maneuver-payload.events.json" + +describe("navigation.onUpdate", () => { + test("fans out maneuver / off_route / rerouting / arrived / error", async () => { + const {session, transport} = await connectedSession({location: true}) + const received: Array<{kind: string}> = [] + session.navigation.onUpdate((u) => received.push(u as {kind: string})) + + for (const data of allKinds) { + pushEvent(transport, MiniappStreamType.NAVIGATION_UPDATE, data) + } + + expect(received.map((u) => u.kind)).toEqual(allKinds.map((u) => u.kind)) + }) + + test("preserves NavManeuver field shape end-to-end", async () => { + const {session, transport} = await connectedSession({location: true}) + const received: Record[] = [] + session.navigation.onUpdate((u) => { + received.push(u as Record) + }) + + pushEvent(transport, MiniappStreamType.NAVIGATION_UPDATE, maneuverPayload) + expect(received[0]).toEqual(maneuverPayload) + }) + + test("unsubscribe stops further deliveries", async () => { + const {session, transport} = await connectedSession({location: true}) + const received: Array<{kind: string}> = [] + const unsub = session.navigation.onUpdate((u) => received.push(u as {kind: string})) + + pushEvent(transport, MiniappStreamType.NAVIGATION_UPDATE, {kind: "rerouting"}) + unsub() + pushEvent(transport, MiniappStreamType.NAVIGATION_UPDATE, {kind: "arrived"}) + + expect(received).toHaveLength(1) + expect(received[0]!.kind).toBe("rerouting") + }) +}) diff --git a/miniapps/navigation/src/test/navigation/pivots/fixtures/route-with-turn.event.json b/miniapps/navigation/src/test/navigation/pivots/fixtures/route-with-turn.event.json new file mode 100644 index 0000000000000000000000000000000000000000..993facf387d8a6bc91c3489ac425c9cb78bf646f --- /dev/null +++ b/miniapps/navigation/src/test/navigation/pivots/fixtures/route-with-turn.event.json @@ -0,0 +1,11 @@ +{ + "points": [ + {"lat": 0, "lng": 0}, + {"lat": 0, "lng": 0.001}, + {"lat": 0.001, "lng": 0.001} + ], + "steps": [ + {"lat": 0, "lng": 0, "routeIndex": 0, "maneuver": "DEPART", "distanceMeters": 100, "road": "First"}, + {"lat": 0, "lng": 0.001, "routeIndex": 1, "maneuver": "TURN_RIGHT", "distanceMeters": 100, "road": "Second"} + ] +} diff --git a/miniapps/navigation/src/test/navigation/pivots/fixtures/start.input.json b/miniapps/navigation/src/test/navigation/pivots/fixtures/start.input.json new file mode 100644 index 0000000000000000000000000000000000000000..5891038291e1df688eb352a7db6192a0d5efe75f --- /dev/null +++ b/miniapps/navigation/src/test/navigation/pivots/fixtures/start.input.json @@ -0,0 +1,5 @@ +{ + "lat": 1, + "lng": 2, + "mode": "walking" +} diff --git a/miniapps/navigation/src/test/navigation/pivots/pivots.test.ts b/miniapps/navigation/src/test/navigation/pivots/pivots.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c1b05f9b049abb7f0f8cdc1ad3f84b07bf84dcd --- /dev/null +++ b/miniapps/navigation/src/test/navigation/pivots/pivots.test.ts @@ -0,0 +1,39 @@ +/// +import {describe, expect, test} from "bun:test" + +import {MiniappStreamType, type StartNavigationOptions} from "@mentra/miniapp" + +import {connectedSession, pushEvent} from "../helpers" + +import startInputJson from "./fixtures/start.input.json" +import routeWithTurn from "./fixtures/route-with-turn.event.json" + +const startInput = startInputJson as StartNavigationOptions + +describe("navigation.pivots", () => { + test("getPivots is empty before any onRoute event", async () => { + const {session} = await connectedSession({location: true}) + void session.navigation.start(startInput) + expect(session.navigation.getPivots()).toEqual([]) + }) + + test("getActivePivot is null when no trip is running", async () => { + const {session} = await connectedSession({location: true}) + expect(session.navigation.getActivePivot()).toBeNull() + }) + + test("getUpcomingPivot is null when no trip is running", async () => { + const {session} = await connectedSession({location: true}) + expect(session.navigation.getUpcomingPivot()).toBeNull() + }) + + test("stop() clears the pivot list and active pivot", async () => { + const {session, transport} = await connectedSession({location: true}) + void session.navigation.start(startInput) + pushEvent(transport, MiniappStreamType.NAVIGATION_ROUTE, routeWithTurn) + session.navigation.stop() + + expect(session.navigation.getPivots()).toEqual([]) + expect(session.navigation.getActivePivot()).toBeNull() + }) +}) diff --git a/miniapps/navigation/src/test/navigation/requestPermission/fixtures/android-accepted.response.json b/miniapps/navigation/src/test/navigation/requestPermission/fixtures/android-accepted.response.json new file mode 100644 index 0000000000000000000000000000000000000000..c4d408a595110a60eb29513413b1811537bf3766 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/requestPermission/fixtures/android-accepted.response.json @@ -0,0 +1,4 @@ +{ + "ok": true, + "accepted": true +} diff --git a/miniapps/navigation/src/test/navigation/requestPermission/fixtures/emit-request.expected.json b/miniapps/navigation/src/test/navigation/requestPermission/fixtures/emit-request.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5e04640e7e4d6729915da561316456793e5375ed --- /dev/null +++ b/miniapps/navigation/src/test/navigation/requestPermission/fixtures/emit-request.expected.json @@ -0,0 +1,3 @@ +{ + "type": "miniapp_navigation_request_permission" +} diff --git a/miniapps/navigation/src/test/navigation/requestPermission/fixtures/ios-not-supported.response.json b/miniapps/navigation/src/test/navigation/requestPermission/fixtures/ios-not-supported.response.json new file mode 100644 index 0000000000000000000000000000000000000000..8862957b8d52f233bf516ac79a0cab37a40316a5 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/requestPermission/fixtures/ios-not-supported.response.json @@ -0,0 +1,4 @@ +{ + "ok": false, + "accepted": false +} diff --git a/miniapps/navigation/src/test/navigation/requestPermission/requestPermission.test.ts b/miniapps/navigation/src/test/navigation/requestPermission/requestPermission.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e253ede6cf247db7a6851269c1b514c00270c2ea --- /dev/null +++ b/miniapps/navigation/src/test/navigation/requestPermission/requestPermission.test.ts @@ -0,0 +1,41 @@ +/// +import {describe, expect, test} from "bun:test" + +import {ackLatest, connectedSession, lastEnvelope} from "../helpers" + +import emitRequest from "./fixtures/emit-request.expected.json" +import androidAccepted from "./fixtures/android-accepted.response.json" +import iosNotSupported from "./fixtures/ios-not-supported.response.json" + +describe("navigation.requestPermission", () => { + test("resolves with {ok: false, accepted: false, error: ...} when LOCATION not declared", async () => { + const {session} = await connectedSession({location: false}) + const result = await session.navigation.requestPermission() + expect(result.ok).toBe(false) + expect(result.accepted).toBe(false) + expect(result.error).toMatch(/LOCATION permission not declared/) + }) + + test("emits NAVIGATION_REQUEST_PERMISSION with a requestId", async () => { + const {session, transport} = await connectedSession({location: true}) + void session.navigation.requestPermission() + + const env = lastEnvelope(transport) + expect(env.payload.type).toBe(emitRequest.type) + expect(env.requestId).toBeDefined() + }) + + test("resolves with the Android-side {ok, accepted} ack", async () => { + const {session, transport} = await connectedSession({location: true}) + const promise = session.navigation.requestPermission() + ackLatest(transport, androidAccepted) + await expect(promise).resolves.toEqual(androidAccepted) + }) + + test("forwards iOS-style {ok: false, accepted: false} verbatim", async () => { + const {session, transport} = await connectedSession({location: true}) + const promise = session.navigation.requestPermission() + ackLatest(transport, iosNotSupported) + await expect(promise).resolves.toEqual(iosNotSupported) + }) +}) diff --git a/miniapps/navigation/src/test/navigation/start/fixtures/accepted.response.json b/miniapps/navigation/src/test/navigation/start/fixtures/accepted.response.json new file mode 100644 index 0000000000000000000000000000000000000000..a9f53b383d35416073a43ea718e876fb14dd6fed --- /dev/null +++ b/miniapps/navigation/src/test/navigation/start/fixtures/accepted.response.json @@ -0,0 +1,3 @@ +{ + "ok": true +} diff --git a/miniapps/navigation/src/test/navigation/start/fixtures/avoid.expected.json b/miniapps/navigation/src/test/navigation/start/fixtures/avoid.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..8eb4b65df81275beaaff31e6414a89799e28be9f --- /dev/null +++ b/miniapps/navigation/src/test/navigation/start/fixtures/avoid.expected.json @@ -0,0 +1,3 @@ +{ + "avoid": {"highways": true, "tolls": false, "ferries": true} +} diff --git a/miniapps/navigation/src/test/navigation/start/fixtures/avoid.input.json b/miniapps/navigation/src/test/navigation/start/fixtures/avoid.input.json new file mode 100644 index 0000000000000000000000000000000000000000..fea85cd3caa47170d0c26a12d303794af657b5f8 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/start/fixtures/avoid.input.json @@ -0,0 +1,5 @@ +{ + "lat": 1, + "lng": 2, + "avoid": {"highways": true, "tolls": false, "ferries": true} +} diff --git a/miniapps/navigation/src/test/navigation/start/fixtures/defaults.expected.json b/miniapps/navigation/src/test/navigation/start/fixtures/defaults.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..651e0c6de6a8dbbbeae7913094d9b9ed23557fa3 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/start/fixtures/defaults.expected.json @@ -0,0 +1,5 @@ +{ + "mode": "driving", + "simulate": false, + "speedMultiplier": 1 +} diff --git a/miniapps/navigation/src/test/navigation/start/fixtures/defaults.input.json b/miniapps/navigation/src/test/navigation/start/fixtures/defaults.input.json new file mode 100644 index 0000000000000000000000000000000000000000..3b932e641c3c1a09b16f6d66ccf005598e2969ef --- /dev/null +++ b/miniapps/navigation/src/test/navigation/start/fixtures/defaults.input.json @@ -0,0 +1,4 @@ +{ + "lat": 1, + "lng": 2 +} diff --git a/miniapps/navigation/src/test/navigation/start/fixtures/host-error.response.json b/miniapps/navigation/src/test/navigation/start/fixtures/host-error.response.json new file mode 100644 index 0000000000000000000000000000000000000000..10e3be98b5f6ad020eebe1b1b5a8a73f7d7d94b6 --- /dev/null +++ b/miniapps/navigation/src/test/navigation/start/fixtures/host-error.response.json @@ -0,0 +1,4 @@ +{ + "ok": false, + "error": "navigation already running" +} diff --git a/miniapps/navigation/src/test/navigation/start/fixtures/multi-stop.expected.json b/miniapps/navigation/src/test/navigation/start/fixtures/multi-stop.expected.json new file mode 100644 index 0000000000000000000000000000000000000000..c50ce762ebf6441237c050f6ea746bda08f8bbed --- /dev/null +++ b/miniapps/navigation/src/test/navigation/start/fixtures/multi-stop.expected.json @@ -0,0 +1,11 @@ +{ + "type": "miniapp_navigation_start", + "lat": 1, + "lng": 2, + "stops": [ + {"lat": 1, "lng": 2}, + {"lat": 3, "lng": 4}, + {"lat": 5, "lng": 6} + ], + "mode": "walking" +} diff --git a/miniapps/navigation/src/test/navigation/start/start.test.ts b/miniapps/navigation/src/test/navigation/start/start.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e96e68e6246984417cd5668e2d17e4dccdb9f1d --- /dev/null +++ b/miniapps/navigation/src/test/navigation/start/start.test.ts @@ -0,0 +1,136 @@ +/// +import {describe, expect, test} from "bun:test" +import type {MiniappSession, StartNavigationOptions} from "@mentra/miniapp" + +import {ackLatest, connectedSession, type FakeTransport, lastEnvelope, lastOutbound} from "../helpers" + +import v1ShorthandInput from "./fixtures/v1-shorthand.input.json" +import v1ShorthandExpected from "./fixtures/v1-shorthand.expected.json" +import multiStopInput from "./fixtures/multi-stop.input.json" +import multiStopExpected from "./fixtures/multi-stop.expected.json" +import defaultsInput from "./fixtures/defaults.input.json" +import defaultsExpected from "./fixtures/defaults.expected.json" +import simulateInput from "./fixtures/simulate.input.json" +import simulateExpected from "./fixtures/simulate.expected.json" +import avoidInput from "./fixtures/avoid.input.json" +import avoidExpected from "./fixtures/avoid.expected.json" +import twoWheelerInput from "./fixtures/two-wheeler.input.json" +import twoWheelerExpected from "./fixtures/two-wheeler.expected.json" +import accepted from "./fixtures/accepted.response.json" +import hostError from "./fixtures/host-error.response.json" + +const computedRoute = { + ok: true, + routes: [ + { + points: [ + {lat: 0, lng: 0}, + {lat: 1, lng: 1}, + ], + totalDistanceMeters: 100, + totalDurationSeconds: 60, + steps: [ + { + lat: 0, + lng: 0, + endLat: 1, + endLng: 1, + distanceMeters: 100, + maneuver: "ARRIVE", + instruction: "Arrive at the destination", + }, + ], + }, + ], +} + +/** Advance the modern start flow through GPS + REST so NAVIGATION_START is latest. */ +async function advanceToNativeStart( + session: MiniappSession, + transport: FakeTransport, + options: StartNavigationOptions, +) { + const promise = session.navigation.start(options) + await Promise.resolve() + expect(lastOutbound(transport).type).toBe("miniapp_location_poll") + ackLatest(transport, {lat: 0, lng: 0, timestamp: Date.now()}) + await Promise.resolve() + await Promise.resolve() + expect(lastOutbound(transport).type).toBe("miniapp_navigation_compute_route") + ackLatest(transport, computedRoute) + await Promise.resolve() + await Promise.resolve() + expect(lastOutbound(transport).type).toBe("miniapp_navigation_start") + return {promise} +} + +describe("navigation.start", () => { + test("resolves with {ok: false, error: ...} when LOCATION not declared", async () => { + const {session} = await connectedSession({location: false}) + const result = await session.navigation.start({lat: 1, lng: 2}) + expect(result.ok).toBe(false) + expect((result as {error?: string}).error).toMatch(/LOCATION permission not declared/) + }) + + test("v1 {lat, lng} shorthand rewrites to a single-element stops array", async () => { + const {session, transport} = await connectedSession({location: true}) + await advanceToNativeStart(session, transport, v1ShorthandInput) + const payload = lastOutbound(transport) + expect(payload).toMatchObject(v1ShorthandExpected) + }) + + test("multi-stop trips serialize stops verbatim and mirror first stop into lat/lng", async () => { + const {session, transport} = await connectedSession({location: true}) + await advanceToNativeStart(session, transport, multiStopInput as never) + const payload = lastOutbound(transport) + expect(payload).toMatchObject(multiStopExpected) + }) + + test("mode defaults to driving, simulate defaults to false, speedMultiplier defaults to 1", async () => { + const {session, transport} = await connectedSession({location: true}) + await advanceToNativeStart(session, transport, defaultsInput) + const payload = lastOutbound(transport) + expect(payload).toMatchObject(defaultsExpected) + }) + + test("simulate options pass through unchanged", async () => { + const {session, transport} = await connectedSession({location: true}) + await advanceToNativeStart(session, transport, simulateInput) + const payload = lastOutbound(transport) + expect(payload).toMatchObject(simulateExpected) + }) + + test("avoid flags serialize verbatim", async () => { + const {session, transport} = await connectedSession({location: true}) + await advanceToNativeStart(session, transport, avoidInput) + const payload = lastOutbound(transport) + expect(payload).toMatchObject(avoidExpected) + }) + + test("two_wheeler mode survives the wire", async () => { + const {session, transport} = await connectedSession({location: true}) + await advanceToNativeStart(session, transport, twoWheelerInput as never) + const payload = lastOutbound(transport) + expect(payload).toMatchObject(twoWheelerExpected) + }) + + test("request carries a requestId so the ack can resolve", async () => { + const {session, transport} = await connectedSession({location: true}) + await advanceToNativeStart(session, transport, {lat: 1, lng: 2}) + expect(lastEnvelope(transport).requestId).toBeDefined() + }) + + test("resolves with the host ack on success", async () => { + const {session, transport} = await connectedSession({location: true}) + const {promise} = await advanceToNativeStart(session, transport, {lat: 1, lng: 2}) + ackLatest(transport, accepted) + await expect(promise).resolves.toEqual(accepted) + }) + + test("forwards host-side error in the ack", async () => { + const {session, transport} = await connectedSession({location: true}) + const {promise} = await advanceToNativeStart(session, transport, {lat: 1, lng: 2}) + ackLatest(transport, hostError) + await expect(promise).resolves.toEqual(hostError) + }) +}) diff --git a/miniapps/navigation/src/test/off-route-hysteresis.test.ts b/miniapps/navigation/src/test/off-route-hysteresis.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..44dd2c0a6927f99532f1a7cd5fc1df0afca82010 --- /dev/null +++ b/miniapps/navigation/src/test/off-route-hysteresis.test.ts @@ -0,0 +1,27 @@ +import {describe, expect, test} from "bun:test" + +import {classifyOffRouteAdvisory} from "../background/NavigationController" + +describe("off-route advisory hysteresis", () => { + test("enters at 20m and recovers only below 15m", () => { + expect(classifyOffRouteAdvisory(19.9, false)).toBe(false) + expect(classifyOffRouteAdvisory(20, false)).toBe(true) + expect(classifyOffRouteAdvisory(19.5, true)).toBe(true) + expect(classifyOffRouteAdvisory(15, true)).toBe(true) + expect(classifyOffRouteAdvisory(14.9, true)).toBe(false) + }) + + test("does not chatter for the distances captured in the incident", () => { + const incidentDistances = [21.2, 17.1, 20.1, 13.6, 20.1, 19.5, 20.2, 19.8, 20, 20, 20.1, 18.6, 23, 18.9, 22.3, 18.4] + let advisoryActive = false + let transitions = 0 + + for (const distance of incidentDistances) { + const next = classifyOffRouteAdvisory(distance, advisoryActive) + if (next !== advisoryActive) transitions += 1 + advisoryActive = next + } + + expect(transitions).toBe(3) + }) +}) diff --git a/miniapps/navigation/src/test/saved-address-actions.test.ts b/miniapps/navigation/src/test/saved-address-actions.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a1ff3c1af90cafb8a72d17f3a3630e807f73e68 --- /dev/null +++ b/miniapps/navigation/src/test/saved-address-actions.test.ts @@ -0,0 +1,113 @@ +import {describe, expect, mock, test} from "bun:test" + +import {getSavedAddresses, setSavedAddress} from "../background/actions/savedAddressActions" +import type {PlaceDetails, SavedPlace} from "../background/lib/places" + +const home: SavedPlace = { + placeId: "home-id", + name: "Home Place", + address: "1 Home St", + lat: 37.1, + lng: -122.1, + savedName: "Home", + type: "home", +} + +const work: SavedPlace = { + placeId: "work-id", + name: "Work Place", + address: "2 Work Ave", + lat: 37.2, + lng: -122.2, + savedName: "Work", + type: "work", +} + +describe("saved-address actions", () => { + test("gets only Home and Work in stable slot order", async () => { + const favorite: SavedPlace = { + placeId: "favorite-id", + name: "Coffee", + address: "3 Coffee Ln", + lat: 37.3, + lng: -122.3, + } + const storage = { + getAllSavedPlaces: mock(async () => [work, favorite, home]), + addSavedPlace: mock(async () => {}), + } + + await expect(getSavedAddresses(storage)).resolves.toEqual({ + addresses: [ + {type: "home", name: "Home Place", address: "1 Home St", latitude: 37.1, longitude: -122.1}, + {type: "work", name: "Work Place", address: "2 Work Ave", latitude: 37.2, longitude: -122.2}, + ], + }) + }) + + test("resolves and saves one address slot", async () => { + const resolved: PlaceDetails = { + placeId: "resolved-id", + name: "Mentra HQ", + address: "369 Hayes St, San Francisco, CA", + lat: 37.7764, + lng: -122.4222, + } + const storage = { + getAllSavedPlaces: mock(async () => []), + addSavedPlace: mock(async () => {}), + } + const resolveAddress = mock(async () => resolved) + + await expect( + setSavedAddress({type: "work", address: " 369 Hayes St "}, storage, resolveAddress), + ).resolves.toEqual({ + address: { + type: "work", + name: "Mentra HQ", + address: "369 Hayes St, San Francisco, CA", + latitude: 37.7764, + longitude: -122.4222, + }, + }) + expect(resolveAddress).toHaveBeenCalledWith("369 Hayes St") + expect(storage.addSavedPlace).toHaveBeenCalledWith({...resolved, type: "work", savedName: "Work"}) + }) + + test.each([ + [{address: "1 Home St"}, "'type' must be 'home' or 'work'"], + [{type: "other", address: "1 Home St"}, "'type' must be 'home' or 'work'"], + [{type: "home"}, "'address' is required"], + [{type: "home", address: " "}, "'address' is required"], + ])("rejects invalid parameters", async (params, message) => { + const storage = { + getAllSavedPlaces: mock(async () => []), + addSavedPlace: mock(async () => {}), + } + + await expect( + setSavedAddress( + params, + storage, + mock(async () => null), + ), + ).rejects.toThrow(message) + expect(storage.addSavedPlace).not.toHaveBeenCalled() + }) + + test("does not overwrite a slot when place search finds no match", async () => { + const storage = { + getAllSavedPlaces: mock(async () => []), + addSavedPlace: mock(async () => {}), + } + + await expect( + setSavedAddress( + {type: "home", address: "not a real place"}, + storage, + mock(async () => null), + ), + ).rejects.toThrow("couldn't find a place matching") + expect(storage.addSavedPlace).not.toHaveBeenCalled() + }) +}) diff --git a/miniapps/navigation/tsconfig.json b/miniapps/navigation/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..337f4f5b4411f2d5793df648f58e9b0cf8945c68 --- /dev/null +++ b/miniapps/navigation/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "outDir": "./dist", + "rootDir": ".", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "paths": { + "@/*": ["./src/*"], + "@/background/*": ["./src/background/*"], + "@/ui/*": ["./src/ui/*"], + "@/shared/*": ["./src/shared/*"] + } + }, + "include": ["src/**/*.ts", "src/**/*.tsx"] +}