diff --git a/.env.example b/.env.example index 5bc02df9c..1949c48f4 100644 --- a/.env.example +++ b/.env.example @@ -129,18 +129,20 @@ AISSTREAM_API_KEY= # 0 disables the silence watch entirely. # AISSTREAM_SILENCE_TIMEOUT_MS=120000 -# Optional: TomTom live traffic flow (BYOK freemium — free tier is ~50,000 tile -# requests/day, get a key at https://developer.tomtom.com). SERVER-SIDE ONLY: +# Optional: TomTom live traffic flow (BYOK freemium — the free tier is 200,000 +# Traffic Flow & Incidents tile requests per MONTH, not per day; no credit card +# required. Get a key at https://developer.tomtom.com). SERVER-SIDE ONLY: # the browser fetches same-origin /api/tomtom/* and never sees the key. # Keyless fallback: the traffic layer runs its built-in simulation (white dots, # hardcoded per-road-class speeds) — no key required for the layer to work. # TOMTOM_API_KEY= -# Optional soft cap on upstream tile fetches per UTC day (default 40000) — a +# Optional soft cap on upstream tile fetches per UTC day (default 6000) — a # configurable application safety ceiling, not a guarantee of staying within # TomTom's free allowance (currently 200K tile requests/month: -# https://docs.tomtom.com/pricing/). Over the cap the proxy serves cached/stale -# tiles instead of hitting upstream. -# TOMTOM_DAILY_TILE_BUDGET=40000 +# https://docs.tomtom.com/pricing/). 6000/day keeps a 31-day month at 186K, +# inside that allowance. Over the cap the proxy serves cached/stale tiles +# instead of hitting upstream. +# TOMTOM_DAILY_TILE_BUDGET=6000 # Optional: CCTV layer tuning (advanced). Defaults are sensible — leave unset # unless you're customizing the camera source pack. diff --git a/.gitignore b/.gitignore index 491a82c15..1a64fff39 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,13 @@ node_modules dist +# Credential files. `.env` alone is not enough: Vite's loadEnv (see +# server/standalone/vite.config.js) and scripts/setup-doctor.mjs both read the +# full dotenv ladder — .env, .env.local, .env. and .env..local — +# so a key placed in any of them is live for the app. Only .env was ignored, +# leaving the other three committable. .env.example is the tracked template. .env +.env.* +!.env.example *.log screenshots/ qa-shots/ diff --git a/CHANGELOG.md b/CHANGELOG.md index f037c3e23..2f1e224e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,150 @@ header lifts it out of the right rail into a floating window that resizes from any edge or corner, remembers its position and size, and snaps back on a header double-click. +- Add a **Recent Imagery** data layer (NASA GIBS · HLS + VIIRS, keyless). + Select a box (drag, the current view, or around a pin; up to 1,000 km a + side) and the right-rail panel lists the last 30 days of Sentinel-2 / + Landsat (30 m) and, when switched on, VIIRS daily overview imagery over it, + with thumbnails and scene cloud. Three modes: IMAGE shows one day, VS + BASEMAP swipes it against the map, A / B swipes two days; a SHOW or A / B + chip on each day card pins it, arrow keys preview the focused day while a + slot is empty, and no control moves when anything changes. While imagery is + shown on Google 3D the map switches to Esri and comes back when it is + cleared. Either image exports as a PNG; box, pins, mode and split travel in + share links; the NASA acknowledgement is in the credits and + `DATA_SOURCES.md`. The swipe is now shared with the Nepal scene + (`src/ui/imagerySplit.js`, `src/maps/imageryComparison.js`), and + `MapSourceController.subscribe()` reports every settled map switch. + +## Unreleased — weather review + +- On 3D Tiles, draw a 4096×2048 detail window around the view on each + observed-weather shell except global infrared, sampled by the shell's own + surface. It follows the view on camera move end, keeps its place while the + view stays near its centre, and hides until its image is ready after a move; + an older frame's detail stays over at most one newer frame. The image proxy + accepts a 2:1 `bbox` inside the product bounds, rounded to 0.25°. + Lightning's whole-extent image is now 4096×2048; each shell caches up to + 128 MiB of decoded images. + +- On 3D Tiles, show observed weather and the wind color field as raised, + translucent shells (5.0–6.6 km, lightning highest) with one full-extent image + per frame instead of draping onto tiles; they show at any camera height. + Globe hosts are unchanged. The weather image proxy serves every product + (radar and regional infrared up to 4096×2048, lightning and global infrared + up to 2048×1024) with a size parameter and a 16 MiB cap. Accept bounded tile + sizes in the proxy with separate immutable cache entries. + +- Cache exact-time weather images and tiles for 24 hours. Retain up to 6 decoded + global mosaics per renderer and warm the next observation during playback; + tile prefetch is bounded to eight requests and cancels when suspended. + +- Move weather times, coverage, legends and cyclone advisory details into keyed + right-rail cards; left rows keep status and configuration. Use one native + observed-history timeline with local preview and coalesced drag commits. +- Add reusable rail card and timeline components. Keep panel collapse, count, + hidden-empty behavior and first-appearance expansion. +- Show wind unit controls beside speed legends and inside inspection readings; + changing units preserves the sampled location and open reading. +- Name satellite imagery Satellite clouds, with Clouds only / Full image modes + and explicit regional coverage. Existing share parameters are unchanged. + +- Share one observed history clock across radar, infrared and lightning. Step + through their union timeline with bounded nearest-at-or-before selection; + hide products without an eligible frame. Latest uses each product's newest + observation; playback waits for all frame loads to settle before advancing. +- Label wind as a forecast that does not follow observed history. Keep history + transient and product readouts synchronized. + +- Keep Google 3D Tiles drawing while draped weather imagery loads and retain the + old observation until the replacement has rendered. +- Decode one bounded global infrared mosaic per frame on both map hosts, then + crop local tiles to avoid request-dependent brightness seams. +- Add Clouds only / Full image controls and share-link state. Filtered mode uses + a soft linear-brightness alpha ramp from 0.40 to 0.70 around the old 0.55 cut. + +- Dock the weather summary in the right rail with standard panel collapse and drag chrome. + +- Filter infrared brightness so cold cloud tops stand out; this is a display + filter, not a cloud mask. +- Retry throttled weather tiles up to three times per tile. + +- Cull regional wind batches per frame, fade curves below 60 km, and stop idle + rendering when no curve is visible. +- Fade the wind color field below ~1,200 km camera height and hide it at 200 km. + On 3D Tiles, update alpha in 0.1 steps only at camera move end or installation; + globe imagery keeps its smooth per-frame fade. + +- Hide cyclone markers, labels, tracks and cones beyond the horizon on every map source. +- Reserve stable weather status space and coalesce panel refreshes per frame. + +- Add keyless NOAA/NHC cyclone advisory positions, coherent forecast tracks and + uncertainty cones, plus NOAA's observed 15-minute lightning density imagery. + Preserve source clocks, basin coverage and explicit pending/stale states. +- Make wind default to trails, preserve earlier share-link appearance, retain + geometry across scalar changes, and show a compact weather summary with a + location marker and selected-field emphasis for forecast inspection. + +- Add keyless NOAA observed rain radar and infrared satellite layers to Weather, + with explicit coverage/freshness, recent observation playback and native Cesium tiles. +- Increase desktop wind density to 7,200 paths and improve temperature contrast + while retaining the 1,200-path narrow-screen budget and unchanged forecast values. + +- Expand Wind into a surface-weather prototype: globe-draped speed shading, + optional same-run 2 m temperature and mean sea-level pressure, GFS/ECMWF model + selection, a numeric legend, wind units, Pause, and a dismissible map-center + reading. Keep wind visible when an optional field is unavailable; respect + reduced motion and stop animation while hidden or disabled. Bake bounded + forecast-following curves once per field and animate their phase on the GPU, + with a canvas fallback and globe view lighting owned only while Wind is enabled. + Display lift does not + change the 10 m forecast level; this adds no cloud volume, radar or forecast-time + playback. Native hardware GPU behavior remains unverified. + +Add feed provenance to analyst/view answers and HUD context while retaining existing response fields and runner ownership (Matt Van Horn, #347). + +Analyst records for loaded satellites, datacenters and dams, with explicit bounded count/rank coverage (Matt Van Horn, #351). + +- Remove the spurious scrollbars that appeared on both panel stacks at narrow + widths (720px and below) as soon as a panel was expanded. The stacks scroll + vertically there, and each panel's decorative glow, absolutely positioned + with a negative inset, became 18–20px of scrollable overflow on both axes: a + horizontal scrollbar band under the expanded CCTV, Context, Data Layers or + Scenes panel plus a vertical scrollbar that scrolled nothing but glow. The + narrow-screen rules now pin the glow to its panel box; the stacks still + scroll for genuinely tall content such as an expanded DISPLAY panel, and the + Context radio popover is not clipped. `src/ui/panelRails.test.mjs` pins the + rule against every 720px media block. + +- Enable responsive trackpad pinch zoom on the globe. Browser pixel-mode + `Ctrl+wheel` pinch gestures now reach Cesium with bounded amplification, + while ordinary wheel, line-mode and touch-pinch inputs retain their existing + behavior; the listener is removed with the application scene. + +- Report AIS speed and course that carry the standard "not available" code as + unknown instead of 102.3 knots and 360 degrees. Genuine readings, including a + stopped vessel's zero and the highest encodable values, are unchanged. + +- Render native `` controls declare a dark colour scheme and explicit option +colours, so the browser-painted option list matches the panel it drops out of. +The scheme is declared on the controls rather than on the document root, so +hand-tuned scrollbar and text-input skins are unchanged. Applies to the HUD +layout, Scenes, CCTV camera, Radio filter and Draw colour menus. + Vessel snapshot completeness is separate from freshness. A current snapshot with rejected or duplicate records shows PARTIAL with accepted/received counts; stale or unknown freshness and transport failures retain their warnings. Partial @@ -111,7 +312,7 @@ Source factories have dedicated `layers//source` exports. ALPR and earth Voice controls bind to a protocol-independent session factory. The default WebRTC adapter preserves the existing Realtime connection, push-to-talk, cost controls and radio handoff. Session subscriptions expose state, transcript, action call/result, interruption and completion events; stopping or replacing a session cancels pending actions. Alternate adapters can use the same controls and action runner. -Voice action argument schemas have one portable owner under `src/voice/actionSchemas.js`. The Realtime provider builds the same 28 tools using separate description-only metadata. Description customization cannot replace argument types, enum values or required fields. +Voice action argument schemas have one portable owner under `src/voice/actionSchemas.js`. The Realtime provider builds 29 tools, retaining the existing 28 names and argument contracts apart from the three additive analyst-layer enum values using separate description-only metadata. Description customization cannot replace argument types, enum values or required fields. Portable source exports provide Radio Browser station normalization, CCTV feed types and regional records independently of HTTP middleware. Radio normalization accepts an explicit URL policy; the standalone directory retains its existing HTTPS rules. Tile coordinate validation accepts explicit zoom bounds with unchanged traffic defaults. Cache, request and rendering owners remain unchanged. @@ -140,7 +341,6 @@ owns disclosure, docking and Cockpit panel snapshots. Each takes explicit operations and reads instead of the complete shell. Existing controls, share formats and one-application-per-page behavior are preserved. - Layer lifecycle transactions are owned by `data/lifecycle`, which has no panel, render-governor or detection imports. Application composition mounts a separate layer presentation owner that reacts to status, accepted visibility/parameter @@ -149,7 +349,6 @@ rendered detection set. The legacy manager retains panel helper compatibility; registration sealing, restoration order and failed-transition rollback remain unchanged. - Application scene setup owns request services, terrain/floor caches and annotation lookup state. Controls, layers and voice share those owners, and cancellation clears caches and removes map-stack listeners. Standalone setup supplies the @@ -158,7 +357,6 @@ framing and annotation boundaries receive their service instances explicitly. Compatibility entrypoints retain defaults for direct callers; normal startup does not change global service slots. Analyst follow-up memory belongs to its voice runner. - Application startup constructs fresh layer instances from explicit source objects. Standalone composition selects the existing providers. Controls, launch orbit lookups, Contacts voice answers and ISS pass queries use the registered catalog. @@ -166,7 +364,6 @@ Aircraft classification is catalog-owned and cancelled with application teardown scene engines still support one application per page. Compatibility data entrypoints remain for direct callers, but normal startup does not configure global sources. - Application data setup receives an ordered layer catalog and serialization metadata. Controls use the same instances. The standalone composition selects the existing default catalog, and restoration starts only after all registrations are sealed. @@ -185,7 +382,6 @@ transports and cancellation through response parsing. Stop and application teardown abort pending connections; reconnect requests a new client secret. Microphone, radio handoff, tool schemas and default model behavior are preserved. - Geospatial lookups are composed through `src/search`: forward/reverse geocoding, text/nearby search and routing use configurable providers/endpoints. Annotation, HUD and voice consumers share the configured service. Existing Google/Photon @@ -193,7 +389,6 @@ selection, route/direct-line honesty and tool schemas are preserved. Node Google, OSRM and Nominatim adapters accept trusted construction-time configuration; request parameters cannot choose arbitrary upstream URLs. See APPLICATION.md. - The optional **ALPR Cameras** layer shows community-mapped OpenStreetMap locations, not camera footage or plate records. City-scale queries use the existing Overpass provider, with capped results, retry, cached-data and incomplete-coverage notices. @@ -297,7 +492,6 @@ Selection changes, disable and destruction cancel pending trail requests; late responses cannot refill a cleared or replacement trail. Heading and course, sea-surface placement, click ownership and card selection policy are unchanged. - ## Military-flight components and aircraft mechanics `gods-eye-view/layers/military` exports `createMilitaryFlightLayer`. It uses the @@ -354,7 +548,6 @@ messages; arbitrary HTTP response bodies are not surfaced as diagnostics. Sources receive cancellation signals and check them after body parsing. The layer's existing lifecycle and selection guards continue to reject late work. - ## State and action outcomes Share preferences, place lookups and Scene playback expose immutable snapshots @@ -403,7 +596,6 @@ retained Cockpit actions cannot restart a disposed controller. Input, subscripti and queued panel work stop before asynchronous layer restoration; final camera and portal cleanup follows that restoration. - ## Context coordination Context controls own Contacts/Space Missions state, entry and exit transactions, @@ -413,7 +605,6 @@ presentation work stop during disposal; layer restoration retains its existing compensation and latest-intent rules. Clear Selected Layers shares this owner, so an older restore cannot replay over a newer Clear action. - ## Camera panel ownership CCTV controls receive the existing camera port and explicit application actions. @@ -424,7 +615,6 @@ calibration edit. Failed refreshes preserve settled pixels for the same camera, while a newly selected camera never shows the prior camera's image. Disposal releases listeners, subscriptions, image handlers, summary timers and chip-hide timers. - ## UI disposal UI disposal releases the CCTV subscription, command-dock observer, legacy drag @@ -466,7 +656,6 @@ and result presentation. Existing search providers and camera handoff policy are preserved. Replacing or closing a POI row cancels its pending expansion frame; destruction releases listeners, pending searches and the orbit indicator. - ## Layer panel ownership Layer rows, feed feedback, counts, focus-preserving chips and toggle listeners @@ -475,7 +664,6 @@ snapshots, lifecycle actions and row descriptors. Remount and teardown remove listeners and row subscriptions; obsolete completions do not repaint old rows. The clear control presents busy state while its existing action owns the transaction. - ## Map Source control ownership Map Source controls own chip listeners, source-state subscriptions and selection @@ -527,7 +715,6 @@ panel, and honors keyboard focus on the right. Mobile layout still releases desktop allocation styles. Stable Display allocation avoids unnecessary style writes. This extraction does not change panel positions or layout defaults. - ## Surface keyboard lifecycle `ui/surfaces` owns the capture-phase keyboard listener, Tab cycling and return @@ -539,7 +726,6 @@ preferences. Provider Settings retains its existing visibility and save policy. Initial focus, transitions and DOM content remain with each screen. This component does not add modal semantics or make the map inert. - ## Panel disclosure lifecycle Panel collapse buttons, nested Escape handling and dock hover/focus timing now @@ -549,7 +735,6 @@ Location draft cleanup and Map Source selection remain with their existing callers. Listener and timer cleanup is synchronous when controls are replaced or disposed, preventing old hover or focus work from changing a later view. - ## Military feed cooldown and loading guidance The adsb.lol military proxy reuses its last response during upstream 429/5xx @@ -563,7 +748,6 @@ Mapped-installation zoom guidance appears in the layer row without counting as a global loading failure. Guidance statuses do not suppress independent refresh errors. - ## Places and CCTV request bounds With a Google key configured, nearby and text search reject missing, blank, @@ -578,16 +762,13 @@ responses are cancelled. Buffered snapshots have a 16 MiB streaming cap; an oversized image remains an upstream miss and uses the normal fallback chain. The existing declared media size ceiling remains 64 MiB. - ## GBFS upstream bounds The station reader addresses the proxy as `/api/gbfs/`; the -feed address is read from the path, and a query-string form is refused with a -400. GBFS refuses upstream redirects and enforces its 5 MiB response cap while +feed address is read from the path, and a query-string form is refused with a 400. GBFS refuses upstream redirects and enforces its 5 MiB response cap while streaming. The 12-second deadline includes reading the body, and rejected or stalled downloads are cancelled. Development and preview use the same handler. - ## Remaining local service modules Overpass query validation, geometry simplification, disk caching and upstream @@ -620,7 +801,6 @@ preview returns JSON 404 for those endpoints. Server credentials come from the local environment; browser keys are captured at build time. Rebuild after changing a browser key. Preview is for local build verification, not a production server. - ## CCTV and radio provider modules CCTV catalog acquisition, source normalization and frame/media delivery now live @@ -714,7 +894,6 @@ supported. `.env.example` and `pinokio/_ENVIRONMENT` document both entries. The Street View headings tool uses the same server-first selection after resolving environment overrides per variable; its explicit `--key` wins. - ## Infrastructure marker visibility Datacenter/dam registration uses fresh reusable factories with the application's @@ -852,7 +1031,6 @@ The existing aircraft normalizer is separately available through the portable `gods-eye-view/sources/adsb-lol` export. Provider URLs, local credentials, cache policy, fallback behavior, response shapes and rendering remain unchanged. - ## Control names for assistive technology Scope, Bloom, Sharpen and location search have explicit accessible names. @@ -947,7 +1125,7 @@ fetching, trailing-24-hour filtering and partial-success caching are unchanged. > durable in this app (`gev:layer-state:v2`, written by > `LayerStateCoordinator._commitExplicit` only for origin `user`/`voice`/`tool`). > A mission enables **its own** layers at `origin: 'user'` — durable, exactly as -> clicking those rows is, because picking the mission *is* that choice. The two +> clicking those rows is, because picking the mission _is_ that choice. The two > Context missions also expand the Context panel, as the visible tabs do; the > globe missions open no panel. Everything else is off limits: detection > mode/density, `gev:detection-allocation:v1`, 3D models, feather, and above all @@ -971,7 +1149,7 @@ fetching, trailing-24-hour filtering and partial-success caching are unchanged. > rule by a unit pin), and session-dismisses rather than contesting the key; if > one is already up at init it **waits** instead of appearing over it. (2) A > surface can take the screen with **no class to watch** — the Cesium attribution -> lightbox is full-screen at `z-index: 200` against the card's `175`, which left +> lightbox is at `z-index: 200` against the card's `175`, which left > the launcher measurable (`getClientRects()` non-empty) and buried, so ESC > dismissed a card nobody could see and burned the session flag. `isTopmost()` > therefore also **hit-tests the card's own centre** with `elementFromPoint`; any @@ -982,7 +1160,7 @@ fetching, trailing-24-hour filtering and partial-success caching are unchanged. > `stopImmediatePropagation()`, and the launcher skips `defaultPrevented` events. > `stopPropagation()` alone does **not** stop later listeners on the same > `document` — that is exactly how the compact Radio disclosure made one key -> close the disclosure *and* dismiss the launcher. +> close the disclosure _and_ dismiss the launcher. > > **Accepted:** a surface class that never clears means no launcher for that page > load, with no timeout. None of the four classes is restored at startup, so an @@ -1038,6 +1216,7 @@ This is the current runtime/source-of-truth snapshot for the project. > [!IMPORTANT] > **Delta since the July-2 body below** (the detailed sections are still accurate > for everything they describe; these landed after): +> > - **"Never answered yet" is a THIRD state, distinct from empty (2026-08-23):** > `sourceState` in `src/data/militaryAwareness.js` treats a dependency that is > busy AND has never produced an answer (`loading === true && !lastUpdate`) as @@ -1060,7 +1239,6 @@ This is the current runtime/source-of-truth snapshot for the project. > samples, `enabling` throughout, panel non-numeric) and across a failing > one. Its `status: 'idle'` is not what saves it — the lifecycle is; the > module has no `loading` status at all. -> > Any new dependency that can be slow must report `loading` and `lastUpdate` > honestly for the contract to hold, and must be pinned against the shape its > own module really returns — a fixture that invents a status the module cannot @@ -1265,7 +1443,7 @@ This is the current runtime/source-of-truth snapshot for the project. > 1,000,000,000 m, plus finite components — not a null check, because a depth > read over empty sky can return a Cartesian that Cesium mishandles three > different ways: non-finite throws `DeveloperError: normalized result is not -> a number`, exactly `(0,0,0)` returns undefined, and a near-center value such +a number`, exactly `(0,0,0)` returns undefined, and a near-center value such > as `(500,0,0)` converts SILENTLY into a point 6,378 km underground that > reverse-geocodes as 0°, 0°. The floor sits ~346 km below the smallest real > surface magnitude (WGS84 polar radius 6,356,752 m); the ceiling is ~24× @@ -1323,17 +1501,17 @@ This is the current runtime/source-of-truth snapshot for the project. > supersession, and run teardown abort it — the data manager rolls an aborted > enable back through the module's own `disable()`, so no layer is left on > carrying stale params. Visuals: `styleManager.applyVisualState(state, { -> isCurrent })` gates BOTH halves of the map-stack switch, which is its only -> suspension point. The switch is a *mutation*, not just a wait, and +isCurrent })` gates BOTH halves of the map-stack switch, which is its only +> suspension point. The switch is a _mutation_, not just a wait, and > `mapStackController` invalidates a switch only when another `setStack()` > arrives — a winning state that omits `mapStack` (every normalized shot does) > never issues one, so a stale switch would otherwise stand on the globe. > So: an already-superseded caller never starts the switch, and one superseded -> *during* it puts the globe back to the stack the winner inherited — but only +> _during_ it puts the globe back to the stack the winner inherited — but only > while `getSwitchGeneration()` shows no newer switch has claimed it, because > a newer switch is a live intent that must not be stomped. The shader-uniform > commit after the await keeps its own gate. Precisely: a stale LOAD's -> *synchronous* prelude (style/bloom/HUD) can still have landed before it was +> _synchronous_ prelude (style/bloom/HUD) can still have landed before it was > superseded, and is then overwritten by the newer state; what cannot survive > is its map stack, its uniform commit, its layers, or its camera flight. > Post-`await` flag checks remain as a backstop. Known remainder: run cleanup @@ -1453,7 +1631,7 @@ This is the current runtime/source-of-truth snapshot for the project. > - **AIS feed watchdog (2026-08-18):** feed liveness is judged by DATA, not > socket state — AISStream can complete the handshake and then deliver > nothing forever. `/api/ais-live` reports `live | stale | reconnecting | -> down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with +down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > `silentForMs`, `reconnectAttempt` and `nextAttemptAt`. Silence is REPORTED > at 120s and ACTED ON at 300s; recovery walks a 5s/15s/60s/300s ladder and > then stops at a terminal `down` with a slow 15-min retry running behind it @@ -1783,7 +1961,7 @@ This is the current runtime/source-of-truth snapshot for the project. > - **Compact data-attribution panel:** the complete Cesium credit inventory > remains available without taking over the viewport. Its expanded desktop > panel is capped at 70dvh/36rem, the wrapped 12px credit list scrolls inside -> it, and narrow screens retain Cesium's full-screen surface with an internal +> it, and narrow screens retain Cesium's surface with an internal > scroller. The title, close control, links, and persistent Google/Cesium line > remain unchanged and visible. > - **Distant-aircraft recession:** both civilian and military billboard fleets @@ -1998,8 +2176,7 @@ This is the current runtime/source-of-truth snapshot for the project. > at `z-index:5`**, not into `#world-overlay-root`: the root is a stacking > context (`z-index:6`), i.e. an isolated blending group, and a surface inside > it has its `mix-blend-mode: screen` silently discarded by the browser -> instead of compositing against the WebGL scene. z-index (5 under the root's -> 6) keeps it beneath ambient-through-tracked host paint. +> instead of compositing against the WebGL scene. z-index (5 under the root's 6) keeps it beneath ambient-through-tracked host paint. > The >22 ms odd-frame relief valve is restored: the host does not clear the > detection surface on a held frame, while unrelated shared lanes repaint, > and `throttleSkipCount` remains a live diagnostic. Detection `data-*` fields @@ -2093,7 +2270,7 @@ This is the current runtime/source-of-truth snapshot for the project. > Identity stays `icao24` on every keyed surface (`getNearby().icao24`, the > detection `sourceId` declutter hashes, and the `id` that `trackById` and the > Context cohorts resolve) — only the displayed string follows the chain. -> Because adsbdb enrichment can answer *after* selection, the Context subject +> Because adsbdb enrichment can answer _after_ selection, the Context subject > re-resolves its label each refresh (`resolveSubjectLabel()`) instead of > freezing the selection-time snapshot. > - **Phase 5 tracked military aircraft label:** The military tracking entity @@ -2211,7 +2388,7 @@ This is the current runtime/source-of-truth snapshot for the project. > active camera is excluded from the 40-card ambient quota and has no host > card by default: its monitor plane is the active representation. The > product option `cctvLayer.setCardPresentationOptions({ -> activeCameraCardEnabled: true })` may publish it through the retained +activeCameraCardEnabled: true })` may publish it through the retained > protected path. CCTV leaders use the source cyan, remain vertical at the > camera anchor except for the off-card edge clamp, and counter-scale to one > CSS pixel through the altitude transform. Card hits come from @@ -2393,7 +2570,7 @@ This is the current runtime/source-of-truth snapshot for the project. > sprites/trails, OpenSky credit governor). The 2026-07-08 CHANGELOG entry > records the subsystem's architecture, invariants, residuals, and verification. > - **Height-datum test surface:** `npm test` 184 unit · `npm run -> test:track` 43 tracking invariants · headless QA harnesses under +test:track` 43 tracking invariants · headless QA harnesses under > `scripts/qa-*.mjs` incl. `qa-height-datum.mjs` (numeric heights) and > `qa-floor-verify.mjs` (any-airport ground-truth oracle). > - **2026-08-19 — display-time ground floor (flights layer).** A grounded @@ -2459,7 +2636,7 @@ This is the current runtime/source-of-truth snapshot for the project. > ISS pass prediction, and per-layer data attribution. Gate at close: unit 98/98, build clean, > track 19/19, + five QA harnesses (heading 16/16, sprites 9/9, cctv 5/5, failstate 5/5, > attribution 18/18). New modules: `src/data/{motionModel,aircraftMeta,aircraftClass,aircraftIcons,issPass,routePlausible,dataCredits}.js`. -> The live runtime now declares 28 voice tools; the 17→20 count above is retained only as milestone history. +> The live runtime now declares 29 voice tools; the 17→20 count above is retained only as milestone history. ## Canonical Docs Order @@ -2496,25 +2673,26 @@ nearby place—always use station selection. Unqualified “turn on/start the ra requests use Play; a qualified Play-shaped tool call is normalized to Select so its criteria cannot be silently ignored. -| Layer | Source | File | Proxy | Update Interval | -|-------|--------|------|-------|-----------------| -| Live Flights ✈️ | OpenSky Network; bounded adsb.lol regional fallback | `src/data/flights.js` | `/api/opensky` (OAuth + fallback) | 30s | -| Military Flights 🎖️ | adsb.lol /v2/mil | `src/data/militaryFlights.js` | `/api/adsblol/mil` | 15s | -| Live AIS Vessels 🚢 | AISStream websocket | `src/data/aisLiveVessels.js` | `/api/ais-live` | 60s (+800ms visibility pass) | -| Mapped Installations ⌖ | OpenStreetMap mapped context; on-demand Google Maps Places supplement | `src/data/militaryInstallations.js` | `/api/military-installations`, `/api/google/text-search` | viewport-driven + user search; while unavailable, auto-retry 30 s → 240 s backoff | -| Earthquakes | USGS | `src/data/earthquakes.js` | — | 60s | -| Satellites | CelesTrak | `src/data/satellites.js` | `/api/celestrak` | 120s | -| Space Missions (30d) | Launch Library 2 + CelesTrak | `src/data/rocketLaunches.js` | `/api/launches` + `/api/celestrak/active` | 5 min | -| Traffic | OSM Overpass (+ optional TomTom live flow) | `src/data/traffic.js` | `/api/overpass` + `/api/tomtom` | viewport-driven | -| CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) | -| Radio | Radio Browser (public-domain station directory) | `src/data/radio.js` | `/api/radio/stations`, `/api/radio/click/:uuid` | 45 min directory refresh | -| Transit 🚌 | Operator GTFS-Realtime VehiclePositions (7 keyless regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) | -| Bikeshare 🚲 | GBFS (Lyft + BCycle) | `src/data/bikeshare.js` | `/api/gbfs` | 60s | -| Directions 🧭 | OSRM on FOSSGIS servers (OpenStreetMap) | `src/data/directions.js` | `/api/route` (`steps=1`) | on placement / mode change | -| Datacenters ▣ | OSM extract (bundled) | `src/data/localLayers.js` | — | static | -| Dams ▰ | OpenInfraMap/OSM extract (bundled) | `src/data/localLayers.js` | — | static | -| Submarine Cables ◠ | TeleGeography public map (bundled) | `src/data/telegeographySubmarineCables.js` | — | static | -| FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×3 NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) | +| Layer | Source | File | Proxy | Update Interval | +| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------------- | +| Live Flights ✈️ | OpenSky Network; bounded adsb.lol regional fallback | `src/data/flights.js` | `/api/opensky` (OAuth + fallback) | 30s | +| Military Flights 🎖️ | adsb.lol /v2/mil | `src/data/militaryFlights.js` | `/api/adsblol/mil` | 15s | +| Live AIS Vessels 🚢 | AISStream websocket | `src/data/aisLiveVessels.js` | `/api/ais-live` | 60s (+800ms visibility pass) | +| Mapped Installations ⌖ | OpenStreetMap mapped context; on-demand Google Maps Places supplement | `src/data/militaryInstallations.js` | `/api/military-installations`, `/api/google/text-search` | viewport-driven + user search; while unavailable, auto-retry 30 s → 240 s backoff | +| Earthquakes | USGS | `src/data/earthquakes.js` | — | 60s | +| Satellites | CelesTrak | `src/data/satellites.js` | `/api/celestrak` | 120s | +| Space Missions (30d) | Launch Library 2 + CelesTrak | `src/data/rocketLaunches.js` | `/api/launches` + `/api/celestrak/active` | 5 min | +| Traffic | OSM Overpass (+ optional TomTom live flow) | `src/data/traffic.js` | `/api/overpass` + `/api/tomtom` | viewport-driven | +| CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) | +| Radio | Radio Browser (public-domain station directory) | `src/data/radio.js` | `/api/radio/stations`, `/api/radio/click/:uuid` | 45 min directory refresh | +| Transit 🚌 | Operator GTFS-Realtime VehiclePositions (7 keyless regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) | +| Bikeshare 🚲 | GBFS (Lyft + BCycle) | `src/data/bikeshare.js` | `/api/gbfs` | 60s | +| Directions 🧭 | OSRM on FOSSGIS servers (OpenStreetMap) | `src/data/directions.js` | `/api/route` (`steps=1`) | on placement / mode change | +| Datacenters ▣ | OSM extract (bundled) | `src/data/localLayers.js` | — | static | +| Dams ▰ | OpenInfraMap/OSM extract (bundled) | `src/data/localLayers.js` | — | static | +| Submarine Cables ◠ | TeleGeography public map (bundled) | `src/data/telegeographySubmarineCables.js` | — | static | +| FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×3 NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) | +| Wind 🌬 | NOAA GFS 10 m wind (keyless, 0.25°→1° grid; animated particles) | `src/data/wind.js` | `/api/wind` | 1 h (forecast cycle) | Directions is a keyless front end to the routing the voice agent already uses. Its row chips are the whole interface: DRIVE / WALK / BIKE pick the @@ -2570,7 +2748,7 @@ tool holds the pointer. FLY runs through the UI shell's immediate-navigation facade — the same camera authority validated voice destinations use — and is handed the shared ground-floor read and corridor warm, so the dolly does not fly a mountain corridor at sea level. A reroute (SWAP, or a profile change), -CLEAR, disable and destroy stop the flight *this layer started* and only that +CLEAR, disable and destroy stop the flight _this layer started_ and only that one: `flyRoute` returns a motion id and `interruptCameraMotionIfActive` refuses to stop a motion someone else began. @@ -3147,7 +3325,7 @@ silently demoting every later lookup for the session. COVERAGE ON enable creates the active/visible 14-camera cohort, and activation always creates the selected frustum even with COVERAGE OFF. **Field validation passed 2026-07-04** (core look + downtown no-clip confirmed); that round fixed three findings: the - ground clamp now lifts the cap *center* only so the wireframe stays a true pyramid welded to + ground clamp now lifts the cap _center_ only so the wireframe stays a true pyramid welded to the plane (was a flattened fan / the ~47.5 m divergence — RESOLVED), re-selecting the active camera is a no-op (killed a click-flash), and texture swaps gate on canvas content (killed a periodic white flash). Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES` @@ -3159,7 +3337,7 @@ silently demoting every later lookup for the session. poses, and the layer is stills-first. sources. Fintraffic Finland road weather cameras (2026-09-13; cap 300, `CCTV_FINTRAFFIC_MAX_SOURCES`, kill switch `CCTV_FINTRAFFIC_ENABLED=0`) are the fourth pack: one keyless GeoJSON station list - covering the whole country, where one *preset* (a station's fixed view) is one camera — 806 + covering the whole country, where one _preset_ (a station's fixed view) is one camera — 806 GATHERING stations carry 2,256 in-collection presets, prioritized to 300 against seven anchors on the main road spine. `CCTV_MAX_SOURCES` is a 4,000 catalog-wide ceiling shared round-robin across packs, so a lower global cap thins every region instead of starving the last pack. @@ -3212,7 +3390,7 @@ silently demoting every later lookup for the session. `activeCameraCardEnabled` presentation option can publish the retained protected-card path. Disable tears the tier down completely. Coverage/viewshed semantics unchanged. -- **Satellites**: orbit rings rotate about Earth's Z by ΔGMST every ~1s (exact inertial→ECEF compensation; no SGP4 re-runs); the tracked satellite propagates per frame with one shared epoch for dot/label/camera. Verified: ISS holds <1km perpendicular to its ring while tracked. +- **Satellites**: orbit rings rotate about Earth's Z by ΔGMST every ~1s (exact inertial→ECEF compensation; no SGP4 re-runs); the tracked satellite propagates per frame with one shared epoch for dot/label/camera. Verified: ISS holds <1km perpendicular to its ring while tracked. Pass prediction (`src/data/satellitePass.js`; `getNextSatellitePass`, `getNextIssPass`) scans at 20s, bisects rise/set to ~0.2s, fits the peak with a parabola, and marks a pass visible when the satellite is outside a cylindrical Earth shadow while the observer's Sun is at or below −6°. `next_iss_pass` preserves its geometric-pass ordering and appends visibility metadata. General `next_satellite_pass` accepts a loaded NORAD ID or unambiguous name, searches 24 hours and optionally requires estimated visibility. These estimates do not account for weather or satellite brightness. - **Space Missions (30d)**: recent launches render as bounded shared-host, horizon-occluded mission markers using Launch Library 2 v2.3 detailed records. Enabling the layer selects the unified right-side Context panel's Space Missions mode and enables the required satellite layer. Before applying its temporary dense/hidden Satellite mode, Space Missions snapshots the complete standalone Satellite parameter set and exact enabled-layer set. Disabling Space Missions from either Context or the left Data Layers rail restores those parameters and the exact prior enabled state, so a Satellite layer that was already on stays on while a mode-owned dependency returns off; enabling Satellites by itself remains independent. Selecting a mission isolates its launch-to-orbit transfer and dashed satellite orbit, fills that same panel with navigation/details, and animates a small phase-colored marker along the exact displayed Cartesian samples. Marker hit testing drill-picks through photorealistic tiles so the depth-test-free tactical dot remains reliably selectable; its text is non-interactive shared-host presentation. The selected pad is the camera's zoom pivot: the overview remains centered on its launch site, wheel zoom approaches that site instead of drifting elsewhere, and camera pitch progressively changes from global nadir to an oblique close 3D view. Its protected shared-host callout remains visible and expands to include both mission and launch-site names. `FOCUS` flies directly to a 12 km oblique frame around the selected launch site and retains the same anchored zoom/orbit behavior. `REPLAY ASCENT` resets the selected marker at the pad, frames it from an oblique third-person angle, and follows it through the mission-specific compressed ascent directly into one orbital lap at the default `1×` rate. A live `0.25×`–`4×` slider changes ascent and orbit playback speed; adjusting it mid-replay preserves the current path position and historical mission timestamp. Re-entry/recovery cannot be inserted into replay. At orbit insertion the camera smoothly pulls back over the first fifth of the orbital replay and pitches to a globe-scale nadir view while continuing to target the moving replay point. Replay Cancel, mission navigation, deselection, layer disable, and data refresh all release camera ownership. Reconstructed paths are one continuous 128-sample geodetic curve: horizontal departure begins near zero while altitude rises quickly, then the climb progressively bends toward insertion without the former hard 120 km corner. Unmatched orbit fallbacks are smooth planar inclined rings rather than longitude/latitude ground-track curves. The panel lists disclosed payload names, types, operators/manufacturers, mass, multiplicity, and destination when supplied; an empty LL2 payload collection is shown as `CLASSIFIED / MULTI-PAYLOAD`. Launcher, spacecraft, and recoverable payload stages appear in a compact stage table with serial/flight/reuse details, recovery outcome/type, destination, and final coordinates when those records exist; an empty recovery collection omits the section. Stage recoveries with confirmed coordinates use those coordinates; return-to-launch-site records use the pad; downrange-only records receive an explicitly labeled estimated endpoint along the ascent azimuth. Available endpoints render as static 2 px dashed descent/recovery paths with a fixed final-position dot and an estimated atmospheric-interface segment when applicable. The ascent is geodetically densified above the ellipsoid toward the orbit's nearest insertion point, then rendered with `ArcType.NONE`, so it neither cuts through Earth nor separates from the marker. Because LL2 does not normally supply continuous ascent telemetry, pad-to-insertion paths without upstream trajectory samples are labeled `RECONSTRUCTED ESTIMATE` / `ASCENT ESTIMATE`; only supplied trajectory samples receive the replay wording. Selected-orbit framing fits the complete ring, rear-side linework uses normal scene depth occlusion, and current distance, speed, and callout data come only from a launch-year-validated satellite match. Speed is the magnitude of the SGP4 inertial velocity vector at the same propagation epoch as position, displayed in km/s with km/h available as hover detail. Unavailable operator, site, launch-time, orbit, current-altitude, and speed values omit their detail rows instead of reserving panel space with placeholders. Newly launched payloads absent from the core operational groups use CelesTrak's cached active TLE feed as a lookup-only fallback; weak constellation-name matches are rejected. The replay callout maps compressed animation progress onto Launch Library's mission-relative timeline, showing the historical UTC date/time at the marker's current path position; unavailable timelines remain explicit. Matched live satellite positions propagate at one-second cadence and use a distinct green dot/callout with the current UTC date/time. When no mission is selected, the Context panel presents a scrollable newest-first roster of every launch in the rolling window, including the smaller 5 px operator-colored marker, provider, and launch date. Hovering or keyboard-focusing a row shows four compact cyan corner brackets on both that roster row and its corresponding globe dot, rotates the globe at the current zoom to center it, and gives its label declutter priority without selecting it; the globe label remains unbracketed. Selecting a roster row invokes the same mission isolation and full-orbit framing as clicking its globe marker. The replay vehicle is one screen-space SVG/CSS HUD overlay rather than separate Cesium billboard, label, and reticle graphics. It is hidden during ordinary Focus and manual close views, where the standard selected launch-site label remains visible, and exists only while ascent replay is active. Its fixed pixel scale is shared by ascent and insertion, so camera range never resizes the rocket on screen before the phase boundary. Generic Launch Library pad names are reduced to their identifying suffix, and replay timestamps use a cyan state title over unprefixed white UTC date/time values. `REPLAY ASCENT` holds the unframed cyan/white rocket at the pad for a real-time `T−10` countdown, transitions through `LIFTOFF`, and attaches six tapered cyan/white ellipse waves directly below it from liftoff through insertion to convey thrust without adding scene geometry. While replay is active, the single start button is replaced by compact Play, Pause, and Cancel icon controls. Pause freezes countdown or mission time, vehicle/stage positions, camera target, labels, and thrust-wave animation; Play resumes from that exact frame, and Cancel releases replay camera ownership. The rocket and thrust group rotates from the path's live screen-space tangent, so its nose follows the visible ascent curve while the adjacent text remains upright. The camera begins as a close oblique launch chase, then smoothly widens between roughly 120 and 420 km vehicle altitude into a higher oblique context view that keeps the moving rocket targeted while exposing the ascent bend and orbit connection. At insertion the rocket/thrust glyph is replaced by the fixed-size cyan orbit dot, which the camera follows through the existing globe-scale orbit pullback. The chase camera limits per-frame yaw changes across heading wraps so it cannot abruptly cross in front of the vehicle and make ascent read in reverse; the replay-speed slider affects mission playback but not countdown duration. Mission world text has no native `LabelGraphics`: overview launch markers publish at most 48 ambient candidates for a 24-winner budget, while selecting a mission clears that overview source and publishes its launch-site callout, stage re-entry annotations, live/estimated payload-position readout, and orbit annotation as protected selected-lane entries. The source retains the exact former strings and colors. Static anchors reuse the Cartesian values used to build their mission geometry; the moving payload entry reads the layer's per-frame live-position cache; catalog-backed orbit annotation positions are cached in the same one-second matrix update that realigns the orbit primitive. Keyhole edge fade, horizon culling, final collision placement, and UI exclusion are owned by the shared host. Deselect restores the bounded overview, and refresh, disable, and destroy replace or clear both mission sources. @@ -3347,7 +3525,8 @@ silently demoting every later lookup for the session. - **Token flow**: browser fetches a short-lived client secret from `/api/realtime/token`; the Vite middleware holds `OPENAI_API_KEY` and posts the full session config (instructions, tool schemas, VAD, truncation) to `api.openai.com/v1/realtime/client_secrets`. SDP exchange goes directly to `api.openai.com/v1/realtime/calls` with the ephemeral token. - **Session defaults** (env-tunable): model `gpt-realtime-2` (or `gpt-realtime-2.1-mini` when the MINI tier is selected — see the model-tier entry below), voice `marin`, reasoning effort `low`, semantic VAD with low eagerness, no response interruption, context window truncated to ~3,000 post-instruction tokens with 0.5 retention ratio — the conversational window stays short because map state is fetched live per turn. -- **Twenty-eight tools** (schemas defined server-side in `vite.config.js`, executed client-side in `src/voice/gevActions.js`): `fly_to_location`, `select_nearest_aircraft`, `adjust_camera_zoom`, `zoom_to_globe`, `set_layer_visibility`, `show_data_layers_menu`, `set_panel_open`, `set_visual_style`, `get_entity_context`, `get_current_view_state`, `set_hud`, `set_detection`, `set_map_stack`, `set_post_processing`, `control_scene`, `control_cctv`, `set_context_mode`, `control_cockpit`, `control_radio`, `track_entity`, `stop_tracking`, `frame_overhead`, `annotate_map`, `clear_annotations`, `move_camera`, `fly_route`, `analyst_query`, and `next_iss_pass`. +- **Twenty-nine tools** (argument schemas in `src/voice/actionSchemas.js`, served with their descriptions by `server/providers/openai/tools.js`, executed client-side in `src/voice/gevActions.js`): `fly_to_location`, `select_nearest_aircraft`, `adjust_camera_zoom`, `zoom_to_globe`, `set_layer_visibility`, `show_data_layers_menu`, `set_panel_open`, `set_visual_style`, `get_entity_context`, `get_current_view_state`, `set_hud`, `set_detection`, `set_map_stack`, `set_post_processing`, `control_scene`, `control_cctv`, `set_context_mode`, `control_cockpit`, `control_radio`, `track_entity`, `stop_tracking`, `frame_overhead`, `annotate_map`, `clear_annotations`, `move_camera`, `fly_route`, `analyst_query`, `next_iss_pass`, and `next_satellite_pass`. + > **Reading `npm test` totals:** the count depends on the Node major. The two > GC-bracketed allocation microbenchmarks (`src/data/focusAllocations.test.mjs` > = 1 test, `src/overlays/worldOverlayAllocation.test.mjs` = 13) only RUN on the @@ -3377,15 +3556,15 @@ silently demoting every later lookup for the session. - **Tier selection.** `standard` = `gpt-realtime-2` (default), `mini` = `gpt-realtime-2.1-mini` (~3× cheaper per audio token). The client sends `?tier=` to `/api/realtime/token`; the endpoint resolves it through the shared registry, so an unknown, empty, or hostile value falls back to `standard` rather than reaching OpenAI as a model id. Responses echo `X-GEV-Voice-Tier` / `X-GEV-Voice-Model` (plus `X-GEV-Voice-Tier-Fallback: 1` when a bogus tier was downgraded). Persisted at `godsEyeView.voiceCost.tier`. - **Applies NEXT session.** The model is fixed when the ephemeral token is minted, so a live session always keeps the model it connected with; toggling mid-session only records the preference (the button title says so). The cost tracker's lifetime is the session's lifetime and its model binding is immutable from `start()` to `stop()` — rebuilding it on toggle would erase accrued spend and let repeated toggles bypass the cap. The tracker may only be replaced once the session is FULLY SETTLED (`isVoiceSessionSettled()`: not active **and** no data channel **and** no peer connection) — `!isActive()` alone is not enough, because the `error` status reports inactive while the transport can still deliver a late `response.done`. The toggle itself reads and writes only the persisted preference, never the live tracker. - **Env overrides.** `OPENAI_REALTIME_MODEL` / `OPENAI_REALTIME_MODEL_MINI` remain authoritative per tier, so a drifted upstream model id is a `.env` fix rather than a code change. Because an override can point a tier at any model, the client prices against the model id the server actually echoed, **not** the tier it requested. An unrecognised id is billed at the most expensive known rates plus one console warning — under-metering is what lets a cap be overrun. - - **Metering.** Token usage from each `response.done` is folded into a per-session estimate. Cached tokens are subtracted from their modality totals; any aggregate-minus-details residual (and any payload with no detail at all) is attributed to audio rates, so uncertainty always resolves *upward*. + - **Metering.** Token usage from each `response.done` is folded into a per-session estimate. Cached tokens are subtracted from their modality totals; any aggregate-minus-details residual (and any payload with no detail at all) is attributed to audio rates, so uncertainty always resolves _upward_. - **Thresholds** (one object, persisted at `godsEyeView.voiceCost.limits`): soft warning at **$2** — amber readout plus exactly one console line; hard cap at **$5** — the session ends through the ordinary stop path (data channel and peer connection closed, mic tracks stopped) and the readout reads `Session ended — cost cap`. `0`/negative disables a threshold and round-trips through storage as an `'off'` sentinel (raw `Infinity` would JSON-serialize to `null` and silently restore the default); a corrupt entry falls back to the defaults rather than disarming the cap. - - **Cap semantics — in-flight tools COMPLETE and are NOT rolled back.** A session-ending latch (`isSessionEnding()`) is checked at the tool-dispatch site, so no *new* tool is dispatched once the cap trips. `extractFunctionCalls` yields at most one call per event, so that single check covers the whole batch. A tool already executing may still finish its map mutation (a camera flight, a layer toggle, an annotation). This is deliberate: unwinding a partially applied map change has no safe general implementation, and a half-reverted camera/layer/annotation state is worse than a completed one. + - **Cap semantics — in-flight tools COMPLETE and are NOT rolled back.** A session-ending latch (`isSessionEnding()`) is checked at the tool-dispatch site, so no _new_ tool is dispatched once the cap trips. `extractFunctionCalls` yields at most one call per event, so that single check covers the whole batch. A tool already executing may still finish its map mutation (a camera flight, a layer toggle, an annotation). This is deliberate: unwinding a partially applied map change has no safe general implementation, and a half-reverted camera/layer/annotation state is worse than a completed one. - **In-flight response at teardown → the accounting is INCOMPLETE.** Usage only arrives with `response.done`, which never comes for a response cut off by teardown (`stop()` closes the peer connection, and the server cancels rather than completes it). Rather than invent a token count for it, the tracker is marked `incomplete`: the chip shows a trailing `*` (`~$1.00*`) as a see-note mark and the tooltip carries the reason. Deliberately **not** presented as a lower bound — the estimate can also run high (residuals and unrecognised models bill at worst-case rates, and sub-cent totals round up), so it is partial rather than directional. (A bounded teardown drain was tried and removed: `pc.close()` closes the data channels a drain would listen on, so it was structurally dead.) - **⚠️ Model ids and rates are external facts** read from OpenAI's model + pricing pages on 2026-08-18 and marked VERIFY-AT-RELEASE in `voiceCost.js`. - **Reliability**: tool-call dedupe (2.5s window across call/item/args keys); response-create queueing that respects active responses and defers follow-ups when the user starts speaking; per-tool follow-up instructions so the agent confirms only what actually happened (zoom confirms only on `ok=true`). - **Aircraft identity honesty:** “What is this aircraft?” reads callsign, operator, registration, type, and route only from the selected contact context. Missing operator, route, or type enrichment is named explicitly rather than silently omitted or inferred from the callsign. - **Diagnostics**: every client/server event is posted to `/api/realtime/debug-log` and appended to `.gev-logs/realtime-conversations.jsonl` (gitignored) with secret/image redaction; last 30 errors persist in `localStorage` (`gev-realtime-errors`); `window.__gevVoiceCommands.getDiagnostics()` in the console. -- **Counting semantics ("near")** — a CONTRACT; new count-bearing tool work inherits it. Three honest numbers exist for one question: the Contacts cohort (250 km around the subject, what the panel shows), `analyst_query`'s count of *currently-loaded* records for the requested scope, and the layer-wide loaded total in `coverage.layersQueried[].records`. They diverge legitimately — the flights layer loads by viewport, so after a camera dive the loaded set can hold a fraction of the cohort (field case: panel 42, analyst 8). The contract: +- **Counting semantics ("near")** — a CONTRACT; new count-bearing tool work inherits it. Three honest numbers exist for one question: the Contacts cohort (250 km around the subject, what the panel shows), `analyst_query`'s count of _currently-loaded_ records for the requested scope, and the layer-wide loaded total in `coverage.layersQueried[].records`. They diverge legitimately — the flights layer loads by viewport, so after a camera dive the loaded set can hold a fraction of the cohort (field case: panel 42, analyst 8). The contract: 1. **Contacts ACTIVE** → "near / nearby / how many aircraft" means the **Contacts window** — the panel's numbers, spoken verbatim. Mechanism: `contactsWindow` (`{centeredOn, radiusKm, flights, military, vessels}`), carried by both `analyst_query` and `get_current_view_state`, derived by `contactsWindowFromSnapshot()` from the same snapshot the panel renders so the two cannot drift. A cohort whose feed cannot answer reports `'unknown'`, never a confident zero. 2. **Contacts OFF** → "nearby" means **in view**; "near \" means a radius around that place. A radius query with Contacts active and no explicit centre is centred on the **active contact**, not the camera. 3. **Every count names its scope in words** — "42 in your window", "8 in view", "about 30 within 250 km of Austin" — never a bare number. `analyst_query` returns `scopeLabel` so this is mechanical. Two different numbers with named scopes are not a contradiction. @@ -3476,6 +3655,18 @@ are omitted rather than framing the wrong part of the globe. - Pure half: `src/annotations/drawMode.js` (session, minimum vertices, double-click de-dup at 0.5 m, vertex ceiling, degenerate-geometry refusal, ring closing, dateline-safe length/area/centroid, hint text). Regression surface: `src/annotations/drawMode.test.mjs` and `src/data/inputOwnership.test.mjs` (pure), `src/annotations/drawToolBehaviour.test.mjs` (the tool driven against DOM and viewer doubles — leases, borrowed input actions, teardown, the Enter key, preview heights), `src/annotations/drawTool.test.mjs` (structural: where files live, which ids the markup carries, what the docs may claim), and the rendered harness `scripts/qa-draw-tool.mjs`. - The annotation tree is a declared ownership group: `./annotations` → `src/annotations/index.js` in `package.json`, with its module graph listed in `scripts/package-boundaries.json`, so an annotation module reaching outside that graph is a gate failure rather than a surprise in a layer's bundle. `drawMode.js`, `drawTool.js` and their tests are in `scripts/format-scope.json`. +### Recent Imagery (September 2026) + +- The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room. +- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. +- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. +- **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. +- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. +- **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape. +- **Panel.** `#recent-imagery-panel` is static rail markup in `src/ui/templates/context.html` beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`. +- **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off). +- Regression surface: the colocated `*.test.mjs` beside each module (shared doubles in `src/layers/recentImagery/testDoubles.mjs`; `src/ui/recentImagery.test.mjs` includes a DOM-structure guard: every control keeps its place in the tree, nothing is hidden, and every fixed-height block keeps the class the stylesheet fixes its height by; it has no layout, so it cannot see movement), `src/ui/layerPanel.test.mjs` (mount), `src/maps/controller.test.mjs` (`subscribe`), `src/data/layerState.test.mjs` (codec), `src/sharelink.celestial.test.mjs` (panel token), and the live gate `scripts/qa-recent-imagery.mjs`, which also measures every control's rect across the transitions within 1 px; that measurement is the real layout-shift check. + ### 3D Aircraft + Tracking (June 2026) - **The TRACKED contact's 2D↔3D handoff is DEFAULT behaviour (2026-08-19), driven by camera distance alone.** It does NOT consult the DISPLAY-rail `3D` toggle, which continues to own the FLEET (the un-instanced draw-call budget stays the operator's decision). Policy lives in `src/data/trackedModelRegime.js` and is shared by both layers: enter below `TRACKED_MODEL_ENTER_ALT_M` = 150,000 m and hand back to the billboard only above `TRACKED_MODEL_EXIT_ALT_M` = 172,500 m. **The swap distance was set by playtesting on 2026-08-20:** a first pass at 1,000,000 m switched too early; 2D reads correctly at ~600 km and the handoff belongs at ~150 km. **Consequence, recorded on purpose:** the tracked contact now enters 3D NEARER than the FLEET does (`MODEL_ALT_CEIL_M` = 800,000 m, unchanged), so with the DISPLAY-rail `3D` toggle on, 150–800 km draws surrounding contacts as models while the selected one is still a glyph. Nothing double-draws (the fleet pass skips the tracked icao) and aligning the two is a fleet-side decision, deliberately out of scope. **The two thresholds are asymmetric on purpose:** a single threshold makes a tracked orbit sitting ON the boundary strobe billboard↔model as the camera's altitude wobbles across it. Do not collapse them. The latch is scoped per selection, so a new target re-evaluates against the ENTER ceiling rather than inheriting the previous target's exit band. Exactly ONE model is involved; it loads on demand when the regime opens, is HIDDEN (not released) on regime exit so re-entry has no load gap, and is released by the existing teardown on deselect/re-track/destroy. Cockpit and TR-3B suppression are unchanged. **Two invariants around it:** (a) the hysteresis latch AND the load-failure latch are per-selection state cleared by `_resetTrackedSelectionState()` in the tracking lifecycle (deselect / re-track / cross-layer / init / destroy) — the predicate's icao-change guard is defence only, since it needs a drawn frame while nothing is selected and the render governor's idle mode does not promise one; (b) on-demand loading is bounded at 3 attempts per selection with a 1.5 s backoff and one console warning naming the asset — the driver runs every `scene.preUpdate`, so an unbounded catch means a missing GLB spins load→reject at frame rate. The billboard stays the visual throughout a failed load. @@ -3543,6 +3734,7 @@ are omitted rather than framing the wrong part of the globe. - Build gate: `npm run build` - Network access: local-only by default (`HOST=localhost` in dev-fresh.sh); LAN is an explicit opt-in via `HOST=0.0.0.0` (launcher prints a key-exposure warning + LAN URL; see SECURITY.md) - OpenSky default mode: OAuth (`OPENSKY_AUTH_MODE=oauth`; `anon` works without credentials) +- Setup doctor resolves `OPENSKY_AUTH_MODE` from the environment and dotenv files. Explicit `anon` and OAuth mode without a client pair report keyless anonymous access (rate-limited); a complete OAuth pair retains the existing presence-only capability wording. Basic and auto modes report the selected mode without guessing which credentials runtime will accept. The proxy's auth behavior is unchanged. - Google key expected in Keychain service `google-maps-api` (or `GOOGLE_MAPS_API_KEY`, or `.env`) - OpenSky credentials expected in Keychain service `opensky-network` (or env, or `.env`); `OPENSKY_AUTH_MODE` and `OPENSKY_CREDENTIALS_FILE` read from `.env` too - Optional-key precedence in `dev-fresh.sh` is uniform — explicit shell env, then `.env`, then Keychain: `OPENAI_API_KEY` (Keychain `openai-api`/`api-key` — voice + HUD summary), `AISSTREAM_API_KEY` (`aisstream-api`/`api-key` — live vessels), `CESIUM_ION_TOKEN` (`cesium-ion`/`token` — Bing stacks), `TOMTOM_API_KEY` (`tomtom-api`/`api-key` — live traffic flow), `FIRMS_MAP_KEY` (`firms-map`/`map-key` — live fires), `LL2_API_TOKEN` (`.env` only) @@ -3558,6 +3750,7 @@ are omitted rather than framing the wrong part of the globe. - A cold OpenSky failure uses the current camera subpoint only to request a cached adsb.lol point fallback capped at 250 nm. A fresh OpenSky response or last-good cache wins; a nominally successful worldwide snapshot more than two minutes old prefers viewport-scoped adsb.lol when available, otherwise the stale source is reported honestly. The fallback is visibly source-labeled and is never presented as a worldwide snapshot. - GBFS proxy refuses upstream redirects (`redirect: 'manual'`; any 3xx becomes a 502 and the redirect target is logged server-side only) and enforces its 5 MB response cap while the body streams, cancelling the upstream read past the cap; CCTV health map is bounded. - Proxy error payloads are sanitized (no internal error details returned to clients). +- That holds for the OpenAI and CCTV media paths too: `/api/openai/hud-summary` never relays OpenAI's own `error.message`, `/api/realtime/token` passes successful ephemeral-token responses through but answers with a fixed error when minting fails or upstream rejects the request, and a failed CCTV media fetch stores a fixed camera health `message` — `GET /api/cctv/health` serializes that field and the CCTV panel renders it as a status label, so it is a client surface as much as the response body is. - `OPENAI_API_KEY` is server-side only; the browser receives ephemeral Realtime client secrets from `/api/realtime/token`. - `AISSTREAM_API_KEY` is server-side only; the browser reads the same-origin `/api/ais-live` cache. - `/api/google/nearby-places` keeps the Google key out of Places requests issued for voice scene context. @@ -3567,9 +3760,14 @@ are omitted rather than framing the wrong part of the globe. - `/api/route` proxies bounded OSRM route requests for annotation routes, with profile allowlisting, distance caps, response caps, caching, and sanitized "no route found" errors. - Track endpoints: `/api/ais-live/track?mmsi=` (server-accumulated ring buffers; sub-route handled before the rows snapshot), `/api/opensky-track?icao24=` (OAuth, 60s cache, sanitized errors, independent OpenSky credit bucket), `/api/adsblol/trace?hex=` (60s cache, 5MB cap, ODbL attribution required in UI). - Realtime debug logs redact API keys, bearer tokens, client secrets, and image data URLs before writing to disk; request bodies are size-capped. +- `/api/realtime/debug-log` enforces an always-on 120-per-client/400-global one-minute limiter (not the opt-in `GEV_RATELIMIT_OPENAI_PER_MIN` bucket the cost-bearing OpenAI routes share), appends asynchronously through a serialized queue, and rotates `realtime-conversations.jsonl` at 32 MB keeping one prior generation, so the sink is bounded at twice that regardless of session length. A malformed record answers 400 and a failed write 500, both with a fixed message. ## UI/UX Runtime Defaults +- Trackpad pinch zoom is registered as Cesium's `Ctrl+wheel` camera input. + Pixel-mode pinch deltas receive bounded amplification before reaching the + canvas; ordinary wheel, line/page-mode and native touch-pinch paths are left + unchanged. The application scene owns and removes the relay listener. - Z ladder: panels promote within 100–139 (renormalized on wrap), voice pill 150, toast 200, clean-view exit 300. - Panel POSITION keys are versioned `v8` (`godsEyeView.v8.panelPos.`); collapsed-state keys remain `v6`. The one-time position reset clears stale DISPLAY placements that could overlap the Context rail. - Map Source lives in the bottom Visual Presets tray. The left accordion contains no MAP STACK panel, and the `k` panel token that addressed it is gone from the share registry, so legacy `ui=k...` state takes the ordinary unknown-token skip. @@ -3578,6 +3776,7 @@ are omitted rather than framing the wrong part of the globe. - The desktop right rail (`#right-context-rail`) owns `DISPLAY`, `CCTV`, its active parameter controls, and `GLOBAL CONTEXT` as one fixed responsive stack in that order. Its compact buttons use the same 176 px width as the left accordion and one consistent 50 px height, share the left stack's 52 px edge inset and measured top baseline across HUD variants, then constrain themselves against visible HUD/chrome rectangles and the remaining vertical corridor. `DISPLAY` is no longer draggable and legacy saved coordinates are ignored. - The right rail is labeled **DISPLAY** (formerly "MOVE") and groups, in order, HUD, DETECT, Bloom, Sharpen, 3D, Clean-UI (HUD + DETECT promoted to the top). Its expanded controls retain the same compact 176 px width as the right-side tabs instead of growing to the wider Context detail-card width. It starts expanded on first run and respects the user's later `v6` collapse choice. Collapses/expands with directional chevrons (`◀` collapsed, `▶` expanded). - Display and Context use matching 330 px expanded widths and matching compact tab dimensions. The parameter panel is part of Display's expanded content. DISPLAY may remain open beside one contextual panel; CCTV and Context are mutually exclusive. In Tactical HUD, expanding CCTV or Context hides the other contextual launcher while DISPLAY remains independently available. The most recently opened right-rail panel owns the constrained lane even when it appears later in DOM order; passive restoration and automatic disclosure do not replace that explicit owner. Minimal and other HUD layouts retain the collapsed launchers; when their active panel exceeds the measured corridor, the rail reserves sibling heights and gaps and scrolls the active panel internally. +- At 720px and below both panel stacks (`#left-panel-stack`, `#right-context-rail`) go edge-to-edge and scroll vertically. Every hosted panel's decorative `.panel-glow` is pinned to its panel box there (`inset: 0` in `src/ui/styles/responsive.css`): on desktop the glow overhangs the panel by 18–20 px as harmless paint, but inside a scroll container that overhang is scrollable overflow on both axes and drew a horizontal scrollbar band plus a vertical scrollbar that scrolled nothing but glow whenever CCTV, Context, Data Layers or Scenes was expanded. The glow's blur is ink overflow and never scrolls, so the look is unchanged. Do not fix this by clipping the stacks: `overflow-x: clip` would also clip the Context radio popover and would not remove the vertical scrollbar. Pinned by `src/ui/panelRails.test.mjs` against every `(max-width: 720px)` block in the flattened stylesheet. - `STYLE PRESETS` and `LOCATIONS` start collapsed, expand on intentional hover/click, and auto-collapse after hover leave delay. - Collapsed mini-status indicators show active style and active location/landmark. - Detection mode is user-controlled and should persist when switching styles. Since 2026-08-22 it also STARTS on — Dense @ 75% for every style on a first run, Normal included — as a `GLOBAL_POST_DEFAULTS` baseline that does NOT set `_detectionUserOverridden`. Exception (unchanged): selecting a military style (CRT/NVG/FLIR) auto-enables the same Dense preset, but only until the user manually changes detection this session (`_detectionUserOverridden` gate), after which style switches never touch it. @@ -3652,7 +3851,7 @@ are omitted rather than framing the wrong part of the globe. - **Aircraft course slew:** civilian and military 3D models retain the 60°/s course limiter, but each rendered frame can consume at most 250 ms of accumulated slew time. A long tile/render stall therefore catches up over multiple visible frames instead of turning one delayed frame into a heading snap. - **Manual-first cockpit briefing:** the right-side Live Signals / Regional News / Local Info carousel does not advance automatically on page load. Previous, Next, and direct page controls remain available; the visible `CYCLE OFF` / `CYCLE ON` toggle explicitly starts or stops the nine-second page cycle, which still pauses on hover/focus and while collapsed, hidden, or outside cockpit mode. Live signal data continues refreshing in either state. - **Photoreal horizon blend:** Cesium's sky atmosphere remains enabled behind the hidden base globe, but its light intensity, saturation, and brightness are reduced from the library defaults so the distant Google Photorealistic 3D Tiles boundary blends into the sky instead of producing a bright cyan horizon seam. - - **Cockpit direction and speed tapes:** plausible destination metadata now drives one translucent, isometric visor chevron labeled directly below with the estimated geographic bearing; the prior full geodesic dashed path is not rendered. A mirrored live ground-speed tape follows the inside-left keyhole rim using the same responsive curve, end fades, fixed pointer, and fractional tick motion as the altitude tape on the right. Speed values scroll upward as they increase while altitude values scroll downward. Its tick endpoints and current-speed pointer share the rail's inset-circle origin, so the markings stay attached to the visible curve rather than drifting inward with the text-label gutter. + - **Cockpit direction and speed tapes:** plausible destination metadata now drives one translucent, isometric visor chevron labeled directly below with the estimated geographic bearing; the prior full geodesic dashed path is not rendered. A mirrored live ground-speed tape follows the inside-left keyhole rim using the same responsive curve, end fades, fixed pointer, and fractional tick motion as the altitude tape on the right. Speed values scroll upward as they increase while altitude values scroll downward. Its tick endpoints and current-speed pointer share the rail's inset-circle origin, so the markings stay attached to the visible curve rather than drifting inward with the text-label gutter. - Voice control UI (`#gev-voice-control`) shows status states OFF / CONNECTING / LISTENING / EXECUTING / ERROR. ### Current Global Post Defaults @@ -3800,7 +3999,8 @@ easier to meet (detection is now on more often), but does not create it. - Traffic runs in `sim` mode (white dots, hardcoded speeds) unless `TOMTOM_API_KEY` is configured (env or Keychain `tomtom-api`/`api-key`), which enables `live` mode: TomTom flow vector tiles via the budget-governed `/api/tomtom` proxy - (`.gev-cache/tomtom/`, 120 s TTL, `TOMTOM_DAILY_TILE_BUDGET` default 40k/day), + (`.gev-cache/tomtom/`, 120 s TTL, `TOMTOM_DAILY_TILE_BUDGET` default 6k/day, + sized so a 31-day month stays inside TomTom's 200K/month free allowance), decoded client-side (`flowTiles.js`), matched onto Overpass roads (`flowMatch.js`), and rendered as green/amber/red dot color + speed/density scaling (`trafficFlowStyle.js`); closures spawn no dots; unmatched roads stay @@ -3894,7 +4094,6 @@ frames. Typing fields, modified keys and key repeats do not toggle it. The readout starts hidden each session and releases its timer and frame listener when hidden or when the application is disposed. - ## Radio components The radio entry composes one layer from directory ingestion, station queries, @@ -3937,3 +4136,55 @@ releases imagery layers/listeners on replacement. Destroy invalidates pending work and releases owned resources, including late factory results. Supplied 3D tilesets remain owned by the caller; tilesets created through the controller's factory are added to its viewer and removed on destruction. + +## Live CCTV integration candidate (#489) + +Daniel Slay's shared-decoder panel/projection feature is adapted to bounded +HTTP(S) HLS. DelDOT uses official HTTPS HLS URLs; RTMP/ffmpeg remux is excluded +because subprocess transport does not inherit the Node redirect policy. Server +sessions reserve synchronously, cap memory and response bytes, reject redirects, +and abort on release/shutdown. No disk store or background sweep exists while +inactive. The panel paints the same video at at most 640px/15 fps; collapse stops +its paint loop. Camera deactivation destroys the decoder, and fatal playback +errors revert to the labeled frame fallback. Camera changes clear the old panel +frame. hls.js is imported only when an HLS camera starts. Two live sessions may +coexist with at most eight independent consumer leases each; no-access lease +expiry is 15 seconds. Closing one consumer leaves other consumers running. Encrypted/fMP4/byte-range playlists fail +closed. Performance and live agency reliability require recorded validation. + +## Wind forecast models + +Wind supports selectable GFS/IFS models with persisted model choice. Each fetch chooses the available cycle and forecast step nearest the current time; rows show both issue and valid UTC timestamps. Grid identities include model, cycle, forecast step and any requested scalar field. The six model/field cache slots each retain the last two issued grids for manifest/grid rollover, coalesce concurrent requests, retain last-good data on failures and retry no faster than once per minute. Model changes clear the old field immediately, cancel old acquisition and ignore superseded results. + +### Local Weather review candidate + +Weather combines the GFS/ECMWF surface forecast with three observation layers: +NOAA Rain radar (CONUS), Satellite clouds (regional GOES or slower global infrared), +and 15-minute lightning density (Americas and Pacific). One transient observed +clock drives all enabled observation rows. Earlier/Later use the sorted union of +non-suspended products' advertised times; each product selects its nearest frame +at or before the requested UTC time, never a future frame or an interpolation. +The maximum gap is 30 minutes for radar, regional infrared and lightning, and +3 hours for hourly global infrared. A missing eligible frame hides that product +and reports the gap; rows show actual displayed UTC time with synced/nearest labels. +Manifest rollover preserves the requested history time, even when frames expire. + +Latest follows each product's own newest frame, so its timestamps can differ. +Playback advances two seconds after all products settle, wraps, and stops with +fewer than two union times or when all products are suspended. Hidden documents, +reduced motion and unavailable imagery hosts suspend products. Re-enabling or +restoring a host joins the retained history target. The wind row explicitly says +“Forecast · does not follow history” while the observed clock is in history mode. +The catalog exposes `weatherClock` and destroys it with its lifetime signal. + +Source, opacity, coverage navigation and transport controls live in the WEATHER +panel's cards and timeline, not in the rows. The viewer clock is untouched. +Observation layers are off by default; share/persist includes appearance and product, while history +is transient and shared links open latest. Rendering retains the previous frame +when an incoming frame fails; no eligible historical frame instead hides imagery. + +Desktop wind now allows 7,200 baked native GPU paths (narrow viewports remain at +1,200). This doubles the maximum desktop geometry budget, not forecast resolution. +Temperature uses stronger fixed −40..50°C colors; the underlying 1° forecast and +numeric inspection values are unchanged. No volumetric cloud height or local rain +arrival prediction is claimed. NOAA source limits are documented in DATA_SOURCES. diff --git a/docs/INFRASTRUCTURE-LAYERS.md b/docs/INFRASTRUCTURE-LAYERS.md index d29e356f9..76567e605 100644 --- a/docs/INFRASTRUCTURE-LAYERS.md +++ b/docs/INFRASTRUCTURE-LAYERS.md @@ -36,7 +36,8 @@ const layers = createInfrastructureLayers({ | `governorRequestRender` | `(reason)`; request a frame through the existing render scheduler | Each returned layer supports `init(viewer)`, `enable(viewer)`, `disable(viewer)`, -`update(viewer)`, `destroy(viewer)`, `getStats()` and `getLodDiagnostics()`. +`update(viewer)`, `destroy(viewer)`, `getStats()`, `getLodDiagnostics()` and +`getAnalystRecords()`. Use the same viewer for the instance's entire lifetime. Each viewer/context/overlay host permits one live instance per layer ID; destroy an old instance before replacing it. Separate applications may use identical IDs with separate hosts. diff --git a/docs/KNOWN-ISSUES.md b/docs/KNOWN-ISSUES.md index 9857052c7..e6f8c2b3f 100644 --- a/docs/KNOWN-ISSUES.md +++ b/docs/KNOWN-ISSUES.md @@ -1,6 +1,6 @@ # KNOWN ISSUES -Updated: July 8, 2026 +Updated: September 22, 2026 This file tracks active runtime issues only. @@ -79,6 +79,56 @@ Status: Open (owner-accepted 2026-07-08, documented) --- +### Weather layers: coverage and meaning +Status: Open (source limits, by design) + +- **Rain radar covers the contiguous United States only.** It shows MRMS + reflectivity in dBZ, not rainfall rate or a forecast; a gap in coverage does not + mean no precipitation. +- **Lightning density is a ground-network grid, not GLM flashes.** It is NOAA's + 15-minute density product derived from Vaisala NLDN/GLD360 on an approximately + 8 km grid, for the Americas and Pacific only (110°E across the dateline to 0°, + 25°S–80°N). It is not a live strike counter or an all-clear. +- **Cyclone advisories cover NOAA's basins only:** the Atlantic and the + eastern/central North Pacific (NHC and CPHC). Storms elsewhere do not appear. + The cone is forecast-center uncertainty, not storm size. +- **Satellite clouds:** global infrared is hourly with typically 2–3 hours of + source latency. Clouds only is a brightness filter, not a cloud mask. +- **Wind is a forecast.** The animation flows through one forecast on an + approximately 1° grid and does not advance forecast time or follow the + observed-history timeline. +- **History is not shared.** Share links carry the weather layers and their + settings but open at Latest. +- **3D Tiles detail window during history playback:** when a frame's detail image + is slow to arrive, the window may fall back to the coarser full-extent image + until it does. +- Native hardware GPU behavior of the wind and weather renderers is not yet + verified. + +--- + +### Satellite passes and analyst answers +Status: Open (by design) + +- Pass predictions search the next 24 hours for satellites in the loaded catalog. + Visibility is a geometric estimate (satellite sunlit, observer's Sun at or + below −6°); it ignores weather, satellite brightness and orbital-element age. +- Analyst counts and ranks cover a bounded set of loaded records (by default + 2,000 per layer for satellites, datacenters and dams), so omitted records can + change a nearest or count answer. Satellite distance is ground distance. + +--- + +### Live camera video (HLS) +Status: Open (limits) + +- At most two live-video sessions run at once. RTMP-only sources and encrypted, + fMP4 or byte-range playlists are not supported. +- When live video fails, the camera falls back to its labeled still, Street View + or placeholder frame, which is not live video. + +--- + ## Closed / Intentional (for clarity) ### Proxy SSRF and error-surface hardening gaps @@ -119,5 +169,14 @@ Context: converted to **live NASA FIRMS data** on 2026-07-16: the `/api/firms` proxy merges three VIIRS NRT sources (trailing 24 h, 30 min cache, serve-stale-on-failure) and the bundled snapshot was deleted. Requires a free server-side `FIRMS_MAP_KEY`; without it - the layer shows a KEY REQUIRED state. -- Weather radar is still held out of OSS v1 after QA found the previous overlay did not provide reliable visible value. + the layer row reads "Needs FIRMS_MAP_KEY — add it in Provider Settings". + +--- + +### Weather radar held out of the open-source release +Status: Closed — observed rain radar shipped (September 2026) + +Context: +- Rain radar, Satellite clouds, Lightning density, Wind and Cyclone advisories + are in the Weather group of Data Layers. Their current limits are listed under + "Weather layers: coverage and meaning" above. diff --git a/package-lock.json b/package-lock.json index c24590e4a..d98116fb4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,8 +10,10 @@ "license": "MIT", "dependencies": { "@mapbox/vector-tile": "^3.0.0", + "@meri-imperiumi/eccodes-wasm": "^2.48.2", "cesium": "^1.124.0", "egm96-universal": "^1.1.1", + "hls.js": "^1.7.3", "mgrs": "^2.1.0", "pbf": "^5.1.2", "satellite.js": "^6.0.2" @@ -1076,6 +1078,24 @@ "pbf": "^5.0.0" } }, + "node_modules/@meri-imperiumi/eccodes-wasm": { + "version": "2.48.2", + "resolved": "https://registry.npmjs.org/@meri-imperiumi/eccodes-wasm/-/eccodes-wasm-2.48.2.tgz", + "integrity": "sha512-Z7rD3xInomPG7FS97ORD1UGKAdgeeRP9ofa9k4m8d+k2sDfDQeAjTzvs9UOndyaZovaSbEQeIoNX8gTmQNhiSA==", + "cpu": [ + "x64", + "arm64" + ], + "license": "Apache-2.0", + "os": [ + "darwin", + "linux", + "win32" + ], + "engines": { + "node": ">=24.0.0" + } + }, "node_modules/@puppeteer/browsers": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.2.tgz", @@ -1944,6 +1964,12 @@ "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", "license": "MIT" }, + "node_modules/hls.js": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.7.3.tgz", + "integrity": "sha512-MsPlx6yVW4Qv4C7mEVou4/gk/5cN2dVxOTnrNjPSmyH2f0Ln+/UkG10Ax1PE6OvrmTVPKgQYozTtBaPOuCzq7A==", + "license": "Apache-2.0" + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", diff --git a/package.json b/package.json index baeb1ba4f..ea32619e9 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "gods-eye-view", "private": true, "version": "0.1.1", - "description": "A real-time intelligence console for planet Earth \u2014 photorealistic 3D globe, live aircraft/ships/satellites/earthquakes/CCTV, and hands-free voice control. Runs in a browser.", + "description": "A real-time intelligence console for planet Earth — photorealistic 3D globe, live aircraft/ships/satellites/earthquakes/CCTV, and hands-free voice control. Runs in a browser.", "type": "module", "license": "MIT", "author": "Bilawal Sidhu", @@ -49,8 +49,10 @@ }, "dependencies": { "@mapbox/vector-tile": "^3.0.0", + "@meri-imperiumi/eccodes-wasm": "^2.48.2", "cesium": "^1.124.0", "egm96-universal": "^1.1.1", + "hls.js": "^1.7.3", "mgrs": "^2.1.0", "pbf": "^5.1.2", "satellite.js": "^6.0.2" @@ -151,6 +153,7 @@ "./aircraft": "./src/layers/aircraft/index.js", "./layers/vessels": "./src/layers/vessels/index.js", "./layers/earthquakes": "./src/layers/earthquakes/index.js", + "./layers/recent-imagery": "./src/layers/recentImagery/index.js", "./sources/firms-csv": "./src/data/firmsCsv.js", "./layers/firms": "./src/layers/firms/index.js", "./layers/satellites": "./src/layers/satellites/index.js", diff --git a/scripts/format-scope.json b/scripts/format-scope.json index b0dfd39a0..4d57fe92a 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -101,6 +101,8 @@ "src/tooling/previewServing.test.mjs", "server/providers/common/request.js", "server/providers/common/source-root.js", + "src/data/tapAddress.test.mjs", + "src/data/tapAddress.js", "server/providers/local.js", "server/providers/military-installations.js", "server/providers/military-installations/cache.js", @@ -144,6 +146,8 @@ "src/keylessGeocoder.js", "src/standalone/placeSearch.js", "src/ui/panelDisclosure.js", + "src/ui/imagerySplit.js", + "src/ui/imagerySplit.test.mjs", "src/ui/surfaceKeyboard.js", "src/ui/surfaceKeyboard.test.mjs", "src/ui/panelRails.js", @@ -386,6 +390,10 @@ "src/layers/launches/model.js", "src/layers/launches/selection.js", "src/layers/launches/camera.js", + "src/data/localGeojson.analyst.test.mjs", + "src/data/satellites.analyst.test.mjs", + "src/data/layerSnapshot.test.mjs", + "src/data/satellitePass.test.mjs", "src/data/satellites.js", "src/data/rocketLaunches.js", "src/layers/satellites/source.test.mjs", @@ -498,6 +506,7 @@ "src/layers/cctv/source.test.mjs", "src/data/alprCameras.js", "src/data/alprCameras.test.mjs", + "src/data/dataCredits.test.mjs", "src/layers/alpr/index.js", "src/layers/alpr/model.js", "src/layers/alpr/policy.js", @@ -551,6 +560,7 @@ "src/maps/catalog.js", "src/maps/controller.js", "src/maps/controller.test.mjs", + "src/maps/imageryComparison.js", "src/maps/credits.js", "src/maps/defaultSources.js", "src/maps/google3d.js", @@ -732,6 +742,27 @@ "scripts/format-runtime.json", "src/tooling/transitService.test.mjs", "src/sources/overpassFeatures.test.mjs", + "src/data/cctvHlsStream.test.mjs", + "src/layers/cctv/videoPlayback.test.mjs", + "src/ui/cctvVideo.test.mjs", + "src/ui/styles/weather.css", + "src/layers/weather/index.js", + "src/layers/weather/clock.js", + "src/layers/weather/clock.test.mjs", + "src/layers/weather/rendering.js", + "src/layers/weather/shellRendering.js", + "src/layers/weather/shellRendering.test.mjs", + "src/layers/weather/infraredAlpha.js", + "src/layers/weather/infraredAlpha.test.mjs", + "src/layers/weather/infraredImage.js", + "src/layers/weather/infraredImage.test.mjs", + "src/layers/weather/source.js", + "src/layers/weather/weather.test.mjs", + "src/layers/weather/rasterTiles.test.mjs", + "src/layers/wind/rendering.test.mjs", + "src/layers/weather/source.test.mjs", + "src/data/weatherProxy.test.mjs", + "server/providers/weather.js", "src/director/clock.test.mjs", "src/director/timeline.test.mjs", "src/scenes/packs/registry.test.mjs", @@ -746,5 +777,39 @@ "src/director/interactions/interactions.test.mjs", "scripts/qa-director-interactions.mjs", "src/director/sharing/sharing.test.mjs", - "scripts/qa-director-sharing.mjs" + "scripts/qa-director-sharing.mjs", + "src/ui/weatherPanel.js", + "src/ui/weatherPanel.test.mjs", + "src/ui/railCards.js", + "src/ui/railCards.test.mjs", + "src/ui/railTimeline.js", + "src/ui/railTimeline.test.mjs", + "src/layers/weather/imageryOrder.js", + "src/layers/weather/imageryOrder.test.mjs", + "server/providers/cyclones.js", + "src/data/cyclonesProxy.test.mjs", + "src/layers/cyclones/index.js", + "src/layers/cyclones/rendering.js", + "src/layers/cyclones/labels.js", + "src/layers/cyclones/source.js", + "src/layers/cyclones/rendering.test.mjs", + "src/layers/cyclones/labels.test.mjs", + "src/layers/cyclones/index.test.mjs", + "src/layers/cyclones/source.test.mjs", + "src/data/aisStreamSentinels.test.mjs", + "scripts/qa-weather-perf.mjs", + "scripts/qa-weather-journey.mjs", + "scripts/qa-weather-swap.mjs", + "scripts/qa-weather-teardown.mjs", + "src/layers/weather/imageryHost.test.mjs", + "src/layers/recentImagery/model.test.mjs", + "src/layers/recentImagery/catalog.test.mjs", + "src/maps/imageryHost.test.mjs", + "src/layers/recentImagery/rendering.test.mjs", + "src/layers/recentImagery/thumbnails.test.mjs", + "src/layers/recentImagery/index.test.mjs", + "src/ui/imageryBoxTool.test.mjs", + "src/ui/recentImagery.test.mjs", + "src/layers/recentImagery/testDoubles.mjs", + "scripts/qa-recent-imagery.mjs" ] diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 8e6cda2cd..fcd951092 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -161,6 +161,7 @@ "server/providers/cctv/normalize.js", "server/providers/cctv/range.js", "server/providers/cctv/sources.js", + "server/providers/cctv/stream.js", "server/providers/common/http.js", "src/data/directionText.js", "server/providers/common/geo.js", @@ -268,6 +269,10 @@ "server/providers/openai/realtime.js", "server/providers/openai/tools.js", "src/hudSummaryResponse.js", + "src/data/layerSnapshot.js", + "src/data/feedState.js", + "src/loadingFeedback.js", + "src/data/installationFeedback.js", "src/voice/voiceCost.js", "src/voice/actionSchemas.js", "server/providers/openai/toolDescriptions.js", @@ -375,11 +380,18 @@ "modules": [ "src/ui/layers.js", "src/ui/layerPanel.js", + "src/ui/weatherPanel.js", + "src/ui/railCards.js", + "src/ui/railCardBlocks.js", + "src/ui/chipGroup.js", + "src/ui/rowList.js", + "src/ui/railTimeline.js", "src/ui/clearLayersControl.js", "src/loadingFeedback.js", "src/data/installationFeedback.js", "src/keySetupCore.mjs", - "src/data/feedState.js" + "src/data/feedState.js", + "src/data/layerSnapshot.js" ], "external": [] }, @@ -413,6 +425,7 @@ "src/ui/cctvCalibration.js", "src/ui/cctvControls.js", "src/ui/cctvFrames.js", + "src/ui/cctvVideo.js", "src/ui/cctvPresentation.js" ], "external": [] @@ -513,6 +526,7 @@ "src/ui/cctvCalibration.js", "src/ui/cctvControls.js", "src/ui/cctvFrames.js", + "src/ui/cctvVideo.js", "src/ui/cctvPresentation.js", "src/ui/clearLayersControl.js", "src/ui/cockpit.js", @@ -540,6 +554,12 @@ "src/ui/effects.js", "src/ui/frameRateMonitor.js", "src/ui/layerPanel.js", + "src/ui/weatherPanel.js", + "src/ui/railCards.js", + "src/ui/railCardBlocks.js", + "src/ui/chipGroup.js", + "src/ui/rowList.js", + "src/ui/railTimeline.js", "src/ui/layers.js", "src/ui/leftPanelRail.js", "src/ui/location.js", @@ -578,7 +598,9 @@ "src/ui/visualSettings.js", "src/worldFocus.js", "src/data/feedState.js", + "src/data/layerSnapshot.js", "src/ui/aircraftDisplay.js", + "src/layers/weather/imageryHost.js", "src/ui/layerBindings.js", "src/ui/displayBindings.js", "src/ui/shellFacade.js" @@ -609,7 +631,9 @@ "src/ui/styles/command-dock-sliding.css", "src/ui/styles/voice-cost.css", "src/ui/styles/first-run.css", - "src/ui/styles/provider-settings.css" + "src/ui/styles/provider-settings.css", + "src/ui/styles/weather.css", + "src/ui/styles/recent-imagery.css" ], "external": [] }, @@ -829,6 +853,18 @@ ], "external": ["cesium"] }, + "recent-imagery": { + "exports": ["./layers/recent-imagery"], + "modules": [ + "src/layers/recentImagery/index.js", + "src/layers/recentImagery/model.js", + "src/layers/recentImagery/catalog.js", + "src/layers/recentImagery/rendering.js", + "src/layers/recentImagery/thumbnails.js", + "src/maps/imageryHost.js" + ], + "external": ["cesium"] + }, "fire-layer": { "exports": ["./layers/firms"], "modules": [ @@ -857,6 +893,7 @@ "modules": [ "src/data/issPass.js", "src/data/satelliteClass.js", + "src/data/satellitePass.js", "src/layers/satellites/catalog.js", "src/layers/satellites/controls.js", "src/layers/satellites/index.js", @@ -865,6 +902,7 @@ "src/layers/satellites/labels.js", "src/layers/satellites/lifecycle.js", "src/layers/satellites/orbits.js", + "src/layers/satellites/records.js", "src/layers/satellites/policy.js", "src/layers/satellites/rendering.js", "src/layers/satellites/source.js", @@ -1026,6 +1064,7 @@ "src/layers/cctv/policy.js", "src/layers/cctv/presentation.js", "src/layers/cctv/projection.js", + "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", "src/layers/cctv/selection.js", "src/layers/cctv/source.js", @@ -1036,7 +1075,7 @@ "src/data/inputOwnership.js", "src/layers/cctv/sourcePolicy.js" ], - "external": ["cesium"] + "external": ["hls.js", "cesium"] }, "alpr-cameras": { "exports": ["./layers/alpr"], @@ -1137,13 +1176,15 @@ "src/maps/availability.js", "src/maps/catalog.js", "src/maps/controller.js", + "src/maps/imageryComparison.js", "src/maps/credits.js", "src/maps/defaultSources.js", "src/maps/google3d.js", "src/maps/imagery.js", "src/maps/registry.js", "src/maps/terrain.js", - "src/keySetupCore.mjs" + "src/keySetupCore.mjs", + "src/maps/imageryHost.js" ], "external": ["cesium"] }, @@ -1203,6 +1244,7 @@ "modules": [ "src/scenes/nepalEvidencePack.js", "src/data/bhoteKoshiEvent.js", + "src/ui/imagerySplit.js", "src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiLocator.js", "src/data/bhoteKoshiIncidentPlaces.js", @@ -1280,6 +1322,19 @@ "src/data/contactMatch.js", "src/data/contextStore.js", "src/data/dataCredits.js", + "src/data/wind.js", + "src/layers/wind/index.js", + "src/layers/wind/model.js", + "src/layers/wind/fields.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/gpuRendering.js", + "src/layers/wind/relief.js", + "src/layers/wind/inspection.js", + "src/layers/wind/presentation.js", + "src/layers/wind/rendering.js", + "src/layers/weather/rasterTiles.js", + "src/layers/wind/source.js", + "src/sources/windBody.js", "src/data/detection.js", "src/data/detectionCohort.js", "src/data/detectionDraw.js", @@ -1333,6 +1388,7 @@ "src/data/rocketLaunches.js", "src/data/routePlausible.js", "src/data/satelliteClass.js", + "src/data/satellitePass.js", "src/data/satellites.js", "src/data/scenePick.js", "src/data/spriteOrder.js", @@ -1415,6 +1471,7 @@ "src/layers/cctv/policy.js", "src/layers/cctv/presentation.js", "src/layers/cctv/projection.js", + "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", "src/layers/cctv/selection.js", "src/layers/cctv/source.js", @@ -1520,6 +1577,7 @@ "src/layers/satellites/labels.js", "src/layers/satellites/lifecycle.js", "src/layers/satellites/orbits.js", + "src/layers/satellites/records.js", "src/layers/satellites/policy.js", "src/layers/satellites/rendering.js", "src/layers/satellites/source.js", @@ -1575,6 +1633,7 @@ "src/maps/availability.js", "src/maps/catalog.js", "src/maps/controller.js", + "src/maps/imageryComparison.js", "src/maps/credits.js", "src/maps/defaultSources.js", "src/maps/google3d.js", @@ -1630,6 +1689,7 @@ "src/ui/cctvCalibration.js", "src/ui/cctvControls.js", "src/ui/cctvFrames.js", + "src/ui/cctvVideo.js", "src/ui/cctvPresentation.js", "src/ui/clearLayersControl.js", "src/ui/cockpit.js", @@ -1658,6 +1718,12 @@ "src/ui/effects.js", "src/ui/frameRateMonitor.js", "src/ui/layerPanel.js", + "src/ui/weatherPanel.js", + "src/ui/railCards.js", + "src/ui/railCardBlocks.js", + "src/ui/chipGroup.js", + "src/ui/rowList.js", + "src/ui/railTimeline.js", "src/ui/layers.js", "src/ui/leftPanelRail.js", "src/ui/location.js", @@ -1729,6 +1795,7 @@ "src/voice/realtimeEvents.js", "src/app/localGeojsonServices.js", "src/data/feedState.js", + "src/data/layerSnapshot.js", "src/layers/alpr/records.js", "src/layers/earthquakes/records.js", "src/layers/cctv/sourcePolicy.js", @@ -1784,6 +1851,13 @@ "src/voice/realtimeRadio.js", "src/voice/realtimeTurns.js", "src/voice/realtimeConnection.js", + "src/layers/weather/index.js", + "src/layers/weather/clock.js", + "src/layers/weather/rendering.js", + "src/layers/weather/shellRendering.js", + "src/layers/weather/infraredAlpha.js", + "src/layers/weather/infraredImage.js", + "src/layers/weather/source.js", "src/director/clock.js", "src/director/timeline.js", "src/scenes/shotPresentation.js", @@ -1811,9 +1885,25 @@ "src/director/sharing/lifetime.js", "src/director/authoring.js", "src/scenes/sharing.js", - "src/ui/sceneSharing.js" + "src/ui/sceneSharing.js", + "src/layers/weather/imageryOrder.js", + "src/layers/weather/imageryHost.js", + "src/layers/cyclones/index.js", + "src/layers/cyclones/rendering.js", + "src/layers/cyclones/labels.js", + "src/layers/cyclones/source.js", + "src/app/layers/recentImagery.js", + "src/layers/recentImagery/index.js", + "src/layers/recentImagery/model.js", + "src/layers/recentImagery/catalog.js", + "src/layers/recentImagery/rendering.js", + "src/layers/recentImagery/thumbnails.js", + "src/maps/imageryHost.js", + "src/ui/recentImagery.js", + "src/ui/imageryBoxTool.js" ], "external": [ + "hls.js", "@mapbox/vector-tile", "cesium", "egm96-universal", @@ -1831,6 +1921,8 @@ "exports": ["./application/layers"], "modules": [ "src/data/bhoteKoshiEvent.js", + "src/ui/imagerySplit.js", + "src/maps/imageryComparison.js", "src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiLocator.js", "src/data/bhoteKoshiIncidentPlaces.js", @@ -1840,6 +1932,16 @@ "src/annotations/resolver.js", "src/app/catalog.js", "src/app/constructCatalog.js", + "src/layers/wind/index.js", + "src/layers/wind/model.js", + "src/layers/wind/fields.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/gpuRendering.js", + "src/layers/wind/relief.js", + "src/layers/wind/inspection.js", + "src/layers/wind/presentation.js", + "src/layers/wind/rendering.js", + "src/layers/weather/rasterTiles.js", "src/app/layers/aisLiveVessels.js", "src/app/layers/alprCameras.js", "src/app/layers/bikeshare.js", @@ -1887,6 +1989,7 @@ "src/data/infrastructure.js", "src/data/installationFeedback.js", "src/data/issPass.js", + "src/data/satellitePass.js", "src/data/labelArbiter.js", "src/data/layerState.js", "src/data/localGeojson.js", @@ -1978,6 +2081,7 @@ "src/layers/cctv/policy.js", "src/layers/cctv/presentation.js", "src/layers/cctv/projection.js", + "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", "src/layers/cctv/selection.js", "src/layers/cctv/source.js", @@ -2083,6 +2187,7 @@ "src/layers/satellites/labels.js", "src/layers/satellites/lifecycle.js", "src/layers/satellites/orbits.js", + "src/layers/satellites/records.js", "src/layers/satellites/policy.js", "src/layers/satellites/rendering.js", "src/layers/satellites/source.js", @@ -2205,9 +2310,30 @@ "src/sources/overpassFeaturesRecords.js", "src/sources/overpassFeatures.js", "src/sources/featureSource.js", - "src/sources/overpassRoads.js" + "src/sources/overpassRoads.js", + "src/layers/weather/index.js", + "src/layers/weather/clock.js", + "src/layers/weather/rendering.js", + "src/layers/weather/shellRendering.js", + "src/layers/weather/infraredAlpha.js", + "src/layers/weather/infraredImage.js", + "src/layers/weather/source.js", + "src/layers/weather/imageryOrder.js", + "src/layers/weather/imageryHost.js", + "src/layers/cyclones/index.js", + "src/layers/cyclones/rendering.js", + "src/layers/cyclones/labels.js", + "src/layers/cyclones/source.js", + "src/app/layers/recentImagery.js", + "src/layers/recentImagery/index.js", + "src/layers/recentImagery/model.js", + "src/layers/recentImagery/catalog.js", + "src/layers/recentImagery/rendering.js", + "src/layers/recentImagery/thumbnails.js", + "src/maps/imageryHost.js" ], "external": [ + "hls.js", "cesium", "egm96-universal", "satellite.js", diff --git a/scripts/qa-layer-panel.mjs b/scripts/qa-layer-panel.mjs index 453009929..1282c6b50 100644 --- a/scripts/qa-layer-panel.mjs +++ b/scripts/qa-layer-panel.mjs @@ -23,13 +23,17 @@ try { `${process.env.QA_BASE_URL || 'http://localhost:4173'}/?welcome=0`, { waitUntil: 'domcontentloaded' }, ); - await page.waitForFunction( - () => window.__godsEyeView?.dataManager?._layerPanel, - { timeout: 60000 }, - ); + await page.waitForFunction(() => window.__godsEyeView?.dataManager, { + timeout: 60000, + }); const results = await page.evaluate(async () => { const manager = window.__godsEyeView.dataManager; - const container = manager._toggleContainer; + const entry = document.querySelector( + 'script[type="module"][src*="/src/main.js"]', + ); + const { application } = await import(entry.src); + const { presentation } = application.getComponents().data; + const container = presentation.panel._toggleContainer; const id = 'qa-panel-lifecycle'; let listener = null; let enabled = 0; @@ -54,7 +58,7 @@ try { }); const result = []; try { - manager.buildTogglePanel(container); + presentation.mount(container); const row = () => container.querySelector(`[data-layer-id="${id}"]`); const first = row().querySelector('.data-toggle-btn'); result.push([ @@ -66,7 +70,7 @@ try { 'row subscription is installed', typeof listener === 'function', ]); - manager.buildTogglePanel(container); + presentation.mount(container); first.click(); await Promise.resolve(); result.push([ @@ -97,7 +101,7 @@ try { ]); await manager.setEnabled(id, true); const final = row().querySelector('.data-toggle-btn'); - manager._layerPanel.destroy(); + presentation._panel.destroy(); final.click(); await Promise.resolve(); result.push([ @@ -109,10 +113,10 @@ try { manager.isEnabled(id), ]); } finally { - manager._layerPanel?.destroy(); - manager._layerPanel = null; + presentation._panel?.destroy(); + presentation._panel = null; await window.__gevQaUnregisterLayer(manager, id); - manager.buildTogglePanel(container); + presentation.mount(container); } result.push([ 'ordinary layer rows return after reassembly', diff --git a/scripts/qa-recent-imagery.mjs b/scripts/qa-recent-imagery.mjs new file mode 100644 index 000000000..1460ed3b5 --- /dev/null +++ b/scripts/qa-recent-imagery.mjs @@ -0,0 +1,1480 @@ +#!/usr/bin/env node +/** + * Rendered acceptance for DATA ▸ Recent Imagery against the real NASA + * endpoints (CMR catalog, GIBS tiles, Worldview snapshots): the rail panel, + * USE VIEW and the live preview, the three modes (IMAGE, VS BASEMAP, A / B) + * with their pins, the divider and the Esri surface on Google 3D, Escape + * order, the oversized-view refusal and ZOOM IN, CLEAR, the share link, + * map-switch rebind (a manual switch to Google 3D keeps the imagery on + * Esri), CCTV stability at 900 and 700 px, scroll preservation, a + * layout-shift measurement across every transition, and disable. + * + * Run: start the app (`./scripts/dev-fresh.sh`) and + * node scripts/qa-recent-imagery.mjs + * Env: QA_BASE_URL (default http://localhost:4173), QA_SHOT_DIR (default + * qa-shots/recent-imagery), QA_HEADFUL=1. Every wait is bounded. Without + * network access to NASA the run skips with exit code 0. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import puppeteer from 'puppeteer'; + +const BASE_URL = process.env.QA_BASE_URL || 'http://localhost:4173'; +const SHOT_DIR = process.env.QA_SHOT_DIR || 'qa-shots/recent-imagery'; +const HEADFUL = process.env.QA_HEADFUL === '1'; +const STEP_TIMEOUT = 20_000; +const AUSTIN = { lon: -97.74, lat: 30.27, height: 12_000 }; +const PANEL = '#recent-imagery-panel'; + +async function networkAvailable() { + try { + const response = await fetch( + 'https://cmr.earthdata.nasa.gov/search/collections.json?page_size=1', + { signal: AbortSignal.timeout(8_000) }, + ); + return response.ok; + } catch { + return false; + } +} + +if (!(await networkAvailable())) { + console.log( + 'SKIP: cmr.earthdata.nasa.gov is unreachable — the live Recent Imagery gate needs network access.', + ); + process.exit(0); +} + +const browser = await puppeteer.launch({ + headless: !HEADFUL, + ...(HEADFUL + ? { + executablePath: + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + } + : {}), + args: [ + '--no-sandbox', + '--disable-background-timer-throttling', + '--disable-renderer-backgrounding', + ...(HEADFUL ? ['--window-size=1280,860'] : []), + ...(process.platform === 'darwin' + ? ['--use-angle=metal', '--enable-gpu'] + : ['--use-gl=angle', '--use-angle=swiftshader']), + ], +}); +const page = await browser.newPage(); +const errors = []; +page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`)); +let failures = 0; +let checks = 0; +function check(name, passed, detail = '') { + checks += 1; + console.log( + `[${passed ? 'PASS' : 'FAIL'}] ${name}${detail ? ` — ${detail}` : ''}`, + ); + if (!passed) failures++; +} +fs.mkdirSync(SHOT_DIR, { recursive: true }); +const shots = []; +const shot = async (name) => { + const file = path.join(SHOT_DIR, `${name}.jpg`); + await page.screenshot({ path: file, type: 'jpeg', quality: 82 }); + shots.push(file); +}; +const panelShot = async (name) => { + const panel = await page.$(PANEL); + if (!panel) return; + const file = path.join(SHOT_DIR, `${name}.png`); + await panel.screenshot({ path: file }); + shots.push(file); +}; +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** Poll a page predicate; false on timeout instead of throwing. */ +async function until(fn, arg, timeout = STEP_TIMEOUT) { + try { + await page.waitForFunction(fn, { timeout, polling: 250 }, arg); + return true; + } catch { + return false; + } +} + +/** + * Page-side helpers every predicate can use: the layer handle, GIBS layers + * per host with their split directions, and whether a header is on screen. + */ +function installPageHelpers() { + window.__riQa = { + layer: () => window.__gevRecentImagery.layer, + snap: () => window.__gevRecentImagery.layer.getSnapshot(), + owned: () => window.__gevRecentImagery.layer.diagnostics().ownedCount, + gibs(collection) { + const out = []; + for (let i = 0; i < (collection?.length || 0); i += 1) { + const layer = collection.get(i); + if ( + String(layer?.imageryProvider?.url || '').includes( + 'earthdata.nasa.gov', + ) + ) + out.push(layer.splitDirection); + } + return out; + }, + hosts() { + const gev = window.__godsEyeView; + const globe = this.gibs(gev.viewer.imageryLayers); + const tileset = this.gibs(gev.tileset?.imageryLayers); + return { + globe: globe.length, + tileset: tileset.length, + splits: [...globe, ...tileset], + globeShown: gev.viewer.scene.globe.show, + }; + }, + splitShown() { + const line = document.getElementById('recent-imagery-split-line'); + return Boolean(line && !line.hidden); + }, + headerOnScreen(id) { + const element = document.getElementById(id); + const header = + element?.querySelector('.panel-header, .pp-header-row') || element; + const rect = header?.getBoundingClientRect(); + return rect + ? rect.height > 0 && rect.top >= 0 && rect.bottom <= window.innerHeight + : false; + }, + activeStack: () => + window.__godsEyeView.mapStackController?.getActiveId?.() ?? null, + }; +} + +const state = () => + page.evaluate(() => { + const qa = window.__riQa; + const snapshot = qa.snap(); + const gev = window.__godsEyeView; + const split = document.getElementById('recent-imagery-split-line'); + const text = (id) => document.getElementById(id)?.textContent || ''; + const hosts = qa.hosts(); + return { + box: snapshot.box, + boxError: snapshot.boxError, + mode: snapshot.mode, + candidates: snapshot.candidates.map((c) => ({ + key: c.key, + drapable: c.drapable, + })), + focus: snapshot.focus?.key || null, + pinA: snapshot.pins.a.key, + pinB: snapshot.pins.b.key, + preview: snapshot.preview.key, + shown: snapshot.shown, + notice: snapshot.notice, + comparison: snapshot.comparison, + borrowedEsri: snapshot.borrowedEsri, + error: snapshot.error, + diagnostics: qa.layer().diagnostics(), + cards: document.querySelectorAll('#recent-imagery-panel .ri-card').length, + panelHidden: document.getElementById('recent-imagery-panel')?.hidden, + noticeText: text('ri-notice-text'), + hintText: text('ri-hint'), + rowA: text('ri-slot-a'), + rowB: text('ri-slot-b'), + splitVisible: Boolean( + split && !split.hidden && split.getBoundingClientRect().height > 0, + ), + splitLabels: split + ? [ + split.querySelector('span.before')?.textContent, + split.querySelector('span.after')?.textContent, + ] + : null, + splitLeft: split ? split.getBoundingClientRect().left : null, + splitPosition: gev.viewer.scene.splitPosition, + canvasWidth: gev.viewer.scene.canvas.clientWidth, + activeStack: qa.activeStack(), + gibsOnGlobe: hosts.globe, + gibsOnTileset: hosts.tileset, + gibsSplits: hosts.splits, + }; + }); +const hostsDetail = (s) => + `owned=${s.diagnostics.ownedCount} host=${s.diagnostics.host} globe=${s.gibsOnGlobe} tileset=${s.gibsOnTileset} splits=${s.gibsSplits}`; + +/** Put the camera straight down over a point at a height, no flight. */ +const setView = (view) => + page.evaluate((target) => { + const viewer = window.__godsEyeView.viewer; + viewer.camera.cancelFlight?.(); + viewer.scene.tweens?.removeAll?.(); + viewer.camera.setView({ + destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({ + longitude: (target.lon * Math.PI) / 180, + latitude: (target.lat * Math.PI) / 180, + height: target.height, + }), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + viewer.scene.requestRender(); + }, view); + +/** Ground width of the camera's view rectangle, in km (0 without one). */ +const viewWidthKm = () => + page.evaluate(() => { + const rect = window.__godsEyeView.viewer.camera.computeViewRectangle?.(); + if (!rect) return 0; + const lat = (rect.south + rect.north) / 2; + return Math.abs(rect.east - rect.west) * 6371 * Math.cos(lat); + }); + +const click = (selector) => + page.evaluate((target) => { + const button = document.querySelector(target); + if (!button || button.disabled || button.hidden) return false; + button.click(); + return true; + }, selector); +const clickAction = (id) => click(`${PANEL} [data-action-id="${id}"]`); +const clickMode = (mode) => click(`${PANEL} .ri-mode-btn[data-mode="${mode}"]`); +const focusStrip = () => + page.evaluate(() => + document.getElementById('ri-strip')?.focus({ preventScroll: true }), + ); +const pressOnStrip = async (key) => { + await focusStrip(); + await page.keyboard.press(key); +}; + +/** Average colour of the canvas centre — the inside of a centred 10 km box. */ +async function probe() { + const base64 = await page.screenshot({ + clip: { x: 540, y: 330, width: 200, height: 200 }, + type: 'png', + encoding: 'base64', + }); + return page.evaluate(async (data) => { + const bitmap = await createImageBitmap( + await (await fetch(`data:image/png;base64,${data}`)).blob(), + ); + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const context = canvas.getContext('2d'); + context.drawImage(bitmap, 0, 0); + const pixels = context.getImageData(0, 0, bitmap.width, bitmap.height).data; + const sum = [0, 0, 0]; + for (let i = 0; i < pixels.length; i += 4) + for (let c = 0; c < 3; c += 1) sum[c] += pixels[i + c]; + return sum.map((value) => Math.round(value / (pixels.length / 4))); + }, base64); +} + +const tilesSettled = () => + until(() => { + const gev = window.__godsEyeView; + if (gev.viewer.scene.globe.show) return gev.viewer.scene.globe.tilesLoaded; + return !gev.tileset || gev.tileset.tilesLoaded; + }); +const backOnPhotoreal = () => + until(() => window.__riQa.activeStack() === 'photoreal'); +const onEsri = () => + until(() => window.__riQa.activeStack() === 'esri-imagery'); +const ownedIs = (count) => + until((n) => window.__riQa.owned() === n, count, 10_000); + +// ── layout-shift measurement ──────────────────────────────────────────────── +const CONTROLS = { + 'select-box': `${PANEL} [data-action-id="select-box"]`, + 'use-view': `${PANEL} [data-action-id="use-view"]`, + clear: `${PANEL} [data-action-id="clear"]`, + notice: '#ri-notice', + 'zoom-in': '#ri-zoom-in', + strip: '#ri-strip', + hint: '#ri-hint', + 'mode-image': `${PANEL} .ri-mode-btn[data-mode="image"]`, + 'mode-basemap': `${PANEL} .ri-mode-btn[data-mode="basemap"]`, + 'mode-ab': `${PANEL} .ri-mode-btn[data-mode="ab"]`, + 'row-a': '#ri-slot-a', + 'row-b': '#ri-slot-b', + 'unpin-a': '#ri-unpin-a', + 'unpin-b': '#ri-unpin-b', + opacity: '#ri-opacity', + swap: '#ri-swap', + 'export-a': `${PANEL} [data-action-id="export-a"]`, + 'export-b': `${PANEL} [data-action-id="export-b"]`, + details: '#ri-details .rail-card-header', +}; +const measure = () => + page.evaluate((controls) => { + const body = document.getElementById('recent-imagery-panel-body'); + const out = { bodyScroll: body?.scrollTop ?? null, rects: {} }; + for (const [name, selector] of Object.entries(controls)) { + const rect = document.querySelector(selector)?.getBoundingClientRect(); + out.rects[name] = rect + ? [rect.left, rect.top, rect.width, rect.height].map( + (v) => Math.round(v * 10) / 10, + ) + : null; + } + return out; + }, CONTROLS); +let layoutBaseline = null; +/** Every control's rect matches the baseline within 1 px. */ +async function checkLayout(label) { + await wait(150); + const now = await measure(); + if (!layoutBaseline) { + layoutBaseline = now; + check( + `layout baseline recorded (${label})`, + Object.values(now.rects).every(Boolean), + JSON.stringify(now.rects), + ); + return; + } + const moved = Object.entries(now.rects).filter(([name, rect]) => { + const base = layoutBaseline.rects[name]; + return ( + !rect || !base || rect.some((value, i) => Math.abs(value - base[i]) > 1) + ); + }); + check( + `no control moves: ${label}`, + moved.length === 0, + moved + .map( + ([name, rect]) => + `${name} ${JSON.stringify(layoutBaseline.rects[name])}→${JSON.stringify(rect)}`, + ) + .join(' '), + ); +} + +try { + await page.setViewport({ width: 1280, height: 860 }); + await page.goto(`${BASE_URL}/?welcome=0`, { waitUntil: 'domcontentloaded' }); + const booted = await until( + () => + window.__gevRecentImagery && + window.__godsEyeView && + document.getElementById('loading-screen')?.classList.contains('hidden'), + null, + 90_000, + ); + check('the app boots with the Recent Imagery handle', booted); + if (!booted) throw new Error('boot timeout'); + await page.evaluate(installPageHelpers); + + await setView(AUSTIN); + await tilesSettled(); + const initialStack = await page.evaluate(() => window.__riQa.activeStack()); + const photoreal = initialStack === 'photoreal'; + console.log(`initial map stack: ${initialStack}`); + const onPhotorealOnly = (name, passed, detail) => + photoreal + ? check(name, passed, detail) + : console.log(`[SKIP] ${name} — the boot stack is ${initialStack}`); + + // ── enable: the panel in the rail, per the rail readout pattern ───────── + const layerToggle = '[data-layer-id="recent-imagery"] .data-toggle-btn'; + check( + 'the data panel carries a Recent Imagery toggle', + await click(layerToggle), + ); + check( + 'the layer enables from its toggle', + await until(() => + window.__godsEyeView.dataManager.isEnabled('recent-imagery'), + ), + ); + check( + 'the panel appears on the right rail once enabled', + await until( + () => document.getElementById('recent-imagery-panel')?.hidden === false, + ), + ); + const railPlacement = await page.evaluate(() => { + const rail = document.getElementById('right-context-rail'); + const panel = document.getElementById('recent-imagery-panel'); + const body = document.getElementById('recent-imagery-panel-body'); + const order = [...rail.children].map((child) => child.id); + const at = (id) => order.indexOf(id); + return { + inRail: panel?.parentElement === rail, + beforeContext: at('recent-imagery-panel') < at('global-context-panel'), + afterWeather: at('weather-panel') < at('recent-imagery-panel'), + collapsed: panel?.classList.contains('collapsed'), + scroller: body?.hasAttribute('data-rail-scroller'), + readoutInBody: body?.firstElementChild?.classList.contains( + 'recent-imagery-readout', + ), + body: body?.offsetHeight, + title: panel?.querySelector('.panel-title')?.textContent, + order, + }; + }); + check( + 'the panel sits in the rail after WEATHER and before CONTEXT, expanded on first appearance', + railPlacement.inRail && + railPlacement.beforeContext && + railPlacement.afterWeather && + railPlacement.collapsed === false && + railPlacement.body > 0, + JSON.stringify(railPlacement), + ); + check( + 'the body is a rail scroller holding the readout, under a RECENT IMAGERY header', + railPlacement.scroller && + railPlacement.readoutInBody && + railPlacement.title === 'RECENT IMAGERY', + JSON.stringify(railPlacement), + ); + const listOf = (selector, key) => + page.evaluate( + (sel, field) => + [...document.querySelectorAll(sel)] + .map((node) => node.dataset[field] || node.id) + .join(','), + selector, + key, + ); + check( + 'the data-panel row carries only the two source chips', + (await listOf( + '[data-layer-id="recent-imagery"] .data-toggle-chip', + 'chipId', + )) === 'hls,viirs', + ); + const actionIds = await listOf( + `${PANEL} .ri-actions-row [data-action-id]`, + 'actionId', + ); + check( + 'the actions row holds SELECT BOX, USE VIEW and CLEAR', + actionIds === 'select-box,use-view,clear', + actionIds, + ); + const blocks = await listOf(`${PANEL} .recent-imagery-readout > *`, 'none'); + check( + 'the body is the fixed stack: actions, notice, strip, hint, selection, controls, details', + blocks === + 'ri-actions,ri-notice,ri-strip,ri-hint,ri-selection,ri-controls,ri-details', + blocks, + ); + let current = await state(); + check( + 'before a box: CLEAR is disabled, the hint says what to do, IMAGE is the mode', + (await page.evaluate( + () => + document.querySelector('#recent-imagery-panel [data-action-id="clear"]') + ?.disabled, + )) === true && + current.hintText === 'Select a box or use the view' && + current.mode === 'image', + `${current.hintText} ${current.mode}`, + ); + await checkLayout('empty'); + await panelShot('01-enabled-panel'); + + // ── USE VIEW at 12 km: days and the live preview ──────────────────────── + const beforeColour = await probe(); + const viewKm = await viewWidthKm(); + check('USE VIEW is clickable', await clickAction('use-view')); + const searched = await until(() => { + const snapshot = window.__riQa.snap(); + return !snapshot.searching && snapshot.candidates.length > 0; + }); + current = await state(); + check( + `USE VIEW at 12 km (${viewKm.toFixed(1)} km wide) sets a box and the catalog returns days within 20 s`, + searched && Boolean(current.box), + `${current.candidates.length} candidates, error=${current.error} boxError=${current.boxError}`, + ); + check( + 'the strip renders one card per day', + current.cards === current.candidates.length && current.cards > 0, + `${current.cards} cards`, + ); + const countText = await page.evaluate( + () => document.getElementById('recent-imagery-panel-count')?.textContent, + ); + check( + 'the header count reads the day count', + /^\d+ DAYS?$/.test(countText), + countText, + ); + const startHere = await page.evaluate(() => + [...document.querySelectorAll('#recent-imagery-panel .ri-card-start')] + .filter((node) => !node.hidden) + .map((node) => node.closest('.ri-card').dataset.key), + ); + check( + 'exactly one card wears START HERE', + startHere.length === 1, + startHere.join(','), + ); + check( + 'the START HERE day previews on its own', + await until(() => { + const snap = window.__riQa.snap(); + return ( + Boolean(snap.preview.key) && + snap.preview.slot === 'a' && + window.__riQa.owned() === 1 + ); + }), + ); + current = await state(); + check( + 'row A reads the previewed day, row B reads the basemap', + /^IMAGE.+ · preview×$/.test(current.rowA) && current.rowB === 'VSBasemap×', + `${current.rowA} | ${current.rowB}`, + ); + onPhotorealOnly( + 'on Google 3D a shown image borrows the Esri surface', + await onEsri(), + ); + const esriNote = await until( + () => + document.getElementById('ri-notice-text')?.textContent === + 'Imagery on Esri · Google 3D returns when cleared', + undefined, + 5_000, + ); + current = await state(); + onPhotorealOnly( + 'the notice says the imagery is on Esri until cleared', + esriNote, + current.noticeText, + ); + check( + 'one owned imagery layer on the globe, no divider', + current.diagnostics.ownedCount === 1 && + current.gibsOnGlobe + current.gibsOnTileset === 1 && + !current.splitVisible, + hostsDetail(current), + ); + check( + 'at least one thumbnail settles (present/empty/error)', + await until(() => + window.__riQa + .snap() + .candidates.some((c) => c.thumbnail.status !== 'unknown'), + ), + ); + await tilesSettled(); + let changedColour = null; + for (let deadline = Date.now() + STEP_TIMEOUT; Date.now() < deadline;) { + const colour = await probe(); + if (Math.hypot(...colour.map((c, i) => c - beforeColour[i])) > 6) { + changedColour = colour; + break; + } + await page.evaluate(() => + window.__godsEyeView.viewer.scene.requestRender(), + ); + await wait(1000); + } + check( + 'the rendered frame inside the box changes once the preview drapes', + Boolean(changedColour), + `before=${beforeColour} after=${changedColour || (await probe())}`, + ); + await checkLayout('preview'); + await shot('02-preview'); + await panelShot('02-preview-panel'); + + // ── arrow keys: the preview follows the focus ─────────────────────────── + await until(() => { + const snap = window.__riQa.snap(); + return snap.candidates.some( + (c) => c.key !== snap.preview.key && c.drapable, + ); + }); + current = await state(); + const targetIndex = current.candidates.findIndex( + (c) => c.key !== current.preview && c.drapable, + ); + check( + 'a present day other than the preview is reachable', + targetIndex >= 0, + String(targetIndex), + ); + const targetKey = current.candidates[targetIndex]?.key; + await focusStrip(); + await page.keyboard.press('Home'); + for (let i = 0; i < targetIndex; i += 1) + await page.keyboard.press('ArrowRight'); + const pressedAt = Date.now(); + check( + 'arrow keys move focus at once', + await until( + (key) => window.__riQa.snap().focus?.key === key, + targetKey, + 2_000, + ), + targetKey, + ); + const followed = await until( + (key) => window.__riQa.snap().preview.key === key, + targetKey, + 1_500, + ); + const elapsed = Date.now() - pressedAt; + check( + 'the focused present day previews within 1 s', + followed && elapsed <= 1_250, + `preview after ${elapsed} ms`, + ); + current = await state(); + check( + 'still a single owned layer while scrubbing', + current.diagnostics.ownedCount === 1, + hostsDetail(current), + ); + const flag = await page.evaluate( + (key) => + document.querySelector( + `#recent-imagery-panel .ri-card[data-key="${key}"] .ri-card-flag`, + )?.textContent, + targetKey, + ); + check('the previewed card wears PREVIEW', flag === 'PREVIEW', flag); + + // ── IMAGE: S pins the focused day; focus no longer moves the map ──────── + await pressOnStrip('s'); + current = await state(); + check( + 'S pins the focused day and its SHOW chip lights', + current.pinA === targetKey && + (await page.evaluate( + (key) => + document + .querySelector( + `#recent-imagery-panel .ri-card[data-key="${key}"] .ri-chip[data-slot="a"]`, + ) + ?.getAttribute('aria-pressed'), + targetKey, + )) === 'true', + current.pinA, + ); + check( + 'row A reads the pinned day without "preview"', + /^IMAGE.+×$/.test(current.rowA) && !/preview/.test(current.rowA), + current.rowA, + ); + await checkLayout('pinned'); + await page.keyboard.press(targetIndex > 0 ? 'ArrowLeft' : 'ArrowRight'); + await wait(700); + current = await state(); + check( + 'with the image pinned, focus moves without changing the map', + current.focus !== targetKey && current.shown.a === targetKey, + `focus=${current.focus} shown=${current.shown.a}`, + ); + await page.evaluate(() => { + const slider = document.getElementById('ri-opacity'); + slider.value = '60'; + slider.dispatchEvent(new Event('input', { bubbles: true })); + }); + current = await state(); + check( + 'OPACITY sets the draped alpha', + Math.abs((await page.evaluate(() => window.__riQa.snap().alpha)) - 0.6) < + 1e-9, + ); + await checkLayout('opacity'); + + // ── VS BASEMAP: the pinned day swipes against the basemap ─────────────── + check('VS BASEMAP is one click', await clickMode('basemap')); + const basemapSwipe = await until( + () => + window.__riQa.snap().shown.swipe === 'basemap' && + window.__riQa.splitShown(), + ); + current = await state(); + check( + 'VS BASEMAP shows the divider, labelled IMAGE / BASEMAP', + basemapSwipe && + JSON.stringify(current.splitLabels) === '["IMAGE","BASEMAP"]', + JSON.stringify(current.splitLabels), + ); + check( + 'the image is on the left and the basemap on the right: one layer, split LEFT', + current.diagnostics.ownedCount === 1 && + JSON.stringify(current.gibsSplits) === '[-1]', + hostsDetail(current), + ); + check( + 'the divider starts centred', + Math.abs(current.splitPosition - 0.5) < 0.01 && + Math.abs(current.splitLeft - current.canvasWidth / 2) <= 2, + `splitPosition=${current.splitPosition} left=${current.splitLeft} canvas=${current.canvasWidth}`, + ); + check( + 'row B reads the basemap, lit', + current.rowB === 'VSBasemap×' && + (await page.evaluate(() => + document.getElementById('ri-slot-b').classList.contains('lit'), + )), + current.rowB, + ); + onPhotorealOnly( + 'the swipe runs on Esri', + current.activeStack === 'esri-imagery', + current.activeStack, + ); + check( + 'the hint says SWAP trades the sides (VS BASEMAP)', + current.hintText === 'Drag the divider · SWAP trades sides', + current.hintText, + ); + await checkLayout('vs basemap'); + await tilesSettled(); + await shot('03-vs-basemap'); + await panelShot('03-vs-basemap-panel'); + + // ── A / B: pin A, preview then pin B, swipe, SWAP, unpin ──────────────── + check('A / B is one click', await clickMode('ab')); + current = await state(); + check( + 'A / B keeps the pin as A and waits for B', + current.mode === 'ab' && + current.pinA === targetKey && + !current.splitVisible && + /^A.+×$/.test(current.rowA) && + current.rowB === 'BNot set×', + `${current.rowA} | ${current.rowB}`, + ); + const chipLabels = await page.evaluate( + (key) => + [ + ...document.querySelectorAll( + `#recent-imagery-panel .ri-card[data-key="${key}"] .ri-chip`, + ), + ].map((chip) => chip.textContent), + targetKey, + ); + check( + 'the cards now carry A and B chips', + JSON.stringify(chipLabels) === '["A","B"]', + JSON.stringify(chipLabels), + ); + await checkLayout('A / B, A pinned'); + const secondIndex = (await state()).candidates.findIndex( + (c) => c.key !== targetKey && c.drapable, + ); + const secondKey = current.candidates[secondIndex]?.key; + await focusStrip(); + await page.keyboard.press('Home'); + for (let i = 0; i < secondIndex; i += 1) + await page.keyboard.press('ArrowRight'); + check( + 'arrows preview the other day as B against A', + await until( + (key) => { + const snap = window.__riQa.snap(); + return snap.preview.key === key && snap.preview.slot === 'b'; + }, + secondKey, + 3_000, + ), + secondKey, + ); + await page.keyboard.press('b'); + const abSwipe = await until( + (key) => + window.__riQa.snap().pins.b.key === key && + window.__riQa.snap().shown.swipe === 'ab' && + window.__riQa.splitShown(), + secondKey, + ); + current = await state(); + check( + 'B pins the second day and the divider reads A / B', + abSwipe && JSON.stringify(current.splitLabels) === '["A","B"]', + JSON.stringify(current.splitLabels), + ); + check( + 'two owned layers: A left, B right', + current.diagnostics.ownedCount === 2 && + JSON.stringify([...current.gibsSplits].sort()) === '[-1,1]', + hostsDetail(current), + ); + check( + 'the divider recentres for the new comparison', + Math.abs(current.splitPosition - 0.5) < 0.01, + String(current.splitPosition), + ); + check( + 'row B reads the pinned day', + /^B.+×$/.test(current.rowB) && !/Not set/.test(current.rowB), + current.rowB, + ); + onPhotorealOnly( + 'the A / B swipe runs on Esri', + current.activeStack === 'esri-imagery', + current.activeStack, + ); + check( + 'the hint says SWAP trades the sides (A / B)', + current.hintText === 'Drag the divider · SWAP trades sides', + current.hintText, + ); + await checkLayout('A / B, both pinned'); + await tilesSettled(); + await shot('04-ab'); + await panelShot('04-ab-panel'); + // SWAP trades the sides (Space is push-to-talk, so no key does this). + const splitBeforeSwap = current.splitPosition; + check('SWAP is one click while the swipe is live', await click('#ri-swap')); + const swapped = await until( + () => + window.__riQa.snap().swapped === true && + document.querySelector('#recent-imagery-split-line span.before') + ?.textContent === 'B', + ); + current = await state(); + check( + 'SWAP trades the divider labels to B / A and keeps the divider where it was', + swapped && + JSON.stringify(current.splitLabels) === '["B","A"]' && + JSON.stringify([...current.gibsSplits].sort()) === '[-1,1]' && + Math.abs(current.splitPosition - splitBeforeSwap) < 0.01, + `${JSON.stringify(current.splitLabels)} ${hostsDetail(current)} split=${current.splitPosition}`, + ); + await checkLayout('A / B, swapped'); + check('SWAP again is one click', await click('#ri-swap')); + const restored = await until( + () => + window.__riQa.snap().swapped === false && + document.querySelector('#recent-imagery-split-line span.before') + ?.textContent === 'A', + ); + current = await state(); + check( + 'SWAP again restores A / B', + restored && JSON.stringify(current.splitLabels) === '["A","B"]', + JSON.stringify(current.splitLabels), + ); + check('B unpins from its ×', await click('#ri-unpin-b')); + const singleA = await until( + () => + window.__riQa.owned() === 1 && + !document.getElementById('recent-imagery-split-line'), + ); + current = await state(); + check( + 'unpinning B drops its layer at once: A alone, no divider', + singleA && current.shown.a === targetKey && !current.shown.b, + hostsDetail(current), + ); + check( + 'without a swipe SWAP keeps its slot, disabled and invisible', + await page.evaluate(() => { + const swap = document.getElementById('ri-swap'); + return Boolean( + swap?.disabled && + swap.classList.contains('is-reserved') && + getComputedStyle(swap).visibility === 'hidden', + ); + }), + ); + onPhotorealOnly( + 'A alone stays on Esri', + current.activeStack === 'esri-imagery', + current.activeStack, + ); + await checkLayout('B unpinned'); + check('A unpins from its ×', await click('#ri-unpin-a')); + check('with nothing shown, no layer remains', await ownedIs(0)); + onPhotorealOnly( + 'with nothing shown, Google 3D comes back', + await backOnPhotoreal(), + ); + await checkLayout('A unpinned'); + + // ── the share link carries the pins and the mode ──────────────────────── + await clickMode('basemap'); + await pressOnStrip('a'); + const shared = await until( + () => { + const params = new URLSearchParams(window.location.hash.slice(1)); + const layers = (params.get('l') || '').split('.'); + const options = params.get('lo') || ''; + return ( + layers.includes('1') && + /(^|_)1\.a\.[SLV]\d{8}/.test(options) && + /(^|_)1\.m\.1(_|$)/.test(options) && + /(^|_)1\.w\.-?\d+/.test(options) + ); + }, + undefined, + 8_000, + ); + check( + 'the share link carries the layer, the box, the pin and the mode', + shared, + await page.evaluate(() => window.location.hash.slice(0, 400)), + ); + + // ── Escape order: preview, then the box tool ──────────────────────────── + await click('#ri-unpin-a'); + await clickMode('image'); + await ownedIs(0); + await focusStrip(); + await page.keyboard.press('ArrowRight'); + check( + 'a focus move previews again', + await until( + () => Boolean(window.__riQa.snap().preview.key), + undefined, + 5_000, + ), + ); + check( + 'SELECT BOX arms the box tool', + (await clickAction('select-box')) && + (await until(() => window.__gevRecentImagery.tool.isActive())), + ); + await page.keyboard.press('Escape'); + const escapedPreview = await until( + () => !window.__riQa.snap().preview.key, + undefined, + 3_000, + ); + const stillArmed = await page.evaluate(() => + window.__gevRecentImagery.tool.isActive(), + ); + check( + 'Escape clears the preview first and leaves SELECT BOX armed', + escapedPreview && stillArmed, + `preview cleared=${escapedPreview} toolActive=${stillArmed}`, + ); + await page.keyboard.press('Escape'); + check( + 'the next Escape cancels the box tool', + await until(() => !window.__gevRecentImagery.tool.isActive()), + ); + onPhotorealOnly( + 'with the preview cleared Google 3D comes back', + await backOnPhotoreal(), + ); + + // ── oversized USE VIEW → refusal in the notice line ───────────────────── + let refusalWidth = 0; + for (const height of [400_000, 900_000, 1_800_000]) { + await setView({ ...AUSTIN, height }); + await wait(300); + refusalWidth = await viewWidthKm(); + if (refusalWidth > 1_100) break; + } + const boxBefore = JSON.stringify((await state()).box); + await clickAction('use-view'); + const refused = await until( + () => + /^View is/.test( + document.getElementById('ri-notice-text')?.textContent || '', + ), + undefined, + 5_000, + ); + current = await state(); + check( + `an oversized USE VIEW (${Math.round(refusalWidth)} km) is refused in the notice line`, + refused && + /^View is [\d,]+ km wide · limit 1,000 km$/.test(current.noticeText), + current.noticeText, + ); + check( + 'the hint says to zoom in or draw a smaller box', + current.hintText === 'Zoom in or draw a smaller box', + current.hintText, + ); + check('the refusal keeps the box', JSON.stringify(current.box) === boxBefore); + const refusalLine = await page.evaluate(() => { + const text = document.getElementById('ri-notice-text'); + const chip = document.getElementById('ri-zoom-in'); + const line = document.getElementById('ri-notice').getBoundingClientRect(); + const rect = chip.getBoundingClientRect(); + return { + fits: text.scrollWidth <= text.clientWidth, + scrollWidth: text.scrollWidth, + clientWidth: text.clientWidth, + chipVisible: + getComputedStyle(chip).visibility === 'visible' && + !chip.disabled && + rect.width > 0, + chipAtEnd: Math.abs(rect.right - line.right) <= 1, + lineHeight: line.height, + }; + }); + check( + 'the refusal fits the notice line without an ellipsis', + refusalLine.fits, + JSON.stringify(refusalLine), + ); + check( + 'ZOOM IN shows at the right end of the notice line, which keeps its height', + refusalLine.chipVisible && + refusalLine.chipAtEnd && + Math.abs(refusalLine.lineHeight - 14) <= 0.5, + JSON.stringify(refusalLine), + ); + await checkLayout('refused'); + await panelShot('05-refused-panel'); + // ZOOM IN: straight down to the height whose view is 400 km wide. + const fitHeight = await page.evaluate(() => { + const viewer = window.__godsEyeView.viewer; + const canvas = viewer.scene.canvas; + const halfWidth = + Math.tan(viewer.camera.frustum.fovy / 2) * + (canvas.clientWidth / canvas.clientHeight); + return Math.min(400, Math.max(5, 400 / (2 * halfWidth))) * 1000; + }); + check('ZOOM IN is clickable', await click('#ri-zoom-in')); + const zoomed = await until( + (target) => + Math.abs( + window.__godsEyeView.viewer.camera.positionCartographic.height - target, + ) <= + target * 0.01, + fitHeight, + 2_000, + ); + const zoomedHeight = await page.evaluate( + () => window.__godsEyeView.viewer.camera.positionCartographic.height, + ); + check( + `ZOOM IN flies to ${Math.round(fitHeight / 1000)} km within 2 s`, + zoomed, + `height=${Math.round(zoomedHeight)} target=${Math.round(fitHeight)}`, + ); + await tilesSettled(); + const fittedWidth = await viewWidthKm(); + await clickAction('use-view'); + const fitted = await until( + () => { + const snap = window.__riQa.snap(); + return Boolean(snap.box) && !snap.boxError && !snap.zoomToFit; + }, + undefined, + 5_000, + ); + current = await state(); + check( + `the next USE VIEW (${Math.round(fittedWidth)} km) succeeds and ZOOM IN is reserved again`, + fitted && + (await page.evaluate(() => + document.getElementById('ri-zoom-in').classList.contains('is-reserved'), + )), + `boxError=${current.boxError} notice=${current.noticeText}`, + ); + await checkLayout('fitted'); + + // ── CLEAR ──────────────────────────────────────────────────────────────── + await setView(AUSTIN); + await pressOnStrip('ArrowRight'); + await until(() => window.__riQa.owned() === 1, undefined, 5_000); + await clickAction('clear'); + const clearedAll = await until(() => { + const snap = window.__riQa.snap(); + return ( + !snap.box && + !snap.pins.a.key && + !snap.pins.b.key && + !snap.preview.key && + window.__riQa.owned() === 0 + ); + }); + current = await state(); + check( + 'CLEAR empties the box, the pins and the preview', + clearedAll && current.noticeText === 'Box and images cleared', + `box=${JSON.stringify(current.box)} owned=${current.diagnostics.ownedCount} notice=${current.noticeText}`, + ); + onPhotorealOnly('CLEAR hands Google 3D back', await backOnPhotoreal()); + await wait(1_500); + onPhotorealOnly( + 'after CLEAR the layer does not take Esri again', + (await page.evaluate(() => window.__riQa.activeStack())) === 'photoreal', + ); + await checkLayout('cleared'); + + // ── map-switch rebind ─────────────────────────────────────────────────── + await tilesSettled(); + await page.evaluate( + (view) => window.__riQa.layer().boxFromPinAt(view.lon, view.lat), + AUSTIN, + ); + const redraped = await until(() => { + const snap = window.__riQa.snap(); + return ( + !snap.searching && + Boolean(snap.preview.key) && + window.__riQa.owned() === 1 + ); + }); + check('a 10 km box previews the START HERE day again', redraped); + const stacks = await page.evaluate(() => + window.__godsEyeView.mapStackController + .getStacks() + .filter((s) => s.available) + .map((s) => s.id), + ); + const setStack = (id) => + page.evaluate( + (stack) => window.__godsEyeView.mapStackController.setStack(stack), + id, + ); + /** Wait for the one GIBS drape to sit on the given host only. */ + const drapeOn = (host) => + until( + (where) => { + const hosts = window.__riQa.hosts(); + return where === 'globe' + ? hosts.globeShown && hosts.globe === 1 && hosts.tileset === 0 + : !hosts.globeShown && hosts.globe === 0 && hosts.tileset === 1; + }, + host, + 10_000, + ); + if (photoreal && stacks.includes('esri-imagery')) { + check('the preview sits on the Esri globe', await drapeOn('globe')); + // While a day is shown the imagery keeps Esri: a manual switch to + // Google 3D is answered at once with a new lease. + await setStack('photoreal'); + const kept = (await onEsri()) && (await drapeOn('globe')); + current = await state(); + check( + 'switching to Google 3D by hand while a day is shown keeps the imagery on the Esri globe', + kept && current.diagnostics.host === 'globe', + `${hostsDetail(current)} stack=${current.activeStack}`, + ); + check( + 'the notice says the imagery stays on Esri until CLEAR, and fits', + current.noticeText === 'Imagery stays on Esri · CLEAR to use Google 3D' && + (await page.evaluate(() => { + const text = document.getElementById('ri-notice-text'); + return text.scrollWidth <= text.clientWidth; + })), + current.noticeText, + ); + await wait(1_500); + check( + 'Esri holds after the re-lease: no switch loop', + (await page.evaluate(() => window.__riQa.activeStack())) === + 'esri-imagery', + ); + // The divider survives a manual switch too. + await clickMode('basemap'); + await until(() => window.__riQa.splitShown(), undefined, 10_000); + await setStack('photoreal'); + const dividerKept = + (await onEsri()) && + (await until( + () => + window.__riQa.splitShown() && window.__riQa.snap().comparison.active, + undefined, + 10_000, + )); + current = await state(); + check( + 'a manual switch to Google 3D during VS BASEMAP keeps the divider', + dividerKept && + current.shown.swipe === 'basemap' && + !current.comparison.suspended, + `${hostsDetail(current)} stack=${current.activeStack} comparison=${JSON.stringify(current.comparison)}`, + ); + await tilesSettled(); + await shot('06-google-3d-kept-on-esri'); + await clickMode('image'); + await until(() => !window.__riQa.splitShown(), undefined, 5_000); + } else { + const other = stacks.find( + (id) => id !== initialStack && id !== 'photoreal', + ); + if (other) { + await setStack(other); + check( + `switching to ${other} keeps the drape on the globe`, + await drapeOn('globe'), + ); + await setStack(initialStack); + } else { + console.log('[SKIP] map-switch rebind — no second map stack available'); + } + } + + // ── collapse / expand, CCTV stability, DISPLAY + CONTEXT reachable ────── + /** Click a panel's collapse button; resolves to whether it is expanded. */ + const togglePanel = (id) => + page.evaluate((panelId) => { + const button = document.querySelector( + `.panel-collapse-btn[data-collapse-target="${panelId}"]`, + ); + if (!button) return null; + button.click(); + return !document.getElementById(panelId)?.classList.contains('collapsed'); + }, id); + const imageryPanel = 'recent-imagery-panel'; + const collapsedNow = (await togglePanel(imageryPanel)) === false; + await wait(400); + const headerOnly = await page.evaluate(() => ({ + panel: document.getElementById('recent-imagery-panel')?.offsetHeight, + body: document.getElementById('recent-imagery-panel-body')?.offsetHeight, + })); + check( + 'collapsing the panel leaves a header bar only', + collapsedNow && + headerOnly.body === 0 && + headerOnly.panel > 0 && + headerOnly.panel <= 80, + JSON.stringify(headerOnly), + ); + const expandedAgain = await togglePanel(imageryPanel); + await wait(400); + const bodyBack = await page.evaluate( + () => document.getElementById('recent-imagery-panel-body')?.offsetHeight, + ); + check( + 'expanding the panel brings the body back', + expandedAgain === true && bodyBack > 0, + `body=${bodyBack}`, + ); + + /** Sample both panel heights for 2 s; settled = the tail never changes. */ + const settledHeights = async () => { + const samples = []; + for (let i = 0; i < 20; i += 1) { + samples.push( + await page.evaluate(() => ({ + imagery: document.getElementById('recent-imagery-panel') + ?.offsetHeight, + cctv: document.getElementById('cctv-panel')?.offsetHeight, + })), + ); + await wait(100); + } + const tail = (key) => new Set(samples.slice(8).map((s) => s[key])); + return { + settled: tail('imagery').size === 1 && tail('cctv').size === 1, + detail: `imagery=${samples.map((s) => s.imagery).join(',')} cctv=${samples.map((s) => s.cctv).join(',')}`, + }; + }; + const railFit = () => + page.evaluate(() => { + const px = (element) => + parseFloat( + element?.style.getPropertyValue('--right-panel-allocated-height'), + ); + const cctv = document.getElementById('cctv-panel'); + const imagery = document.getElementById('recent-imagery-panel'); + const rail = document.getElementById('right-context-rail'); + // Reachable: its header is on screen, or the rail's exclusive policy + // (an expanded panel under the tactical HUD) hid it while collapsed. + const reach = (id) => { + const element = document.getElementById(id); + return ( + window.__riQa.headerOnScreen(id) || + (rail?.classList.contains('layout-exclusive') && + element?.classList.contains('collapsed') && + element.getBoundingClientRect().height === 0) + ); + }; + return { + cctvRendered: cctv?.offsetHeight ?? null, + cctvAllocated: px(cctv), + imageryRendered: imagery?.offsetHeight ?? null, + imageryAllocated: px(imagery), + imageryCollapsed: Boolean(imagery?.classList.contains('collapsed')), + imageryDisplay: imagery ? getComputedStyle(imagery).display : null, + focus: rail?.classList.contains('layout-focus'), + exclusive: rail?.classList.contains('layout-exclusive'), + display: reach('pp-toggles'), + context: reach('global-context-panel'), + }; + }); + for (const height of [900, 700]) { + const at = `(${height} px viewport)`; + await page.setViewport({ width: 1280, height }); + await wait(600); + check( + `the CCTV panel expands from its launcher ${at}`, + (await togglePanel('cctv-panel')) === true, + ); + const expanded = await settledHeights(); + check( + `the imagery and CCTV panel heights settle with CCTV expanded ${at}`, + expanded.settled, + expanded.detail, + ); + const fit = await railFit(); + check( + `CCTV renders at its allocated height beside the imagery panel ${at}`, + !fit.focus || + (Number.isFinite(fit.cctvAllocated) && + Math.abs(fit.cctvRendered - fit.cctvAllocated) <= 2), + JSON.stringify(fit), + ); + // A collapsed panel has no allocation, so it is judged on its own terms: + // the exclusive rail (one expanded panel) hides it outright, otherwise it + // is a header bar. An expanded panel must have been allocated a height. + const imageryFits = fit.imageryCollapsed + ? fit.exclusive + ? fit.imageryRendered === 0 && fit.imageryDisplay === 'none' + : fit.imageryRendered > 0 && fit.imageryRendered <= 80 + : !fit.focus || + (Number.isFinite(fit.imageryAllocated) && + fit.imageryRendered <= fit.imageryAllocated + 2); + check( + `the imagery panel stays within its allocation, or takes no room when the exclusive rail hides it collapsed ${at}`, + imageryFits, + JSON.stringify(fit), + ); + check( + `DISPLAY and CONTEXT stay reachable ${at}`, + fit.display && fit.context, + JSON.stringify(fit), + ); + await shot(`07-cctv-expanded-${height}`); + check( + `the CCTV panel collapses again ${at}`, + (await togglePanel('cctv-panel')) === false, + ); + const collapsed = await settledHeights(); + check( + `the panel heights settle with CCTV collapsed ${at}`, + collapsed.settled, + collapsed.detail, + ); + const imageryExpanded = await page.evaluate( + () => + !document + .getElementById('recent-imagery-panel') + ?.classList.contains('collapsed'), + ); + if (imageryExpanded) await togglePanel(imageryPanel); + await wait(400); + const onScreen = await page.evaluate(() => + Object.fromEntries( + [ + 'pp-toggles', + 'global-context-panel', + 'recent-imagery-panel', + 'cctv-panel', + ].map((id) => [id, window.__riQa.headerOnScreen(id)]), + ), + ); + check( + `DISPLAY, CONTEXT, CCTV and the imagery header are all on screen once everything is collapsed ${at}`, + Object.values(onScreen).every(Boolean), + JSON.stringify(onScreen), + ); + await togglePanel(imageryPanel); + await wait(400); + } + + // ── scroll preservation (700 px viewport, body scrollable) ─────────────── + await page.evaluate(() => { + const header = document.querySelector('#ri-details .rail-card-header'); + if (header?.getAttribute('aria-expanded') !== 'true') header?.click(); + }); + await wait(300); + const bodyScroll = () => + page.evaluate(() => { + const body = document.getElementById('recent-imagery-panel-body'); + return { + top: body.scrollTop, + max: body.scrollHeight - body.clientHeight, + }; + }); + const start = await page.evaluate(() => { + const body = document.getElementById('recent-imagery-panel-body'); + const max = body.scrollHeight - body.clientHeight; + if (max > 0) body.scrollTop = Math.round(max / 2); + return { max, top: body.scrollTop }; + }); + check( + 'with DETAILS open at 700 px the body scrolls', + start.max > 0, + JSON.stringify(start), + ); + if (start.max > 0) { + await page.evaluate(() => { + const layer = window.__riQa.layer(); + layer.setAlpha(0.9); + layer.setToolActive(true); + layer.setToolActive(false); + }); + await wait(300); + const afterNotify = await bodyScroll(); + check( + 'the body scroll position survives alpha and state notifications', + Math.abs(afterNotify.top - start.top) <= 1, + `before=${start.top} after=${afterNotify.top}`, + ); + await focusStrip(); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('ArrowRight'); + await wait(600); + const afterArrows = await bodyScroll(); + check( + 'the body scroll position survives arrow navigation', + Math.abs(afterArrows.top - start.top) <= 1, + `before=${start.top} after=${JSON.stringify(afterArrows)}`, + ); + await shot('08-scrolled'); + } + await page.setViewport({ width: 1280, height: 860 }); + + // ── disable ─────────────────────────────────────────────────────────────── + await click(layerToggle); + check( + 'the layer disables from its toggle', + await until( + () => !window.__godsEyeView.dataManager.isEnabled('recent-imagery'), + ), + ); + const cleared = await until(() => { + const hosts = window.__riQa.hosts(); + return ( + window.__riQa.owned() === 0 && + hosts.globe + hosts.tileset === 0 && + !document.getElementById('recent-imagery-split-line') + ); + }); + current = await state(); + check( + 'disabling leaves zero owned layers and no split line', + cleared, + `${hostsDetail(current)} split=${current.splitVisible}`, + ); + check('the panel hides when the layer is off', current.panelHidden === true); + onPhotorealOnly('disabling hands Google 3D back', await backOnPhotoreal()); + await wait(1_500); + onPhotorealOnly( + 'disabled, the layer never takes Esri again', + (await page.evaluate(() => window.__riQa.activeStack())) === 'photoreal', + ); + await shot('09-disabled'); + + check( + 'no page errors during the run', + errors.length === 0, + errors.join(' | '), + ); +} catch (error) { + check( + 'run completed', + false, + error?.stack || error?.message || String(error), + ); +} finally { + await browser.close(); +} +console.log(`shots: ${shots.join(', ')}`); +console.log(`RESULT: ${checks} checks, ${failures} failures`); +process.exitCode = failures ? 1 : 0; diff --git a/scripts/qa-weather-journey.mjs b/scripts/qa-weather-journey.mjs new file mode 100644 index 000000000..75cd2c269 --- /dev/null +++ b/scripts/qa-weather-journey.mjs @@ -0,0 +1,423 @@ +#!/usr/bin/env node +/** + * qa-weather-journey — drive the Weather layers the way a person would and + * keep the evidence: numbered screenshots plus per-step layer diagnostics. + * + * Starts at the Earth view, opens Data Layers, switches Wind on from its real + * row button, cycles the wind fields/models, switches radar, satellite clouds, + * lightning and cyclones on, follows "View storm" and "View US radar", zooms + * into a regional view, a city view and a street view, replays history, and + * ends with real wheel/drag input. Every step records the enabled layers' + * diagnostics (imagery tiles loaded, shown observation time, wind geometry) + * and a 2 s `scene.postRender` count so a stalled renderer cannot pass as a + * healthy screenshot. + * + * Usage: + * node scripts/qa-weather-journey.mjs [--url http://localhost:4173] + * [--label google] [--headless] [--out qa-shots/weather-journey] + * + * Requires a running dev server. Screenshots and steps.json land in + * /