diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..174f7990a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,24 @@ +# Keep keys and local state out of the build context: compose bind-mounts the +# checkout at run time, so the image never needs them. +.git +node_modules +dist +.env +.env.* +!.env.example +**/ENVIRONMENT +pinokio/ENVIRONMENT +pinokio/.installed +.gev-cache +.gev-logs +qa-artifacts +qa-shots +screenshots +output +3d-models +.gstack +*.log +.DS_Store +# AppleDouble sidecars from a macOS `tar` copy; `npm test` would otherwise +# collect `._*.test.mjs` as test files. +._* diff --git a/.env.example b/.env.example index c89680b30..c9700c5be 100644 --- a/.env.example +++ b/.env.example @@ -18,7 +18,8 @@ # (they're used client-side) and WILL be visible in devtools. Restrict/scope them rather than trying to hide # them (see SECURITY.md). All other keys below stay server-side. -# Optional: direct Google Photorealistic 3D Tiles and GEV place search. +# Optional: direct Google Photorealistic 3D Tiles, GEV place search and Street +# View (Street View also needs the Maps JavaScript API enabled for the key). # Without it, a Cesium ion token can still load ion-hosted Google 3D; with # neither credential, the app starts on keyless Esri World Imagery with OSM # available in the map tray and as the automatic provider-failure fallback. @@ -82,6 +83,12 @@ OPENAI_REALTIME_TRANSCRIBE_MODEL=gpt-4o-mini-transcribe # keep them while debugging; delete the log when you are done. GEV_VOICE_LOG_CONTENT= OPENAI_HUD_SUMMARY_MODEL=gpt-5-nano +# Optional: Gemini Live voice, selected in the GEV MIC provider chooser. +# Server-only key. Do not prefix with VITE_. Provider Settings can save it. +GEMINI_API_KEY= +GEMINI_LIVE_MODEL=gemini-3.8-live +# Token starts per IP per minute; 0 disables the throttle, not provider quotas. +# GEV_RATELIMIT_GEMINI_PER_MIN=30 # Per-IP rate limit for the OpenAI cost endpoints # (/api/realtime/token + /api/openai/hud-summary), in requests per minute. # DEFAULTS TO 30, the value the Pinokio build also ships. That clears ordinary @@ -95,13 +102,21 @@ OPENAI_HUD_SUMMARY_MODEL=gpt-5-nano # spend protection set a provider-side budget: OpenAI platform -> Settings -> # Limits (usage limits). # GEV_RATELIMIT_OPENAI_PER_MIN=30 # the default; uncomment only to change it +# Optional: exact socket addresses (comma-separated, no wildcards or prefixes) +# that Provider Settings treats as this machine in addition to loopback. Leave +# unset. The Docker launcher sets it to the container's gateway at start, +# because that is where Docker delivers your own browser from; it is safe only +# while the port is published on 127.0.0.1. Read SECURITY.md before setting it +# by hand. +# GEV_KEY_SETUP_TRUSTED_PEERS= # Optional: Mapillary imagery for the Street Level layer. Free client token from # https://www.mapillary.com/dashboard/developers (register an app, copy its # Client Token). Client-exposed by design, like GOOGLE_MAPS_API_KEY. MAPILLARY_CLIENT_TOKEN= -# Optional: OpenSky auth mode (oauth | basic | auto | anon) +# Optional: OpenSky auth mode (oauth | auto | anon). OpenSky retired +# username/password (basic) sign-in on 2026-03-18; "basic" now loads anonymously. # Default: oauth — requires client credentials below # Set to "anon" to skip aircraft auth (rate-limited but works) OPENSKY_AUTH_MODE=oauth @@ -110,11 +125,13 @@ OPENSKY_AUTH_MODE=oauth OPENSKY_CLIENT_ID= OPENSKY_CLIENT_SECRET= -# Optional: higher Launch Library 2 request allowance. Public access works -# without a token. +# Launch Library 2: leave blank for standard public access (no key needed). +# Optional paid Patreon tokens raise request limits; there is no free API key. LL2_API_TOKEN= -# Optional: OpenSky credentials JSON file path (alternative to above) +# Optional: OpenSky credentials JSON file path, used when the two values above +# are empty: the credentials.json your OpenSky account page downloads when you +# create an API client. Use an absolute path for compatibility with launchers. # OPENSKY_CREDENTIALS_FILE=/path/to/credentials.json # Optional: dev server config @@ -193,6 +210,7 @@ AISSTREAM_API_KEY= # CCTV_TFL_ENABLED=1 # set 0 to disable Transport for London JamCams # CCTV_TFL_MAX_SOURCES=250 # cap cameras loaded from TfL # CCTV_ONTARIO_ENABLED=1 # set 0 to disable Ontario 511 cameras +# ONTARIO_511_API_KEY= # free developer key: sign up at 511on.ca/my511/register, then request it at 511on.ca/developers/doc # CCTV_ONTARIO_MAX_SOURCES=1000 # cap cameras loaded from Ontario 511 # CCTV_FINTRAFFIC_ENABLED=1 # set 0 to drop the Fintraffic (Finland) pack # CCTV_FINTRAFFIC_MAX_SOURCES=300 # cap cameras loaded from the Fintraffic catalog @@ -211,10 +229,35 @@ AISSTREAM_API_KEY= # CCTV_CALGARY_ENABLED=1 # set 0 to disable the Open Calgary (Alberta) cameras # CCTV_CALGARY_MAX_SOURCES=220 # cap cameras loaded from the Open Calgary catalog # CCTV_CALGARY_ROWS_URL= # override the Open Calgary catalog URL +# CCTV_CATALONIA_ENABLED=1 # set 0 to disable the Servei Català de Trànsit cameras +# CCTV_CATALONIA_MAX_SOURCES=150 # cap cameras loaded from Catalonia (~130 exist today) +# CCTV_HK_ENABLED=1 # set 0 to disable the Hong Kong Transport Department cameras +# CCTV_HK_MAX_SOURCES=1100 # cap cameras loaded from Hong Kong (~1,013 exist today); min 8, max 1200 +# CCTV_HK_CAMERAS_URL= # override the DATA.GOV.HK camera locations XML URL +# CCTV_KINGCOUNTY_ENABLED=1 # set 0 to disable the King County (Washington) road cameras +# CCTV_KINGCOUNTY_MAX_SOURCES=125 # cap cameras loaded from the King County catalog +# CCTV_WSDOT_ENABLED=1 # set 0 to disable the WSDOT (Washington State) highway cameras +# CCTV_WSDOT_MAX_SOURCES=250 # cap cameras loaded from the WSDOT catalog, nearest Seattle/Spokane first; min 8, max 1200 # CCTV_VEGVESEN_ENABLED=1 # set 0 to disable the Statens vegvesen (Norway) road cameras # CCTV_VEGVESEN_MAX_SOURCES=900 # cap cameras loaded from Statens vegvesen (default loads all ~850 live; max 1000) # CCTV_VEGVESEN_VIDEO=1 # set 0 to show stills instead of live HLS for Statens vegvesen video cameras +# CCTV_VEGVESEN_HEIGHTS=1 # set 0 to skip Kartverket ground heights for Statens vegvesen cameras (flat prior instead) # CCTV_VEGVESEN_URL= # override the Statens vegvesen catalog URL +# CCTV_NYC_ENABLED= # off by default; set 1 only if you hold a NYC DOT data-sharing agreement (tmcdot@dot.nyc.gov) for the camera feed +# CCTV_NYC_MAX_SOURCES=250 # cap cameras loaded from the NYC TMC catalog (nearest borough cores first) +# CCTV_NYC_CAMERAS_URL= # override the NYC TMC catalog URL +# CCTV_TORONTO_ENABLED=1 # set 0 to disable the City of Toronto RESCU cameras +# CCTV_TORONTO_MAX_SOURCES=336 # cap cameras loaded from Toronto RESCU (clamped to 8–500) +# CCTV_TORONTO_LIST_URL= # override the Toronto RESCU camera list URL +# CCTV_LITHUANIA_ENABLED= # off by default; set 1 to load Via Lietuva / Eismoinfo road cameras (photo licence unconfirmed; see DATA_SOURCES.md) +# CCTV_LITHUANIA_MAX_SOURCES=400 # cap Lithuanian cameras; no API key required +# CCTV_FLORIDA_ENABLED= # off by default; set 1 to load FL511 (Florida) cameras (individual, personal use only; any other use, including a public deployment, needs FDOT's express written consent; see DATA_SOURCES.md) +# CCTV_FLORIDA_MAX_SOURCES=500 # cap cameras loaded from the FL511 catalog (nearest regional anchors first) +# CCTV_TAIWAN_ENABLED=1 # set 0 to skip Taiwan Freeway Bureau (MOTC) road cameras +# CCTV_TAIWAN_MAX_SOURCES=600 # cap Taiwan freeway cameras (1-2000); no API key required +# CCTV_TAIWAN_URL= # override the Freeway Bureau MOTC 2.0 CCTV.xml URL +# CCTV_A22_ENABLED=1 # set 0 to disable the Autostrada del Brennero (A22, Italy) webcams +# CCTV_A22_URL= # override the Open Data Hub A22 webcam catalog URL # CCTV_MAX_SOURCES=4000 # catalog-wide ceiling, shared round-robin across packs # CCTV_PREFER_AUSTIN=1 # prioritize Austin cameras in the registry # CCTV_FORCE_AUSTIN= # force live default sources when a source-pack JSON is configured diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000..e8c9f8bdf --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,59 @@ +## What this changes + + + +## How I verified it + +- [ ] `npm run build` +- [ ] `npm test` +- [ ] `npm run test:track` (dev server running) +- [ ] Feature gate for the area I touched: + + + +## New layer checklist + + + +**Screenshots** + + + +**Recording** + + + +**Proposed category** + + + +Category: + +**Data source and licence** + +- Source (provider and endpoint): +- Licence or terms (link): +- Attribution shown in the app: +- Needs a key? (none / optional / required): +- Fetched at runtime, or bundled in the repo: + + + +- [ ] Added a row to `DATA_SOURCES.md` +- [ ] Credit is registered in `src/data/dataCredits.js` +- [ ] Share-link token assigned with `npm run layer-token:next`, if the layer is shareable + +## Docs + +- [ ] `docs/CURRENT-STATE.md` updated and a `changelog.d/-.md` fragment added, or this PR doesn't change runtime behaviour diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 375bc9077..ce3563685 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,8 +67,6 @@ jobs: timeout-minutes: 30 env: GEV_REQUIRE_ALLOCATION_GATE: '0' - # Fail on a missed header press unless the panel itself moved. - QA_FAIL_ON_RETRY: '1' steps: - name: Check out source uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 @@ -104,10 +102,6 @@ jobs: - name: Street Level gate with Mapillary fixtures run: npm run qa:street-level:fixtures -- --strict --url http://localhost:4173 - - name: Portable panel gate - if: success() || failure() - run: npm run qa:panel-resize -- --url http://localhost:4173 - - name: Preview server log if: failure() run: cat preview.log @@ -150,7 +144,7 @@ jobs: run: npm run check:boundaries - name: Run focused onboarding tests - run: node --test src/setupDoctor.test.mjs src/pinokioEnvironment.test.mjs src/pinokioPreflight.test.mjs src/pinokioLauncherContract.test.mjs src/keySetupHardening.test.mjs src/mapStartup.test.mjs src/hudSummaryResponse.test.mjs + run: node --test src/setupDoctor.test.mjs src/pinokioEnvironment.test.mjs src/pinokioPreflight.test.mjs src/pinokioLauncherContract.test.mjs src/keySetupHardening.test.mjs src/mapStartup.test.mjs src/hudSummaryResponse.test.mjs src/codexOauthRealtime.test.mjs - name: Build production bundle run: npm run build diff --git a/.gitignore b/.gitignore index 14e8d320b..11e081e7d 100644 --- a/.gitignore +++ b/.gitignore @@ -16,8 +16,15 @@ output/ .gev-cache/ # Browser QA gate evidence (screenshots, console and network dumps). qa-artifacts/ +# Playwright MCP session logs: browser consoles can carry tokens in URLs. +.playwright-mcp/ +# Local Claude Code settings and preview configs. +.claude/ .DS_Store .gstack/ 3d-models/ pinokio/ENVIRONMENT pinokio/.installed + +# Transient: a release interrupted mid-assembly (npm run changelog recovers it) +changelog.d/.assembling/ diff --git a/.prettierignore b/.prettierignore index 1aaad8a03..2b2cc755a 100644 --- a/.prettierignore +++ b/.prettierignore @@ -20,3 +20,8 @@ node_modules .vite .vite-* *.min.js + +# Application views, and panels lifted from them, hold the page markup +# verbatim; reflowing it changes the DOM +src/ui/views/*View.vue +src/ui/views/panels/ diff --git a/.prettierrc.json b/.prettierrc.json index b1e6b2baf..095bf4e98 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -2,5 +2,11 @@ "singleQuote": true, "tabWidth": 2, "semi": true, - "endOfLine": "lf" + "endOfLine": "lf", + "overrides": [ + { + "files": "*.vue", + "options": { "htmlWhitespaceSensitivity": "strict" } + } + ] } diff --git a/CHANGELOG.md b/CHANGELOG.md index 68ab1c52d..356289841 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,890 @@ # Changelog +## [Unreleased] + +## [0.3.0] — 2026-10-27 — Street Level, On Your Phone, in Your Language + +- Show a Street Level view facing 359.5° or more as 0°. The viewer caption + rounded the bearing without wrapping, so a view facing 359.6° read "360°" + (Aditya, @Rohilalala, #1431). + +- The visual styles and their presets mark their labels with the catalog-free + `msg()`, so the share-link codec, and any server that loads it, no longer + bundles every translation catalog (about 0.9 MB) (samehkhamis, #1421). + +- Keep a location search that found nothing, or failed, in the field so it can + be corrected: the query stays, focused and selected, and a persistent + announced message under the search row says what to do next, instead of a + toast followed by a cleared and closed field (samehkhamis, #1420). + +- Hosts can read share links on their server: the share-link codec and the + `/share/` address helpers are now package exports, + `@gods-eye-view/core/share/view-codec` and `@gods-eye-view/core/share/link-path` + (samehkhamis, #1419). + +- Share links are now short: the share button makes `/share/` links + that open on any copy of the app, follow the aircraft, military aircraft or + satellite you were following, and fall back to its last-known position with + a notice if it isn't reporting. A mistyped link is refused instead of + opening a different view. Long `#v=2` links keep working (samehkhamis, #1418). + +- Make Clear All clear the saved and shared layer selection. Layers that a + context mode had already switched off no longer stay in the share link and + come back on reload (samehkhamis, #1417). + +- Restore a share link opened in an already-open tab. Pasting a link into the + address bar, following one, or using Back/Forward now moves the camera and + restores the style, map, panels and layers instead of changing only the URL + (samehkhamis, #1416). + +- Add a Scope checkbox and extend feathering to 200%, retaining scope settings + across HUD layouts, share links and scenes. First run opens with Scope ON at + 100% feather; explicit settings and historical links retain their values. Give + Tactical, Operator and Minimal text black backplates only when Scope is OFF, + including vertical metadata, without changing the original HUD text color, glow or + opacity. Scope ON retains its original HUD presentation (bilawalsidhu, #1410). + Keep title and tagline positions stable when toggling Scope, include the eye + in the title backing, and brighten the two secondary labels only with Scope OFF. + +- Remove four modules nothing in the app imports: `src/app/sourceSlot.js`, + `src/data/flowTiles.js`, `src/data/issPass.js` and `src/data/localGeojson.js`. + The local GeoJSON layer tests now build layers the way the catalog does, so + they keep covering `localGeojsonCore.js`. Package exports are unchanged + (samehkhamis, #1403). + +- Aircraft on the ground keep getting ground-height samples after the + computer's clock steps back, instead of waiting for it to catch up + (quanticsoul4772, #1399). + +- The Sharpen slider at 0 now turns the sharpen pass off instead of still + sharpening at a low amount (quanticsoul4772, #1398). + +- Show a locally heard aircraft tracking 359.5° or more as TRK 0°. The Local + ADS-B card rounded the track without wrapping, so 359.7° read "TRK 360°" + (Rudy Celekli, @rudycelekli, #1396). + +- Report a fire detection's acquisition time as a UTC timestamp in + `get_active_fires`. The tool joined FIRMS's unpadded date and time, so a + 00:45 UTC detection read "2026-01-01 45"; it now reads + `2026-01-01T00:45:00.000Z`. Missing or invalid dates and times remain + unknown rather than rolling into another calendar day + (Rudy Celekli, @rudycelekli, #1395). + +- Report Docker container health with a local HTTP check using Node, with the + same port parsing as the launcher (John Rogers, @14traits, #1394). + +- Start the Docker install on SELinux hosts such as Fedora and RHEL. Compose now + mounts the checkout with `:z`; without it the container could not read `/app` + and stopped with "Cannot find module '/app/scripts/docker-start.mjs'" + (Anıl Güvenç, @anilguvenc, #1391). + +- Render awareness-overlay bearings and courses that round through north as + `000°`, rather than `360°` (Rudy Celekli, #1390). + +- Show cockpit wind from 359.5° or more as 0°, not 360°. Rounding 359.6° + printed "N · 360°" on the local wind direction + (Rudy Celekli, @rudycelekli, #1389). + +- Show a drawn line of 999.5 m or more as 1.0 km. The draw hint kept metres + below 1000, then rounded 999.6 m up to "1000 m" + (Rudy Celekli, @rudycelekli, #1388). + +- Show a Contacts entry 999.5 m or more away as 1.0 km. The panel kept meters + below 1000, then rounded 999.6 m up to "1000 m" + (Rudy Celekli, @rudycelekli, #1387). + +- Show a route leg of 995 m or more as 1.0 km. The route summary and step + cards kept meters below 1000, then rounded 996 m up to "1000 m" + (Rudy Celekli, @rudycelekli, #1386). + +- Show a route leg of 59.5 seconds or more as 1 min. The route summary and step + cards kept seconds below 60, then rounded 59.6 s up to "60 s" + (Rudy Celekli, @rudycelekli, #1385). + +- The HUD's AI place summary drops a reply that arrives after the camera has + started moving, so a summary asked for before a flight no longer names the + old place mid-flight. Cancelled or partially typed summaries retry even if the place + context stays the same (quanticsoul4772, #1384). + +- Reduce repeated work in aircraft detection candidates by caching unchanged + callsign/registration text and reusing resolved fleet models. Metadata updates, + live positions and tracked-aircraft/model handoffs remain immediate + (samehkhamis, #1379). + +- Increase touch-first globe zoom sensitivity to three times the default while + retaining Cesium collision and distance limits. +- Reuse one delayed display timestamp per civil-aircraft fleet update and cache + extrapolation coordinate frames until their fix coordinates change. Preserve + contact counts, movement cadence, tracked motion and ground corrections. + +- Turning a layer off frees the memory its entities held. Cesium kept + removed layers' draw commands in reused per-pass arrays, so Data Centers + kept 116 MiB after it was switched off, submarine cables 74 MiB and dams + 30 MiB; they now keep 13, 9 and 9 MiB (quanticsoul4772, #1367). + +- Aircraft 3D models (Flights, Military Flights, Local ADS-B) skip Cesium's + dynamic environment map, a sky render and GPU readback per model. With + ~150 models in the scene at Atlanta on Google 3D, GPU time per frame at + rest falls from 14.3-14.8 ms to 12.1-12.5 ms; a same-model comparison + showed no visible change (quanticsoul4772, #1366). + +- Drop the decimal when fire radiative power rounds to 10 MW. A 9.96 MW + detection was labeled 10.0 MW because the one-decimal cutoff ran before + rounding (Rudy Celekli, @rudycelekli, #1354). + +- Count a transit report that is 90 seconds old as one minute. The card kept + seconds through 89s, then rounded 90s up to "Reported 2 min ago" + (Rudy Celekli, @rudycelekli, #1353). + +- Read a destination heading that rounds to north as 000. 359.6° was shown as + 360° on the destination bearing while the compass tape already uses 000 + (Rudy Celekli, @rudycelekli, #1352). + +- Keep a tracked vessel's speed, course, heading and fix time when AISStream + static data arrives; the static message only merges name, type, destination + and IMO (rudycelekli, #1351). +- Apply changed static metadata immediately, retaining known fields when a + later static report omits them, without refreshing the vessel's position + (samehkhamis, #1351). + +- Convert NHC cyclone movement speed from miles per hour to knots, so + `movement.speedKt` in cyclone query results is no longer about 15% high + (rudycelekli, #1350). + +- Label NHC cyclone classifications by their published meanings: `PTC` is a + post-tropical cyclone, `PC` a potential tropical cyclone, and subtropical + systems arrive as `STS` and `STD` (rudycelekli, #1349). + +- Wake staged weather imagery on a 150 ms timer while waiting for readiness, + avoiding a continuous render loop and cancelling the wake when work ends + (@nu-stats, #1345). + +- Phrase slight and sharp ramps as directions, so a ramp reads "slightly left" + instead of "on the slightly left", and a lane names its side in both + the proxy response and localized browser instructions + (Rudy Celekli, @rudycelekli, #1343). + +- Keep an impossible wildfire acquisition date off the detection clock, so a + fire is not labeled with a later day it did not happen + (Rudy Celekli, @rudycelekli, #1342). + +- Reject impossible KartaView photo timestamps, so 31 February is unknown + instead of rolling forward into March and passing the imagery date filter + (Rudy Celekli, @rudycelekli, #1341). + +- Read a hemisphere letter that is separated from its number, so a search for + `40.7128 N 74.0060 W` flies there instead of falling through to the geocoders + (Rudy Celekli, @rudycelekli, #1340). + +- Carry HUD LAT/LON seconds that round up to 60.00" into the minutes and + degrees, so longitude -122.35 reads `122°21'00.00"W` instead of + `122°20'60.00"W` (rudycelekli, #1339). + +- Improve touch selection of aircraft and vessels through the shared contact + picker, reveal tracked aircraft details when opening Context, support downward + swipe dismissal of phone drawers while preserving scrolling and controls, and + enlarge the phone logo (samehkhamis, #1338). + +- Evict terrain-height cache entries in fetch-time order without repeatedly + sorting the full cache, while keeping refreshed points newest and ordering + restored entries by their fetch time (daikaginza, #1326). + +- Add a phone layout for viewports 720px and narrower: the globe stays full + screen and a bottom tab bar (Layers, Cameras, Context, Search, More) opens one + panel sheet at a time, keeping attribution visible and scene STOP reachable. + Adapted from the phone tab-shell in #203 by blearymoth (samehkhamis, #1325). + +- Export the KartaView and Panoramax Street Level providers, so a host composing + its own provider list can offer the keyless providers without Mapillary + (samehkhamis, #1324). +- A Mapillary source can take a `graphEndpoint`, a Graph API base that adds the + token itself (such as a same-origin proxy). Its sequence lookups go there + through the source's transport, and the photo viewer uses MapillaryJS's + Graph provider at that endpoint, so no client token is needed in the page + (samehkhamis, #1324). + +- Remove dead code across the repository: three modules nothing imports + (`src/ui.js`, `src/standalone/ui.js`, `src/data/localLayers.js`), exports + and locals nothing reads, a duplicate copy of the bundled dams data and an + unused ship model. The app no longer builds an unused default wind layer + and Bhote Koshi locator layer when it loads. Package exports are unchanged + (samehkhamis, #1321). + +- Validate provider response formats, strengthen camera source checks, and apply consistent API response protections (samehkhamis, #1317). + +- Clarify shared field CSS ownership: CCTV owns calibration editor sizing, + while Radio and Cyber supply explicit field palettes without changing the + current appearance or native control behavior (mazy1998, #1309). + +- Share read-only status badge presentation across CCTV source/frame labels, + calibration provenance and Weather coverage, preserving status meanings, + palettes, translations and announcements while preparing the view contract + for a future Vue migration (mazy1998, #1306). + +- Share native dropdown and numeric-field styling across Scene, CCTV, Display + and Radio controls, with a shared CCTV number-input builder that preserves + existing precision, validation and commit behavior (mazy1998, #1305). + +- Point distances wrap longitude differences across the antimeridian, in voice + proximity checks and `places_nearby` (quanticsoul4772, #1304). + +- `get_wind` flags stale forecasts (`stale`) when the wind proxy serves a + cached model run (quanticsoul4772, #1303). + +- Give ordinary Scene and CCTV actions shared native buttons with consistent + default, destructive and compact styling while preserving their existing + behavior and specialized controls (mazy1998, #1302). + +- Unify segmented selectors for model coverage, detection allocation, drawing + shape, Street View and imagery comparison while preserving their existing + behavior. Keep compact labels such as FILL and FLAT on one line, and let + collapsed Weather release space to the open rail panel. Reserve the full mode + button height in Recent Imagery so keyboard focus is not clipped (mazy1998, #1301). + +- Add a shared Voice Preview and Settings panel with browser-local preferences, + inactivity controls and accessible floating provider controls on compact layouts; + recover inactivity after confirmed audio-less replies, release retired audio + observers and keep cost warnings visible outside Settings + (manjunath22466, #1299). + +- Add Simplified Chinese (zh-CN) to the language picker, with localized dates + and readable Chinese labels. Based on translations by @abiyeenzo (#914) + and @EDIT-Aeterna (#979). + (German, @gekh, #1298). + +- Add the S2 GhostMaps layer: S2 Underground's public KMZ intel products + (Common Intelligence Picture, 30-day kinetic pull, Border Crisis Map, Iran + and Yemen products and the newest incident drop) from + github.com/s2underground/GhostMaps, with one chip per product and report + cards on click. `/api/ghostmaps` watches the repository's branch head every + 15 s and pushes each new commit to open pages, which reload only the + products that changed (Black Pine Defense). +- Clear a temporary GhostMaps upstream error and notify open pages when the + repository becomes reachable again, including when no new edition was published. +- Release packed-image resources when a load is cancelled or fails, respect + injected or omitted GhostMaps sources, and wait for background cache warm-up + before removing provider test fixtures. +- Include Simplified Chinese translations and keep the combined voice prompt + within its existing size limit while retaining all spoken aliases. + +- A Street Level provider whose `zoomFor` still answers `{zoom, kind}`, the + shape before the core went slim, draws its lines again instead of a silent + blank; an overview level or any answer that is not a whole zoom shows the + zoom-in hint (asturksever, #1288). + +- Give ordinary sliders a shared native control and consistent track, thumb, + value, focus and disabled styling while preserving feature behavior and + specialized controls (mazy1998, #1287). + +- The Street Level SINCE note sits on the value's line, in its type and a + size smaller: with KartaView lit it reads ANY DATE (by upload date). It + had lost its size variable in the Street Level slim-down and rendered + larger than the value, on a line of its own (asturksever, #1286). + +- Keep aircraft route labels on the scheduled airport leg instead of accepting + its distant great-circle extensions, preserving generous endpoint tolerance + across the signed-angle branch cut (rudycelekli, #1284). + +- Report cached CelesTrak satellite records as stale in the Data Layers row, + preserving separate core and dense catalog provenance through refresh, + removal and lifecycle cleanup (rudycelekli, #1283). + +- Pause periodic network updates in hidden tabs; the overdue update on return restarts the polling schedule, so the next poll follows one interval later even when that update fails (asturksever, #1282). +- Report and guard browser visibility during Transit QA so hidden-page polling pauses cannot masquerade as playback regressions (asturksever, #1282). +- Require each live city to supply its own feed vehicles in Transit QA; retained vehicles cannot qualify another city (asturksever, #1282). +- Bound the Transit card-anchor probe by observed poll coverage instead of a fixed 20-second window (asturksever, #1282). +- Keep visible-page Transit probes focused through the browser testing API (asturksever, #1282). +- Add a real-browser regression gate for hidden-tab periodic work, explicit refresh, resume and teardown (asturksever, #1282). +- Restore minimized test windows before screenshots so native compositor pauses cannot stall browser acceptance (asturksever, #1282). + +- Hold rendering only for animated content (asturksever, #1281). +- Exercise current vector road sources and published camera bounds in Traffic fixture QA (asturksever, #1281). +- Establish browser-level foreground visibility for Traffic QA and reject hidden-page samples (asturksever, #1281). +- Supply CORS headers on cross-origin traffic fixtures and report browser exceptions without disabling browser security (asturksever, #1281). +- Isolate the Traffic keyless browser scenario from the keyed page’s workers and intercepted cache (asturksever, #1281). +- Restore minimized test windows before screenshots so native compositor pauses cannot stall browser acceptance (asturksever, #1281). +- Intercept only Traffic provider URLs, leaving Cesium worker and module loading untouched (asturksever, #1281). +- Settle an unfinished Traffic height correction when the last animated point leaves, so the layer stops reporting loading once its render hold is released (asturksever, #1281). + +- Throttle mission hover picks with a trailing check for the last pointer position, and clear stale cursors (asturksever, #1279). + +- Reserve singleflight before disk cache reads (asturksever, #1278). + +- Bound each height request to one upstream chunk (asturksever, #1276). + +- Preserve enable during first-load replacement (asturksever, #1275). +- Release disabled weather camera listeners and make teardown resource leaks fail the browser probe (asturksever, #1275). +- Keep visible-page weather teardown probes focused through the browser testing API (asturksever, #1275). + +- Scan the kml root delimiter in bounded time (asturksever, #1274). + +- Retire unavailable history and keep local trails (asturksever, #1273). + +- Normalize geocoder bias across the antimeridian (asturksever, #1272). + +- Reject inherited style keys during restore (asturksever, #1271). + +- Respect provider cooldowns and bound tle groups (asturksever, #1270). + +- Coalesce refreshes and cool down opensky failures (asturksever, #1269). + +- Normalize station tags and retain valid mixed rows; skipped malformed rows still report degraded coverage (asturksever, #1268). +- Correct Radio QA push-to-talk setup to target the mounted voice controller (asturksever, #1268). + +- Honor Docker Compose trusted-peer and allowed-host settings from the shell + or project `.env`, and let `GEV_KEY_SETUP_TRUSTED_PEERS=none` disable gateway + access to Provider Settings before Vite starts (asturksever, #1265). + +- Prevent malformed Overpass filters from blocking the local server, and reject + cross-site or excessive query requests before reading their bodies + (asturksever, #1264; fixes #1248). +- Release unread responses from the optional Google-token probe so keyless + browser validation can settle; the Overpass gate recognizes only that probe's + expected 404 as an unavailable capability (asturksever, #1264). +- Make tracking arrival checks respect the aircraft update cadence while checking + orientation on the first reveal, avoiding false failures at faster render + rates (asturksever, #1264). + +- The terrain-heights bounds tests no longer read the checkout's + `.gev-cache/terrain-heights.json`. Each test gets a cache file of its own, so + `npm test` no longer fails after the dev server has cached terrain near + Austin (KnottyDyes, #1244). + +- Replace the blocky JPEG sky around the globe with the 9,096 stars of the + Yale Bright Star Catalogue, drawn as sharp points where they are at the + scene time, over a soft Milky Way from ESO/S. Brunier (CC BY 4.0). The Sun + and Moon stay; the anime style hides the Milky Way. Assets: 296 kB (gekh, + #1243). + +- `get_traffic_flow` flags stale cached TomTom tiles and reports the oldest + tile fetch time (`stale`, `oldest_tile_at`), with pending freshness metadata + released on failed or cancelled tile reads (quanticsoul4772, #1239). + +- Add Taiwan's national freeway cameras from the Freeway Bureau, MOTC to CCTV: + ~1,800 cameras read at runtime from the official MOTC 2.0 open-data table, + with on-demand snapshots and attribution. No API key is required; set + `CCTV_TAIWAN_ENABLED=0` to skip it (419vive, #1237). + +- Require a geocoded containment anchor for ambiguous analyst region names, + preserve boundary provenance and cancellation safety, and retain exact-name + precedence for natural outlines (manjunath22466, #1235). + +- Serve the camera catalog while it refreshes. An expired catalog made every + camera request wait for the slowest pack to reload; it is now answered at + once while one background refresh runs, so only the first load waits. Estonia's + slow Tarktee feeds get 30 s instead of 15 s, so the pack no longer drops out + on about a third of loads (quanticsoul4772, #1234). + +- Harden the Tarktee (Estonia) DATEX2 camera catalog fetches: refuse redirects, + cancel both response streams when either response fails or overflows the 4 MB + byte cap, and deduplicate camera IDs before per-pack prioritization + (yaka0007, #1233). + +- Skip bike-share stations with missing, blank or invalid coordinates instead + of placing them at coerced zero coordinates or accepting out-of-range values. + Explicit zero coordinates and numeric strings remain supported (Bortlesboat, #1232). + +- OpenSky sign-in matches what OpenSky accepts since 2026-03-18. The server + now reads `OPENSKY_CREDENTIALS_FILE` (the `credentials.json` OpenSky's + account page downloads) on every platform, not only through the macOS + launcher, and no longer sends retired username/password Basic auth: + `OPENSKY_AUTH_MODE=basic` loads anonymously with one warning saying what to + set instead (quanticsoul4772, #1229). +- Credential-file warnings omit parser excerpts and filesystem error details; + the path example also works with the macOS launchers. + +- Load Ontario 511 cameras again. 511on.ca's camera endpoint now requires a + free developer key; set `ONTARIO_511_API_KEY` to enable the pack, which is + otherwise skipped with one log line saying where to get a key + (quanticsoul4772, #1228). + +- The first-run card can be closed on a phone or tablet. "ESC to dismiss" is + now a button that closes the card the same way ESC does; touch screens read + DISMISS, and phones no longer hide it, so choosing a mission is not the only + way out (KnottyDyes, #1226). + +- Add continuous globe rotation with direction and speed controls and a globe-fit + check before starting (manjunath22466, #1225). + +- Open God's Eye View from Pinokio in the system browser using the supported + `popout` menu option. The application's framing policy is unchanged + (NukeThemAII, #1222). + +- Avoid starting or queuing a reply when the local channel rejects a typed OpenAI + command, while preserving an earlier accepted deferred input + (Manjunath, #1220). + +- Keep NASA FIRMS fire and ALPR camera labels English in voice tool results + (`track_entity`, `get_entity_context`, pointer context); the voice card still + shows them in the interface language (daikaginza, #1207). + +- Report actual outcomes when voice enables or disables CCTV through the shared + layer lifecycle, including failed and cancelled changes (manjunath22466, + #1205). + +- Draw CCTV stills at their source aspect on the monitor plane instead of + stretching them to the 16:9 canvas. Most DOT cameras publish 4:3 frames, so + every still was widened; they are now centered and pillarboxed on the dark + the placeholder already ends on (Danielslay86, #1201). + +- Color CCTV cameras with a video feed violet. Cameras with an HLS, MP4 or + WebM feed were the same cyan as stills, so a DelDOT or Statens vegvesen + video camera could only be found by opening it. Stills stay cyan and the + active camera stays amber, and focus de-emphasis fades the violet the same + way (Danielslay86, #1200). + +- Keep Space Missions marked STALE when Launch Library 2 falls back to cached + launch data, and return to NOMINAL after a fresh response without discarding + retained missions (rudycelekli, #1199). + +- Share Launch Library request cache keys across installations refreshing in the + same UTC minute, identify the app to the provider, and explain that standard + space-missions access needs no key. Optional higher-rate LL2 tokens are paid + upgrades; existing local cache and server-only token handling are unchanged + (rudycelekli, #1197). + +- Add nine Spanish city bike systems to Bike Share and `get_bike_share`: BiciMAD + (Madrid), Valenbisi (Valencia), Bizi Zaragoza, Sevici (Seville), BIKI + (Valladolid), BiciCoruña, Dbizi (Donostia-San Sebastián), Bilbao Bizi and + BicinRivas, about 1,840 stations. Station names read underscores as word + breaks, and station capacity counts docks rather than PBSC's geofenced area + (ulihhhh, #1190). + +- Keep missing launch-pad coordinates unknown so launches use the location + fallback or stay off the map instead of appearing at 0°N 0°E. Missing stage + flight numbers no longer show "FLIGHT 0" + (Rudy Celekli, @rudycelekli, #1186). + +- Flights' ground floor works across the antimeridian. The viewer-distance + check behind the 150 km floor radius and its copy in the photoreal mesh-floor + sampler subtracted longitudes without wrapping, so two points 21 km apart + across 180° measured about 38,000 km and low or grounded aircraft just across + the line from the viewer were never floored. A contact's display corridor + walked a segment across 180° the long way round, spending its cell budget on + ground behind the contact, and a contact on the seam lost its cell hysteresis. + SEARCH NEARBY SITES on a view across 180° searched Google Places around + longitude 0, on the far side of the globe, with a radius sized from the view's + height alone; it now searches the view (Aditya, @Rohilalala, #1173). + +- Keep missing CCTV numbers unknown instead of reading them as zero. `Number` + turns null, blank strings and booleans into 0 or 1, and the camera source + list sends an unknown number as JSON null, so a source-pack camera that left + out its pose reached the browser as zeros clamped to each field's floor — + facing north, pitch −2°, FOV 20°, range 120 m, mount 6 m and ground 0 m — + instead of the defaults (id-hash heading, −17°, 74°, 700 m, 24 m and the + city's ground); a null or blank position placed the camera at 0,0. The + server's `toFiniteNumber` and the browser's `safeNumber` now treat absent, + blank and boolean values as missing. The same conversion also stops a + Tallinn row with a null heading reading as a confident north-facing camera, + a Caltrans camera with a blank elevation losing its 150 m ground prior, and + a TfL or Catalonia camera with a null or blank coordinate being kept at 0,0 + or on the zero meridian (omerbberk, #1172). + +- Director shot actions land on the requested shot. A seek to a shot's start + could round a hair below it and select the end of the previous shot for some + shot counts and durations (Aditya, @Rohilalala, #1171). + +- Fire-perimeter queries handle outlines and holes crossing the antimeridian: + areas enclosed near ±180° are included, areas at the opposite meridian are + excluded, and returned perimeter coordinates stay near the dateline. Incident + cards use the same circular longitude mean and compare multipart outline + areas along short longitude edges, keeping the card on the largest polygon + (Arianna Method, @ariannamethod, #1142). + +- Scenes keep the "Scene not saved" status when a capture, update, append or + import cannot be saved, and an unreadable saved project no longer overwrites + the recovery checkpoint. `startScene()` resolves to its documented result, + `afterShotId` works without an explicit scene, and `scenesRun` counts the + distinct scenes queued (djabhi31, #1135). + +- Label camera-tool Street View fallbacks as historical Google imagery rather + than the current camera view; keep unknown frame provenance explicit + (rudycelekli, #1118). + +- Release superseded Google Street View open waits and suppress metadata + requests whose viewer was unmounted while the service loaded (rudycelekli, + #1117). + +- Exclude aircraft without a reported altitude from requested altitude bands; + unfiltered aircraft queries still retain them (rudycelekli, #1115). + +- A failed Esri Satellite or keyless terrain load still shows OSM or flat terrain + at once, but no longer lasts the whole session: while the fallback is on + screen, the real provider is retried in the background (30 seconds, doubling + to a 10-minute cap) and replaces it live once it loads. Map switches never + wait for a retry (Aditya, @Rohilalala, #1111). + +- Skip TLE sets whose line 1 and line 2 carry different catalog numbers, so a + spliced catalog cannot pair one satellite's elements with another's; the next + valid set still parses (VG31OP, #1101). + +- Overpass data whose element tags contain a failure phrase ("timed out", + "runtime error", "too many requests" and similar, e.g. a place named "Timed + Out Escape Rooms") is returned as data instead of being refused and putting + the endpoint on cooldown; upstream failures are read from the remark (Aditya, + @Rohilalala, #1097). + +- Military aircraft keep their last heading and speed when an adsb.lol row omits + `track` or `gs`, instead of turning north and stopping; a grounded row without + a speed still reads 0 (Aditya, @Rohilalala, #1096). + +- Update DOMPurify to 3.4.17, Sharp to 0.35.5 and source-map-js to 1.2.2 for + GHSA-p98j-92pf-mc4p, GHSA-6688-9rhm-gjv2, GHSA-wq5f-xc86-pv6w and + GHSA-68fv-2mgg-jv7q; `npm audit` now reports no vulnerabilities (NurstarK, + #1094). + +- Location search accepts two-dimensional WGS84 `geo:` URIs offline, with + the existing coordinate framing and label. Unsupported URI fields are passed + to the remaining search providers unchanged (cj-vana, #1071). + +- Keyless standalone startup answers an unavailable Google tile-token endpoint + with uncached 204 instead of a browser-visible 404. Existing providers take + precedence, and unrelated API routes behave as before. (dvilrgamerz, #1066) + +- On Windows, `npm run doctor` and the Pinokio install no longer print Node's + DEP0190 warning ("Passing args to a child process with shell option true can + lead to security vulnerabilities"): npm.cmd's fixed subcommand is now part of + the shell command string instead of an argument array (quanticsoul4772, #1057). + +- `aircraft_in_area` and `vessels_in_area` take `group_by` and `stats`, so an + MCP client can ask which airlines, countries, aircraft types or ship types + dominate an area, or the average altitude or speed, over every match instead + of estimating from the returned rows. Airlines come from the ICAO designator + in each callsign (SWA1234 counts as SWA), so the breakdown works on feeds + that report no operator; operator and type are counted only where the feed + reports them. Ship types count by family, so AIS codes 70 to 79 are all + cargo; type 0 ("not available") and the reserved codes 100 to 255 count as + unknown. Altitude and speed stats cover airborne aircraft only, so parked + aircraft do not pull the means down. Every vessel answer, `find_vessel` + included, now reads AIS ship-type codes as their family and a destination + with no letters as unknown (quanticsoul4772, #1056). + +- Add Hong Kong Transport Department traffic snapshot cameras as a keyless CCTV + source pack: the public DATA.GOV.HK English locations XML, frames pinned to + `tdcctv.data.one.gov.hk`, with DATA.GOV.HK Terms of Use attribution. By + default nearly the full TD catalog (~1,013 cameras; cap 1,100) loads, + prioritized across Hong Kong Island, Kowloon and the New Territories. Headings + use the shared id-hash fallback at low confidence. `CCTV_HK_MAX_SOURCES` sets + the cap (8–1,200) and `CCTV_HK_ENABLED=0` turns the pack off (JCY2515, #990). + +- Cross-site pages can no longer fill the terrain-height cache or spend the + visitor's own `/api/terrain/heights` rate-limit quota through the visitor's + browser. The route refuses a cross-site `Sec-Fetch-Site` or a foreign or + opaque `Origin` before rate limiting, cache access or upstream work. Unlike + the cost-bearing routes it still answers same-origin requests that arrive + through a reverse proxy, so terrain keeps rendering behind nginx, Caddy or + Cloudflare instead of falling back to the geoid (Sunil56224972, daikaginza, + #975). + +- Street Level is rebuilt around one small provider registry: Mapillary, + KartaView, Panoramax and Google Street View share one coverage drawer and + one photo viewer, one source lit at a time. Floating and docked panels, + FOLLOW, surface modes, the legend and the Mapillary proxy's disk cache are + gone; `.gev-cache/mapillary/` from earlier runs is no longer read and can be + deleted (gekh, #974). + +- Cross-site browser requests can no longer spend the TomTom traffic-tile + budget through `/api/tomtom/*`. The shared same-site gate runs before status, + cache, and upstream work; same-origin app requests and non-browser local + callers remain supported (Sunil56224972, #973). + +- Recent Imagery: opening DETAILS scrolls its card into view when it opens below + the fold. The panel used to restore the previous scroll position right after + the reveal, so the card stayed out of sight (Ian Blenke, #970). + +- Harden Vite's filesystem deny list for local-only artifacts: repo `dist/`, + `.gev-logs/`, and `.gev-cache/` are denied without blocking dependency + `dist/` directories, and checkout paths containing glob metacharacters are + escaped before building the root-anchored pattern (blowing-a-raspberry, #948). + +- Give each Statens vegvesen camera its own ground height from Kartverket's + keyless point-height API (CC BY 4.0) instead of one flat 150 m prior, so + mountain-pass cameras no longer sit hundreds of metres below the terrain + where neither the point-height prior nor the ground snap resolves. About 850 + of ~855 cameras get a height; the rest keep the old prior. Requests carry 20 + points, the most the API answers from its 1 m terrain model, eight at a + time; a cold lookup takes about 6–13 s. Cameras over water use the water + surface rather than the sea-floor depth the API returns there; for bridge + cameras that is still below the deck. Heights are cached for good and misses + for 6 h, so a refresh only asks about new or moved cameras. After a + failing request (a 408, 429 or 5xx, a network error, a request over 10 s or + an unreadable body) the lookup stops and backs off (Retry-After, else + 30 min, longer than the refresh). The lane waits at most 12 s from its + start, and only on a cold cache; a slower first lookup leaves the cameras it + had not reached on the flat prior until the next 15-minute refresh, and + keeps filling the cache meanwhile. + `CCTV_VEGVESEN_HEIGHTS=0` turns it off. Follow-up to #929 (trygvehhh, #945). + +- Extract a reusable model-free World Packet from the existing voice + `get_current_view_state` owner without restoring disabled layers to the + model context. Keep the enabled-only payload, disabled-layer count, source + provenance, action result and view-state contract; read the layer roster once + per packet; voice retains the speech/card envelope at its own boundary. + Credits: original GEV voice/layer contributors and #880 implementation. + +- Add optional Gemini Live voice to the standalone app, with a provider chooser, + server-held API key, microphone streaming, shared map actions and captions. + Switching providers ends the old conversation and preserves the input mode + (Manjunath, #872). + +- Close the compact Radio disclosure when an adaptive tactical right-rail + restore directly expands Context, before Space Missions can be covered. + A repeated Context-open request also clears stale disclosure state. + Real PanelChrome constructor wiring and the rail reflow path are covered + by focused regressions. Credits: kvnloo (#816), raysung-2026's original + #804 report, asturksever's review, and quanticsoul4772's independent + Windows diagnosis. + +- Changelog entries are now one file per pull request. A change adds + `changelog.d/-.md` instead of editing the top of + `CHANGELOG.md`, which two pull requests in flight could not share — it was the + most frequent merge conflict in the open queue, and for six of them the only + one. `npm run changelog` splices the directory into `CHANGELOG.md` at release + time and empties it; `npm run changelog:check` reports the batch and changes + nothing. Fragment text is copied through unchanged (daikaginza, #787). + +- Read satellite catalog numbers written in Alpha-5, the TLE spelling of + numbers above 99999: a letter for the first two digits, skipping I and O + (`A0000` is 100000, `Z9999` is 339999). The satellites layer converted such a + field to `NaN`, so every Alpha-5 satellite shared one catalog entry and all + but the first were dropped as duplicates; the satellite tools read the same + field as no number, so such a satellite could not be found by it. The layer + and the tools now decode the field in `src/sources/tle.js`, and reject a + malformed one (a sign, decimal point, hex, embedded space or stray letter) + instead of reading part of it as a number. This is Alpha-5 TLE + compatibility: CelesTrak's TLE feed carries no satellite above 99999, which + needs the OMM feed (#1191) (Honorius Neogy, #767, fixes #751). + +- The dev server no longer watches `.gev-cache` and `.gev-logs`. Providers write + cache files and logs there while the app runs, and none of it is source, so + the watcher now skips it; this guards against the DNS-lookup delays heavy + cache writes have caused, though no difference was measured on current main + (monwiss, #761). + +- Bound what a caller can grow through `/api/terrain/heights`. Every distinct + 5-decimal point was a permanent in-memory entry, a permanent line in an + uncapped `.gev-cache/terrain-heights.json`, and a live upstream call, with + nothing limiting the rate. The point cache now holds at most 50,000 entries + and evicts oldest-first, a cache file above + 24 MB is not read back, and the route is limited to 90 requests/minute per + client (270 global). Evicting a point costs one refetch, never a wrong + answer, since terrain does not move. Ordinary use is unaffected: a full + `test:track` run drives 10 requests, peaking at 8/min (daikaginza, #686). + +- Add FL511 (Florida DOT) traffic cameras as an opt-in CCTV source pack: + the statewide ArcGIS catalog, read a page at a time under a byte cap with + redirects refused, and frames pinned to FL511's two image hosts over HTTPS. + FL511's terms limit its content to individual, personal use, and any other + use (a public deployment included) needs FDOT's express written consent, so + the pack stays off unless `CCTV_FLORIDA_ENABLED=1`. Headings come from the + catalog's direction codes, and camera ids come from the image channel, since + the catalog's ID column repeats across regions. `CCTV_FLORIDA_MAX_SOURCES` + sets the cap (Danielslay86, #605). + +- The client's great-circle distances now come from one shared + `src/geoDistance.js` (`greatCircleKm`/`greatCircleMeters`, `{lat, lon}` + points). The Earth radius is standardized on 6371.0088 km, so distances shift + by about 1.4 ppm and region areas by about 2.8 ppm, and missing or + out-of-range points return `Infinity` (onionviolet, #287; Rajojha-1, #749). + +- The tracked-aircraft descriptor now publishes `verticalRateMps`, on both the + civil and military layers, so a consumer reading `getTrackedInfo()` no longer + has to reach past it into the raw poll record for climb/descent. Reported, + never derived: an aircraft that has not transmitted a rate reads as `null` + rather than a level-flight `0`. + +- Bound how often the GBFS proxy will relay. `/api/gbfs` already restricted + where it could go — https, an allowlisted host, a station feed path, no + redirects, a 12-second deadline and a 5 MB body cap — but nothing restricted + how often, so the dev server would make unlimited requests at a third-party + bikeshare operator on any caller's behalf. The route now admits 120 + requests/minute per client address, refusing the rest with 429 and + `Retry-After` before any outbound fetch. The bikeshare layer needs about 15 a + minute with every catalogued system in range, so ordinary use is unchanged. + +- Add nine Ontario transit feeds: TTC, MiWay, Hamilton HSR, Durham Region, + YRT/Viva, Guelph, Burlington, Barrie and Kingston, each carrying its own + licence quote and attribution. A feed can now name its own modes, so Toronto's + trams read "Streetcar" while Helsinki's stay "Tram", and a feed whose route ids + are internal keys can translate them to the number a rider would say. TTC + vehicles take their mode from the fleet number first, so replacement buses on + streetcar routes read as buses and out-of-service streetcars stay streetcars. + +- CCTV cameras with identified hardware show the model's datasheet specs. When a + source names a camera model found in the vendored CCTV Camera Database records + (CC0), the HUD meta line adds its resolution, night vision and PTZ capability. + A fixed single-lens model's horizontal FOV fills in when the source states no + FOV and the pose is not curated (`FOV n° (DATASHEET)`); a PTZ or varifocal + range is what the lens can do, not its current zoom, so those cameras keep the + estimate and show `SPEC FOV min–max° (CAPABILITY)` beside it (bassem chagra, + #452). + +- Ship a web app manifest and raster home-screen icons, so adding the app to a + phone home screen or installing it on desktop uses the God's Eye View mark + instead of a blank tile. The icons are generated from `public/logo.svg` by + `node scripts/generate-icons.mjs` and committed, so a plain `vite build` needs + no image toolchain. The existing SVG favicon still serves the browser tab. + Manifest paths are relative to the manifest, so a build served under a path + prefix installs and launches inside that prefix. + +- Cyclone advisories no longer go dark while NHC publishes an advisory ahead + of its nominal time: advisory and position times up to 90 minutes ahead of + the server clock are accepted (previously 5 minutes), so the whole feed is + not rejected for about half an hour each advisory cycle. + +- Flights age out vanished aircraft again. OpenSky's routine position-less rows + no longer mark every snapshot partial, which had kept vanished and landed + aircraft at full opacity for up to five minutes; those rows retain only their + own aircraft, and a likely-landed one still leaves on the landed limit. + +- Add WSDOT highway cameras (Washington State) as a keyless CCTV source pack: + WSDOT's official Travel Center camera layer, with frames registered only on + WSDOT's own image host (partner-hosted cameras such as Oregon DOT and City of + Seattle are skipped). Cameras with a single cardinal `CompassDirection` get + a high-confidence heading; `B` (both directions), `O`, and unset directions + use the shared id-hash fallback at low confidence. By default the 250 + cameras nearest Seattle and Spokane load; `CCTV_WSDOT_MAX_SOURCES` sets the + cap (8–1,200) and `CCTV_WSDOT_ENABLED=0` turns the pack off (bassem chagra, + #644). + +- Refuse still-image cameras on the CCTV media relay. `/api/cctv/media` is the + live-feed route, but it also relayed any registered still camera through an + ordinary fetch that followed redirects to any host, passed through whatever + content type came back and had no cap on the body, bypassing every protection + `/api/cctv/frame` applies to the same URL. Only HLS, MP4, WebM and MJPEG + feeds are relayed now; a still camera, or an unknown id, gets a JSON 404 + without an upstream request and is served only through `/api/cctv/frame`. + The client already loaded stills through `/frame`, so nothing it requests + changes. + +- Add Lithuania's public Via Lietuva / Eismoinfo road cameras to CCTV, with published coordinates, on-demand snapshots, attribution and bounded catalog requests. No API key is required. The pack is opt-in (`CCTV_LITHUANIA_ENABLED=1`) because its camera endpoints are the eismoinfo.lt website backend, not a service listed in Via Lietuva's open-data statement, so the licence for the photos is unconfirmed. + +- Add King County road cameras (Washington State) as a keyless CCTV source + pack: one public King County DOT ArcGIS layer, fetched with an explicit field + list so its staff-name columns are never requested, and frames pinned to the + county's own image host and upgraded to HTTPS. WSDOT-owned rows are skipped, + and city-owned cameras the county hosts credit their owner. The layer + publishes no facing, so headings use the shared id-hash fallback at low + confidence. It does publish each camera's hardware, which is served on + `/api/cctv/sources` as `model` and `manufacturer`. `CCTV_KINGCOUNTY_MAX_SOURCES` + sets the cap and `CCTV_KINGCOUNTY_ENABLED=0` turns the pack off + (bassem chagra, #645). + +- Add City of Toronto RESCU traffic cameras as a keyless CCTV source pack: the + ~336 municipal cameras the Ontario 511 pack does not carry — downtown + arterials plus the Gardiner, DVP, Allen and Lake Shore. The list is the + City's own open data feed; frames are built from the documented + `loc####.jpg` convention and a digits-only camera number, so the frame proxy + is pinned to the portal origin by construction. The dataset publishes no + camera facing — its `D1`-`D4` fields describe static 2016 comparison images, + not the live pan-tilt-zoom frame — so headings use the shared id-hash + fallback at low confidence and are corrected with the calibration gizmo. + Carries the required Open Government Licence – Toronto attribution. Disable + with `CCTV_TORONTO_ENABLED=0`. + +- Stop one retired bikeshare feed from reporting the whole layer as failed. + City feeds are fetched independently, but failure was recorded in a single + flag that only a successful *activation* cleared — and an already-loaded city + never activates again. A dead feed re-entering camera range therefore latched + LOAD FAILED permanently over a map still drawing every other city's stations. + Failure is now tracked per city: a city that fails beside others still + drawing marks the layer DEGRADED, polls that all fail over previously drawn + points read STALE without advancing freshness, and LOAD FAILED is reported + only when nothing is left to draw. A city that recovers clears its own + failure, a failure is dropped once its city leaves range or the camera rises + above the activation altitude, and late results from superseded requests are + ignored. + + Repointed the three feeds whose operators had moved: Reddy Bikeshare (Buffalo) + to Social Bicycles, Tugo (Tucson) and Trinity Metro (Fort Worth) to PBSC. + Dropped CoGo (Columbus) and Broward B-cycle (Fort Lauderdale), whose systems + have wound down — CoGo's feed reports no stations and last moved a bike in + March 2025. The three repointed feeds were verified live. + +- Add seven Brazilian Bike Itaú (Tembici) cities to the GBFS bikeshare registry: + São Paulo, Rio de Janeiro, Salvador, Recife, Porto Alegre, Brasília and + Curitiba (about 1,000 stations in total). These are the layer's first stations + in South America. + +- Add Bike Share Toronto (1,069 stations) to the bikeshare registry. The system + publishes the same PBSC GBFS v2 feeds as the Austin, Honolulu and Chattanooga + entries, so it needs no new plumbing; a registry test now holds every city's + feed URLs against the proxy host and path allowlists, so a city the proxy + would refuse fails the suite instead of rendering an empty layer. + +- GBFS v3 station names use English translations when available, then the first + usable translation or short name. Empty or malformed names no longer appear as + `[object Object]` or interrupt station loading; legacy string names remain + supported in the globe and bike-share tools. Thanks to + [Kristóf Kékesi](https://github.com/KristofKekesi) (#61). + +- Overpass and military-installation disk caches no longer serve answers from a + previously configured `OVERPASS_UPSTREAMS` instance after it is repointed. + +- A Radio Browser mirror answering 204, 205 or 304, or a status outside + 200–599, no longer crashes the local dev/preview server. Null-body statuses + get an empty body; anything else that cannot become a response fails that + mirror so the next one is tried. + +- Snow flakes sway within a fixed range instead of drifting sideways faster the + longer the app runs; the Wind setting still scales the sway. + +- The right rail ignores panels that other CSS hides, such as during an event + view, so they no longer force one-panel-at-a-time layout or collapse visible + panels. Panels the rail collapses itself are still restored. + +- Coordinate searches refuse empty latitude or longitude components instead of navigating to an unintended location. + +- Bing Aerial and Bing Labels request HTTPS tiles on HTTP localhost through + their ion-backed providers, retaining ion and per-tile attribution without + widening the Content Security Policy. + +- Add New York City traffic cameras from the NYC DOT Traffic Management Center + as an opt-in CCTV pack. NYC DOT requires a data-sharing agreement for the + camera feed, so the pack is off unless `CCTV_NYC_ENABLED=1` is set by an + operator who holds one; otherwise no request reaches NYC DOT. NYC DOT's + requested disclaimer is in the Data attribution popover. The camera list is one keyless JSON request to + `webcams.nyctmc.org/api/cameras`; frames are stills synthesized from each + camera UUID on that same host, so a catalog field cannot steer the proxy + off-host. Offline cameras are dropped. Once enabled, the 250 cameras nearest + the five borough cores load and `CCTV_NYC_MAX_SOURCES` changes the cap. The catalog-wide ceiling is + unchanged; extra cameras share it round-robin with the other packs. + +- Spanish interface (`es`), translated by @meirm (#602) and reviewed against the + current English. + +- Interface localization, starting with Russian. UI text is marked with + `t()`, `tn()` (plurals) and `msg()` in code and `data-i18n*` in markup, keyed + by the English text itself; each language is one flat JSON catalog + (`src/i18n/locales/ru.json`). The language comes from `?lang=`, the language + picker (the globe button in the bottom-right corner), then the browser + language; English stays the default and the fallback. `npm run i18n`, also + run by `npm test`, fails on missing, unused or broken translations. Built on + the i18n foundation by @meirm (#601), with the Russian catalog started + from #312. It also fails on UI text that is not marked at all. +- Street Level counts unique tiles before ranking so overlapping dateline halves + in polar views do not waste slots in the 16-tile overview budget. + +- Directions no longer shows a truncation notice for a route with exactly 200 + turns, and a roundabout at the 200th turn keeps its exit distance. + +- Weather records keep missing conditions unknown and refuse summaries without a measured temperature. + +- Tool string length validation counts Unicode characters correctly, including characters outside the basic multilingual plane. + +- Director timeline seeks cross the dateline along the short longitude arc. + +- Keep unknown GBFS availability counts neutral instead of turning null or empty + values into zero bikes. + +- Recent Imagery continues past malformed records in full catalog pages, respects the requested record limit, and reports results as truncated when that limit drops valid records. + +- Regional articles retain unknown publication times when compact source dates do not identify a real calendar instant. + +- Add Detroit (MoGo), Pittsburgh (POGOH), Aspen (WE-cycle) and Kona & Hilo + (HIBike) to the GBFS bikeshare registry, the layer's first stations in + Michigan. + - Treat explicitly current, complete empty vessel coverage as a successful update, clearing obsolete contacts while retaining stale or incomplete snapshots. @@ -93,7 +978,104 @@ point. A slow render gets one bounded second frame request, while hidden, stale, moved-camera, invalid and oversized captures still fail closed. -## [Unreleased] +- Add a keyless Air quality layer to the Weather group, with Environment and + Climate Change Canada's AQHI as the first registered provider. Readings carry + `{ provider, scale, value, band }` so another network can be added without + inventing a shared numeric meaning across indices that do not share one; the + row and readout both state that coverage is Canada only. The WEATHER card + shows the band legend and the highest readings currently in view. AQHI is + reported as an integer from 1 with an open-ended "10+", so readings round to + that published form rather than the decimal precision the API returns. + Readings older than six hours are dropped, and the layer reports `stale` + through `getStats()` (also when every observation was dropped) so feed + provenance cannot describe an aged feed as live. Voice can switch it on and + query readings by value, band, station and observation time. + +- Bound six upstream body reads (FIRMS CSV, CelesTrak TLE groups, adsb.lol + `/v2/mil`, TomTom flow tiles, OpenSky `states/all` and adsbdb lookups) with + streaming size caps that cancel the body at the cap or the route's deadline; + the adsb.lol military poll gains a deadline of its own. An oversized OpenSky + snapshot is not retried, and an OpenSky 429 starts its cooldown before the + body is read. + +- Keep later satellites when a TLE catalog entry is missing an orbital line. + The parser skips the incomplete set and resumes at the next complete named + set, instead of losing the rest of the group (#906). + +- Satellite clouds keep Clouds only / Full as quick endpoints and add a continuous + cloud-filter slider: 0% is Full, 100% is the existing brightness key, and + intermediate values blend the keyed alpha. The slider commits on release to + avoid restaging imagery for every drag event. Filter percentages round-trip in + share links; legacy mode codes retain their old endpoint meanings. Background + panel refreshes preserve the pending drag value until release. Contributed by + [NotProniss](https://github.com/NotProniss) (#1084). + +- Street Level: Panoramax is the fourth provider, keyless. Light its chip + (orange; off by default, one provider at a time): below about 60 km the + federated commons' sequences draw as lines from `api.panoramax.xyz` vector tiles. A click on a + line opens that sequence's picture nearest the click without moving the + camera, flat or 360°, with cones along the sequence around it and ‹ › / + ← → following the picture's own links. The 360° and since filters apply, + in the lines and in the lookup. The caption names each picture's author + and licence (CC BY-SA 4.0, Licence Ouverte 2.0…) and links to it in the + Panoramax viewer. HD originals load once, only when the viewer is wider + than the 2,048 px version (a panorama: expanded), and every download stops + when the photo changes; an image whose header declares more than 64 MP is + refused before it decodes. Share links carry it as + `0.m.0_0.r.google-0*kartaview-0*panoramax-1` (`0.m.0_0.r.panoramax-1` works + too). KartaView's photo viewer + is now shared (`photoViewer.js`, `panorama.js`); in it, for KartaView too, + Esc clears the selected drive before it collapses the panel. Lines are + simplified and drawn within a point budget (a tile's unsimplified lines + over Paris hung the tab), decoded in slices so the globe keeps moving, + and kept; the cones' tiles have their own connection, and the open + picture's tile draws its cones before its neighbours arrive. + +- Flights and Military Flights highlight emergency transponder broadcasts in + fleet billboards, 3D models and Cockpit contacts. Colors update when a status + starts or clears. Emergency squawks outrank ADS-B priority statuses; GEV + reports minimum fuel and lifeguard without red tint. Cockpit names the code + or ADS-B status, and analyst/voice results retain broadcast provenance and + the latest known contact time. One omitted ADS-B status poll during a source + switch may retain the previous status if the squawk is unchanged; an explicit + clear takes effect immediately. Broadcasts are not confirmed incidents. + Contributed by [Leo Pechnicki](https://github.com/leopechnicki) (#856). + +- Street Level: KartaView is the third provider, keyless. Light its chip + (purple; off by default, one provider at a time) and zoom in below about + 6 km: the lines are the streets KartaView has photos of (z13–14 tiles from + `api.kartaview.org`). A click on a line opens the photo nearest the click + without moving the camera, flat or 360° (a small WebGL panorama: drag to + look, wheel to zoom), with cones along its drive and ‹ › / ← → to step + through it. The caption links to the full-size photo (KartaView's photo + pages fail for signed-out visitors), and the globe credits "© KartaView + contributors, CC BY-SA 4.0". Share links carry it in the provider + switches (`0.m.0_0.r.google-0*kartaview-1`). Archived photos (KartaView + answers 409) are skipped by the click and by ‹ ›. Shift+← →, ↑ ↓, + − and + pinch look around a 360° photo. The open photo's marker is a purple view + cone pointing along the drive (KartaView's own compass headings are often + 0 or far off). The IMAGERY (ALL / 360° / FLAT) and SINCE filters apply to + KartaView as to Mapillary: its lines are filtered by KartaView's own + server (its filtered PNG tiles, as a mask over the JSON lines), and the + photo a click opens, and the cones, by each photo's projection and upload + date. KartaView's SINCE is the upload date (all its server can filter by); + a note under the slider says so while KartaView is lit (`sinceBasis: + 'upload'` in the provider contract). + Mapillary's line coverage and sequence cones are now shared by both + (`lineCoverage.js`, `sequenceCones.js`). + +- Street Level: Google Street View is the second provider. On the Google 3D + map (Google's terms keep it off other maps), light its chip (off by + default: every panorama is billed to the Google Maps key, which needs the + Maps JavaScript API) and click a street, or press OPEN STREET VIEW, to + open Google's own panorama in + the panel, with its arrows, the address and month in the caption, a link + to Google Maps. Share links carry it in the provider switches + (`r.google-1`). One provider is lit at a time (lighting one switches the + other off), Mapillary by default since it is free. Street View's panoramas + are all 360°, so the IMAGERY and SINCE filters apply to + Mapillary only and hide while GOOGLE STREET VIEW is lit; its globe marker + is a Google-blue view cone. - Add an experimental ChatGPT/Codex OAuth option for cloud voice in Provider Settings. API-key voice remains the default. Local sign-in can start from @@ -107,6 +1089,21 @@ [TheSmokeDev](https://github.com/TheSmokeDev) for the credential handling from #653. +- **Docker install path.** `docker compose up` builds on CI's Node 24.14.0 image, + pinned by digest, and serves the app on `http://localhost:4173` with no local + Node install. The repo is bind-mounted and the container runs as the host user + (never root), so `.env`, + `.gev-cache`, and `.gev-logs` persist on the host exactly as they do under + `npm run dev` — Provider Settings included. The launcher + (`scripts/docker-start.mjs`) trusts the container's gateway address for that + panel, since that is where Docker delivers the host's own browser from; the + opt-in behind it, `GEV_KEY_SETUP_TRUSTED_PEERS`, takes exact addresses only + and is unset (so loopback-only, unchanged) under every other launcher. + Thanks to [jklaze](https://github.com/jklaze) for finding and diagnosing the + container-to-host 403, and to [14traits](https://github.com/14traits), + [PoBruno](https://github.com/PoBruno) and [milu70hub](https://github.com/milu70hub) + for testing on Apple silicon, Docker Engine on Linux, and NAS hosts. + - Stdio servers from one install share a panel key so a page read from one process can make requests through another. Concurrent malformed-key repairs now select one winner; unavailable storage or a busy repair retains the @@ -115,21 +1112,27 @@ proposed diagnosis in #927, and [kvnloo](https://github.com/kvnloo) for identifying the repair race. Windows/Claude Desktop Cowork confirmation remains outstanding. -- Street Level: a street-level imagery layer modelled on the iD editor's photo - overlay, with Mapillary as its first provider (free client token, CC BY-SA 4.0 - imagery). One right-rail panel holds a chip per provider, shared 360°/flat and - captured-since filters, and an embedded viewer with EXPAND, FIT/FILL and - FOLLOW (Google 3D only). Coverage lines and image cones are drawn from orbit - down to a single street; on Google 3D they sit on the bare earth, refined - against the rendered mesh near the camera, so trees and buildings hide them. - Share links carry the provider switches, the filters and the panel's collapsed - state. A server proxy caches Mapillary coverage tiles (24 h, 1 GiB on disk), - refuses cross-site requests, rate-limits per IP and backs off when Mapillary - rejects the token or rate-limits. +- Street Level: street-level imagery from providers, Mapillary first (free + client token, CC BY-SA 4.0). A right-rail panel holds a chip per provider, + 360°/flat and captured-since filters and an embedded viewer with EXPAND and + FIT/FILL. Coverage lines (below 60 km) and image cones drape on terrain and + Google 3D tiles; opening a photo frames it with one camera flight. Share + links carry the provider switches, the filters and the panel's collapsed + state. A server proxy adds the token to Mapillary coverage tiles, trims and + caches them for 24 h, refuses cross-site requests and redirects, and limits + load per IP and upstream. The panel reads KEY REQUIRED without a token and + KEY REJECTED when Mapillary refuses it. -- The CCTV and Street Level panels are portable: drag the header to float the - panel, resize it from any edge or corner, and double-click the header to dock - it again. The position persists across reloads. +- Add Norway's city bikes to the Bike Share layer: Oslo, Bergen and + Trondheim Bysykkel (Urban Sharing), Kolumbus Bysykkel in Stavanger and + Farte Bysykkel in Skien/Porsgrunn (Entur Mobility), and Bysykkel + Lillestrøm (JCDecaux), about 760 stations in all. Every feed is keyless + GBFS. `gbfs.urbansharing.com`, `api.entur.io` and `api.cyclocity.fr` join + the proxy allowlist; the last two are kept to their GBFS paths. The proxy + now sends `Client-Identifier: gods-eye-view` on every request and + `ET-Client-Name: gods-eye-view-bikeshare` to Entur, as the operators ask, + and accepts Entur's extensionless feed paths. Attributed under NLOD and + Licence Ouverte. `get_bike_share` covers the six systems too. - Add Norway's road cameras from Statens vegvesen as a CCTV pack. The camera list is one keyless GeoJSON request to the agency's OGC API view of its @@ -142,6 +1145,75 @@ largest cities) and `CCTV_VEGVESEN_VIDEO=0` keeps stills only. Attributed under NLOD 2.0. +- Add Catalonia (Servei Català de Trànsit) as a keyless CCTV source pack: ~130 + cameras from a WFS/GML feed that aggregates SCT's own highway cameras with + hotlinked Barcelona and Terrassa municipal cameras, each partner named as a + credit beside the shared provider. Ambient-card refresh paced to 3 minutes, + matching the empirically observed upstream cadence. `CCTV_CATALONIA_MAX_SOURCES` + sets the cap and `CCTV_CATALONIA_ENABLED=0` turns the pack off. The catalog + is fetched over https with redirects refused and a 1 MiB body cap, and frame + links carrying userinfo or an explicit port, or outside the publisher's frame + directory, are rejected even on an allowlisted host. Camera ids come from + each frame's SCT camera file or image path rather than the feed's + restart-dependent feature id, and rows the feed repeats collapse to one. + +- Import your own GeoJSON, KML, KMZ and GPX files from DISPLAY or by dropping + them onto the app. Show, hide, fly to or remove each file for the session. + GeoJSON/GPX draw on the ground; KML retains its styles and explicit heights. + Large repeated-style exports use shared local pins, while recorded track + vertices and segment gaps stay intact. Imports respect newer camera gestures, + leave the shared clock alone, and report malformed or oversized files. + File bytes stay on the device; rendered overlays may appear in shared map + screenshots. Thanks to [Chase Mills](https://github.com/kapturner) (#925). + +- GNSS Integrity (Events, voice-addressable, share token `3`) draws navigation + accuracy scores from a keyless regional adsb.lol sample; aircraft-level analyst + queries are unavailable for these aggregate cells. Cells do not intercept + map clicks. Pan/zoom refreshes automatically; feed failures retain the display + and explain the next retry. Aircraft-reported quality includes MLAT-positioned + contacts after GPS loss, excludes TIS-B/MLAT-derived quality, and locates GPS-loss + evidence at the last good GNSS position when available. Scores discount one + bad aircraft per cell and retain 30 minutes of visited-view evidence; they + do not confirm jamming. See [method and limits](DATA_SOURCES.md#gnss-integrity). + Contributed by [Leo Pechnicki](https://github.com/leopechnicki) (#855). + +- Live HLS cameras play on a page opened over plain HTTP from another machine + (`HOST=0.0.0.0`). The client lease id came from `crypto.randomUUID`, which + browsers only expose in secure contexts, so starting a live feed threw + before playback. The id now falls back to a v4 UUID built from + `crypto.getRandomValues`, which the server's lease check accepts. + +- Move Google geocoding behind the local server. Forward and reverse lookups now + go through `/api/google/geocode` and `/api/google/reverse-geocode` with the + server key, joining Places and Street View. Google's Geocoding web service + refuses referrer-restricted keys, so the previous browser call left + `SECURITY.md`'s advice and working search mutually exclusive: the bundled + browser key had to be unrestricted for search to work at all. That key now + needs only the Map Tiles API and the Maps JavaScript API (Street View). Keyless sessions and the Photon/Nominatim + fallback order are unchanged. + +- Voice can switch on every shipped data layer (the two scene-driven + Bhote Koshi layers stay scene-only), including transit, Recent + Imagery, wind, the weather layers, cyclones and mapped installations, and + understands their spoken names ("buses", "hurricanes", "military bases"). + One voice manifest (`src/voice/layerManifest.js`) generates the tool enums + and aliases, and a unit test fails when a new layer has no entry. +- `analyst_query` counts up to 250,000 loaded records per layer instead of the + first 2,000, and says when a layer went past that (`complete: false`). It + also answers over bikeshare stations, transit vehicles, rocket launches, + cyclones, ALPR cameras, mapped installations, local ADS-B aircraft and fire perimeters; fire + records carry their sensor (VIIRS or MODIS). +- Unknown fields, operators, units, value types, scope kinds and invalid + centres are refused with the allowed values instead of answering zero or widening to anywhere. A + layer that is off, still loading or unavailable is reported as such, not + as a count of zero; a partly answerable query is marked `partial`. + Distance sorts honour `sortDir`, a written unit such as `altitudeM(ft)` + converts, and large rankings no longer sort the whole set. +- Results carry `lat`/`lon` for each item and a `display` object with the + scope, the feed window (earthquakes and fires cover the last 24 h) and any + caveat for the screen. The model is asked to answer in one short phrase. +- The weather and Recent Imagery panels can be opened by voice. + ## [0.2.1] — 2026-10-02 — God's Eye View through Your Agent (with security fixes and other features) - Ship each bundled data pack once. The region, marine, admin-boundary, @@ -424,32 +1496,6 @@ (`src/ui/imagerySplit.js`, `src/maps/imageryComparison.js`), and `MapSourceController.subscribe()` reports every settled map switch. -## Unreleased — voice reaches every layer; honest analyst answers - -- Voice can switch on every shipped data layer (the two scene-driven - Bhote Koshi layers stay scene-only), including transit, Recent - Imagery, wind, the weather layers, cyclones and mapped installations, and - understands their spoken names ("buses", "hurricanes", "military bases"). - One voice manifest (`src/voice/layerManifest.js`) generates the tool enums - and aliases, and a unit test fails when a new layer has no entry. -- `analyst_query` counts up to 250,000 loaded records per layer instead of the - first 2,000, and says when a layer went past that (`complete: false`). It - also answers over bikeshare stations, transit vehicles, rocket launches, - cyclones, ALPR cameras, mapped installations, local ADS-B aircraft and fire perimeters; fire - records carry their sensor (VIIRS or MODIS). -- Unknown fields, operators, units, value types, scope kinds and invalid - centres are refused with the allowed values instead of answering zero or widening to anywhere. A - layer that is off, still loading or unavailable is reported as such, not - as a count of zero; a partly answerable query is marked `partial`. - Distance sorts honour `sortDir`, a written unit such as `altitudeM(ft)` - converts, and large rankings no longer sort the whole set. -- Results carry `lat`/`lon` for each item and a `display` object with the - scope, the feed window (earthquakes and fires cover the last 24 h) and any - caveat for the screen. The model is asked to answer in one short phrase. -- The weather and Recent Imagery panels can be opened by voice. - -## Unreleased — local receiver feeds - ### Local receiver feeds - The Local ADS-B layer also reads local 1090 MHz and 978 MHz UAT decoder @@ -592,7 +1638,6 @@ 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). - - New Fire Perimeters layer (Events group): live NIFC WFIGS interagency wildfire incident perimeters as ground-clamped polygons with a containment-colored fire line, refreshed every 5 minutes from the public @@ -869,6 +1914,7 @@ of current runtime behavior, see [`docs/CURRENT-STATE.md`](docs/CURRENT-STATE.md ### Other changes + - Add ECMWF IFS model selection to Wind (#464, thanks @beneduzi), with model-scoped forecast-step caches, cancellation of replaced requests, and separate issue/valid timestamps. - Add bounded Director feature actions with accessible controls, explicit camera/layer admission and cancellation; restore pack geometry on same-shot seek. Preserve existing scenes and content attribution. @@ -1677,3 +2723,4 @@ represent previously published GitHub Releases. ## [0.1.0] — 2026-02-09 - Initial project version. + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1762175ce..5e625cd84 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -71,8 +71,8 @@ head -40 scripts/qa-radio.mjs # what this runnable gate proves and how to run i Runnable gate entrypoints document what they assert and how to invoke them. Most need a dev server; some also need a specific provider key or port. Follow the entrypoint's header rather than assuming every matching file accepts the -same arguments. Only a couple (`qa:map-source-tray`, `qa:transit`) have an -`npm run` alias. +same arguments. Four have an `npm run` alias: `qa:map-source-tray`, +`qa:street-level`, `qa:street-level:fixtures` and `qa:transit`. If you aren't sure which gate covers your change, search `docs/CURRENT-STATE.md` for the feature: it names the gate for many of them, and it's the authoritative @@ -80,12 +80,12 @@ runtime reference either way. `scripts/qa-l9-matrix.mjs` aggregates the broader release-candidate checks and selected harnesses; it does not replace the focused gate for the feature you changed. -> **CI does not cover this for you.** The workflow runs the setup policy +> **CI covers only two of these for you.** The workflow runs the setup policy > checks, the formatting and package-boundary checks, the unit suite and the > production build, plus a Windows onboarding job. It runs neither -> `npm run test:track` nor any `qa-*.mjs` gate — both need a live dev server -> and a browser. Include the applicable local run in your PR's validation -> evidence. +> `npm run test:track` nor any `qa-*.mjs` gate except the Street Level fixture +> gate (`street-level-browser` job) — they need a live dev server and a +> browser. Include the applicable local run in your PR's validation evidence. ## Share-link layer tokens @@ -96,8 +96,8 @@ if its layer is later removed. New layers first use the remaining unreserved single-character digits (`0` through `9`), then the two-character base-36 namespace (`00` through `zz`). On the -current published ledger, `0`, `1` and `2` are already owned, so the next -choices are `3` through `9`, then `00`. After rebasing onto the latest `main`, run +current published ledger, `0`, `1`, `2` and `3` are already owned, so the next +choices are `4` through `9`, then `00`. After rebasing onto the latest `main`, run `npm run layer-token:next -- `, add that result to both the permanent JSON reservation ledger and registry entry, and keep the exact registered-layer count assertion up to date. The token is assigned against the merge-time base, not @@ -115,7 +115,7 @@ remove only your still-unpublished layer's registry entry and ledger row so the local registry is valid again, then rerun `npm run layer-token:next -- `. For example, if PR A publishes `0` while PR B still provisionally uses `0`, PR B removes only its own provisional entry, reruns the helper, and receives -`3`. Put `3` on PR B's registry entry and ledger row, update its pinned count +`4`. Put `4` on PR B's registry entry and ledger row, update its pinned count and token tests, then rerun `npm run layer-token:check -- --base-ref origin/main`. An invalid duplicate ledger can fail during module import before the helper prints anything; never fix that by renaming or deleting PR A's published token. @@ -125,15 +125,15 @@ prints anything; never fix that by renaming or deleting PR A's published token. The highest-leverage places to jump in: - **🌆 Add a CCTV source pack.** Austin is the reference camera source. Adding another city means a clean public camera catalog with coordinates, attribution, and server-registered frame URLs (the proxy only fetches registered URLs — never client-supplied ones, see [SECURITY.md](SECURITY.md)). City packs are the best first lane. -- **🛰️ Add or improve a data layer.** Layer factories live in `src/layers//`, with source, record, controller and renderer owners implementing the layer interface (`init/enable/disable/update/destroy/getStats`, optional `getDetectableObjects`/`getStats`). Use an existing layer as a template. +- **🛰️ Add or improve a data layer.** Layer factories live in `src/layers//`, with source, record, controller and renderer owners implementing the layer interface (`init/enable/disable/update/destroy/getStats`, optional `getDetectableObjects`/`getStats`). Use an existing layer as a template, and see [Adding a new layer](#adding-a-new-layer) for what the PR needs. - **🎙️ Extend voice control.** Voice arguments are defined in `src/voice/actionSchemas.js`, with server-side descriptions in `server/providers/openai/tools.js` and client-side execution in `src/voice/gevActions.js`. Keep the tool surface tight and the responses honest (confirm only what actually happened). - **🎨 Add a visual style.** Styles are GLSL post-process shaders in `src/styles/`. - **🐛 Fix bugs / improve the first-run experience.** See [docs/KNOWN-ISSUES.md](docs/KNOWN-ISSUES.md). ## Architecture in one minute -- **No framework.** Vanilla JS + [CesiumJS](https://cesium.com/platform/cesiumjs/) + [Vite](https://vitejs.dev/). -- **Assembly lives in `src/app/`; standalone defaults live in `src/standalone/`.** UI controllers live in `src/ui/`, layer factories in `src/layers/`, portable sources in `src/sources/`, and application operations in `src/services/`. Existing `src/ui.js` and `src/data/.js` entries retain compatibility; new code belongs with its focused owner. +- **Vue 3 + Pinia for the interface,** [CesiumJS](https://cesium.com/platform/cesiumjs/) for the globe and [Vite](https://vitejs.dev/) to build. See [Building UI](#building-ui). +- **Assembly lives in `src/app/`; standalone defaults live in `src/standalone/`.** UI controllers live in `src/ui/`, layer factories in `src/layers/`, portable sources in `src/sources/`, and application operations in `src/services/`. Existing `src/data/.js` entries retain compatibility; new code belongs with its focused owner. - Sources acquire records; renderers own Cesium resources. Import `gods-eye-view/layers//source` when only a source factory is needed. Common voice controls consume the session interface; protocol adapters own connection details. - **Secrets stay server-side.** Anything needing a private key goes through a local proxy under `server/providers/`. The browser only ever sees the Google Maps key (which you restrict) and ephemeral tokens. - `docs/CURRENT-STATE.md` is the authoritative runtime reference — read it first. @@ -143,8 +143,65 @@ The highest-leverage places to jump in: - ES modules, **2-space indent, single quotes, semicolons.** - JSDoc on exported/public functions. - Match the surrounding code — comment density, naming, and idiom. +- User-visible text goes through `t()` or `tn()`, with `msg()` marking English that is stored and translated later. Components call `t()` in their templates, so their text follows the locale; `data-i18n*` attributes are only for static page markup such as the loading screen, and `npm run i18n` rejects them in a template. `npm run i18n` must pass. See [docs/I18N.md](docs/I18N.md). - Prefer small, reviewable commits. Conventional-commit-style prefixes (`feat:`, `fix:`, `perf:`, `docs:`) are appreciated but not required. +## Building UI + +New UX elements are Vue components whose state lives in a Pinia store, and so +are existing ones when a change converts them: + +- **Views are Vue components.** Application views live in `src/ui/views/` and + the components they place in `src/ui/views/panels/`; a component that + belongs to one feature sits beside its owner (`src/ui/rail/`, + `src/ui/weather/`). A view renders what its store holds and forwards + clicks and input to the store; it holds no application logic. +- **State lives in a Pinia store** in `src/ui/stores/`. The owner presents a + plain view object and publishes it to the store; the view renders it. User + actions return to the owner through handlers it connects to the store, + which replace an earlier owner's. Where several owners answer different + actions of one store, use `createOwners()` from `src/ui/stores/owners.js`: + `act(name, ...args)` calls the newest connected owner that handles `name`, + and the owner calls `detach(token)` when it stops. +- **Portable owners stay framework-free.** An owner in a portable export + imports neither Vue nor Pinia: it takes a `publish` option or offers a + `subscribe…()`, and the application shell connects it to the store. + `npm run check:boundaries` enforces this. +- **Reuse the kit first.** `src/ui/kit/` has one component per control: + `UiButton` (including pressed toggles and pressable chips), `UiSelect`, + `UiSlider`, `UiSegmented`, `UiChip` (a label, not a control), `UiBadge`, + `UiEmpty`, `UiIcon`, `UiTooltip`, `UiPanel` and `UiRail`. Use these before + writing a control. When the kit lacks something, extend a kit component or + add one that follows the kit's names, props, events and class names (see + [Component kit](docs/VUE-MIGRATION.md#component-kit)), rather than + building a one-off. +- **No hand-written DOM binding.** Don't build elements or write text, + classes or attributes from a controller to show UI state; render it from + the store. New controls take input through the store rather than through + listeners the owner adds. To render outside the view's host (the body, the + globe container, or a slot another surface opens), use `` to + `body`, a fixed id or a container the owner publishes; don't move nodes by + hand. What stays imperative: classes on `` and ``, which sit + outside Vue (`cockpit-mode`, `ui-clean-view`); focus moves; positions a + layout pass measures in the same task that writes them; and surfaces an + owner paints or plays, such as the Cesium canvas, overlay canvases and live + video. A few existing surfaces keep listeners or bindings that + [docs/VUE-MIGRATION.md](docs/VUE-MIGRATION.md) records; keep those + contracts when you change them, and don't copy them into new UI. +- **Text** goes through `t()` or `tn()` where the template renders it. + English kept in a constant or a store is marked with `msg()` and passed to + `t()` when it renders, since a `t()` at module load would fix the English. +- **Test components, not markup strings.** Mount the component over + happy-dom with `@vue/test-utils` or `createApp` and assert what it renders + from its store (see `src/testSupport/vueDom.mjs`, `src/ui/kit/*.test.mjs` + and `src/ui/views/intelHudView.test.mjs`). Run one such file with + `node --import=./build/registerVue.js --test `. Don't pass happy-dom + nodes to `assert.equal`/`deepEqual`; compare them with `assertSameNode()` + from `src/testSupport/domAssert.mjs`. + +[docs/VUE-MIGRATION.md](docs/VUE-MIGRATION.md) records how each surface moved +and what stays imperative, and why. + ## Formatting and reusable components Run `npm run format` before submitting changes, then `npm run format:check` @@ -166,9 +223,36 @@ ownership and adoption process. 1. Branch off `main`. 2. Keep `npm run build`, `npm test`, and `npm run test:track` green and avoid new console errors, plus the [feature gate](#feature-regression-gates) for the area you touched. -3. If you change runtime behavior, update `docs/CURRENT-STATE.md` and `CHANGELOG.md` in the same PR. +3. If you change runtime behavior, update `docs/CURRENT-STATE.md` in the same PR, and add your changelog entry as `changelog.d/-.md` instead of editing `CHANGELOG.md` — see [changelog.d/README.md](changelog.d/README.md). Distinct filenames don't conflict; a release assembles the directory into `CHANGELOG.md`. A documentation claim that needs a regression test should assert against `docs/CURRENT-STATE.md` or `README.md`, which a PR still edits directly. 4. If you add or change a data source, update [DATA_SOURCES.md](DATA_SOURCES.md) with its license and attribution. **Don't add data you don't have the right to redistribute** — fetch it at runtime instead. 5. Describe what you changed and how you verified it (screenshots welcome for anything visual). +6. If you add a new layer, fill in the new-layer section of the PR template. See [Adding a new layer](#adding-a-new-layer). + +## Adding a new layer + +A new layer changes what everyone sees on the globe, so maintainers need to see +it working and know where its data comes from before reviewing the code. PRs +that add a layer must include all four of these in the description. The PR +template has a section for them. + +1. **Screenshots.** At least one of the layer on the globe, plus its info card + or panel if it has one. +2. **A screen recording**, preferably 15 to 30 seconds: turn the layer on, move + around, and open a record. Drag an `.mp4` or `.mov` into the PR description. + GitHub accepts videos up to 10 MB on free accounts, so link to a larger file + instead of attaching it. +3. **The proposed category.** Say which layer-panel group the layer belongs in. + The groups are defined in `PANEL_GROUPS` in `src/ui/layerPanel.js` (today: + Movement, Cameras, Infrastructure, Events, Weather and Utilities). A layer + that isn't listed there falls under "Other layers". If none of the groups + fits, propose a new one and explain why. +4. **The data source and licence.** Name the provider and endpoint, link its + licence or terms, give the attribution shown in the app, and say whether it + needs a key and whether the data is fetched at runtime or bundled. Add the + same details to [DATA_SOURCES.md](DATA_SOURCES.md) and register the credit + in `src/data/dataCredits.js`. + +Maintainers may hold a layer PR until all four are there. ## Maintainers diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index f42517706..0ae94b746 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -20,11 +20,14 @@ How to read this: | **NOAA nowCOAST observed weather** (`nowcoast.noaa.gov/geoserver/observations/{weather_radar,satellite}/ows`, WMS 1.1.1) | Rain radar (MRMS base reflectivity, contiguous US, about 4-minute updates) and Satellite clouds (GOES-19/18 Band 14 regional infrared, about 5-minute updates; global infrared mosaic, hourly). Keyless; layer metadata refreshed every 2 minutes, exact-time images cached for up to 24 hours | [NOAA disclaimer](https://oceanservice.noaa.gov/disclaimer.html) | "NOAA nowCOAST · NWS/OAR MRMS radar; NESDIS GOES and global satellite partners" | | **NOAA nowCOAST lightning density** (`nowcoast.noaa.gov/geoserver/observations/lightning_detection/ows`) | Lightning density: 15-minute accumulated strike density on an approximately 8 km grid, Americas and Pacific. Keyless; layer metadata refreshed every 10 minutes, exact-time images cached for up to 24 hours | NOAA Level-5 derived product from Vaisala NLDN/GLD360; the [product description](https://ocean.weather.gov/lightning/lightning_pdd.php) permits public distribution of this density product, not of raw Vaisala detections | "NOAA/NWS nowCOAST; derived from Vaisala NLDN/GLD360" | | **NOAA NHC / CPHC advisories** (`www.nhc.noaa.gov/CurrentStorms.json` + the `mapservices.weather.noaa.gov` tropical weather summary MapServer) | Cyclone advisories: storm positions, forecast tracks, points and cones for the Atlantic and eastern/central North Pacific. Keyless through `/api/cyclones`; cached for 5 minutes | [NWS public-data terms](https://www.weather.gov/disclaimer); no endorsement implied | "NOAA/NWS NHC / CPHC" | -| **Mapillary** (vector tiles, Graph API, MapillaryJS) | Street Level: coverage lines, image cones and the embedded viewer. Coverage tiles cached for 24 h | Imagery [CC BY-SA 4.0](https://www.mapillary.com/terms); API under the Mapillary terms with a client token | "© Mapillary contributors, CC BY-SA 4.0", shown on the globe while the provider is on | +| **Mapillary** (vector tiles, Graph API, MapillaryJS) | Street Level: coverage lines, image cones and the embedded viewer. Coverage tiles kept in server memory for 24 h | Imagery [CC BY-SA 4.0](https://www.mapillary.com/terms); API under the Mapillary terms with a client token | "© Mapillary contributors, CC BY-SA 4.0", shown on the globe while the provider is on | +| **Google Street View** (Maps JavaScript API) | Street Level, on the Google 3D map only (Google's terms): Google's panorama viewer and nearest-panorama lookups; panorama dates and addresses kept for the session only | Google Maps Platform ToS (your own key + billing; every panorama load is billed) | "Street View imagery © Google" on the globe while the provider is on, and Google's logo and terms in the viewer | +| **KartaView** (`api.kartaview.org` coverage tiles and photo API, `cdn.kartaview.org` image proxy, `storage*.openstreetcam.org` photos) | Street Level: coverage lines (z13–14 JSON tiles; with the imagery filter on, KartaView's filtered PNG tiles as a mask), nearest-photo lookups, the photo's sequence and the photo itself, fetched by the browser. Keyless; nothing cached beyond the session | Imagery [CC BY-SA 4.0](https://kartaview.org/terms) (KartaView terms §4); the public API needs no token | "© KartaView contributors, CC BY-SA 4.0", shown on the globe while the provider is on | +| **Panoramax** (`api.panoramax.xyz` meta-catalogue: vector tiles and STAC search; pictures from the federated instance holding each one, e.g. `panoramax.openstreetmap.fr`, `panoramax.ign.fr`) | Street Level: coverage lines, nearest-picture lookups, a sequence's pictures as cones, and the picture itself, fetched by the browser. Keyless; tiles cached by the browser for an hour (the API's own header) | Per picture: mostly [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), IGN's [Licence Ouverte 2.0](https://www.etalab.gouv.fr/licence-ouverte-open-licence/); the API needs no token | "© Panoramax contributors, licence per picture" on the globe while the provider is on; the caption names each picture's author and licence | | **OpenStreetMap** | Map and place data (roads, military areas and names, ALPR, place search, outlines); via vector tiles, hourly ALPR extract, bundled data, Nominatim and optional self-configured Overpass | [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/) | © OpenStreetMap contributors | | **Google Map Tiles API** (Photorealistic 3D Tiles) + Places/Geocoding | The 3D globe, voice scene context, and on-demand nearby installation search | Google Maps Platform ToS (proprietary, your own key + billing) | "Google" / "Google Maps" logo — **shown in-app**, required | | **OpenSky Network** | Primary worldwide live-flight snapshot | Non-commercial research/education license | Schäfer et al., _"Bringing Up OpenSky"_, IPSN 2014 + opensky-network.org | -| **adsb.lol point API** | Bounded live-flight fallback when OpenSky has no usable snapshot | ODbL 1.0 | adsb.lol contributors; `api.adsb.lol/v2/lat/{lat}/lon/{lon}/dist/{radius}` | +| **adsb.lol point API** | Bounded live-flight fallback when OpenSky has no usable snapshot; GNSS Integrity layer (aircraft-reported NIC/NACp and GPS-loss integrity facts, via `/api/gnss-integrity`, 60 s server cache) | ODbL 1.0 | adsb.lol contributors; `api.adsb.lol/v2/lat/{lat}/lon/{lon}/dist/{radius}` | | **adsb.lol** | Military flights + aircraft traces | ODbL 1.0 | "adsb.lol" (ODbL) | | **adsbdb** (`api.adsbdb.com`) | Aircraft type, model name and registration by ICAO hex for enriched flights; airline and origin/destination airports for the tracked flight's callsign | No licence or rate limit is published for the service. Its own credits: aircraft data from PlaneBase, ICAO-to-N-number conversion by Guillaume Michel, and flight route data that "is the work of David Taylor, Edinburgh and Jim Mason, Glasgow, and may not be copied, published, or incorporated into other databases without the explicit permission of David J Taylor, Edinburgh" | "adsbdb — api.adsbdb.com" (courtesy); route data credited to David Taylor, Edinburgh, and Jim Mason, Glasgow | | **AISStream.io** | Live vessels (AIS) | Free, beta, no formal ToS; AIS is a public broadcast | "AISStream.io" (courtesy) | @@ -32,8 +35,10 @@ How to read this: | **The Space Devs — Launch Library 2 v2.3** | Recent launch, payload, stage, and recovery metadata for Space Missions (30d) | [The Space Devs terms of use](https://github.com/TheSpaceDevs/Tutorials/blob/main/faqs/faq_TSD.md#terms-of-use): data may be used and shared in any form; avoid forwarding it without added value; attribution is encouraged (not mandatory). [Official API limits](https://ll.thespacedevs.com/docs/): 15 unauthenticated calls/hour; optional token | "Launch Library 2 — The Space Devs" (courtesy attribution) | | **Esri World Imagery** (ArcGIS Online tile service) | The keyless satellite basemap — the default landing when no Google/ion credential is configured, and the "Esri Satellite" map stack | [Esri Master Agreement](https://www.esri.com/en-us/legal/terms/full-master-agreement): the public World Imagery service is usable in public-facing apps with attribution; no key is required for this classic endpoint, but Esri governs and can change access — an app at scale should review current ArcGIS Location Platform terms | "Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community" (provider carries the service's own credit line) | | **USGS** | Earthquakes | U.S. public domain | "Data courtesy of the U.S. Geological Survey" | +| **Environment and Climate Change Canada** (MSC GeoMet OGC API) | Air quality (AQHI) — Canadian station observations | [ECCC Data Servers End-use Licence](https://eccc-msc.github.io/open-data/licence/readme_en/) (open, attribution required, no endorsement implied) | "Contains information licensed under the Environment and Climate Change Canada Data Servers End-use Licence" | | **NASA GIBS** (WMTS tiles + Worldview Snapshots) and **NASA CMR** (granule catalog) | Recent Imagery layer: HLS S30/L30 (Sentinel-2, Landsat 8/9) and VIIRS true-colour tiles draped on the map, per-day thumbnails and PNG exports; the HLS granule catalog (dates, cloud, footprints) for a selected box | U.S. public domain (NASA data); keyless, browser-direct (CORS `*`); no bulk use — one 30-day catalog query per box, tiles bounded to the box, six tile requests in flight | "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS)." — [gibs.earthdata.nasa.gov](https://gibs.earthdata.nasa.gov), [HLS](https://lpdaac.usgs.gov/products/hlss30v002/) | | **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" | +| **S2 Underground GhostMaps** (`github.com/s2underground/GhostMaps`) | S2 GhostMaps layer: the current edition of S2's KMZ intel products (Common Intelligence Picture, 30-day kinetic pull, Border Crisis Map, Iran and Yemen products, newest incident drop). Keyless. `/api/ghostmaps` reads the branch head from git's ref advertisement every 15 s (`GHOSTMAPS_POLL_SECONDS`, minimum 5 s), lists the tree through the GitHub REST API only when the head changes (optional `GITHUB_TOKEN`), downloads files by commit-pinned raw URLs into `.gev-cache/ghostmaps/` and pushes new catalogs to browsers over server-sent events | [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (repository README: "S2 Underground © 2025 by S2A1"); non-commercial, attribution required; files are fetched at runtime, never stored in this repository | "S2 GhostMaps intel products: S2 Underground © by S2A1, CC BY-NC-SA 4.0" — shown in-app | | **InciWeb** (inciweb.wildfire.gov) | Per-incident "InciWeb ↗" card links to official incident pages (narratives, evacuation/closure notices) | U.S. government public incident information. Links are matched best-effort by incident name and state, with incident page origin and update times checked on selection. Same-origin `/api/fire-perimeters/inciweb` routes cache the catalog for 1 hour and publication metadata for 30 minutes; linked pages remain InciWeb content | "Incident information: InciWeb (inciweb.wildfire.gov)" | | **OpenFreeMap / OpenMapTiles** | Vector tiles | OpenStreetMap data under ODbL 1.0 | OpenFreeMap © OpenMapTiles | | **Overture Maps Foundation** | Military area names pack | [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/) | Overture Maps Foundation | @@ -44,6 +49,7 @@ How to read this: | **GDELT Project DOC 2.0** | Fail-soft fallback for location-matched cockpit headlines | [GDELT Terms of Use](https://www.gdeltproject.org/about.html#termsofuse): unrestricted academic/commercial/governmental dataset use, with citation and link required; linked articles retain publisher terms | "GDELT Project" plus each article's linked publisher/domain | | **City of Austin Open Data** | CCTV camera catalog + frames | City of Austin Open Data Terms of Use | "City of Austin, TX — data.austintexas.gov" | | **TxDOT ITS (its.txdot.gov)** | CCTV camera catalogs + frames, Texas districts | Public TxDOT traffic camera data | "Texas Department of Transportation" (courtesy) | +| **FL511 (Florida DOT)** | CCTV camera catalog + frames, Florida statewide | FL511 content, individual personal use only; any other use needs FDOT's express written consent ([terms](https://fl511.com/privacy#disclaimer)). **Off by default**; set `CCTV_FLORIDA_ENABLED=1` to enable | "Florida DOT — FL511.com" (courtesy) | | **City of Tallinn (ristmikud.tallinn.ee)** | CCTV camera catalog + frames, Tallinn intersections | Public City of Tallinn traffic camera data | "City of Tallinn — ristmikud.tallinn.ee" (courtesy) | | **Transpordiamet / Tarktee** | CCTV camera catalog + frames, Estonia road-weather cameras | Public Transpordiamet / Tarktee road camera data | "Transpordiamet / Tarktee — tarktee.transpordiamet.ee" (courtesy) | | **Stadt Warendorf webcam** | Webcam frames, Marktplatz / Historisches Rathaus (`config/cctv_sources.warendorf.json`) | Public municipal webcam data | "Stadt Warendorf — webcam.warendorf.de" (courtesy) | @@ -55,8 +61,25 @@ How to read this: | **Fintraffic / Digitraffic (weathercams)** | CCTV camera catalog + frames, Finland | [CC BY 4.0](https://www.digitraffic.fi/en/terms-of-service/) — attribution REQUIRED | "Fintraffic / digitraffic.fi, license CC BY 4.0" | | **DriveBC** (Government of British Columbia) | CCTV camera catalog + frames, British Columbia highways | [Open Government Licence – British Columbia](https://www2.gov.bc.ca/gov/content/data/open-data/open-government-licence-bc) — attribution REQUIRED | "DriveBC. Contains information licensed under the Open Government Licence – British Columbia" | | **Open Calgary** (`data.calgary.ca`) | CCTV camera catalog + frames, Calgary | [Open Government Licence – City of Calgary](https://data.calgary.ca/stories/s/Open-Calgary-Terms-of-Use/u45n-7awa) — attribution REQUIRED | "Contains information licensed under the Open Government Licence – City of Calgary" | +| **Servei Català de Trànsit** (+ Ajuntament de Barcelona, Ajuntament de Terrassa) | CCTV camera catalog + frames, Catalonia | [Llicència oberta d'ús d'informació - Catalunya](https://web.gencat.cat/ca/generalitat/dades-indicadors/dades-obertes/llicencies) — attribution REQUIRED | "Servei Català de Trànsit"; partner-supplied cameras also name their owner | +| **King County Road Services** (`services.arcgis.com`, King County GIS) | CCTV camera catalog + frames, unincorporated King County WA road network | [KCGIS Center terms](https://kingcounty.gov/en/dept/kcit/data-information-services/gis-center/about/terms-conditions-copyrights) — attribution required; public ArcGIS layer | "King County Road Services" (partner-city cameras name their owner) | +| **WSDOT** (`data.wsdot.wa.gov`) | CCTV camera catalog + frames, Washington State highways | [WSDOT travel information disclaimer](https://wsdot.wa.gov/about/policies/travel-information-disclaimer) — public "low volume" feed; catalog cached, frames on WSDOT's own image host only | "Washington State Department of Transportation (Travel Center)" (courtesy) | +| **Hong Kong Transport Department / DATA.GOV.HK** | CCTV camera catalog + frames, Hong Kong traffic snapshot cameras | [DATA.GOV.HK Terms of Use](https://data.gov.hk/en/terms-and-conditions) — attribution REQUIRED | "Hong Kong Transport Department / DATA.GOV.HK" | | **Statens vegvesen** (catalog `ogckart-sn1.atlas.vegvesen.no`, frames `kamera.atlas.vegvesen.no`, HLS `kamera.vegvesen.no`) | CCTV camera catalog + frames + live HLS video, Norway road cameras | [NLOD 2.0](https://data.norge.no/nlod/en/2.0) — attribution REQUIRED | "Contains data under the Norwegian licence for Open Government data (NLOD) distributed by Statens vegvesen" | -| **GBFS (Lyft / BCycle)** | Bikeshare availability | Per-feed (attribution-only) | Credit the operator (e.g. Austin BCycle) + its `license_url` | +| **Kartverket** (`ws.geonorge.no/hoydedata/v1/punkt`) | Terrain heights (NN2000) used as the ground prior for Statens vegvesen cameras | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) — attribution REQUIRED | "© Kartverket", modified (heights over water set to 0 m, rounded to 0.1 m) | +| **NYC DOT Traffic Management Center** (`webcams.nyctmc.org`) | CCTV camera catalog + frames, New York City five boroughs | NYC DOT requires developers to sign a [data-sharing agreement](https://www.nyc.gov/html/dot/html/about/datafeeds.shtml) for the camera feed. **Off by default**; enable only under your own agreement | "NYC DOT Traffic Management Center" + NYC DOT's required application disclaimer (in the Data attribution popover) | +| **City of Toronto Open Data** (`opendata.toronto.ca`) | CCTV camera catalog + frames, Toronto city streets | [Open Government Licence – Toronto](https://www.toronto.ca/city-government/data-research-maps/open-data/open-data-licence/) — attribution REQUIRED | "Contains information licensed under the Open Government Licence – Toronto" | +| **Autostrada del Brennero (A22)** (catalog `tourism.api.opendatahub.com`, frames `www.autobrennero.it/WebCamImg/`) | CCTV camera catalog + frames, A22 Brenner–Modena motorway, Italy | Public Autobrennero webcam images; camera list republished by the Open Data Hub, whose records are tagged CC0 (`ClosedData: false`, licence holder Autobrennero); Autobrennero publishes no terms of its own for the images | "Webcam images © Autostrada del Brennero S.p.A., via the Open Data Hub (NOI Techpark)" (courtesy) | +| **GBFS (Lyft / BCycle / Social Bicycles / PBSC)** | Bikeshare availability | Per-feed (attribution-only) | Credit the operator (e.g. Austin BCycle) + its `license_url` | +| **Bike Share Toronto** (`toronto.publicbikesystem.net`) | Bikeshare station availability, Toronto | Operator GBFS feed. No licence is published: the City's open-data package declares none and the feed has no `license_url`. Attribution is given to the operator. | "Bike Share Toronto (Toronto Parking Authority)" | +| **Bike Itaú / Tembici** (`*.publicbikesystem.net`, seven Brazilian cities, Santiago and Bogotá) | Bikeshare station availability: São Paulo, Rio de Janeiro, Salvador, Recife, Porto Alegre, Brasília, Curitiba, Santiago de Chile and Bogotá | Operator GBFS feeds. No licence is published: the feeds' `system_information.json` carries no `license_url`, operator or attribution fields. Attribution is given to the operator. | "Bike Itaú (Tembici)"; "Tembici Bogotá" | +| **Bicing** (`barcelona.publicbikesystem.net`) | Bikeshare station availability, Barcelona | Operator GBFS feed (PBSC), keyless. The feed publishes no licence; the City's own open-data copy of the same station data is CC BY 4.0 but needs a token. Attribution is given to the operator. | "Bicing, Barcelona City Council (B:SM)" | +| **BiciMAD** (`madrid.publicbikesystem.net`) | Bikeshare station availability, Madrid | Operator GBFS feed (PBSC), keyless. Madrid's open-data catalogue publishes this feed (`datos.madrid.es`, dataset `900021-0-bicimad-gbfs`, owner EMT Madrid) under [EMT's open-data terms](https://mobilitylabs.emtmadrid.es/sip/terms-of-use): commercial and non-commercial reuse, with attribution REQUIRED (section 5.2). | "Powered by EMT de Madrid", linking to `https://www.emtmadrid.es` | +| **Spanish city bikes on PBSC** (`*.publicbikesystem.net`: Zaragoza, Valladolid, A Coruña, Donostia-San Sebastián, Bilbao, Rivas-Vaciamadrid) | Bikeshare station availability: Bizi Zaragoza, BIKI, BiciCoruña, Dbizi, Bilbao Bizi, BicinRivas | Operator GBFS feeds, keyless. The feeds' `system_information.json` carries no `license_url`, and no operator or city publishes a licence for them; MobilityData's catalogue lists CC BY 4.0 without naming a source. Attribution is given to the operator. | "Bizi Zaragoza"; "BIKI, AUVASA (Valladolid)"; "BiciCoruña"; "Dbizi (Donostia-San Sebastián)"; "Bilbao Bizi, Bilbao City Council"; "BicinRivas, Rivas-Vaciamadrid City Council" | +| **AMBici** (nextbike, `gbfs.nextbike.net`) | Bikeshare station availability, Barcelona metropolitan area (e-bikes) | Operator GBFS feed, keyless. `system_information.license_id` is **CC0-1.0**; no attribution required, given anyway. | "AMBici, Àrea Metropolitana de Barcelona, operated by nextbike" | +| **Oslo / Bergen / Trondheim Bysykkel** (Urban Sharing, `gbfs.urbansharing.com`) | Bikeshare availability, Oslo, Bergen and Trondheim city bikes. Keyless GBFS; the proxy sends the `Client-Identifier` header the operators ask for | [NLOD 2.0](https://data.norge.no/nlod/en/2.0) — attribution REQUIRED ([Oslo](https://oslobysykkel.no/en/open-data/realtime), [Bergen](https://bergenbysykkel.no/en/apne-data/sanntid), [Trondheim](https://trondheimbysykkel.no/en/open-data/realtime)) | "Contains data under the Norwegian licence for Open Government data (NLOD) made available by Oslo Bysykkel, Bergen Bysykkel and Trondheim Bysykkel" | +| **Kolumbus / Farte Bysykkel** (Entur Mobility, `api.entur.io/mobility/v2/gbfs`) | Bikeshare availability, Kolumbus Bysykkel (Stavanger/Nord-Jæren) and Farte Bysykkel (Skien/Porsgrunn). Keyless GBFS; the proxy sends the `ET-Client-Name` header Entur requires and is limited to Entur's GBFS paths | [NLOD](https://data.norge.no/nlod/en/2.0) per the [Entur Mobility API docs](https://developer.entur.org/pages-mobility-docs-mobility-v2) — attribution REQUIRED | "Contains data under the Norwegian licence for Open Government data (NLOD) made available by Entur (Kolumbus Bysykkel, Farte Bysykkel)" | +| **JCDecaux Cyclocity** (`api.cyclocity.fr`) | Bikeshare availability: Bysykkel Lillestrøm, Valenbisi (Valencia) and Sevici (Seville). Keyless GBFS; the proxy is limited to JCDecaux contract paths | [Licence Ouverte / Etalab](https://developer.jcdecaux.com/files/Open-Licence-fr.pdf) (each feed's `license_url`) — attribution REQUIRED | "Bysykkel Lillestrøm, Valenbisi, Sevici: JCDecaux, Licence Ouverte" | | **MBTA / MassDOT** (cdn.mbta.com) | Transit layer live vehicles and up to 15 minutes of recently observed positions, Greater Boston | MBTA / MassDOT open realtime vehicle data, used for the live view and up to fifteen minutes of recently observed positions; published for developer use and not against their use. | Attribution to MBTA / MassDOT (courtesy text) | | **CapMetro** (data.texas.gov) | Transit layer live vehicles, Austin TX | CapMetro open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to CapMetro (courtesy text) | | **Metro Transit** (Metropolitan Council) | Transit layer live vehicles, Minneapolis–St Paul | Metro Transit / Metropolitan Council open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to Metro Transit / Metropolitan Council (courtesy text) | @@ -64,6 +87,15 @@ How to read this: | **Entur** (api.entur.io) | Transit layer live vehicles, Norway | Entur open realtime vehicle data, used for the live view; published for developer use and not against their use. The client sends the `ET-Client-Name` identifying header. | Attribution to Entur (courtesy text) | | **TransLink** (Queensland Government) | Transit layer live vehicles, South East Queensland | TransLink / Queensland Government open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to TransLink / Queensland Government (courtesy text) | | **HSL** (realtime.hsl.fi) | Transit layer live vehicles, Helsinki | HSL (Helsinki Region Transport) open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to HSL (Helsinki Region Transport) (courtesy text) | +| **TTC** (bustime.ttc.ca) | Transit layer live vehicles, Toronto — surface vehicles (buses and streetcars) only | Toronto Transit Commission BusTime open realtime vehicle data, published through City of Toronto Open Data and used for the live view. The subway publishes no vehicle positions, so Lines 1/2/4 are absent rather than inferred. | Attribution to Toronto Transit Commission — City of Toronto Open Data, under the Open Government Licence – Toronto | +| **MiWay** (miapp.ca) | Transit layer live vehicles, Mississauga ON | MiWay open realtime vehicle data, published by the City of Mississauga under its Open Data Terms of Use, used for the live view. The licence is revocable and asks that the Terms of Use link travel with the data. | Attribution to MiWay — City of Mississauga Open Data, linked to the Terms of Use | +| **Hamilton HSR** (opendata.hamilton.ca) | Transit layer live vehicles, Hamilton ON | Hamilton Street Railway open realtime vehicle data, published by the City of Hamilton for commercial and non-commercial use. Not one of its 80 route ids is the number on the bus, so the route-number table in `src/data/transitFeeds.js` is derived from the City’s own published GTFS `routes.txt` under the same licence; two generations of id run at once and both are listed. | "Contains public sector Data made available under the City of Hamilton’s Open Data Licence" — wording prescribed by the licence | +| **Durham Region Transit** (drtonline.durhamregiontransit.com) | Transit layer live vehicles, Durham Region ON | Durham Region Transit open realtime vehicle data, published under the Region of Durham Open Data Licence v.1.0, which permits commercial use. | "Contains public sector information made available under The Regional Municipality of Durham's Open Data Licence" | +| **Guelph Transit** (glphtrpcloud.com) | Transit layer live vehicles, Guelph ON | Guelph Transit open realtime vehicle data, published by the City of Guelph on its open-data developer page and used for the live view. Its route ids are internal database keys, so the 33-row route-number table in `src/data/transitFeeds.js` is derived from the City’s own published GTFS `routes.txt` under the same licence. | "Contains information licensed under the Open Government Licence – City of Guelph" — wording prescribed by the licence | +| **Kingston Transit** (api.cityofkingston.ca) | Transit layer live vehicles, Kingston ON | Kingston Transit open realtime vehicle data, catalogued by the City of Kingston as open data and used for the live view. | "Contains information licensed under the Open Data Licence – City of Kingston" — wording prescribed by the licence | +| **Barrie Transit** (myridebarrie.ca) | Transit layer live vehicles, Barrie ON | Barrie Transit realtime data, published by the City of Barrie under a licence accepted by use of the data. The licence is revocable and requires no attribution. | Courtesy credit to the City of Barrie (the licence requires none, and its trademark clause is broad) | +| **YRT/Viva** (rtu.york.ca) | Transit layer live vehicles, York Region ON | York Region Transit realtime data, first-party York Region infrastructure under the YRT Open Data Licence v2.0, which permits commercial use and makes attribution optional. Viva route ids are named by colour from York Region’s published GTFS. | "Contains public transit Information made available under YRT’s Open Data Licence" — the licence’s own wording, given though not required | +| **Burlington Transit** (opendata.burlington.ca) | Transit layer live vehicles, Burlington ON | Burlington Transit realtime data under the City of Burlington Open Data Terms of Use, which permit any lawful purpose. The terms are revocable and must travel with the data, so the credit links them. Route ids are internal keys and are joined to the City’s published GTFS. | Credit to the City of Burlington plus a link to its Open Data Terms of Use, which the licence requires | | **Radio Browser** | Geolocated internet-radio station directory and station-level tags | Public-domain directory data under PDDL 1.0; individual broadcaster stream terms apply | "Radio Browser" plus a link to the selected broadcaster | | **Re:Earth Terrain** (Mapterhorn) | Terrain (keyless globe stacks — OSM etc. — + `/api/terrain/heights` ellipsoidal-height lookups) | Terrain mesh: CC BY 4.0; geoid: EGM2008 (NGA, public domain) | "Terrain (keyless globe stacks): Re:Earth Terrain / Mapterhorn (CC BY 4.0) / EGM2008 (NGA)" | | **OSRM on the FOSSGIS routing servers** (`routing.openstreetmap.de`) | Street-following routes for the Directions layer and voice route annotations, via `/api/route` | [FOSSGIS routing usage policy](https://routing.openstreetmap.de/about.html): "Display the required attribution and display a link to 'fix the map'", "Use a valid user agent and, if applicable, a correct referrer", "One request per second max", "No scraping, no heavy usage". The full policy is the German [FOSSGIS Nutzungsbedingungen](https://www.fossgis.de/arbeitsgruppen/osm-server/nutzungsbedingungen/); FOSSGIS also states that the server may be embedded in your own pages but "eine gewerbliche Nutzung ist nur mit Einschränkungen erlaubt" (commercial use only with restrictions). Route data derives from OpenStreetMap (ODbL 1.0) | "Routing: OSRM on the FOSSGIS servers" + a "fix the map" link — shown in the Data attribution popover | @@ -74,13 +106,59 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei ### Notes on the live sources +- **Air quality (ECCC AQHI).** Keyless. Read from the MSC GeoMet OGC API (`api.weather.gc.ca`): the `aqhi-stations` catalog plus `aqhi-observations-realtime`. **Coverage is Canada only** — ECCC is the single registered provider, and the layer row and readout card both say so. Roughly 134 stations across ECCC's five administrative zones (Atlantic, Quebec, Ontario, Prairies & North, Pacific & Yukon). AQHI publishes hourly, so readings poll every 20 minutes and the station catalog, which changes a few times a year, is refetched only every 12 hours. Observations are requested with `latest=true`; without it the collection returns the full history, roughly 2,000 rows nationally. Readings older than six hours are dropped rather than displayed as current. + + Readings are stored as `{ provider, scale, value, band }` rather than a bare number, because air-quality indices are not interchangeable: AQHI runs 1-10+ on health risk, the US AQI runs 0-500 on concentration breakpoints, and Europe's EAQI is a five-step category. Naming the index a value belongs to is what lets another network be added later without inventing a shared numeric meaning that does not exist. + + AQHI is reported by ECCC as an integer from 1 to 10 with an open-ended "10+" above that. The API returns the underlying decimal (1.08, 2.32); the layer rounds to the published form rather than displaying a precision the index does not claim. + + **Quebec is thinly represented**, and that is upstream rather than a filter here: the province runs its own Info-Smog program, so only a handful of Quebec stations appear in ECCC's national feed. The reporting station count also varies hour to hour as stations report or fall silent. + +- **Via Lietuva / Eismoinfo (Lithuania).** Public road-camera catalogs and periodically updated still images from [Eismoinfo](https://eismoinfo.lt/), credited to Via Lietuva / eismoinfo.lt in the app. **Off by default.** The camera endpoints are the eismoinfo.lt website backend and are not among the services listed in Via Lietuva's [open-data statement](https://eismoinfo.lt/eismoinfo-backend/content?id=44), whose conditions are attribution and reuse on the same terms. Until the statement is confirmed to cover the camera photos, the pack loads only when an operator sets `CCTV_LITHUANIA_ENABLED=1`; with the flag unset, empty or any other value, the server makes no request to Eismoinfo. `eismoinfo-backend/camera-info-table` is joined by ID to `layer-static-features/VKR`. Without `lks=true`, the latter returns WGS84 `[latitude, longitude]`; the table's `x/y` instead use LKS-94 metres. Only the official HTTPS `/eismoinfo-backend/image-provider/camera/last?id=…` image endpoint is registered. Catalogs use the shared 15-minute cache; frames are fetched on demand and never bundled or archived. These are periodic snapshots, not continuous video. Camera headings are low-confidence estimates. No API key is required. `CCTV_LITHUANIA_MAX_SOURCES` defaults to 400. +- **Freeway Bureau, MOTC (Taiwan).** National freeway cameras from the Freeway Bureau's keyless [CCTV static table](https://tisvcloud.freeway.gov.tw/history/motc20/CCTV.xml) in the MOTC 2.0 standard, refreshed daily and fetched at runtime (never bundled). Freeway Bureau traffic data is published under the [Open Government Data License, Taiwan (Version 1.0)](https://data.gov.tw/license), which permits reuse, including commercial reuse, with attribution; the app credits the Freeway Bureau, MOTC, names the dataset and links the licence, as its attribution exhibit asks. The table publishes each camera's MJPEG stream on one of four official camera servers (`cctvn`, `cctvn5`, `cctvc`, `cctvs` under `freeway.gov.tw`). The frame proxy relays single images, so each published stream URL is mapped to the same server's single-JPEG path for the same camera number (`/abs2mjpg/bmjpg` → `/abs2mjpg/jpg`, `/live-view/mjpg/video.cgi` → `/live-view/jpg/image.cgi`); only those exact HTTPS pairs are registered, and the still path is not itself listed in the table. These are on-demand snapshots, not continuous video. Camera headings are low-confidence estimates. No API key is required. The table host does not answer from some networks outside Taiwan (the camera servers do); there the pack is empty, logs one warning and retries hourly. On by default; `CCTV_TAIWAN_ENABLED=0` skips the pack, and `CCTV_TAIWAN_MAX_SOURCES` defaults to 600 (bounded to 1–2000). + - **Google Maps Platform.** You supply your own API key and are bound by [Google's ToS](https://cloud.google.com/maps-platform/terms). Google Maps Content (tiles, geocodes, places) **may not be cached, stored, rehosted, or committed** — this app only ever uses it live, which is the compliant pattern. The "Google" attribution is displayed on the globe and must stay visible. Restrict your key (see [SECURITY.md](SECURITY.md)). - **OpenSky Network.** Its license is **non-commercial**, and operational use of the REST API in a live product can require a prior written agreement with OpenSky — even for non-profit/government use. If you deploy this commercially, contact OpenSky for your own terms. The flights layer is a toggle and runs anonymously by default. - **adsb.lol flight fallback.** When OpenSky is unavailable and no last-good OpenSky response exists, the server requests a cached, capped 250 nm adsb.lol point snapshot around the current camera subpoint. This is regional observed context, not worldwide completeness; provenance is exposed in the Flights stats/context row. Military ICAOs remain reconciled through the existing dedicated military registry rather than duplicated. + + +- **GNSS integrity (adsb.lol).** A separate keyless point request samples a 250 nm + circle around the screen centre, snapped once to whole degrees. This does not + reuse the Flights fallback cache. Cache lifetime is 60 s; 429 backoff is capped + at one hour and other upstream failures cool down for 15 s. Future access may + require feeder keys under the [API terms](https://github.com/adsblol/api). + Airborne decoded ADS-B v1/v2 aircraft with a known 0–60 s position age qualify, + including MLAT-positioned aircraft still broadcasting their own quality. + TIS-B/MLAT-derived NIC and NACp are ignored. GPS-loss evidence uses + `gpsOkLat/gpsOkLon` when present, otherwise the current known position. + The proxy strips identity metadata and tags its response with classifier + `gev-nic-nacp-v2`; rows carry only integrity facts. + + The method has three separately attributed parts: + 1. **GEV classifier (unvalidated):** GPS-loss flag, aircraft-reported NACp < 8, + or aircraft-reported NIC < 7 except NIC 0 with NACp ≥ 10 (unknown containment). + The numerical minima come from US 14 CFR 91.227(c), not a published jamming + classifier. Readsb's [JSON contract](https://github.com/wiedehopf/readsb/blob/dev/README-json.md) + describes the quality field origins and GPS-loss flag. + 2. **GPSJAM aggregation:** score = `100 × max(0, bad − 1) / total`, with percent + bands < 2, 2–10, > 10. One bad aircraft is discounted. This is not the raw + share of bad aircraft. See the [GPSJAM FAQ](https://gpsjam.org/faq). + 3. **GEV window:** 30 minutes over visited views, at least three aircraft per + 0.5° cell. These bands were developed for daily totals; with fewer than ten + observations a cell can skip the middle band. Source timestamps date evidence + even through cache replays, and degraded evidence expires independently. + + Medium/high cells report navigation-integrity anomalies. Interference is one + possible explanation, not a detected or located emitter. Avionics faults and + manoeuvring military trainers can also lower reported accuracy. Blank areas + can be outside coverage or lack enough observations. Attribution: adsb.lol + contributors, ODbL 1.0; GPSJAM for aggregation only. + + - **adsbdb enrichment.** `/api/adsbdb` resolves an ICAO hex to aircraft type, model name and registration, and the tracked flight's callsign to an airline and an origin/destination pair. Fan-out is deliberately small because adsbdb is a free community API that publishes no quota: at most 4 requests in flight, dispatches dripped to roughly 5/s, and each key asked for at most once per session, with route lookups reserved for the tracked aircraft. The dev-server proxy caches each key for 24 hours in `.gev-cache/adsbdb.json`, negative answers included, so fresh entries survive server restarts. That gitignored cache remains local to the deployment and is not bundled with this repo. adsbdb publishes no general service license; its README says the route data may not be copied, published, or incorporated into other databases without the explicit permission of David J Taylor, Edinburgh. Deployers are responsible for obtaining any permission their use requires. Enrichment is best-effort and fail-silent — a flight that gets no answer keeps what the flight feed already gave it. - **Launch Library 2.** `/api/launches` makes a server-side rolling-30-day query against the supported v2.3 detailed launch endpoint, caches successful responses for 15 minutes in memory and on disk, and serves the last successful response during a throttle or transient outage. Anonymous access is limited to 15 calls/hour; deployments can provide `LL2_API_TOKEN` for authenticated access. The Space Devs' published terms permit using and sharing the API data in any form, ask users not to forward it without adding value, disclaim complete accuracy, and encourage—but do not require—attribution. This app keeps a courtesy credit. Payload and stage/recovery records are shown only when supplied. Failed launches expose their source status and never receive fallback orbit geometry or a live/estimated marker. LL2 supplies launch context and event timing, not continuous ascent telemetry or live orbital state. - **TfL JamCams.** The camera list comes from the keyless `api.tfl.gov.uk` endpoint (an optional `TFL_APP_KEY` raises its rate limit); frames come from TfL's public S3 bucket. The "Powered by TfL Open Data" attribution is required by TfL's terms and is registered in the Data attribution popover. -- **Ontario 511 CCTV.** The camera list comes from the keyless `511on.ca/api/v2/get/cameras` endpoint; frames are server-registered still images under `511on.ca/map/Cctv/`. The source is live-fetched at runtime and attributed under the Open Government Licence - Ontario. +- **Ontario 511 CCTV.** The camera list comes from the `511on.ca/api/v2/get/cameras` endpoint, which now requires a free developer key (`ONTARIO_511_API_KEY`: sign up at 511on.ca/my511/register, then request it while logged in at 511on.ca/developers/doc; throttled to 10 calls a minute). Without the key the pack is skipped. Frames are server-registered still images under `511on.ca/map/Cctv/`. The source is live-fetched at runtime and attributed under the Open Government Licence - Ontario. Access is governed by Ontario 511's Developer's Access Agreement (511on.ca/developers/resources): the data stays under the Open Government Licence - Ontario unless otherwise specified; key requests are reviewed case by case and ask for the intended use and any third parties that will receive the data; attribution by link to 511on.ca is encouraged, and the Ontario 511 logo may not be altered or used to imply endorsement (this app links and shows no logo); and the data is provided "as is", a disclaimer distributors should pass on, which the credit does. - **DelDOT live video cameras.** The keyless `tmc.deldot.gov/json/videocamera.json` catalog supplies active cameras and official `https://video.deldot.gov/live/…/playlist.m3u8` links. The local server transiently buffers bounded MPEG-TS segments in memory and deletes them on session release or idle expiry. No recordings are retained. `CCTV_DELDOT_ENABLED=0` disables the pack. Public availability is not a blanket redistribution license; deployment beyond personal local viewing needs confirmation of applicable DelDOT terms. - **Fintraffic weathercams.** The camera list is one keyless GeoJSON request to `tie.digitraffic.fi/api/weathercam/v1/stations` (809 stations / 2,275 presets), sent with the `Digitraffic-User: gods-eye-view` header the service asks clients to identify themselves with and with gzip; frames are stills on `weathercam.digitraffic.fi`, refreshed on each station's 600 s collection interval, which is also the client's ambient-still refresh cadence for this pack (the active camera keeps the usual 10-second refresh). One preset (a fixed camera view) is one camera; stations not `GATHERING` and presets not `inCollection` are dropped. Attribution is required by the CC BY 4.0 licence and is registered in the Data attribution popover. `CCTV_FINTRAFFIC_ENABLED=0` is the kill switch. - **DriveBC highway cameras.** The camera list comes from the keyless `https://www.drivebc.ca/api/webcams/` endpoint served by the DriveBC.ca site ([bcgov/DriveBC.ca](https://github.com/bcgov/DriveBC.ca)); frames come from `https://www.drivebc.ca/images/.jpg`, built from the numeric camera id. DataBC's [DriveBC HighwayCams](https://catalogue.data.gov.bc.ca/dataset/bc-highwaycams) catalogue entry publishes the same cameras under the Open Government Licence – British Columbia, but its CSV still lists the retired `images.drivebc.ca` frame URLs, which now return a placeholder. The licence's attribution statement is required and is registered in the Data attribution popover. By default the 250 cameras nearest Vancouver and Victoria load; `CCTV_DRIVEBC_MAX_SOURCES` changes the cap and `CCTV_DRIVEBC_ENABLED=0` turns the pack off. Some cameras in the feed are supplied by partners (TransLink, the City of Vancouver, the City of Surrey, Parks Canada / Alberta Motor Association and others); the feed's per-camera credit is carried onto the camera record and shown beside the provider in the CCTV panel. @@ -90,10 +168,19 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei - **Warendorf webcam.** The Stadt Warendorf Marktplatz webcam, registered from the curated `config/cctv_sources.warendorf.json` (the Kreis Warendorf registration-office cameras from the contributing PR are indoor waiting rooms and were left out); only the municipal image host is proxied, frames are fetched at request time and never stored or redistributed. Disable with `CCTV_WARENDORF_ENABLED=0`. - **Live Traffic NSW cameras.** The camera list is the keyless public `data.livetraffic.com/cameras/traffic-cam.json` feed (Transport for NSW open data, CC BY 4.0); frames are stills on `webcams.transport.nsw.gov.au`, and only that host is registered. That image host answers non-browser clients with an HTML placeholder, so the proxy identifies as a browser for that one host and as itself everywhere else. Frames are fetched at request time and never stored or redistributed. Disable with `CCTV_NSW_ENABLED=0`. - **Open Calgary traffic cameras.** Keyless. The camera list is the public Socrata dataset `k7p9-kppz` on `data.calgary.ca`; frames are stills on the city's own `trafficcam.calgary.ca` host, and only that host is registered. Most rows publish an `http://` frame URL and the host redirects those to HTTPS, so URLs are upgraded and pinned to that origin before registration. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing: the `quadrant` field and the quadrant suffix on each camera name are Calgary's address grid, not a bearing, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. The licence requires the attribution statement above. Disable with `CCTV_CALGARY_ENABLED=0`. +- **FL511 Florida cameras.** Off by default; set `CCTV_FLORIDA_ENABLED=1` to load them. The camera list is the keyless FL511 traffic camera layer on ArcGIS (`services.arcgis.com/.../FL511_Traffic_Cameras`), published from a Florida Division of Emergency Management account rather than by FL511 directly, and the service carries no licence text of its own. It is paged up to 2,000 rows at a time, ordered by the layer's object id and following ArcGIS's `exceededTransferLimit`, to cover the ~4,000-camera statewide set. Frames are stills on two Divas Cloud hosts (`images-dis.divas.cloud`, `snapshots.divas.cloud`); both are host-pinned and a row whose image resolves elsewhere is dropped. `CCTV_FLORIDA_MAX_SOURCES` caps the pack (default 500, anchored per region across the state). Each catalog page is read under a 2 MiB cap and redirects are refused. Frames are fetched live at request time and never stored or redistributed. FL511's terms (fl511.com/privacy#disclaimer) license its content for individual, personal use only; any other use, including a public deployment, needs FDOT's express written consent. +- **Catalonia (Servei Català de Trànsit) cameras.** The camera list is the keyless `https://www.gencat.cat/transit/opendata/cameres.xml` WFS/GML feed, fetched over https with redirects refused and the body read capped at 1 MiB, since the list decides ids, coordinates and which allowlisted frame path is proxied. It carries a `font` field naming the real publisher per camera; this pack keeps SCT's own highway cameras plus hotlinked Barcelona (IMI) and Terrassa municipal cameras (~130 total), each confirmed to return a real frame, so frame URLs are checked against a small host allowlist (`mct.gencat.cat`, `www.bcn.cat`, `emap.terrassa.cat`) rather than one pinned origin (a link carrying `user:pass@` userinfo or an explicit port, or pointing outside that host's frame directory, is rejected even on an allowed host; an SCT `sctidcam` must be a bare `.gif`/`.jpg` filename), and every non-SCT camera carries its real owner as a `credit` shown beside the shared `provider`. The feed carries no compass heading, so every camera loads at low heading confidence (same as TfL and Fintraffic). SCT's own feed link (`RenderService`) needed a workaround: it always 302s to a second endpoint (`TransitCamera`) on a Location the upstream hardcodes as plain http even when requested over https — refused by `fetchWithinHost`'s same-origin (scheme-included) redirect policy — and separately, `mct.gencat.cat`'s TLS setup fails the handshake with Node's fetch outright (`ERR_SSL_WRONG_SIGNATURE_TYPE`) even though other HTTP clients complete it. The loader therefore builds the `TransitCamera` URL itself, over plain http, from `RenderService`'s `sctidcam` id, rather than registering the (broken) upstream link — the only transport this one host actually serves to this runtime. Camera ids are built from the SCT camera file or the partner image path, not the feed's `fid` (which embeds an upstream server-start stamp and changes on every upstream restart), and rows the feed lists more than once collapse to one camera. The feed carries no camera status field, so a camera its publisher has taken offline still registers and shows the publisher's own "image unavailable" still (SCT and Barcelona both serve one with HTTP 200), the same as other packs without a status field. Frames are fetched at request time and never stored or redistributed. The feed itself states no licence; the pack relies on the Generalitat de Catalunya open-data portal's terms for this dataset (the licence and attribution above). Disable with `CCTV_CATALONIA_ENABLED=0`. +- **King County road cameras.** Keyless. The camera list is one public ArcGIS FeatureServer GeoJSON query (King County DOT Road Services, "King County and WSDOT Traffic Cameras"). The `outFields` list is explicit on purpose: the layer also carries asset-administration columns — including staff names — that are never fetched. Only live, active cameras with frames on the county's own `info.kingcounty.gov` image handler are registered (the feed writes `http://`; the handler serves HTTPS, so URLs are upgraded and pinned before registration). WSDOT-owned rows in the layer are skipped because their frames are WSDOT-hosted, outside the pinned image origin; partner-city cameras hosted on the county image handler (e.g. Newcastle) name their owner as the per-camera credit. The layer publishes no facing, so headings use the shared id-hash fallback at low confidence. Uniquely, the county publishes each camera's hardware `Manufacturer`/`Model` (Cohu 3950/3965, Bosch AUTODOME, Axis PTZ domes); both are carried on the source (and served by `/api/cctv/sources`) as `model` and `manufacturer` for identified-hardware consumers (vendor-generic strings such as `PTZ` name no model and are omitted). Frames are fetched at request time and never stored or redistributed. Disable with `CCTV_KINGCOUNTY_ENABLED=0`. +- **WSDOT highway cameras.** Keyless. The camera list is the Esri JSON layer `data.wsdot.wa.gov/travelcenter/Cameras.json` — the same layer WSDOT's own Travel Center map consumes (~1,700 point features, EPSG:3857 geometry converted to WGS84 on load; the body carries Windows-1252 bytes and is decoded as such). Only frames on WSDOT's own `images.wsdot.wa.gov` host are registered — the catalog also lists ~70 partner cameras (Oregon DOT, City of Seattle, lodges, airports) whose own terms apply, and those are skipped rather than proxied. WSDOT's layer metadata marks the feed for "low volume" use (see WSDOT's [travel information disclaimer](https://wsdot.wa.gov/about/policies/travel-information-disclaimer)). The catalog is fetched once per CCTV catalog refresh (every 15 minutes), and a camera's frame is fetched only when that camera is viewed; frames are never stored or redistributed. The live feed's `CompassDirection` is a single cardinal (N/E/S/W), `B` (both directions — most rows), `O`, or null. A single cardinal gives a high-confidence heading (the diagonals NE/SE/SW/NW are mapped too should they appear); `B`, `O`, null, and any other code carry no single facing and use the shared id-hash fallback at low confidence. By default the 250 cameras nearest Seattle and Spokane load; `CCTV_WSDOT_MAX_SOURCES` changes the cap (8–1,200) and `CCTV_WSDOT_ENABLED=0` turns the pack off. A keyed WSDOT Traveler Information API serves the same population for higher-volume use and is deliberately not required here. +- **Hong Kong Transport Department traffic snapshot cameras.** Keyless. The English camera list is the public DATA.GOV.HK XML at `static.data.gov.hk/td/traffic-snapshot-images/code/Traffic_Camera_Locations_En.xml`; frames are stills on `tdcctv.data.one.gov.hk`, and only that host is registered. Frame URLs are rebuilt from each camera key (`https://tdcctv.data.one.gov.hk/{KEY}.JPG`) rather than taken verbatim from the catalog. Stills were probed to answer directly on that origin with no redirect hop. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. By default nearly the full catalog loads (~1,013; pack cap 1,100), prioritized nearest Central, Tsim Sha Tsui, Sha Tin, Tsuen Wan, Tai Po, Fanling, Tuen Mun, Yuen Long and Tseung Kwan O so a lowered cap still spans Hong Kong Island, Kowloon and the New Territories. When the sum of packs exceeds the catalog-wide ceiling, shared round-robin keeps every lane represented. `CCTV_HK_MAX_SOURCES` (8–1200) changes the cap and `CCTV_HK_ENABLED=0` turns the pack off. The DATA.GOV.HK Terms of Use require attribution to the Government / Transport Department / DATA.GOV.HK. - **Statens vegvesen road cameras.** Keyless. The camera list is one GeoJSON request to the OGC API Features view of the official DATEX 3.1 CCTV site table (`ogckart-sn1.atlas.vegvesen.no/ogc/features/v1/collections/datex_3_1:CctvSimple/items`), so no DATEX account is needed; frames are stills on `kamera.atlas.vegvesen.no/api/images/`, and only that exact path per camera is registered. Cameras the feed reports as faulty are dropped. About 135 working cameras also publish live HLS (`kamera.vegvesen.no/public//manifest.m3u8`, MPEG-TS); those play as live video through the bounded in-memory HLS relay, with the still as the snapshot fallback, and only that exact manifest path per camera is registered. `CCTV_VEGVESEN_VIDEO=0` keeps every camera on stills. `orientationDescription` names the place a camera faces, not a bearing, so it goes into the label and headings use the id-hash fallback at low confidence. By default every live camera loads (~850); `CCTV_VEGVESEN_MAX_SOURCES` (8–1000) lowers the cap, keeping the cameras nearest Oslo, Bergen, Stavanger, Trondheim, Kristiansand, Bodø and Tromsø and `CCTV_VEGVESEN_ENABLED=0` turns the pack off. Frames are fetched at request time and never stored or redistributed. The NLOD attribution is registered in the Data attribution popover. +- **Kartverket ground heights for Statens vegvesen cameras.** The camera feed's points are 2D, so the loader asks Kartverket's keyless point-height API (`ws.geonorge.no/hoydedata/v1/punkt`, CC BY 4.0) for the terrain height at each camera. Requests carry 20 points: the API accepts 50, but above ~20 it answers the extra points from contour lines (`hoydekurver`, metres to ~20 m off) or not at all. Eight requests run at a time, about 36 for the whole country: a cold lookup took 6–13 s in testing (single requests 0.6–9.5 s). Answers are matched by the coordinates the API echoes and recorded only for points that request asked about. Over water the API returns the sea-floor depth (`dybdekurver` or `Havflate`), which is replaced by 0 m, the water surface; for the ~14 bridge cameras that is below the deck, but much closer than the sea floor or the flat prior. Heights are cached in memory by position for the life of the server, and points with no height (a few ferry quays and bridges, or a point a 200 answer leaves out) for 6 h, so the 15-minute catalog refresh only asks about new or moved cameras. The first failing request (a 408, 429 or 5xx, a network error, a request over 10 s, or an unreadable or oversized body) stops the lookup, with no retries, and no new lookup starts until the backoff ends (Retry-After when sent, else 30 min, longer than the refresh; bounded to 1 min–1 h). Any other 4xx marks that request's points as having no height and the lookup carries on. The whole lookup has a 30 s deadline; a lookup cut short by it resumes on the next refresh without a backoff. The lane waits at most 12 s, counted from the start of the loader, and only when more than 10% of the cameras have no answer yet; a few new cameras or expired misses are looked up in the background. A slower lookup keeps filling the cache, and the cameras it had not reached keep the flat prior until the next 15-minute refresh (about 190 of 865 on one slow first run). Only coordinates are sent, with the same User-Agent as the other CCTV requests. `CCTV_VEGVESEN_HEIGHTS=0` turns the lookup off. The Kartverket credit, with a note that heights over water are set to 0 m and heights are rounded to 0.1 m, is shown beside the Statens vegvesen entry in the Data attribution popover. +- **NYC DOT Traffic Management Center cameras.** Off by default. NYC DOT's [developer data feeds page](https://www.nyc.gov/html/dot/html/about/datafeeds.shtml) asks developers who want the camera feed to contact `tmcdot@dot.nyc.gov` and sign a data-sharing agreement. This project does not hold one that covers downstream installations, so the pack loads only when an operator who holds their own agreement sets `CCTV_NYC_ENABLED=1`; with the flag unset, empty or any other value, the server makes no request to NYC DOT. The endpoint needs no key. The camera list is the public `webcams.nyctmc.org/api/cameras` catalog (~980 cameras across the five boroughs); frames are stills at `webcams.nyctmc.org/api/cameras//image`, synthesized from a validated UUID rather than taken from the payload, and only that host is registered. Cameras the feed reports as offline are dropped. The catalog publishes no camera facing, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. Once enabled, the 250 cameras nearest the borough cores load; `CCTV_NYC_MAX_SOURCES` (8–400) changes the cap. Frames are fetched at request time and never stored or redistributed. NYC DOT asks every application that uses its data to carry its disclaimer; it is registered verbatim in the Data attribution popover. +- **City of Toronto RESCU cameras.** Keyless. The camera list is the City's public `tmcearthcameras.json` on `opendata.toronto.ca` (dataset "Traffic Cameras", Transportation Services), served as JSONP and unwrapped with an anchored pattern. This is the municipal network the Ontario 511 pack does not carry: downtown arterials plus the Gardiner, DVP, Allen and Lake Shore. The list publishes no frame URL, so frame URLs are BUILT from the documented `CameraImages/loc####.jpg` convention and a strictly-digits camera number, pinning the frame proxy to the portal origin by construction; the list fetch refuses redirects and bounds the body it buffers. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing: the `D1`-`D4` fields are the directions of the *comparison* images (static reference stills captured in 2016 under a different path), not a bearing for the live pan-tilt-zoom frame, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. A camera that is temporarily out of service still answers 200 with a byte-identical "Image Unavailable" placeholder rather than an error (about 6% of the network at any moment), so such a camera reads as healthy; the frame it shows is the agency's, not a synthesized one. The licence requires the attribution statement above. Disable with `CCTV_TORONTO_ENABLED=0`. +- **Autostrada del Brennero (A22) webcams.** Keyless. The camera list is one request to the Open Data Hub tourism API (`tourism.api.opendatahub.com/v1/WebcamInfo?source=a22`), run by NOI Techpark in South Tyrol, which republishes Autobrennero's own list of 13 motorway webcams with coordinates and kilometre markers. Frames are the operator's stills on `www.autobrennero.it/WebCamImg/km.jpg`, refreshed about once a minute, and only the exact image for each camera's kilometre is registered. The feed names no bearing, so headings use the id-hash fallback at low confidence. The road climbs from about 20 m in the Po valley to about 1,370 m at the Brenner Pass, so each camera's ground elevation comes from a per-kilometre table sampled from the Copernicus GLO-90 DEM (via Open-Meteo's elevation API); a camera not in the table uses a 200 m prior. The Open Data Hub tags every record CC0 (`ClosedData: false`, Autobrennero as licence holder), but that tag is the aggregator's metadata and Autobrennero publishes no terms of its own for the images, so they are credited to the operator as a courtesy and are not redistributed. Frames are fetched at request time and never stored. Disable with `CCTV_A22_ENABLED=0`. - **Camera frame content.** Public camera frames can contain people, vehicles and license plates, and the camera layer does nothing with them beyond putting them on the map. A successful upstream response is relayed as the provider served it: nothing in the camera pipeline blurs, redacts, enhances or restores it, and nothing there runs face, plate or object detection or otherwise recognises or classifies what is in the picture. (The ALPR layer described below maps where plate-reader cameras are, from locations contributors tagged in OpenStreetMap; it reads nothing from any camera frame.) When an upstream has no frame for a camera, what you see instead is a Google Street View still or the app's own placeholder card; the panel's source badge names which of them you are looking at, and a refresh that fails after a frame has arrived leaves the last good picture on screen rather than replacing it. The browser resamples each frame for display: onto a fixed 1920x1080 surface for the camera's projection plane in the scene, and onto a 192x108 canvas for the small ambient card. That scaling is the only change made to the picture, and the only pixels the camera layer reads back are a 64x36 downscale hashed to tell whether the picture has changed. Live streams are piped through; the still path reads the image into memory to pass it on — TxDOT wraps its JPEG in a JSON envelope, which is decoded there — and no frame is written to disk (the disk cache, `.gev-cache/`, holds feed JSON for other layers and never camera imagery). Outside that pipeline, the voice assistant is the one feature that sends imagery anywhere: when it answers a question about what is in view it may attach a downscaled screenshot of the rendered scene — including any camera plane on screen — to the request it sends to the voice model. Frames are fetched only from server-registered camera URLs — a client cannot hand the proxy a URL (see [SECURITY.md](SECURITY.md)). What the app does stays inside the line README draws: no named-person search, no face recognition, no tracking individuals. -- **Transit (GTFS-Realtime).** The proxy requests only registered operator feeds, validates redirects, bounds responses, and uses conditional requests, short snapshot caching and failure backoff. All seven registered regions are live-enabled; each can be disabled independently. Vehicles use delayed playback between reports, with report age and waiting states shown separately. Session-local selected trails are available for every feed. MBTA additionally retains up to 15 minutes of recently observed positions in the running proxy, so available history can survive a browser reload; server restart clears it. History reads never fetch upstream, and other feeds have no proxy retention. Nothing is archived to disk or collected in the background. Operator text credits are included as a courtesy and do not imply endorsement. Heights are aligned to work with Google 3D tiles; subway markers are shown at street level because these feeds do not supply depth. -- **Radio Browser.** `/api/radio/stations` discovers official API mirrors, makes bounded and coalesced healthy/geolocated HTTPS-station queries, caches the normalized public-domain directory for 45 minutes, and may serve the last good catalog for up to seven days during an outage. Refreshes must meet minimum accepted-query and station coverage before replacing a warm catalog; schema-valid responses whose rows all fail the product's health policy do not count as successful queries. A usable partial cold catalog is explicitly `DEGRADED`, and malformed or empty successful payloads are rejected atomically. Every directory and click-count request rejects redirects, validates all resolved addresses as globally routable (including reserved/documentation IPv4 and special/non-global IPv6 exclusions), and pins the TLS connection to a validated address. Only MP3/AAC non-HLS directory rows with public HTTPS stream targets are returned; favicons are intentionally omitted. Pressing play connects one browser audio element directly to the selected broadcaster and calls the directory's click counter through known-ID-only `POST /api/radio/click/:uuid`. GEV never proxies, caches, records, bundles, or redistributes audio. Radio Browser supplies station-level tags, not dependable current-song or upcoming-program metadata, so Radio filtering never claims either. Direct playback exposes the listener's IP address to the broadcaster, whose own stream terms apply. +- **Transit (GTFS-Realtime).** The proxy requests only registered operator feeds, validates redirects, bounds responses, and uses conditional requests, short snapshot caching and failure backoff. All sixteen registered regions are live-enabled; each can be disabled independently. Vehicles use delayed playback between reports, with report age and waiting states shown separately. Session-local selected trails are available for every feed. MBTA additionally retains up to 15 minutes of recently observed positions in the running proxy, so available history can survive a browser reload; server restart clears it. History reads never fetch upstream, and other feeds have no proxy retention. Nothing is archived to disk or collected in the background. Operator text credits are included as a courtesy and do not imply endorsement. Heights are aligned to work with Google 3D tiles; subway markers are shown at street level because these feeds do not supply depth. The TTC feed is BusTime, the surface system: it carries buses and streetcars and no subway at all. About four in ten of its vehicles report no route at all (unassigned or deadheading), and those are shown with the feed default rather than a route-established mode. It sends no ETag or Last-Modified, so its conditional requests fall through to the ordinary snapshot cache. Three Golden Horseshoe neighbours run alongside it — MiWay, Hamilton HSR and Durham Region Transit — each bus-only and each polled only near its own region. Durham Region Transit publishes no bearing on any vehicle, so those sprites take their heading from observed movement like any other feed that omits it. Guelph, Kingston and Barrie extend the same pattern eastward and north. Hamilton, Guelph, Burlington and YRT publish route ids that are not the number on the vehicle, so those entries carry a route-name table taken from each operator’s own published GTFS; any id missing from a table renders unchanged rather than blank. A label is never invented: YRT runs a route `9101` that appears nowhere in its published routes, so it stays as the feed sends it. Burlington’s is the one that cannot be shortcut: `351` is route 1 while `3510` is route 10, so the table is a real join rather than a trimmed prefix. GO Transit / Metrolinx is deliberately absent: its REALTIME feed requires an API key issued by manual review, which the keyless admission rule excludes (its static schedule download is keyless, but carries no vehicle positions). Barrie and YRT/Viva each invite acceptance of their licence through a form, and each licence also states that using the data is itself acceptance; this deployment relies on that clause, which is recorded in both entries. Grand River Transit in Waterloo is absent for a different reason: it answers, but its feed header was months stale and it publishes no per-vehicle timestamps, so it would render vehicles that look live and are not. Ottawa’s OC Transpo falls to the same keyless admission rule as GO Transit — its realtime feed requires an API key. London Transit and Thunder Bay Transit publish vehicle positions over plain HTTP with no HTTPS endpoint available. Every other Ontario system — Brampton, Oakville, Niagara, Milton, Windsor, Greater Sudbury, UP Express and a dozen smaller operators — publishes static GTFS schedules only, with no realtime vehicle positions to register. Between the nine included and these exclusions, every Ontario realtime vehicle-position feed catalogued in the Mobility Database is accounted for. +- **Radio Browser.** `/api/radio/stations` discovers official API mirrors, makes bounded and coalesced healthy/geolocated HTTPS-station queries, caches the normalized public-domain directory for 45 minutes, and may serve the last good catalog for up to seven days during an outage. Refreshes must meet minimum accepted-query and station coverage before replacing a warm catalog; schema-valid responses whose rows all fail the product's health policy do not count as successful queries. A usable partial cold catalog is explicitly `DEGRADED`, and non-array or empty successful payloads are rejected atomically. Individual structurally malformed rows are skipped rather than failing the whole query; the response carries their bounded `rejectedStationCount` (at most 10,000), which the client adds to its own rejected rows and reports as degraded coverage without discarding the accepted generation. Every directory and click-count request rejects redirects, validates all resolved addresses as globally routable (including reserved/documentation IPv4 and special/non-global IPv6 exclusions), and pins the TLS connection to a validated address. Only MP3/AAC non-HLS directory rows with public HTTPS stream targets are returned; favicons are intentionally omitted. Pressing play connects one browser audio element directly to the selected broadcaster and calls the directory's click counter through known-ID-only `POST /api/radio/click/:uuid`. GEV never proxies, caches, records, bundles, or redistributes audio. Radio Browser supplies station-level tags, not dependable current-song or upcoming-program metadata, so Radio filtering never claims either. Direct playback exposes the listener's IP address to the broadcaster, whose own stream terms apply. - **TomTom Traffic.** Optional and BYOK: without `TOMTOM_API_KEY` the traffic layer runs its built-in simulation and no TomTom data (or attribution) appears. With a key, flow vector tiles are fetched through the server-side `/api/tomtom` proxy (120 s cache + a daily tile-budget governor — `TOMTOM_DAILY_TILE_BUDGET`, default 6,000 — sized so a 31-day month stays inside TomTom's 200K monthly free allowance; still a configurable application safety ceiling, not a guarantee; TomTom's [current pricing](https://docs.tomtom.com/pricing/) lists 200K free tile requests per month) and the "Traffic flow data © TomTom" credit is registered in the Data attribution popover the moment live mode activates. TomTom data is served live and cached only transiently (≤120 s TTL under `.gev-cache/`, gitignored) — it is not bundled or redistributed. One 23 KB point-in-time tile snapshot is committed as a decode-test fixture (`src/data/fixtures/`, © TomTom, never served to the app). - **Routing (OSRM / FOSSGIS).** `/api/route` proxies the public OSRM instances FOSSGIS e.V. runs for the OpenStreetMap community (car, bike, foot profiles). They are keyless and intended for fair, interactive use — the proxy rate-limits clients (60/min, 200/min total), caps route span and response size, caches each route for 10 minutes, and identifies itself in the User-Agent. Heavy or automated use must run its own OSRM. Routes are computed from OpenStreetMap data (ODbL); the Directions layer and voice routes never redistribute them. A route the router cannot find is reported as such; the Directions layer draws nothing in that case, and voice routes fall back to a clearly labeled straight line. - **Re:Earth Terrain.** Keyless (no API key). Used two ways: (1) `src/mapStackController.js` swaps in a `Cesium.CesiumTerrainProvider` pointed at Re:Earth's `cesium-mesh/ellipsoid` quantized-mesh endpoint for globe stacks without a Cesium ion token (e.g. OSM), replacing a flat `EllipsoidTerrainProvider`; falls back to the flat provider if the endpoint can't be reached. (2) The server-side `/api/terrain/heights` proxy (disk-cached, serve-stale) resolves per-point ellipsoidal ground height for entity placement. Both are best-effort with a keyless-safe fallback (bundled EGM96 geoid math) if Re:Earth is unreachable. @@ -121,7 +208,10 @@ The [Bhote Koshi event pack](public/events/bhote-koshi-2026/README.md), under `p | **DataSF Analysis Neighborhoods** (41 SF neighborhood polygons) | `neighborhoods/` | **PDDL 1.0** (public domain) | ✅ (no restrictions) | "City & County of San Francisco — DataSF" (courtesy — not legally required) | | **Natural Earth countries, states and provinces** (260 admin-0/map units + 4,587 admin-1 polygons) | `natural_earth/` | **Public domain** | ✅ (no restrictions) | "Made with Natural Earth" (courtesy credit — not legally required) | | **US Census Bureau counties** (3,235 county polygons) | `us_census_counties/` | **Public domain** | ✅ (no restrictions) | "U.S. Census Bureau" (courtesy — not legally required) | +| **Yale Bright Star Catalogue** (9,096 stars, sky background) | `sky/` | **Public domain** | ✅ (no restrictions) | "Yale Bright Star Catalogue (Hoffleit & Warren, via CDS)" (courtesy credit) | +| **ESO Milky Way panorama** (eso0932a, blurred cube map, sky background) | `sky/` | **CC BY 4.0** | ✅ (attribution; changes stated) | "ESO/S. Brunier" | | **CCTV ground heights** (3,445 cameras) | `cctv_ground_heights/` | Precomputed camera placement heights, aligned to work with Google Photorealistic 3D Tiles (folder README) | — | — | +| **CCTV Camera Database** model-enrichment extract v2.26.0 (17 camera-model records) | `src/layers/cctv/modelSpecs.js` | **CC0-1.0** (public domain dedication) | ✅ (no restrictions) | "Specs: cctv-database.com" (courtesy — not legally required) | ### ⚠️ TeleGeography is bundled but NonCommercial @@ -147,6 +237,17 @@ commercial use with attribution and applicable database share-alike/access obligations; it does not license the application code. Trimmed test-only tile fixtures retain their provenance in `src/data/fixtures/README.md`. +### CCTV Camera Database (`src/layers/cctv/modelSpecs.js`) + +The CCTV layer's hardware-model specs are a small verbatim extract (v2.26.0) of the +[CCTV Camera Database](https://github.com/ch-bas/cctv-camera-database), an open dataset of +camera models transcribed from manufacturer datasheets, dedicated to the public domain under +**CC0-1.0**. Only the records for hardware that the integrated public catalogs name (King +County, Sarasota County and Sioux Falls) are bundled, compiled into the module. Nothing is +fetched at runtime. The records describe camera products (optics, resolution, night vision) +only, never endpoints, stream paths or access data. CC0 requires no attribution; the CCTV HUD +credits it anyway as `SPECS: CCTV-DATABASE.COM` beside any spec line it renders. + ### Bundled OpenStreetMap data Bundled OSM-derived data is distributed under [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/), separately from the MIT code: [datacenters](src/data/local_data/datacenters/), [dams](src/data/local_data/dams/) (via Open Infrastructure Map), [military names](src/data/local_data/osm_military_names/), and [OSM test fixtures](src/data/fixtures/). Keep © OpenStreetMap contributors and offer modified databases under ODbL. @@ -181,6 +282,11 @@ https://www.naturalearthdata.com/about/terms-of-use/). We credit anyway: "Made w Earth". Registration in the in-app `dataCredits.js` attribution list ships with the resolver wiring (see below). +### Sky background (`sky/`) + +Sources, licences, the changes CC BY asks to state, hashes and build commands +are in [`sky/README.md`](src/data/local_data/sky/README.md). + ### DataSF Analysis Neighborhoods (`neighborhoods/`) `neighborhoods/san-francisco.json` bundles the City & County of San Francisco's official diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..433d170a8 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,50 @@ +# syntax=docker/dockerfile:1 +# +# The dev server is the whole app: Vite serves the client AND runs the API +# proxies (ADS-B, AIS, Overpass, OpenAI Realtime, ...) as middleware, so there +# is nothing else to containerise. See compose.yaml for the usual entry point. +# Same Node as CI (package.json engines, .github/workflows), pinned by digest. +FROM node:24.14.0-slim@sha256:d8e448a56fc63242f70026718378bd4b00f8c82e78d20eefb199224a4d8e33d8 + +# Puppeteer is only used by the QA scripts; skip its ~150MB Chromium download. +ENV PUPPETEER_SKIP_DOWNLOAD=1 + +# `npm test` builds fixtures with `git init`, so the suite cannot run in a +# container without it (71 failures on node:24-slim, all ENOENT on git). +RUN apt-get update && apt-get install -y --no-install-recommends git && rm -rf /var/lib/apt/lists/* +# The repo is bind-mounted, so inside the container it can show an owner other +# than the user the container runs as - always, on Docker Desktop. git then +# refuses it as "dubious ownership", which fails the tests that shell out to +# git. It is the user's own checkout, so trust that one path. +RUN git config --system --add safe.directory /app + +# Never run as root. The image's own user is `node` (1000); compose overrides +# it with the host user so bind-mounted files stay yours. +WORKDIR /app +RUN chown node:node /app +USER node + +COPY --chown=node:node package.json package-lock.json ./ +RUN npm ci +# node_modules belongs to `node`, but compose may run as another UID. Vite only +# needs to write its dep-optimizer cache, so open up those two directories +# rather than chowning a few hundred MB to a UID we cannot know at build time. +RUN mkdir -p node_modules/.vite && chmod 777 node_modules node_modules/.vite + +COPY --chown=node:node . . + +# Bind to all interfaces, otherwise the published port hits nothing. This does +# not widen the Host allowlist: IP addresses and localhost are accepted, other +# names only via GEV_ALLOWED_HOSTS (see build/allowedHosts.js). +ENV HOST=0.0.0.0 +ENV PORT=4173 +EXPOSE 4173 +# node:slim has no curl, so probe with Node's built-in fetch. 127.0.0.1 is +# always on the Host allowlist, and the generous start period covers Vite's +# first-run dependency optimisation. +HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \ + CMD ["node", "-e", "fetch('http://127.0.0.1:'+(Number.parseInt(process.env.PORT,10)||4173)+'/').then((r)=>process.exit(r.ok?0:1),()=>process.exit(1))"] +# The launcher is `npm run dev` plus one step: it trusts the container's +# gateway address for Provider Settings, because that is where Docker delivers +# the host's own browser from (never 127.0.0.1). See scripts/docker-start.mjs. +CMD ["node", "scripts/docker-start.mjs"] diff --git a/README.md b/README.md index 5d97dfb2f..3a4c5fc43 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Start with the included data sources, then add your own. Each layer is a separat - **🎯 Click-to-track anything:** Camera locks on, draws a fading trail, surfaces full metadata — and a tracked fire or vessel hands you off to the nearest live camera in one click. - **🖊️ Voice whiteboard:** Speak annotations onto the world — real boundary polygons, marks, and routes. - **🛫 3D hangar:** Real per-class aircraft models — 787, ATR-72, Citation, Bell 206, MQ-9 — and a tracked contact swaps from glyph to 3D model as you close in. -- **🎨 Reskin reality:** GLSL sensor looks over the normal globe — CRT, NVG, FLIR/thermal, Noir, Snow. +- **🎨 Reskin reality:** GLSL sensor looks over the normal globe — CRT, NVG, FLIR/thermal, Noir. - **🟩 Detection overlay:** Screen-space bounding boxes and IDs on everything in view. - **🎖️ Military HUD:** Tactical heads-up display with intelligence-style telemetry. - **🌐 Global Context:** Stage the full situational picture with one switch — and get your exact view back when you leave. @@ -73,7 +73,7 @@ Start with the included data sources, then add your own. Each layer is a separat - **🔭 Satellite passes:** Ask by voice when any loaded satellite next rises over you: rise, peak and set times, and whether you can see it. - **🔎 Analyst answers:** Count, filter and rank satellites, datacenters and dams by voice, alongside flights, ships, fires and quakes; answers say when a feed is stale or on a fallback. - **🧭 Tilt and North Up:** Switch between straight-down and a 35° oblique, or put north at the top, while a tracked target stays centered. -- **🔍 Keyless search:** Type coordinates or a bundled city or landmark to fly there with no network request; other names use Google when configured, then Photon and Nominatim. +- **🔍 Keyless search:** Type decimal coordinates, a two-dimensional WGS84 `geo:` URI (for example, `geo:39.7392,-104.9903`), or a bundled city or landmark to fly there with no geocoder request; other names use Google when configured, then Photon and Nominatim. - **📦 Shareable scenes:** Import, preview and share Director scenes as files or bundles, with camera anchors, authored moves and data packs. - **🌊 Nepal flood scene:** Replay the Bhote Koshi flood: flood path, witness sources and before-and-after imagery (bundled data is non-commercial; see [DATA_SOURCES.md](DATA_SOURCES.md)). @@ -111,12 +111,22 @@ app's **POWER UP** panel; [Keys & Costs](#-api-keys) explains the options. Available on **Windows, macOS, and Linux**. The Pinokio maintainer reports cross-platform testing of the fixed installer. The launcher installs the -locked dependencies, finds a free local port, and opens the app. +locked dependencies, finds a free local port, and opens the app in your system +browser. The Server menu item keeps the launcher console available. **Tried before and installation failed?** Update Pinokio and try again. Version 8.2 fixes the launcher installation issue; [details from the Pinokio maintainer](https://pinokio.co/posts/01m1m4p9xxm3qw7dnnpj2wr93g). +**Using an older launcher or opening the embedded view manually?** If the globe +is very choppy, before treating that as a GPU +compatibility or minimum-hardware problem, copy the local server URL shown by +Pinokio and open the same URL in your normal hardware-accelerated browser. One +Pinokio 8.2.0 user reported severe stutter in Pinokio's embedded view that went +away when the same running server was opened in an external browser ([#365](https://github.com/bilawalsidhu/gods-eye-view/issues/365)). +That points to the embedded browser rather than the app server or your +hardware; it does not establish a minimum GPU requirement. + ### Path 2 — Terminal / coding agent Use **Node.js 24.x (24.14.0 or later) or 26.x**. The setup doctor warns about @@ -145,6 +155,84 @@ See [docs/PERFORMANCE.md](docs/PERFORMANCE.md). **macOS shortcut:** `./scripts/dev-fresh.sh` clears the Vite cache and pulls any configured keys straight from the Keychain. It starts keyless too. +### Path 3 — Docker + +No Node install needed; the container publishes the same dev server. + +```bash +git clone https://github.com/bilawalsidhu/gods-eye-view.git +cd gods-eye-view +docker compose up +``` + +Open **`http://localhost:4173`** as above. Everything the app saves stays in the folder you cloned, so `docker compose down` never loses anything: + +- `.env` - your API keys, whether saved from Provider Settings or typed in by hand +- `.gev-cache/` - downloaded map and satellite data, so later starts are faster +- `.gev-logs/` - logs + +Back up that folder and you've backed up everything; delete `.env` to forget your keys. Source edits still hot-reload. The port is published to `127.0.0.1` only, so the default matches the native one. + +The local MCP server and ChatGPT OAuth voice are not available under Docker; use an OpenAI API key for voice. + +Publishing it wider is the [Sharing an instance](#-sharing-an-instance) opt-in, and it hands out **Provider Settings** too: the launcher trusts the container gateway as this machine, and a wider publish delivers everyone else from that same address. For an instance you mean to share, put the keys in `.env` by hand instead. [SECURITY.md](SECURITY.md) has the detail. + +When you widen the publish, also set `GEV_KEY_SETUP_TRUSTED_PEERS=none` so the launcher trusts no gateway address. + +```bash +GEV_KEY_SETUP_TRUSTED_PEERS=none docker compose up +``` + +Compose forwards `GEV_KEY_SETUP_TRUSTED_PEERS` and `GEV_ALLOWED_HOSTS` from your +shell or the project's `.env`; an exported shell value takes precedence. You can +also put `GEV_KEY_SETUP_TRUSTED_PEERS=none` in `.env` for a persistent setting. +Unset or blank trusted peers retain automatic gateway discovery; `none` explicitly +disables it. The startup log confirms that no additional peers are trusted. + +
+Running on Linux, a NAS, or behind a reverse proxy + +Run it as the user who should own the files it writes. `id` shows the numbers; for yourself on Linux: + +```bash +env UID=$(id -u) GID=$(id -g) docker compose up +``` + +On a NAS, clone onto the share you want the data on and use the share owner's ids: + +```bash +cd /volume1/docker +git clone https://github.com/bilawalsidhu/gods-eye-view.git +cd gods-eye-view +env UID=1026 GID=100 docker compose up -d +``` + +Keep the `env`: bash treats `UID` as read-only, so a plain `UID=1026` in front of a command is silently ignored. If the container can't write the checkout, it says so at start. Docker Desktop on macOS and Windows maps ownership for you. + +On SELinux hosts (Fedora, RHEL), compose mounts the checkout with `:z` so the container may read it; Docker may relabel the checkout for container access, which can take a moment on a large checkout. Without that, the start fails with `Cannot find module '/app/scripts/docker-start.mjs'`. + +Behind a reverse proxy, put your keys in `.env` or pass them as environment variables - Provider Settings refuses proxied requests on purpose - and add the hostname you serve it on, for example `GEV_ALLOWED_HOSTS=globe.example.lan` (see [Sharing an instance](#-sharing-an-instance)). + +
+ +
+IPv6-only networks, rebuilding, and the test suites + +The launcher reads the IPv4 default gateway, so an IPv6-only Docker network +finds none: it logs `No default gateway; Provider Settings stays loopback-only` +and the panel refuses every save. Put your keys in `.env` by hand there, or name +the gateway yourself with `GEV_KEY_SETUP_TRUSTED_PEERS` after reading +[SECURITY.md](SECURITY.md). + +`node_modules` deliberately stays inside the image, so it survives in an +anonymous volume across restarts: after a `git pull` that changes dependencies, +recreate it with `docker compose down -v && docker compose up --build`. The +image also skips Puppeteer's Chromium download, which keeps it small but leaves +`npm run test:track` to the host — `npm run build` and `npm test` run fine in +the container. + +
+ ### Then power it up — in the app, not in a file Keys are upgrades, not prerequisites. When you want one, click the **POWER UP** @@ -206,14 +294,14 @@ Choose a first-run mission, or try these in order. The GIFs show Google Photorea ![Tracking the ISS along its orbital path as it crosses over Ukraine](docs/media/14-iss-over-ukraine.gif) -6. **Switch the optics.** Tap `1`–`7` — CRT, NVG, FLIR — and the whole live planet re-renders through a different sensor. +6. **Switch the optics.** Tap `1`–`6` — CRT, NVG, FLIR — and the whole live planet re-renders through a different sensor. ![Cycling a dense live globe through CRT, FLIR, and NVG in one continuous view](docs/media/01-style-sweep.gif) 7. **Talk to it** _(needs an OpenAI key)_: _"Take me to LAX and select the nearest airborne aircraft."_ 8. **Come home.** Hit **Reset Globe** — or just say _"zoom out to a globe view."_ -**Keyboard:** `1`–`7` visual styles · `H` HUD · `D` detection · `C` cockpit · `` ` `` frame rate · `Esc` out. Trackpad pinch zooms the globe. +**Keyboard:** `1`–`6` visual styles · `H` HUD · `D` detection · `C` cockpit · `` ` `` frame rate · `Esc` out. Trackpad pinch zooms the globe. --- @@ -235,6 +323,10 @@ _Why cockpit mode exists: you're riding a real aircraft over real terrain — an ## 🎙️ Talk to It +The standalone app offers **OpenAI** and **Gemini** in the GEV MIC provider chooser. OpenAI is the initial default; your choice is saved in this browser. To use Gemini, add `GEMINI_API_KEY` in Provider Settings or your local `.env` file, then select Gemini. `GEMINI_LIVE_MODEL` defaults to `gemini-3.8-live`. The permanent key stays on the local server, which issues a constrained, single-use session credential. + +Changing provider ends the current conversation. If voice is on, the new provider starts with the same open-mic or push-to-talk mode; a held Space key is not carried over. Gemini uses the same map actions and captions, but has no OpenAI cost meter or MINI tier. When Gemini reports that its session has expired, start voice again for a new conversation. The provider chooser does not change the OpenAI-backed AI HUD summary. + > Voice can use an **OpenAI API key** or, on the same machine, an opt-in signed-in **ChatGPT/Codex OAuth** session. The API-key path remains the default. Selecting ChatGPT OAuth in Provider Settings reuses an existing local sign-in or starts the Codex browser sign-in flow and selects OAuth when it completes. The OpenAI key still drives the **AI HUD summary**: a terse, five-word intelligence-style readout of the current view that regenerates as you move. The OAuth option is experimental. OpenAI documents ChatGPT plan usage for the [Responses API](https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference); a supported third-party Realtime contract for reusing Codex tokens has not been confirmed. A successful token mint does not establish billing or support terms. @@ -255,6 +347,10 @@ Thirty tools, four jobs — the commands below come straight from the product's **🎥 Direct it** — drone-operator camera verbs: +“Rotate the globe” spins Earth to the right continuously; ask for left, a speed, +or stop. If it refuses, follow its reset-and-rotate or further-zoom guidance; +camera input stops rotation. + > 🗣️ _"Take me to Tokyo."_ · _"Orbit around this area slowly."_ · _"Draw the walking route from the Capitol to Zilker Park."_ → _"Fly the route we just drew."_ · _"Zoom out to a globe view."_ **🖊️ Annotate it** — a whiteboard over the real world: @@ -289,26 +385,29 @@ _Ask for radio near anywhere and the globe starts broadcasting — every station ## 🛰️ What's on the Globe -Twenty layers and map sources. **Seventeen have a keyless path.** Some offer additional capabilities with a provider key. (🟢 no key · 🟡 free key · 🔴 metered.) +Twenty layers and map sources. **Eighteen have a keyless path.** Some offer additional capabilities with a provider key. (🟢 no key · 🟡 free key · 🔴 metered.) | Layer | What you get | Source | Auth | | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------- | | 🗺️ **Map Stack** | Esri satellite imagery, Google Photorealistic 3D, OSM, plus additional ion-hosted stacks | Esri / Google / Ion / OSM | 🟢 Esri satellite + OSM · 🟡 ion-hosted Google 3D + world terrain · 🔴 direct Google + place search | | ✈️ **Live Flights** | 11,000+ live aircraft + route history | OpenSky + adsb.lol | 🟢 (🟡 optional for more polling credits) | -| 🎖️ **Military Flights** | ADS-B military traffic in amber | adsb.lol | 🟢 | +| 🎖️ **Military Flights** | ADS-B military traffic in amber, emergency broadcasts in red | adsb.lol | 🟢 | +| 📡 **GNSS Integrity** | Regional navigation accuracy scores; anomalies do not confirm interference | adsb.lol, GPSJAM aggregation | 🟢 | +| 🔥 **Fire Perimeters** | Incident boundaries and reported containment | WFIGS / NIFC | 🟢 | | 🚢 **Live Vessels** | Thousands of ships worldwide | AISStream | 🟡 | | 🛰️ **Satellites** | 838-object catalog, color-coded by class with a live legend — the **DENSE** chip drops in the whole Starlink shell | CelesTrak | 🟢 | | 🌍 **Earthquakes** | Global seismic activity, last 24h | USGS | 🟢 | +| ◍ **Air quality** | Live AQHI on the published 1–10+ health-risk scale, with a Weather-panel card showing the band legend and the highest readings in view. **Canada only** — ECCC is the first registered provider | ECCC MSC GeoMet | 🟢 | | 🚗 **Traffic** | Simulated vehicles on OSM roads. With TomTom, live flow speeds drive the simulation and congestion colors below ~8 km; individual vehicle positions are not live observations | TomTom + OSM | 🟢 simulation · 🟡 live flow speeds | -| 📹 **CCTV Mesh** | ~3,900 public cameras projected _into_ the 3D space — Austin · Texas (TxDOT) · California (Caltrans) · London (TfL) · Ontario (511) · Finland (Fintraffic) · British Columbia (DriveBC) · Estonia (Tallinn, Tarktee) · Delaware (DelDOT live video) · New South Wales (Live Traffic NSW) · Calgary · Norway (Statens vegvesen). Positions are published; poses are estimated priors **you calibrate by dragging a gizmo on the camera itself** | City APIs | 🟢 | +| 📹 **CCTV Mesh** | ~4,000 public cameras (shared cap) projected _into_ the 3D space — Austin · Texas (TxDOT) · California (Caltrans) · London (TfL) · Ontario (511, free developer key) · Finland (Fintraffic) · British Columbia (DriveBC) · Estonia (Tallinn, Tarktee) · Delaware (DelDOT live video) · New South Wales (Live Traffic NSW) · Calgary · Norway (Statens vegvesen) · Toronto · King County (WA) · Washington (WSDOT) · Catalonia (Servei Català de Trànsit) · Hong Kong (Transport Department) · Taiwan (Freeway Bureau, MOTC) · Italy (A22 Brennero motorway), plus opt-in New York City (NYC DOT TMC, needs your own NYC DOT agreement), opt-in Lithuania (Via Lietuva / Eismoinfo, photo licence unconfirmed) and opt-in Florida (FL511, individual personal use only; other use needs FDOT's written consent). Positions are published; poses are estimated priors **you calibrate by dragging a gizmo on the camera itself** | City APIs | 🟢 | | 📷 **Mapped ALPR Cameras** | License-plate-reader camera locations tagged by OpenStreetMap contributors, loaded one city-sized view at a time, with **SHOW NEAREST**. Locations and tags only: no plate data, no video | OpenStreetMap (incl. DeFlock mapping) | 🟢 | -| 📷 **Street Level** | Street-level photos behind one panel, one chip per provider: coverage on the streets, image cones, an embedded viewer and **FOLLOW**. Mapillary first; Panoramax, KartaView and Google Street View planned | Mapillary | 🟡 Mapillary client token | +| 📷 **Street Level** | Street-level photos behind one panel, one chip per provider: coverage on the streets, image cones, an embedded viewer with full-screen **EXPAND**. Mapillary, Google Street View, KartaView and Panoramax | Mapillary · Google · KartaView · Panoramax | 🟢 KartaView, Panoramax · 🟡 Mapillary token · 🔴 Google Maps key | | 📻 **Radio** | Geolocated world radio with an **analog tuner** — drag the needle across up to 750 stations and the globe flies to each broadcaster | Radio Browser / broadcasters | 🟢 | -| 🚌 **Transit** | Live buses, trams, metros, trains and ferries with delayed playback between reports, selected-vehicle trails, and mode-coloured DETECT labels — Boston, Austin, Minneapolis, Helsinki, the Netherlands, Norway, South East Queensland | Operator GTFS-Realtime feeds | 🟢 | +| 🚌 **Transit** | Live buses, trams, metros, trains and ferries with delayed playback between reports, selected-vehicle trails, and mode-coloured DETECT labels — Boston, Austin, Minneapolis, Helsinki, the Netherlands, Norway, South East Queensland, and nine in Ontario: Toronto (surface vehicles; the subway publishes no positions), Mississauga, Hamilton, Durham Region, York Region, Guelph, Burlington, Barrie and Kingston | Operator GTFS-Realtime feeds | 🟢 | | 🚲 **Bikeshare** | Live station availability | GBFS | 🟢 | | 🧭 **Directions** | Click A and B on the globe for a street-following drive, walk or cycle route draped on the terrain with turn-by-turn steps — then FLY the camera along it. No key, no geocoder, no mic | OSRM on FOSSGIS servers (OpenStreetMap) | 🟢 | | 🔥 **Active Fires** | Live NASA FIRMS detections, trailing 24h | NASA FIRMS | 🟡 | -| 🚀 **Space Missions** | Rolling 30-day launches with payload, stage, and recovery detail | Launch Library 2 | 🟢 (🟡 optional token raises the allowance) | +| 🚀 **Space Missions** | Rolling 30-day launches with payload, stage, and recovery detail | Launch Library 2 | 🟢 (🔴 optional paid token raises the allowance) | | 🎖️ **Mapped Installations** | Viewport-bounded military-site context from community mapping — incomplete by nature, and labeled that way | OpenStreetMap | 🟢 | | 🌬️ **Wind** | Animated 10 m forecast wind with an optional speed, temperature or pressure color field and a reading at map center | NOAA GFS / ECMWF IFS | 🟢 | | 🌦️ **Observed Weather** | Rain radar (contiguous US), Satellite clouds (GOES regional or global infrared, Clouds only or Full image) and Lightning density (Americas and Pacific) on one history timeline | NOAA nowCOAST | 🟢 | @@ -340,13 +439,13 @@ _The Space Missions layer replaying a Falcon 9 ascent — labeled `RECONSTRUCTED ## 📷 Street Level -> Street-level photos from any provider in one panel. This build ships **Mapillary**, which needs a free client token. +> Street-level photos from any provider in one panel. This build ships **Mapillary** (a free client token), **Google Street View** (your Google Maps key), **KartaView** and **Panoramax** (no key). -**Setup.** At [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), register an application with **Read** access and copy its **Client Token** (`MLY|…`). Paste it into **POWER UP → Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart. Without it the panel reads **KEY REQUIRED**. +**Setup.** At [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), register an application with **Read** access and copy its **Client Token** (`MLY|…`). Paste it into **POWER UP → Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart. Without it the panel reads **KEY REQUIRED**. **Google Street View** uses `GOOGLE_MAPS_API_KEY` with the **Maps JavaScript API** enabled for it in Google Cloud; its chip starts off, since every panorama is billed to the key. **KartaView** and **Panoramax** need nothing: their public APIs are keyless. -**Use.** Turn on **Street Level** under DATA LAYERS → Cameras, or with the pill in the STREET LEVEL panel header. Each provider has a chip in its own colour (Mapillary green). The **IMAGERY** (ALL / 360° / FLAT) and **SINCE** filters apply to every provider. Click a coverage line for its image cones and a cone to open the photo. Above the photo: **EXPAND**, **FIT / FILL**, and **FOLLOW** (the globe camera follows the photo's view; Google 3D map only). The caption links to the image on the provider's site, and the globe credits "© Mapillary contributors, CC BY-SA 4.0" while Mapillary is on. +**Use.** Turn on **Street Level** under DATA LAYERS → Cameras, or with the pill in the STREET LEVEL panel header. Each provider has a chip in its own colour (Mapillary green), and one is lit at a time: lighting one switches the others off. Mapillary, which is free, is lit by default. Zoom in to street level (below 60 km) for the coverage lines; from orbit the panel says to zoom in. The **IMAGERY** (ALL / 360° / FLAT) and **SINCE** filters apply to Mapillary, KartaView and Panoramax; Street View panoramas are all 360°, so with Street View lit the filters are hidden. Click a coverage line for its image cones and a cone to open the photo. Light **KARTAVIEW** (purple) and zoom in below about 6 km: its lines are the streets KartaView has photos of, and a click on one opens the photo nearest the click, flat or 360° (drag to look around), with cones along its drive; **‹ ›** or ← → step through the drive (Shift+← →, ↑ ↓ and + − look around a 360° photo; pinch zooms on a phone). Photos KartaView has archived are skipped, and where all are archived the panel says so. For KartaView, **SINCE** goes by upload date, as KartaView's own map does (it can filter by nothing else), and the panel notes it beside the SINCE value (ANY DATE (by upload date)); KartaView filters its lines on its own server, and a filtered area KartaView has not drawn before can take several seconds. Light **PANORAMAX** (orange) for the open, federated commons (strongest in France and Belgium): below about 60 km its lines are sequences. A click on a line opens that sequence's picture nearest the click without moving the camera, flat or 360°, with cones along the sequence around it; **‹ ›** or ← → step through it, and both filters apply. Its caption names the picture's authors (or the instance holding it) and licence (mostly CC BY-SA 4.0; pictures on the IGN instance are Licence Ouverte 2.0). On the **Google 3D** map (Google's terms keep Street View off other maps, where it does not appear), light **GOOGLE STREET VIEW** and click a street from below 3 km, or press **OPEN STREET VIEW** for the view centre, to open Google's panorama there; step along its arrows. Above the photo: **EXPAND** (full screen; Esc leaves) and **FIT / FILL** (Mapillary, and flat KartaView and Panoramax photos). The caption links to the image on the provider's site, and the globe credits each provider that is on ("© Mapillary contributors, CC BY-SA 4.0", "Street View imagery © Google", "© KartaView contributors, CC BY-SA 4.0", "© Panoramax contributors, licence per picture"). KartaView's own photo pages fail for signed-out visitors, so its link opens the full-size photo. -Drag the panel header to float the panel, and resize it from any edge. Double-click the header or collapse it to put it back in the rail. Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`. +Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.m.0_0.r.google-1` Street View on, `0.m.0_0.r.google-0*kartaview-1*panoramax-0` KartaView on and `0.m.0_0.r.google-0*kartaview-0*panoramax-1` Panoramax on, as the app writes them (`0.m.0_0.r.kartaview-1` and `0.m.0_0.r.panoramax-1` work too; a link that leaves out `m` keeps Mapillary, the default, lit), `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`. ## 🎖️ Field Missions @@ -392,12 +491,12 @@ How the globe handles live data: - **Sits on the real ground.** Entity heights are aligned to work with Google 3D tiles, so aircraft park on aprons and cameras stand on street corners instead of floating. - **Caching and request budgets.** An OpenSky credit governor, a TomTom daily tile budget, and disk-cached TLEs reduce repeated requests. These controls do not replace provider quotas or billing controls. - **Server-side credentials.** Every API that touches a private key (OpenAI, AISStream, OpenSky OAuth, camera frames) is brokered through a hardened server-side proxy with SSRF protection, response caps, and sanitized errors. The only keys the browser sees are Google Maps and Cesium ion (restrict both at the provider). -- **No framework.** Vanilla JavaScript, **CesiumJS**, and **Vite** — plus **Google Photorealistic 3D Tiles** for the planet and the **OpenAI Realtime API** for voice. Fast to read, fast to hack on. +- **A small stack.** **Vue 3** and **Pinia** for the interface, **CesiumJS** for the globe and **Vite** to build it — plus **Google Photorealistic 3D Tiles** for the planet and the **OpenAI Realtime API** for voice. Fast to read, fast to hack on. ``` src/ ├── main.js # Bootstrap: Google 3D tiles, layer registration -├── ui.js # Runtime UI — panels, HUD, styles, control facade +├── ui/ # Runtime UI — Vue views, Pinia stores, kit, controllers, styles ├── hud.js # Intelligence HUD + AI scene summary ├── keySetup.js # POWER UP panel — in-app provider keys (dev server only) ├── mapStackController.js # Basemap switching — Google 3D / Esri / OSM / ion stacks @@ -434,7 +533,7 @@ Seven keys. Five have a free tier, and the two 🔴 ones are metered: | | Key | Why | Get it | | --- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 🟡 | **Cesium ion** | 🗺️ Google Photorealistic 3D, world terrain, and additional ion-hosted imagery stacks. The free Community plan is for eligible individual, personal/non-commercial use and has quotas | [cesium.com/ion](https://cesium.com/ion) — use a public `assets:read` token and check current [pricing/eligibility](https://cesium.com/platform/cesium-ion/pricing/) | -| 🔴 | **Google Maps** | Direct Google Photorealistic 3D + Google place search ([Map Tiles API](https://developers.google.com/maps/documentation/tile)) | [Google Cloud Console](https://console.cloud.google.com/) — URL-restrict it | +| 🔴 | **Google Maps** | Direct Google Photorealistic 3D, Google place search and Street View ([Map Tiles API](https://developers.google.com/maps/documentation/tile); Street View also needs the Maps JavaScript API) | [Google Cloud Console](https://console.cloud.google.com/) — URL-restrict it | | 🔴 | **OpenAI** | 🎙️ Voice + AI HUD summary through an API key. Provider Settings also offers **USE CHATGPT OAUTH** for cloud voice without removing the API-key option | [platform.openai.com](https://platform.openai.com) — API-key usage is metered, see costs below | | 🟡 | **AISStream** | 🚢 Live global ships | [aisstream.io](https://aisstream.io) — free signup | | 🟡 | **NASA FIRMS** | 🔥 Live active fires | [firms.modaps.eosdis.nasa.gov](https://firms.modaps.eosdis.nasa.gov/api/map_key/) — free | @@ -450,9 +549,11 @@ _What the TomTom key buys you: rush-hour density painted on the city — then di | | Key | Why | Get it | | --- | -------------------- | ------------------------------------------------------------- | -------------------------------------------------- | | 🟡 | **OpenSky** | ✈️ More flight-polling credits (🟢 anonymous works without) | [opensky-network.org](https://opensky-network.org) | -| 🟡 | **Launch Library 2** | 🚀 Higher space-missions request allowance (🟢 works without) | [thespacedevs.com](https://thespacedevs.com) | +| 🔴 | **Launch Library 2** | 🚀 Optional paid token for higher limits (🟢 no key needed for public access) | [thespacedevs.com/supportus](https://thespacedevs.com/supportus) | Add these if you need higher polling allowances. +Leave `LL2_API_TOKEN` blank for standard public access. LL2 tokens are optional +paid Patreon upgrades for higher limits; there is no free API-key signup. `npm run doctor` reports Node/npm readiness, the primary provider routes, and where each configured provider was found without printing credential values. diff --git a/SECURITY.md b/SECURITY.md index 53437a83c..4423eead3 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,6 +2,11 @@ God's Eye View is a local-first client for **public** data. It is built for exploration, demos, and learning — not as a hardened production service. This document explains the security model so you can run it safely and report issues responsibly. +Vite's development file server also denies `.gev-logs/`, `.gev-cache/`, and +the package checkout's root `dist/` directory. Dependency `dist/` directories +remain available. This filesystem deny list does not filter `public/` assets or +preview output; never put private artifacts in a public asset directory. + ## Reporting a vulnerability Please report security issues **privately** — do not open a public issue for anything exploitable. @@ -21,19 +26,19 @@ The golden rule: **secret-bearing API keys stay on the server side.** The dev/pr | ChatGPT sign-in through Codex (optional, experimental) | Codex's own `auth.json` (`CODEX_HOME`, default `~/.codex`); GEV reads it server-side and never writes or refreshes it | Only after **USE CHATGPT OAUTH** is selected in Provider Settings: the server mints the same ephemeral Realtime token with the ChatGPT access token, for loopback clients only | | `AISSTREAM_API_KEY` | Server only | Server holds the AISStream websocket; browser polls the same-origin `/api/vessels` cache | | OpenSky OAuth (`OPENSKY_CLIENT_ID/SECRET`) | Server only | Server mints + refreshes the token behind `/api/flights` | -| `GOOGLE_MAPS_SERVER_API_KEY` (optional, #33) | Server only | Server calls Places (`/api/google/nearby-places`, `/api/google/text-search`) and the Street View fallback with this key; falls back to `GOOGLE_MAPS_API_KEY` when unset | +| `GOOGLE_MAPS_SERVER_API_KEY` (optional, #33) | Server only | Server calls Places (`/api/google/nearby-places`, `/api/google/text-search`), Geocoding (`/api/google/geocode`, `/api/google/reverse-geocode`) and the Street View fallback with this key; falls back to `GOOGLE_MAPS_API_KEY` when unset | ### Three deliberately client-side keys — restrict them These are designed to be used directly in the browser (like a Mapbox public token). They are injected into the client bundle via Vite's `define`, so they **will** be visible in browser devtools. Scope and restrict them rather than trying to hide them: -1. **Google Maps API key** — loads Photorealistic 3D Tiles directly and powers GEV place search. **Restrict it** (HTTP referrer + API restriction to the required Google APIs) in the Google Cloud Console. An unrestricted key in a public deployment can be abused and billed to you. +1. **Google Maps API key** — loads Photorealistic 3D Tiles directly and powers Street View (Maps JavaScript API; add it to the key's API restrictions). **Restrict it** (HTTP referrer + API restriction to the required Google APIs) in the Google Cloud Console. An unrestricted key in a public deployment can be abused and billed to you. Restrict it to the **Map Tiles API and Maps JavaScript API only**: a referrer restriction applies to the Maps JavaScript API and the client SDKs, not to the web services, so a key carrying Geocoding under one is refused with `API keys with referer restrictions cannot be used with this API`. Search does not need it — geocoding goes through the server proxies above (#363). 2. **Cesium ion token** (`CESIUM_ION_TOKEN`, optional — for ion-hosted Google Photorealistic 3D Tiles, Bing world imagery, and world terrain) — used as `Cesium.Ion.defaultAccessToken` client-side. Use a public **`assets:read`** token with **URL restrictions** for any hosted deployment. The Community plan has eligibility and usage limits; a public token is not a secret, but it can still consume the account's quota. -3. **Mapillary client token** (`MAPILLARY_CLIENT_TOKEN`, optional, Street Level) — used by the MapillaryJS viewer and Graph API lookups in the browser, and by the server's coverage-tile proxy. Mapillary client tokens are meant for browser use. +3. **Mapillary client token** (`MAPILLARY_CLIENT_TOKEN`, optional, Street Level) — used by the MapillaryJS viewer and Graph API lookups in the browser, and by the server's coverage-tile proxy, which sends it only to `tiles.mapillary.com` over HTTPS (an upstream redirect is refused and answered 502, never followed) and caches tiles in memory only. Mapillary client tokens are meant for browser use. > The explicit browser `define` block in `build/vite.js` controls exactly what reaches the client: only these three keys. Everything else stays server-side. -**Places and Street View never needed to be on that list** (#33): they're called from the server-side proxies in the table above, which use `GOOGLE_MAPS_SERVER_API_KEY` when it's set. Splitting it from the browser-exposed key lets each key's Google Cloud restriction actually match what it does — the browser key referrer-restricted to the APIs the client loads, the server key IP-restricted (never a referrer, since it never leaves your server) to Places + Street View Static — instead of one key that has to be either over-permissioned or broken for one of its two jobs. A single shared `GOOGLE_MAPS_API_KEY` still works if you don't split them; it just has to cover every API both sides use. +**Places, Geocoding and the Street View Static fallback never needed to be on that list** (#33, #363): they're called from the server-side proxies in the table above, which use `GOOGLE_MAPS_SERVER_API_KEY` when it's set. Splitting it from the browser-exposed key lets each key's Google Cloud restriction actually match what it does — the browser key referrer-restricted to Map Tiles + Maps JavaScript API, the server key IP-restricted (never a referrer, since it never leaves your server) to Places + Geocoding + Street View Static — instead of one key that has to be either over-permissioned or broken for one of its jobs. A single shared `GOOGLE_MAPS_API_KEY` still works if you don't split them, but then it cannot carry a referrer restriction at all: the web services refuse one, and search would be the half that breaks. Never commit real keys. `.env` is gitignored; only `.env.example` (placeholder names) is tracked. On macOS `dev-fresh.sh` can read keys from the Keychain; plain Vite uses env vars or a local `.env`, and Pinokio uses its ignored app `ENVIRONMENT` file. @@ -69,11 +74,16 @@ The data proxies under `server/providers/` are written so the browser cannot tur - **No verbatim client headers upstream.** The CCTV media route is the one route that relays a request header (`Range`, for video seeking). It is parsed and canonicalized before it is forwarded: one `bytes=` range only, with every accepted form — explicit span, open-ended and suffix — bounded to the same 64 MiB ceiling the relay applies to a declared response body. Multi-range, malformed, inverted and non-`bytes` values are dropped and the request proceeds without a `Range`, as RFC 7233 §3.1 prescribes. Bounding the request bounds what is asked for: a response that declares no length — live streamed media, or a chunked body from an upstream that ignores the `Range` — has no ceiling. An upstream request the browser has stopped waiting for is cancelled rather than left running, whether the viewer leaves before the headers arrive or during the body. - **Transit fetches registered feeds only.** `/api/transit/vehicles/` resolves the id against `src/data/transitFeeds.js`; the browser never supplies a URL, and a feed that is registered but disabled does not resolve at all. Redirects are followed manually and each hop is validated against the feed's own https origin before it is requested, so an off-origin or downgraded hop is refused rather than contacted. Bodies are capped at 8 MB, the protobuf is decoded server-side under entity-count and string-length ceilings, a differential feed is refused, and snapshots live 15 s in memory with no disk cache. A per-feed admission limiter and a failure cooldown ladder bound what this process can ask of any operator. - **Local receiver feeds are operator-configured and local-only.** `/api/local-receivers/aircraft` reads only the `aircraft.json` URLs in the server's `LOCAL_RECEIVER_FEEDS`; the browser never supplies an address. Each host must pass the shared tap address rule (`src/data/tapAddress.js`: loopback, RFC1918, `localhost`, `*.local`; no link-local, IPv6 or other names), the scheme must be http(s), the path must end in `aircraft.json`, and credentials, queries and fragments are refused. Invalid entries are logged at startup and never fetched. Reads use a 2 s timeout, refuse redirects, cap bodies at 2 MB and share one read per second; responses name each feed by band only and never carry upstream error text. +- **Validated response formats.** Proxied bodies are relayed only in the format the route serves. CCTV frames and the Street View fallback accept JPEG, PNG, GIF, WebP and AVIF only, sent under their canonical type; any other type falls through to the next fallback. Live CCTV media must match its feed kind (`video/mp4`, `video/webm`, or `multipart/x-mixed-replace` with a boundary) before it is relayed or the camera counts as healthy, and its redirects stay on the registered origin. GBFS bodies must parse as JSON and are re-serialized as `application/json; charset=utf-8`. Camera catalog URLs are pinned by parsed URL — scheme, exact host, no credentials, default port, and a normalized path inside the agency's image directory — and a redirect on a pinned host must stay inside the same directory. Every `/api/cctv` route uses the keyless cross-site checks described below, so cameras stay reachable behind a reverse proxy; a request carrying forwarding headers never reaches the key-bearing Street View fallback and gets the placeholder frame instead, as when no key is configured. +- **Consistent API response headers.** Every `/api` response, including errors, partial content, Host refusals and unknown routes, carries `Content-Security-Policy: default-src 'none'; sandbox` and `X-Content-Type-Options: nosniff` (`apiResponseHeadersPlugin` in `build/vite.js`, installed ahead of the Host check). A route that sets its own policy adds it as a further policy; it never replaces this one. - **Response-size caps and timeouts** on proxied responses. - **Sanitized errors** — internal error details are not echoed back to clients. - **Coalesced OAuth refresh** and cached successful responses only (OpenSky). - **Redacted debug logging.** The voice debug log (`.gev-logs/`, gitignored) strips API keys, bearer tokens, client secrets, and image data URLs before writing. -- **Cross-site gate on cost/log endpoints.** The cost-bearing (`/api/realtime/token`, `/api/openai/hud-summary`, `/api/google/nearby-places`, `/api/google/text-search`), quota-bearing (`/api/mapillary/*`, with a per-IP limit on tiles) and log (`/api/realtime/debug-log`) endpoints refuse cross-site browser requests: a foreign or opaque `Origin`, a `Sec-Fetch-Site` other than `same-origin`/`none` (this is what blocks an ``/navigation that carries no `Origin`), or any reverse-proxy/CDN forwarding header returns `403`. Non-browser loopback tools (the repo QA harnesses POST the token endpoint with no `Origin`) and the explicit `HOST=0.0.0.0` LAN opt-in keep working — the gate deliberately does not require a loopback remote address; that stricter requirement belongs only to the credential panel (`admitKeySetupRequest`). The Host check (`allowedHosts`, applied by `hostCheckPlugin` ahead of every route, since Vite's own check runs only after plugin middleware) rejects a rebinding `Host` before any handler runs, in every mode, and the gate is defense in depth behind it: the LAN opt-in keeps that check and accepts only IP addresses, `localhost` and names listed in `GEV_ALLOWED_HOSTS`. **Limit:** a name you list there is trusted like the app's own address, so list only names you control. +- **Cross-site gate on cost/log endpoints.** The cost-bearing (`/api/realtime/token`, `/api/openai/hud-summary`, `/api/google/nearby-places`, `/api/google/text-search`), quota-bearing (`/api/mapillary/*`, with a per-IP limit on tiles, and `/api/tomtom/*`, backed by its persistent daily tile budget) and log (`/api/realtime/debug-log`) endpoints refuse cross-site browser requests: a foreign or opaque `Origin`, a `Sec-Fetch-Site` other than `same-origin`/`none` (this is what blocks an ``/navigation that carries no `Origin`), or any reverse-proxy/CDN forwarding header returns `403`. Non-browser loopback tools (the repo QA harnesses POST the token endpoint with no `Origin`) and the explicit `HOST=0.0.0.0` LAN opt-in keep working — the gate deliberately does not require a loopback remote address; that stricter requirement belongs only to the credential panel (`admitKeySetupRequest`). The Host check (`allowedHosts`, applied by `hostCheckPlugin` ahead of every route, since Vite's own check runs only after plugin middleware) rejects a rebinding `Host` before any handler runs, in every mode, and the gate is defense in depth behind it: the LAN opt-in keeps that check and accepts only IP addresses, `localhost` and names listed in `GEV_ALLOWED_HOSTS`. **Limit:** a name you list there is trusted like the app's own address, so list only names you control. The keyless terrain route (`/api/terrain/heights`) uses the same cross-site checks, minus the forwarding-header refusal: it guards only the per-client quota and point cache, not a key or a bill, and the map needs it to render behind a reverse proxy. The CCTV routes (`/api/cctv/*`) use the same keyless checks; their one key-bearing step, the Street View fallback, is skipped for any request with forwarding headers. +- **Full Content-Security-Policy.** The dev and preview servers send a real CSP (`script-src 'self' 'unsafe-eval' blob:` plus the YouTube, Facebook and X scripts the Nepal event's embedded media loads and the Maps JavaScript API that Street View runs on, with a matching `frame-src` for their players and posts: no inline script and no other script origin; `blob:` covers the object URLs Cesium's bundled workers bootstrap through in the built app), alongside the existing `X-Frame-Options: DENY` and `frame-ancestors 'none'`. `'unsafe-eval'` stays because Knockout, bundled inside Cesium's widgets package, resolves the global object with `eval` at load time and the globe does not initialize without it; styles permit `'unsafe-inline'` and Google Fonts because Vite's dev client injects `'; +const notes = 'A local observation with supporting detail. '.repeat(120); +const placemarks = Array.from({ length: 5000 }, (_, i) => { + const lon = -122.6 + (i % 100) * 0.002; + const lat = 37.65 + Math.floor(i / 100) * 0.003; + return `Point ${i}#base${style}${notes}${lon},${lat},0`; +}); +const wrap = (body) => + `${body}`; +const large = wrap(placemarks.join('')); +fs.writeFileSync(file, large); +const bytes = fs.statSync(file).size; +if (bytes < 20 * 1024 * 1024 || bytes > 30 * 1024 * 1024) + throw new Error(`Fixture must be 20–30 MiB, got ${bytes} bytes`); +const small = wrap( + Array.from({ length: 6 }, (_, i) => { + const kind = i % 3; + const geometry = + kind === 0 + ? '-122.49,37.77,0' + : kind === 1 + ? '-122.50,37.77,0 -122.49,37.77,0' + : '-122.50,37.77,0 -122.49,37.77,0 -122.49,37.78,0 -122.50,37.77,0'; + const override = + kind === 0 + ? style + : kind === 1 + ? '' + : ''; + return `Small ${i}#base${override}${geometry}`; + }).join('') + + '' + + '' + + 'normal' + + ['named-a', 'named-b', 'paired'] + .map( + (id) => + `${id}#${id}-122.49,37.77,0`, + ) + .join(''), +); +const browser = await puppeteer.launch({ + headless: true, + args: + process.platform === 'darwin' + ? ['--use-gl=angle', '--use-angle=metal'] + : ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader'], +}); +const page = await browser.newPage(); +await hookRenderErrors(page); +const errors = []; +const fileRequests = []; +page.on('pageerror', (e) => errors.push(e.message)); +await page.setRequestInterception(true); +page.on('request', (request) => { + if (new URL(request.url()).hostname === 'earthquake.usgs.gov') { + fileRequests.push(request.url()); + void request.abort(); + } else void request.continue(); +}); +let failures = 0; +const check = (name, ok, detail) => { + console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name}`, detail ?? ''); + if (!ok) failures++; +}; +try { + await page.setViewport({ width: 1440, height: 900 }); + await page.goto(`${base}/?welcome=0`, { waitUntil: 'domcontentloaded' }); + await page.waitForFunction( + () => + window.__gevGeoImport && + document.getElementById('loading-screen')?.classList.contains('hidden'), + { timeout: 60000 }, + ); + await page.evaluate(async () => { + const { viewer, dataManager } = window.__godsEyeView; + const C = window.__CESIUM__; + for (const id of dataManager.layers.keys()) + await dataManager.setEnabled(id, false); + viewer.clock.shouldAnimate = false; + viewer.imageryLayers.removeAll(); + viewer.terrainProvider = new C.EllipsoidTerrainProvider(); + viewer.camera.cancelFlight(); + viewer.camera.setView({ + destination: C.Cartesian3.fromDegrees(-122.5, 37.72, 50000), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + window.__qaStyleSnapshot = (source) => { + const now = viewer.clock.currentTime; + const images = new Map(); + const imageValue = (p) => { + const value = p?.getValue(now); + if (value?.tagName !== 'CANVAS') return value; + if (!images.has(value)) images.set(value, value.toDataURL()); + return images.get(value); + }; + const color = (p) => p?.getValue(now)?.toCssColorString(); + const positions = (p) => p?.getValue(now)?.map((v) => [v.x, v.y, v.z]); + const renderedPins = new Map(); + const collection = source.importedBillboards; + if (collection) + for (let i = 0; i < collection.length; i++) { + const pin = collection.get(i); + renderedPins.set(pin.id, pin); + } + const actual = (e, key, fallback) => { + const pin = renderedPins.get(e); + return pin ? pin[key] : (e.billboard?.[key]?.getValue(now) ?? fallback); + }; + return (source.importedEntities || source.entities.values) + .map((e) => ({ + name: e.name, + point: renderedPins.get(e)?.position || e.position?.getValue(now), + scale: e.billboard ? actual(e, 'scale', 1) : undefined, + rotation: e.billboard ? actual(e, 'rotation', 0) : undefined, + image: renderedPins.get(e)?.image || imageValue(e.billboard?.image), + color: e.billboard + ? actual(e, 'color', C.Color.WHITE).toCssColorString() + : undefined, + width: e.polyline?.width?.getValue(now), + lineColor: color(e.polyline?.material?.color), + line: positions(e.polyline?.positions), + fill: e.polygon?.fill?.getValue(now), + outline: e.polygon?.outline?.getValue(now), + polygonColor: color(e.polygon?.material?.color), + polygon: e.polygon?.hierarchy + ?.getValue(now) + ?.positions?.map((v) => [v.x, v.y, v.z]), + })) + .sort((a, b) => a.name.localeCompare(b.name)); + }; + window.__qaUnsharedKml = async (text) => { + const doc = new DOMParser().parseFromString(text, 'application/xml'); + for (const el of [...doc.getElementsByTagName('*')]) + if ( + ['description', 'ExtendedData', 'BalloonStyle'].includes(el.localName) + ) + el.remove(); + const source = await C.KmlDataSource.load(doc, { + camera: viewer.scene.camera, + canvas: viewer.scene.canvas, + clampToGround: true, + }); + for (const e of source.importedEntities || source.entities.values) + e.label = undefined; + return source; + }; + }); + const equivalent = await page.evaluate(async (text) => { + const { viewer } = window.__godsEyeView; + const control = await window.__qaUnsharedKml(text); + const outcomes = await window.__gevGeoImport.importFiles([ + new File([text], 'style-equivalence.kml'), + ]); + const candidate = viewer.dataSources.get(viewer.dataSources.length - 1); + const result = { + ok: outcomes[0]?.ok, + same: + JSON.stringify(window.__qaStyleSnapshot(control)) === + JSON.stringify(window.__qaStyleSnapshot(candidate)), + entities: (candidate.importedEntities || candidate.entities.values) + .length, + }; + await window.__gevGeoImport.remove(outcomes[0]?.id); + return result; + }, small); + check( + 'shared inline and named styles preserve point, line and polygon overrides/inheritance', + equivalent.ok && equivalent.same && equivalent.entities === 9, + JSON.stringify(equivalent), + ); + + // The control bypasses the former style-count refusal solely in this test, + // to compare native unshared rendering against normalized rendering. + await page.evaluate(async (text) => { + const source = await window.__qaUnsharedKml(text); + window.__qaUnsharedSnapshot = JSON.stringify( + window.__qaStyleSnapshot(source), + ); + window.__qaControl = source; + await window.__godsEyeView.viewer.dataSources.add(source); + }, large); + const measure = async () => + page.evaluate(async () => { + const C = window.__CESIUM__, + { viewer } = window.__godsEyeView; + const scene = viewer.scene; + viewer.camera.cancelFlight(); + viewer.camera.setView({ + destination: C.Cartesian3.fromDegrees(-122.5, 37.72, 50000), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + const started = performance.now(), + samples = []; + let last, + frames = 0; + const remove = scene.postRender.addEventListener(() => { + const t = performance.now(); + if (t - started < 2000) return; + frames++; + if (last !== undefined) samples.push(t - last); + last = t; + }); + await new Promise((resolve) => { + let previous = performance.now(); + function tick(t) { + viewer.camera.rotate( + C.Cartesian3.UNIT_Z, + Math.min(t - previous, 100) * 0.0000002, + ); + previous = t; + scene.requestRender(); + if (t - started < 7000) requestAnimationFrame(tick); + else resolve(); + } + requestAnimationFrame(tick); + }); + remove(); + samples.sort((a, b) => a - b); + const gl = scene.context._gl, + debug = gl.getExtension('WEBGL_debug_renderer_info'); + return { + fps: frames / 5, + p50Ms: samples[Math.floor(samples.length * 0.5)], + p95Ms: samples[Math.floor(samples.length * 0.95)], + renderer: debug ? gl.getParameter(debug.UNMASKED_RENDERER_WEBGL) : null, + }; + }); + console.log('UNSHARED CONTROL', JSON.stringify(await measure())); + await page.evaluate(() => + window.__godsEyeView.viewer.dataSources.remove(window.__qaControl, true), + ); + + const loadPicked = async (filename, expected) => { + const before = await page.evaluate( + () => window.__godsEyeView.viewer.dataSources.length, + ); + const priorIds = await page.evaluate(() => + window.__gevGeoImport.list().map((f) => f.id), + ); + const started = performance.now(); + await (await page.$('#geo-import-input')).uploadFile(filename); + const name = path.basename(filename); + const loaded = await page + .waitForFunction( + ({ name, priorIds }) => + window.__gevGeoImport.list().some((f) => !priorIds.includes(f.id)) || + document + .getElementById('geo-import-hint') + .textContent.startsWith(`${name}:`), + { timeout: 120000 }, + { name, priorIds }, + ) + .then( + () => true, + () => false, + ); + const state = await page.evaluate(() => ({ + files: window.__gevGeoImport.list(), + hint: document.getElementById('geo-import-hint').textContent, + sources: window.__godsEyeView.viewer.dataSources.length, + })); + const item = state.files.find((f) => !priorIds.includes(f.id)); + check( + `picked ${name} loads`, + loaded && + (expected === null + ? item?.entityCount > 0 + : item?.entityCount === expected) && + state.sources === before + 1, + JSON.stringify({ + bytes: fs.statSync(filename).size, + loadMs: Math.round(performance.now() - started), + ...state, + }), + ); + return item; + }; + const item = await loadPicked(file, 5000); + if (item) { + const same = await page.evaluate(() => { + const viewer = window.__godsEyeView.viewer; + const source = viewer.dataSources.get(viewer.dataSources.length - 1); + return ( + JSON.stringify(window.__qaStyleSnapshot(source)) === + window.__qaUnsharedSnapshot + ); + }); + check('all 5,000 normalized graphics match their unshared control', same); + console.log('NORMALIZED CANDIDATE', JSON.stringify(await measure())); + await page.evaluate((id) => window.__gevGeoImport.remove(id), item.id); + } + if (supplied) { + const clockBefore = await page.evaluate(() => { + const v = window.__godsEyeView.viewer, + C = window.__CESIUM__; + return [ + C.JulianDate.toIso8601(v.clock.startTime), + C.JulianDate.toIso8601(v.clock.stopTime), + C.JulianDate.toIso8601(v.clock.currentTime), + v.clock.multiplier, + ]; + }); + const suppliedItem = await loadPicked(supplied, null); + const clockAfter = await page.evaluate(() => { + const v = window.__godsEyeView.viewer, + C = window.__CESIUM__; + return [ + C.JulianDate.toIso8601(v.clock.startTime), + C.JulianDate.toIso8601(v.clock.stopTime), + C.JulianDate.toIso8601(v.clock.currentTime), + v.clock.multiplier, + ]; + }); + check( + 'real dated KML leaves the shared clock unchanged', + JSON.stringify(clockBefore) === JSON.stringify(clockAfter), + ); + if (suppliedItem && process.argv.includes('--expect-local-pins')) { + const markers = await page.evaluate(() => { + const { viewer } = window.__godsEyeView, + C = window.__CESIUM__; + const source = viewer.dataSources.get(viewer.dataSources.length - 1); + const points = ( + source.importedEntities || source.entities.values + ).filter((e) => e.position && e.billboard); + const images = points.filter((e) => + e.billboard.image?.getValue(viewer.clock.currentTime), + ); + if (images.length) { + const at = C.Cartographic.fromCartesian( + images[0].position.getValue(viewer.clock.currentTime), + ); + viewer.camera.cancelFlight(); + viewer.camera.setView({ + destination: C.Cartesian3.fromRadians( + at.longitude, + at.latitude, + 100000, + ), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + } + return { points: points.length, images: images.length }; + }); + check( + 'supplied point markers have drawable images', + markers.points > 0 && markers.images === markers.points, + JSON.stringify(markers), + ); + if (markers.points) { + const yellowPixels = async () => { + const shot = await page.screenshot({ + clip: { x: 620, y: 350, width: 200, height: 200 }, + type: 'png', + encoding: 'base64', + }); + return page.evaluate(async (base64) => { + const bitmap = await createImageBitmap( + await (await fetch(`data:image/png;base64,${base64}`)).blob(), + ); + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height), + context = canvas.getContext('2d'); + context.drawImage(bitmap, 0, 0); + const data = context.getImageData( + 0, + 0, + bitmap.width, + bitmap.height, + ).data; + let count = 0; + for (let i = 0; i < data.length; i += 4) + if (data[i] > 150 && data[i + 1] > 150 && data[i + 2] < 100) + count++; + return count; + }, shot); + }; + const setVisible = (visible) => + page.evaluate( + ({ id, visible }) => window.__gevGeoImport.setVisible(id, visible), + { id: suppliedItem.id, visible }, + ); + await setVisible(false); + await new Promise((resolve) => setTimeout(resolve, 1000)); + const hidden = await yellowPixels(); + await setVisible(true); + let shown = hidden; + const deadline = performance.now() + 10000; + while (performance.now() < deadline && shown <= hidden + 10) { + await new Promise((resolve) => setTimeout(resolve, 500)); + shown = await yellowPixels(); + } + check( + 'real USGS markers paint when shown and disappear when hidden', + shown > hidden + 10, + JSON.stringify({ hidden, shown }), + ); + await page.screenshot({ + path: path.join(directory, 'real-kml-visible.png'), + }); + } + } + if (suppliedItem) + await page.evaluate( + (id) => window.__gevGeoImport.remove(id), + suppliedItem.id, + ); + } + check( + 'file-directed USGS icon/metadata requests never leave the page', + fileRequests.length === 0, + fileRequests.length, + ); + errors.push(...(await readRenderErrors(page))); + check( + 'no uncaught page or render errors', + errors.length === 0, + JSON.stringify(errors), + ); + check( + 'all imported sources are removed', + await page.evaluate(() => window.__gevGeoImport.list().length === 0), + ); + console.log('Fixture retained at', file); +} finally { + await browser.close(); +} +process.exitCode = failures ? 1 : 0; diff --git a/scripts/qa-geo-import-regressions.mjs b/scripts/qa-geo-import-regressions.mjs new file mode 100644 index 000000000..ba5a040a2 --- /dev/null +++ b/scripts/qa-geo-import-regressions.mjs @@ -0,0 +1,564 @@ +#!/usr/bin/env node +/** Import regressions through the real UI controller and Cesium loaders. + * Run against dev and preview: QA_BASE_URL=http://localhost:4173 node scripts/qa-geo-import-regressions.mjs + */ +import puppeteer from 'puppeteer'; +import * as Cesium from 'cesium'; +import { hookRenderErrors, readRenderErrors } from './qa-browserEvidence.mjs'; + +const browser = await puppeteer.launch({ headless: true }); +const page = await browser.newPage(); +const meshBytes = Buffer.alloc(60); +[ + -2000, 2000, -2000, 2000, 2000, -2000, -2000, 2000, 2000, 2000, 2000, 2000, +].forEach((value, i) => meshBytes.writeFloatLE(value, i * 4)); +[0, 1, 2, 2, 1, 3].forEach((value, i) => + meshBytes.writeUInt16LE(value, 48 + i * 2), +); +const fixture = { + '/__qa_import_surface/tileset.json': { + asset: { version: '1.1' }, + geometricError: 0, + root: { + transform: Cesium.Matrix4.toArray( + Cesium.Transforms.eastNorthUpToFixedFrame( + Cesium.Cartesian3.fromDegrees(-122.5, 37.7), + ), + ), + boundingVolume: { box: [0, 0, 2000, 2000, 0, 0, 0, 2000, 0, 0, 0, 100] }, + geometricError: 0, + content: { uri: 'surface.gltf' }, + }, + }, + '/__qa_import_surface/surface.gltf': { + asset: { version: '2.0' }, + scene: 0, + scenes: [{ nodes: [0] }], + nodes: [{ mesh: 0 }], + meshes: [ + { + primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }], + }, + ], + materials: [{ doubleSided: true }], + buffers: [ + { + byteLength: 60, + uri: `data:application/octet-stream;base64,${meshBytes.toString('base64')}`, + }, + ], + bufferViews: [ + { buffer: 0, byteOffset: 0, byteLength: 48, target: 34962 }, + { buffer: 0, byteOffset: 48, byteLength: 12, target: 34963 }, + ], + accessors: [ + { + bufferView: 0, + componentType: 5126, + count: 4, + type: 'VEC3', + min: [-2000, 2000, -2000], + max: [2000, 2000, 2000], + }, + { bufferView: 1, componentType: 5123, count: 6, type: 'SCALAR' }, + ], + }, +}; +await page.setRequestInterception(true); +page.on('request', (request) => { + const body = fixture[new URL(request.url()).pathname]; + if (body) + void request.respond({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(body), + }); + else void request.continue(); +}); +const errors = [], + requests = []; +page.on('pageerror', (e) => errors.push(e.message)); +page.on('console', (m) => { + if (/Ignoring clampToGround/.test(m.text())) errors.push(m.text()); +}); +await hookRenderErrors(page); +let failed = 0; +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto( + `${process.env.QA_BASE_URL || 'http://localhost:4173'}/?welcome=0`, + { waitUntil: 'domcontentloaded' }, + ); + await page.waitForFunction( + () => + window.__gevGeoImport && + document.getElementById('loading-screen')?.classList.contains('hidden'), + { timeout: 90000 }, + ); + await page.evaluate(async () => { + const { viewer, dataManager } = window.__godsEyeView, + C = window.__CESIUM__; + for (const id of dataManager.layers.keys()) + await dataManager.setEnabled(id, false); + viewer.imageryLayers.removeAll(); + viewer.terrainProvider = new C.EllipsoidTerrainProvider(); + viewer.clock.shouldAnimate = false; + viewer.camera.cancelFlight(); + viewer.camera.setView({ + destination: C.Cartesian3.fromDegrees(-122.5, 37.7, 100000), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + }); + page.on('request', (r) => { + if (!/^(data:|blob:)/.test(r.url())) requests.push(r.url()); + }); + const results = await page.evaluate(async () => { + const { viewer } = window.__godsEyeView, + C = window.__CESIUM__, + tool = window.__gevGeoImport; + const results = [], + now = C.JulianDate.clone(viewer.clock.currentTime); + const check = (name, pass, detail = '') => + results.push({ name, pass: Boolean(pass), detail }); + const wrap = (body, attrs = '') => + `${body}`; + const point = '-122.5,37.7,0'; + const load = async (value, name) => { + const content = + typeof value === 'object' && !ArrayBuffer.isView(value) + ? JSON.stringify(value) + : value; + const [outcome] = await tool.importFiles([new File([content], name)]); + return { + outcome, + source: outcome.ok + ? viewer.dataSources.get(viewer.dataSources.length - 1) + : null, + }; + }; + const remove = (r) => { + if (r.outcome.ok) tool.remove(r.outcome.id); + }; + let r = await load( + { + type: 'FeatureCollection', + features: [ + { + type: 'Feature', + id: 'kartaview-owned', + properties: { + name: 'XYZ', + addProperty: 1, + 'marker-symbol': 'rail', + }, + geometry: { type: 'Point', coordinates: [-122.5, 37.7, 100] }, + }, + { + type: 'Feature', + geometry: { + type: 'Polygon', + coordinates: [ + [ + [-122.5, 37.7, 10], + [-122.4, 37.7, 10], + [-122.4, 37.8, 10], + [-122.5, 37.7, 10], + ], + ], + }, + }, + ], + }, + 'xyz.geojson', + ); + const pin = (r.source?.importedEntities || r.source?.entities.values).find( + (e) => e.billboard, + ), + polygon = (r.source?.importedEntities || r.source?.entities.values).find( + (e) => e.polygon, + ); + check( + 'XYZ ground footprint and isolated entity IDs', + r.outcome.ok && + pin.id !== 'kartaview-owned' && + Math.abs( + C.Cartographic.fromCartesian(pin.position.getValue(now)).height, + ) < 0.01 && + polygon.polygon.perPositionHeight?.getValue(now) !== true, + ); + check( + 'ground pins have no persistent clamping callbacks', + pin?.billboard.heightReference?.getValue(now) === + C.HeightReference.NONE && + pin.billboard.disableDepthTestDistance.getValue(now) === Infinity, + ); + remove(r); + r = await load( + wrap( + 'ground-122.5 37.7 0-122.4 37.8 0' + + 'absoluteabsolute-122.5 37.7 10000-122.4 37.8 10000' + + 'line-122.5,37.7 -122.4,37.8', + ), + 'tracks.kml', + ); + const find = (name) => + (r.source?.importedEntities || r.source?.entities.values).find( + (e) => e.name === name, + ); + check( + 'ground tracks and untessellated authored lines clamp', + find('ground')?.polyline.clampToGround?.getValue(now) && + find('line')?.polyline.clampToGround?.getValue(now), + ); + check( + 'explicit track altitude and original vertices survive', + find('absolute')?.polyline.positions.getValue(now).length === 2 && + find('absolute') + .polyline.positions.getValue(now) + .every( + (p) => + Math.abs(C.Cartographic.fromCartesian(p).height - 10000) < 0.01, + ), + ); + remove(r); + r = await load( + wrap( + ` #s ${point}`, + ), + 'local-style.kml', + ); + check('whitespace around a local style remains local', r.outcome.ok); + remove(r); + r = await load( + wrap( + `normalhttps://gev-qa-trap.invalid/style${point}`, + ), + 'incomplete-style.kml', + ); + check('removing external style does not hang the queue', r.outcome.ok); + remove(r); + r = await load( + wrap( + `0${point}`, + ), + 'hidden-folder.kml', + ); + check( + 'import show controls own previously hidden KML content', + r.outcome.ok && + (r.source.importedEntities || r.source.entities.values).every( + (e) => e.isShowing, + ), + ); + remove(r); + r = await load( + wrap( + 'ff00ff0037.837.7-122.4-122.5', + ), + 'colored.kml', + ); + check( + 'a colored overlay without an icon is drawable', + r.outcome.ok && + (r.source.importedEntities || r.source.entities.values).some( + (e) => e.rectangle, + ), + ); + remove(r); + const xml = wrap(`${point}`); + const utf16 = new Uint8Array(2 + xml.length * 2); + utf16.set([255, 254]); + for (let i = 0; i < xml.length; i++) { + utf16[2 + i * 2] = xml.charCodeAt(i) & 255; + utf16[3 + i * 2] = xml.charCodeAt(i) >> 8; + } + r = await load(utf16, 'utf16.kml'); + check('UTF-16 BOM is decoded', r.outcome.ok); + remove(r); + r = await load( + wrap( + `${point}`, + 'xmlns:gx="http://www.google.com/kml/ext/2.2" xsi:schemaLocation="test"', + ), + 'namespaces.kml', + ); + check( + 'ordinary duplicate and missing export namespaces are repaired', + r.outcome.ok, + ); + remove(r); + for (const [name, value] of [ + ['null geometry', { type: 'Feature', geometry: null }], + ['invalid coordinates', { type: 'Point', coordinates: ['bad', 37] }], + [ + 'missing feature type', + { + type: 'FeatureCollection', + features: [{ geometry: { type: 'Point', coordinates: [0, 0] } }], + }, + ], + [ + 'nested unsupported geometry', + { type: 'Feature', geometry: { type: 'Topology', arcs: [] } }, + ], + ]) { + r = await load(value, 'refused.geojson'); + check(`${name} is refused without stopping rendering`, !r.outcome.ok); + remove(r); + } + r = await load( + wrap( + 'NaN,37,0', + ), + 'invalid.kml', + ); + check('non-finite KML coordinates are refused', !r.outcome.ok); + remove(r); + r = await load( + { + type: 'LineString', + coordinates: [ + [-122.6, 37.7], + [-122.4, 37.7], + ], + }, + 'portrait.geojson', + ); + await new Promise((resolve) => setTimeout(resolve, 2300)); + const positions = (r.source?.importedEntities || + r.source?.entities.values)[0].polyline.positions.getValue(now); + const screen = positions?.map((p) => + C.SceneTransforms.worldToWindowCoordinates(viewer.scene, p), + ); + check( + 'portrait flight includes both route endpoints', + screen?.every( + (p) => p && p.x > 0 && p.x < innerWidth && p.y > 0 && p.y < innerHeight, + ), + screen?.map((p) => p && [p.x, p.y]), + ); + remove(r); + r = await load( + { + type: 'MultiPoint', + coordinates: [ + [-74, 40.7], + [139.7, 35.7], + ], + }, + 'intercontinental.geojson', + ); + await new Promise((resolve) => setTimeout(resolve, 2300)); + const intercontinental = ( + r.source?.importedEntities || r.source?.entities.values + ) + .filter((e) => e.position) + .map((e) => e.position.getValue(now)); + const occluder = new C.EllipsoidalOccluder( + C.Ellipsoid.WGS84, + viewer.camera.positionWC, + ); + check( + 'intercontinental points remain in frame and in front of the horizon', + intercontinental?.every((p) => { + const s = C.SceneTransforms.worldToWindowCoordinates(viewer.scene, p); + return ( + occluder.isPointVisible(p) && + s && + s.x > 0 && + s.x < innerWidth && + s.y > 0 && + s.y < innerHeight + ); + }), + ); + remove(r); + r = await load( + wrap( + 'absolute14.9,52.37,3000 5.12,52.09,30005.12,52.09', + ), + 'wall.kml', + ); + await new Promise((resolve) => setTimeout(resolve, 2300)); + check( + 'a wall contributes both endpoints to the flight', + r.outcome.ok && + (r.source.importedEntities || r.source.entities.values) + .find((e) => e.wall) + ?.wall.positions.getValue(now) + .every((p) => { + const s = C.SceneTransforms.worldToWindowCoordinates( + viewer.scene, + p, + ); + return ( + s && s.x > 0 && s.x < innerWidth && s.y > 0 && s.y < innerHeight + ); + }), + ); + remove(r); + r = await load( + { + type: 'MultiPoint', + coordinates: [ + [0, 0], + [180, 0], + ], + }, + 'antipodal.geojson', + ); + await new Promise((resolve) => setTimeout(resolve, 1800)); + check( + 'symmetric global extents keep a finite camera', + r.outcome.ok && + Number.isFinite(viewer.camera.positionCartographic.height), + ); + remove(r); + viewer.camera.cancelFlight(); + viewer.camera.setView({ + destination: C.Cartesian3.fromDegrees(-122.5, 37.7, 100000), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + const mesh = await C.Cesium3DTileset.fromUrl( + `${location.origin}/__qa_import_surface/tileset.json`, + ); + viewer.scene.primitives.add(mesh); + // This fixture installs a mesh outside the app's map-source lifecycle. + // Let the new camera/tiles reach a rendered frame before testing sampling. + await new Promise((resolve) => { + let frames = 0; + const remove = viewer.scene.postRender.addEventListener(() => { + if (++frames >= 2) { + remove(); + resolve(); + } else viewer.scene.requestRender(); + }); + viewer.scene.requestRender(); + }); + const fixtureDeadline = performance.now() + 5000; + while (!mesh.tilesLoaded && performance.now() < fixtureDeadline) { + viewer.scene.requestRender(); + await new Promise((resolve) => setTimeout(resolve, 50)); + } + const globeShown = viewer.scene.globe.show; + viewer.scene.globe.show = false; + + r = await load( + { type: 'Point', coordinates: [-122.5, 37.7, 0] }, + 'mesh-point.geojson', + ); + const meshPoint = (r.source?.importedEntities || r.source?.entities.values) + .find((e) => e.billboard) + ?.position.getValue(now); + const meshHeight = + meshPoint && C.Cartographic.fromCartesian(meshPoint).height; + check( + 'native 3D Tiles ground sampling keeps pins on the rendered mesh', + r.outcome.ok && Math.abs(meshHeight - 2000) < 2, + { + meshHeight, + tilesLoaded: mesh.tilesLoaded, + globeShown: viewer.scene.globe.show, + }, + ); + tool.flyTo(r.outcome.id); + await new Promise((resolve) => setTimeout(resolve, 2300)); + const meshScreen = + meshPoint && + C.SceneTransforms.worldToWindowCoordinates(viewer.scene, meshPoint); + check( + 'a high-surface arrival frames the elevated pin', + meshScreen && + Math.abs(meshScreen.x - innerWidth / 2) < 20 && + Math.abs(meshScreen.y - innerHeight / 2) < 20, + { + screen: meshScreen && [meshScreen.x, meshScreen.y], + camera: { + height: viewer.camera.positionCartographic.height, + pitch: viewer.camera.pitch, + }, + meshHeight, + }, + ); + const groundSource = r.source; + const elevated = await load( + wrap( + 'absolute-122.5,37.7,5000', + ), + 'elevated-pin.kml', + ); + await new Promise((resolve) => setTimeout(resolve, 2600)); + check( + 'a higher imported pin never becomes the sampled ground', + elevated.outcome.ok && + Math.abs( + C.Cartographic.fromCartesian( + groundSource.importedBillboards.get(0).position, + ).height - 2000, + ) < 2, + ); + remove(elevated); + remove(r); + viewer.scene.primitives.remove(mesh); + viewer.scene.globe.show = globeShown; + const before = tool.list().length; + const transfer = new DataTransfer(); + transfer.items.add( + new File( + [JSON.stringify({ type: 'Point', coordinates: [-122.5, 37.7] })], + 'panel-drop.geojson', + ), + ); + const event = new DragEvent('drop', { + bubbles: true, + cancelable: true, + dataTransfer: transfer, + }); + document.getElementById('geo-import-button').dispatchEvent(event); + for (let i = 0; i < 100 && tool.list().length === before; i++) + await new Promise((resolve) => setTimeout(resolve, 20)); + check( + 'a panel drop imports and prevents the browser default', + event.defaultPrevented && tool.list().length === before + 1, + ); + for (const file of tool.list()) tool.remove(file.id); + check( + 'the shared clock stays exactly unchanged', + C.JulianDate.equals(now, viewer.clock.currentTime), + ); + check('no file sources remain', tool.list().length === 0); + return results; + }); + for (const r of results) { + console.log( + `[${r.pass ? 'PASS' : 'FAIL'}] ${r.name}`, + JSON.stringify(r.detail), + ); + if (!r.pass) failed++; + } + const renderErrors = await readRenderErrors(page); + if (errors.length || renderErrors.length) { + failed++; + console.log( + '[FAIL] browser/render errors', + JSON.stringify({ errors, renderErrors }), + ); + } + // Terrain belongs to the base map; imported files may sample that provider. + const unexpected = requests.filter( + (url) => + new URL(url).pathname !== '/logo.svg' && + !new URL(url).pathname.startsWith('/__qa_import_surface/') && + !/\/api\/|\.terrain(?:\?|$)|reearth|cesium|arcgis|openstreetmap|\.pbf(?:\?|$)/i.test( + url, + ), + ); + console.log( + `[${unexpected.length ? 'FAIL' : 'PASS'}] no unexpected file-directed requests`, + JSON.stringify(unexpected), + ); + if (unexpected.length) failed++; +} finally { + await browser.close(); +} +process.exitCode = failed ? 1 : 0; diff --git a/scripts/qa-geo-import.mjs b/scripts/qa-geo-import.mjs new file mode 100644 index 000000000..074eb8fbd --- /dev/null +++ b/scripts/qa-geo-import.mjs @@ -0,0 +1,594 @@ +#!/usr/bin/env node +/** + * Rendered acceptance for DISPLAY ▸ Import: real files through the real file + * input and a real drop, parsed by Cesium in the page. + * + * Proves: GeoJSON, KML, KMZ (with a packed icon and ground overlay) and GPX + * each become one row and one data source; the imported shape actually paints + * on the globe in its row's color (a GeoJSON `stroke`/`fill` does not override + * it) and stops painting when hidden; no import makes the page request + * anything named in it (network link, remote icon, remote style, palette + * icon, balloon or extended-data HTML, maki marker) or anything outside the + * page for it; no entity keeps a description, label or properties; dated KML + * and GPX leave the app's clock alone and still draw now; a GPX track keeps + * its two segments apart; keyboard focus survives hide/show; a dropped file + * imports like a picked one; a file that is not geodata is refused with a + * reason and leaves nothing behind; Remove gives every data source back; no + * page errors. + * + * Usage: dev server up (`npm run dev`), then `node scripts/qa-geo-import.mjs`. + * QA_BASE_URL (default http://localhost:4173), QA_SHOT_DIR, QA_HEADFUL=1. + */ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import puppeteer from 'puppeteer'; +import { hookRenderErrors, readRenderErrors } from './qa-browserEvidence.mjs'; + +const BASE_URL = process.env.QA_BASE_URL || 'http://localhost:4173'; +const SHOT_DIR = process.env.QA_SHOT_DIR || 'qa-shots/geo-import'; +const HEADFUL = process.env.QA_HEADFUL === '1'; +// Golden Gate Park: a big, flat, green rectangle the test polygon can cover. +const VIEW = { lon: -122.4862, lat: 37.7694, height: 4200, pitch: -88 }; +const TRAP_HOST = 'gev-qa-trap.invalid'; + +/* ── fixtures ──────────────────────────────────────────────────────────── */ + +const ring = [ + [-122.511, 37.7645], + [-122.4545, 37.7645], + [-122.4545, 37.7745], + [-122.511, 37.7745], + [-122.511, 37.7645], +]; +const geojson = JSON.stringify({ + type: 'FeatureCollection', + features: [ + { + type: 'Feature', + // A file's own simplestyle and HTML must not survive the import. + properties: { + name: 'QA park', + stroke: '#ff0000', + fill: '#ff0000', + 'fill-opacity': 1, + description: ``, + }, + geometry: { type: 'Polygon', coordinates: [ring.map((p) => [...p, 0])] }, + }, + { + type: 'Feature', + properties: { name: 'QA pin', 'marker-symbol': 'rail' }, + geometry: { type: 'Point', coordinates: [-122.4862, 37.7694, 0] }, + }, + ], +}); +const kml = (iconHref) => ` + + + + + https://${TRAP_HOST}/link.kml + QA KML pin#s + ]]> + 2019-01-01T00:00:00Z2019-01-02T00:00:00Z + ]]> + -122.47,37.77,0 + QA palette pin#palette + -122.48,37.771,0 + QA moving + 2019-01-01T00:00:00Z2019-01-01T01:00:00Z + -122.49 37.767 0-122.475 37.772 0 + QA split tracks + -122.50 37.767 0-122.49 37.768 0 + -122.47 37.771 0-122.46 37.772 0 + + QA remote stylehttps://${TRAP_HOST}/styles.kml#x + -122.50,37.766 -122.46,37.772 + https://${TRAP_HOST}/overlay.png + 37.7737.76-122.46-122.47 + +`; +const gpx = ` + + QA waypoint + QA track<img src="https://${TRAP_HOST}/gpx.png"> + + + + +`; +// 1×1 PNG. +const PNG = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==', + 'base64', +); +/** Stored (uncompressed) zip — enough for a KMZ fixture. */ +function storedZip(files) { + const parts = []; + const central = []; + let offset = 0; + for (const [name, data] of files) { + const n = Buffer.from(name); + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt32LE(data.length, 18); + local.writeUInt32LE(data.length, 22); + local.writeUInt16LE(n.length, 26); + const c = Buffer.alloc(46); + c.writeUInt32LE(0x02014b50, 0); + c.writeUInt32LE(data.length, 20); + c.writeUInt32LE(data.length, 24); + c.writeUInt16LE(n.length, 28); + c.writeUInt32LE(offset, 42); + parts.push(local, n, data); + central.push(c, n); + offset += 30 + n.length + data.length; + } + const dir = Buffer.concat(central); + const end = Buffer.alloc(22); + end.writeUInt32LE(0x06054b50, 0); + end.writeUInt16LE(files.length, 8); + end.writeUInt16LE(files.length, 10); + end.writeUInt32LE(dir.length, 12); + end.writeUInt32LE(offset, 16); + return Buffer.concat([...parts, dir, end]); +} +const kmzDoc = kml('files/pin.png').replace( + `https://${TRAP_HOST}/overlay.png`, + 'files/overlay.png', +); + +const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gev-qa-geo-import-')); +const fixture = (name, data) => { + const file = path.join(dir, name); + fs.writeFileSync(file, data); + return file; +}; +const FILES = [ + fixture('park.geojson', geojson), + fixture('remote-bits.kml', kml(`https://${TRAP_HOST}/icon.png`)), + fixture( + 'packed.kmz', + storedZip([ + ['doc.kml', Buffer.from(kmzDoc)], + ['files/pin.png', PNG], + ['files/overlay.png', PNG], + ]), + ), + fixture('walk.gpx', gpx), +]; + +/* ── harness ───────────────────────────────────────────────────────────── */ + +const browser = await puppeteer.launch({ + headless: !HEADFUL, + args: [ + '--no-sandbox', + '--disable-background-timer-throttling', + '--disable-renderer-backgrounding', + ...(process.platform === 'darwin' + ? ['--use-angle=metal', '--enable-gpu'] + : ['--use-gl=angle', '--use-angle=swiftshader']), + ], +}); +const page = await browser.newPage(); +await hookRenderErrors(page); +const errors = []; +const trapped = []; +page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`)); +page.on('console', (message) => { + if (/Ignoring clampToGround/.test(message.text())) + errors.push(message.text()); +}); +// Anything a file names, and the icon assets Cesium would load on a file's +// behalf (KML palette icons from maps.google.com, GeoJSON maki markers). +const FILE_FETCH = [TRAP_HOST, 'maps.google.com/mapfiles', '/maki/']; +page.on('request', (request) => { + if (FILE_FETCH.some((needle) => request.url().includes(needle))) + trapped.push(request.url()); +}); +let failures = 0; +function check(name, passed, detail = '') { + console.log( + `[${passed ? 'PASS' : 'FAIL'}] ${name}${detail ? ` — ${detail}` : ''}`, + ); + if (!passed) failures++; +} +fs.mkdirSync(SHOT_DIR, { recursive: true }); +const shot = (name) => + page.screenshot({ + path: path.join(SHOT_DIR, `${name}.jpg`), + type: 'jpeg', + quality: 82, + }); +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const CLIP = { x: 380, y: 240, width: 480, height: 320 }; + +/** Pixels in the clip close to the first import color (#39d0ff). */ +async function cyanPixels() { + await page.evaluate(() => window.__godsEyeView.viewer.scene.requestRender()); + await wait(600); + const base64 = await page.screenshot({ + clip: CLIP, + type: 'png', + encoding: 'base64', + }); + return page.evaluate(async (b64) => { + const bitmap = await createImageBitmap( + await (await fetch(`data:image/png;base64,${b64}`)).blob(), + ); + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const context = canvas.getContext('2d'); + context.drawImage(bitmap, 0, 0); + const { data } = context.getImageData(0, 0, bitmap.width, bitmap.height); + let n = 0; + for (let i = 0; i < data.length; i += 4) { + const [r, g, b] = [data[i], data[i + 1], data[i + 2]]; + if (b > 45 && g > 30 && r < 100 && b - r > 30) n += 1; + } + return n; + }, base64); +} +const state = () => + page.evaluate(() => ({ + files: window.__gevGeoImport.list(), + dataSources: window.__godsEyeView.viewer.dataSources.length, + rows: document.querySelectorAll('#geo-import-list .geo-import-row').length, + hint: document.getElementById('geo-import-hint')?.textContent || '', + })); + +try { + await page.setViewport({ width: 1280, height: 860 }); + await page.goto(`${BASE_URL}/?welcome=0`, { waitUntil: 'domcontentloaded' }); + await page.waitForFunction( + () => + window.__gevGeoImport && + window.__godsEyeView?.viewer && + document.getElementById('loading-screen')?.classList.contains('hidden'), + { timeout: 90_000 }, + ); + await page.evaluate(async (view) => { + const viewer = window.__godsEyeView.viewer; + for (const id of window.__godsEyeView.dataManager.layers.keys()) + await window.__godsEyeView.dataManager.setEnabled(id, false); + viewer.imageryLayers.removeAll(); + viewer.terrainProvider = new window.__CESIUM__.EllipsoidTerrainProvider(); + viewer.scene.globe.baseColor = window.__CESIUM__.Color.BLACK; + viewer.scene.globe.enableLighting = false; + viewer.camera.cancelFlight?.(); + viewer.camera.setView({ + destination: window.__CESIUM__.Cartesian3.fromDegrees( + view.lon, + view.lat, + view.height, + ), + orientation: { heading: 0, pitch: (view.pitch * Math.PI) / 180, roll: 0 }, + }); + viewer.scene.requestRender(); + }, VIEW); + await wait(4000); + await page.evaluate(() => { + const rail = document.getElementById('pp-toggles'); + if (rail?.classList.contains('collapsed')) + document + .querySelector('.panel-collapse-btn[data-collapse-target="pp-toggles"]') + ?.click(); + }); + await page.waitForFunction( + () => + document.getElementById('geo-import-button')?.getBoundingClientRect() + .width > 0, + { timeout: 10_000 }, + ); + const before = await state(); + check( + 'Import is on the DISPLAY rail with an empty, hidden list', + before.rows === 0 && + !(await page.evaluate(() => + document + .getElementById('geo-import-list') + .classList.contains('visible'), + )), + ); + const cyanBefore = await cyanPixels(); + await page.evaluate(() => { + window.__godsEyeView.viewer.clock.shouldAnimate = false; + }); + const clock = () => + page.evaluate(() => { + const c = window.__godsEyeView.viewer.clock; + const iso = (t) => window.__CESIUM__.JulianDate.toIso8601(t, 0); + return { + start: iso(c.startTime), + stop: iso(c.stopTime), + range: c.clockRange, + step: c.clockStep, + multiplier: c.multiplier, + animate: c.shouldAnimate, + // Wall-clock drift aside, the current time must not jump to 2018/2019. + currentTime: window.__CESIUM__.JulianDate.toIso8601(c.currentTime), + }; + }); + const clockBefore = await clock(); + const sourcesBefore = before.dataSources; + + // Picked through the real . + const input = await page.$('#geo-import-input'); + await input.uploadFile(...FILES); + const imported = await page + .waitForFunction(() => window.__gevGeoImport.list().length === 4, { + timeout: 60_000, + }) + .then( + () => true, + () => false, + ); + const after = await state(); + check( + 'four picked files become four rows and four data sources', + imported && + after.rows === 4 && + after.dataSources === before.dataSources + 4, + JSON.stringify( + after.files.map((f) => `${f.name}:${f.format}:${f.entityCount}`), + ), + ); + check( + 'formats are recognized', + after.files.map((f) => f.format).join() === 'geojson,kml,kmz,gpx', + ); + check( + 'the KML and KMZ had their outside references removed', + after.files[1].removed > 0 && after.files[2].removed > 0, + `removed ${after.files[1].removed}/${after.files[2].removed}`, + ); + check( + 'the hint says so', + /Added 4 files\..*left out/.test(after.hint), + after.hint, + ); + const clockAfter = await clock(); + check( + "dated KML and GPX leave the app's clock alone", + JSON.stringify(clockAfter) === JSON.stringify(clockBefore) && + (await page.evaluate( + () => + window.__godsEyeView.viewer.clockTrackedDataSource?.clock === + undefined, + )), + `${JSON.stringify(clockBefore)} → ${JSON.stringify(clockAfter)}`, + ); + const inside = await page.evaluate((from) => { + const viewer = window.__godsEyeView.viewer; + const now = viewer.clock.currentTime; + const sources = []; + for (let i = from; i < viewer.dataSources.length; i++) + sources.push(viewer.dataSources.get(i)); + const entities = sources.flatMap( + (ds) => ds.importedEntities || ds.entities.values, + ); + const named = (name) => entities.find((e) => e.name === name); + const gpx = sources[3].importedEntities || sources[3].entities.values; + const kmz = sources[2].importedEntities || sources[2].entities.values; + return { + sources: sources.length, + clocks: sources.filter((ds) => ds.clock !== undefined).length, + described: entities.filter((e) => e.description !== undefined).length, + labelled: entities.filter((e) => e.label !== undefined).length, + withProperties: entities.filter((e) => e.properties !== undefined).length, + withKml: entities.filter((e) => e.kml !== undefined).length, + hidden: entities.filter((e) => !e.isAvailable(now)).length, + datedPinNow: Boolean(named('QA KML pin')?.isAvailable(now)), + fallbackPins: ['QA KML pin', 'QA palette pin'].filter((name) => + named(name)?.billboard?.image?.getValue(now), + ).length, + movingIsLine: Boolean( + named('QA moving')?.polyline && !named('QA moving')?.position, + ), + movingVertices: + named('QA moving')?.polyline?.positions?.getValue(now)?.length, + splitTracks: (sources[1].importedEntities || sources[1].entities.values) + .filter((e) => e.parent?.name === 'QA split tracks' && e.polyline) + .map((e) => e.polyline.positions.getValue(now).length), + gpxLines: gpx.filter((e) => e.polyline).length, + gpxPoints: gpx.filter((e) => e.billboard || e.point).length, + kmzLocalImage: kmz.some((e) => + String(e.billboard?.image?.getValue(now) || '').startsWith('blob:'), + ), + kmzOverlay: kmz.some((e) => e.rectangle), + groundedLines: sources + .slice(1, 3) + .every((ds) => + (ds.importedEntities || ds.entities.values) + .filter((e) => e.polyline) + .every((e) => e.polyline.clampToGround?.getValue(now)), + ), + xyzPolygon: + (sources[0].importedEntities || sources[0].entities.values) + .find((e) => e.polygon) + ?.polygon.perPositionHeight?.getValue(now) !== true, + }; + }, sourcesBefore); + check( + 'no imported entity keeps a description, label, properties or KML data', + inside.sources === 4 && + inside.described + + inside.labelled + + inside.withProperties + + inside.withKml === + 0, + JSON.stringify(inside), + ); + check( + 'no imported source has a clock, and dated features draw now', + inside.clocks === 0 && + inside.hidden === 0 && + inside.datedPinNow && + inside.movingIsLine && + inside.movingVertices === 2, + JSON.stringify(inside), + ); + check( + 'blocked KML icon sources use drawable local fallback pins', + inside.fallbackPins === 2, + JSON.stringify({ fallbackPins: inside.fallbackPins }), + ); + check( + 'KML MultiTrack keeps its segments and original vertex count', + inside.splitTracks.join() === '2,2', + JSON.stringify(inside.splitTracks), + ); + check( + 'the GPX track keeps its two segments apart', + inside.gpxLines === 2 && inside.gpxPoints === 1, + JSON.stringify(inside), + ); + check( + 'KMZ retains its own packed image and overlay', + inside.kmzLocalImage && inside.kmzOverlay, + ); + check( + 'XYZ polygons and KML/KMZ lines use ground geometry', + inside.xyzPolygon && inside.groundedLines, + ); + await page.evaluate((from) => { + for (const entity of window.__godsEyeView.viewer.dataSources.get(from) + .entities.values) + if (entity.billboard) entity.show = false; + }, sourcesBefore); + await page.evaluate((view) => { + const viewer = window.__godsEyeView.viewer; + viewer.camera.cancelFlight?.(); + viewer.camera.setView({ + destination: window.__CESIUM__.Cartesian3.fromDegrees( + view.lon, + view.lat, + view.height, + ), + orientation: { heading: 0, pitch: (view.pitch * Math.PI) / 180, roll: 0 }, + }); + }, VIEW); + await wait(2500); + const cyanShown = await cyanPixels(); + await shot('imported'); + check( + 'the imported polygon paints on the globe', + cyanShown > cyanBefore * 4 && cyanShown > cyanBefore + 5000, + `${cyanBefore} → ${cyanShown}`, + ); + + const parkId = after.files[0].id; + await page.click( + `#geo-import-list [data-import-id="${parkId}"] button[data-action="toggle"]`, + ); + const cyanHidden = await cyanPixels(); + check( + 'hiding it stops it painting', + cyanHidden < cyanShown / 3, + `${cyanShown} → ${cyanHidden}`, + ); + await page.click( + `#geo-import-list [data-import-id="${parkId}"] button[data-action="toggle"]`, + ); + check( + 'showing it again paints it again', + (await cyanPixels()) > cyanHidden * 4, + ); + + // Keyboard: focus stays on the same control when the list is rebuilt. + const toggleSelector = `#geo-import-list [data-import-id="${parkId}"] button[data-action="toggle"]`; + await page.focus(toggleSelector); + await page.keyboard.press('Enter'); + const focusAfterHide = await page.evaluate( + (sel) => document.activeElement === document.querySelector(sel), + toggleSelector, + ); + await page.keyboard.press('Enter'); + const focusAfterShow = await page.evaluate( + (sel) => + document.activeElement === document.querySelector(sel) && + document.activeElement.getAttribute('aria-pressed') === 'true', + toggleSelector, + ); + check( + 'keyboard focus stays on the toggle through hide and show', + focusAfterHide && focusAfterShow, + ); + + // Dropped onto the globe, as a person drags from their file manager. + await page.evaluate((text) => { + const container = window.__godsEyeView.viewer.container; + const transfer = new DataTransfer(); + transfer.items.add( + new File([text], 'dropped.geojson', { type: 'application/geo+json' }), + ); + for (const type of ['dragenter', 'dragover', 'drop']) + container.dispatchEvent( + new DragEvent(type, { + dataTransfer: transfer, + bubbles: true, + cancelable: true, + }), + ); + }, geojson); + const dropped = await page + .waitForFunction(() => window.__gevGeoImport.list().length === 5, { + timeout: 20_000, + }) + .then( + () => true, + () => false, + ); + check('a file dropped on the globe imports', dropped); + + // Not geodata: refused with a reason, nothing added. + await page.evaluate(() => { + const transfer = new DataTransfer(); + transfer.items.add( + new File(['just some notes'], 'notes.txt', { type: 'text/plain' }), + ); + window.__godsEyeView.viewer.container.dispatchEvent( + new DragEvent('drop', { + dataTransfer: transfer, + bubbles: true, + cancelable: true, + }), + ); + }); + await wait(800); + const refused = await state(); + check( + 'a file that is not geodata is refused with a reason', + refused.files.length === 5 && + /notes\.txt: Only GeoJSON, KML, KMZ and GPX/.test(refused.hint), + refused.hint, + ); + + // Remove every file through its row button. + for (const { id } of refused.files) + await page.click( + `#geo-import-list [data-import-id="${id}"] button[data-action="remove"]`, + ); + const cleared = await state(); + check( + 'Remove gives every data source back', + cleared.rows === 0 && cleared.dataSources === before.dataSources, + `${cleared.dataSources} vs ${before.dataSources}`, + ); + await wait(1500); + check( + 'nothing named inside a file, and no icon asset for one, was ever requested', + trapped.length === 0, + trapped.join(' '), + ); + errors.push(...(await readRenderErrors(page))); + check('no page or rendering errors', errors.length === 0, errors.join(' | ')); +} catch (error) { + check('harness ran to completion', false, error?.stack || String(error)); +} finally { + await browser.close(); + fs.rmSync(dir, { recursive: true, force: true }); +} +console.log(failures ? `\n${failures} check(s) failed` : '\nall checks passed'); +process.exit(failures ? 1 : 0); diff --git a/scripts/qa-ghostmaps.mjs b/scripts/qa-ghostmaps.mjs new file mode 100644 index 000000000..83dc8ed97 --- /dev/null +++ b/scripts/qa-ghostmaps.mjs @@ -0,0 +1,645 @@ +#!/usr/bin/env node +/** + * qa-ghostmaps.mjs — headless proof for the S2 Underground GhostMaps layer + * (id `s2-ghostmaps`): S2's public KMZ intel products, kept current from + * github.com/s2underground/GhostMaps. + * + * Drives the REAL app in headless Chromium against a dev server (keyless). + * + * (i) LIVE — enabling the layer loads the default products (Common + * Intelligence Picture and the 30-day kinetic pull) from the live + * repository through /api/ghostmaps, one data source per product, + * matching the proxy's catalog commit; the row shows one chip per + * catalog product with the defaults active, and the page holds an + * open event stream to /api/ghostmaps/events. + * (ii) PICK — a Common Intelligence Picture marker at the screen centre + * picks as this layer's entity; clicking it paints its report card + * and clicking empty ground clears it. + * (iii) PUSH (synthetic) — the event stream is replaced in the page and a + * catalog naming a new edition of one product is pushed: only that + * product reloads (a new data source replaces the old one, no + * duplicates), the other keeps its data source. A catalog without a + * product removes it. + * (iv) CHIPS — clicking an active product chip removes that product, + * clicking it again restores it; the choice survives a reload. + * (v) DISABLE — every GhostMaps data source leaves the viewer. + * (vi) VIEWPORT — at a 390x844 phone viewport the open row and its chips + * fit the panel width with no horizontal overflow. + * (vii) FAR SIDE — pins skip the depth test, so they are horizon-culled: + * seen from over the Indian Ocean no pin clearly behind the planet is + * shown; back over North America the near-side pins show again. + * + * Screenshots go to qa-shots/ghostmaps-*.png (gitignored). + * + * Run: node scripts/qa-ghostmaps.mjs --url http://localhost:4173 + * Optional: --timeout-ms 180000 for a slow boot, --shots . + * Exits non-zero on any FAIL. Does not commit anything. + */ + +import puppeteer from 'puppeteer'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const argv = process.argv.slice(2); +const getOpt = (name, dflt) => { + const i = argv.indexOf(name); + return i >= 0 && argv[i + 1] ? argv[i + 1] : dflt; +}; +const APP_URL = getOpt('--url', 'http://localhost:4173'); +const HEADFUL = argv.includes('--headful'); +const TIMEOUT_MS = Number(getOpt('--timeout-ms', '90000')); +const SHOTS_DIR = path.resolve( + getOpt('--shots', path.join(__dirname, '..', 'qa-shots')), +); +const LAYER_ID = 's2-ghostmaps'; + +const results = []; +function record(name, ok, detail) { + results.push({ name, ok, detail }); + const tag = ok ? '\x1b[32mPASS\x1b[0m' : '\x1b[31mFAIL\x1b[0m'; + console.log(` [${tag}] ${name}${detail ? ` — ${detail}` : ''}`); +} +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +async function boot(page) { + await page.goto(`${APP_URL}/?welcome=0`, { + waitUntil: 'domcontentloaded', + timeout: TIMEOUT_MS, + }); + await page.waitForFunction( + () => window.__godsEyeView?.viewer && window.__godsEyeView?.dataManager, + { timeout: TIMEOUT_MS }, + ); + await sleep(5000); + await page.keyboard.press('Escape'); +} + +/** GhostMaps data sources on the viewer: name → entity count. */ +function ghostSources(prefix) { + const { dataSources } = window.__godsEyeView.viewer; + const out = []; + for (let i = 0; i < dataSources.length; i++) { + const ds = dataSources.get(i); + if (ds.name?.startsWith(prefix)) + out.push({ name: ds.name, count: ds.entities.values.length }); + } + return out; +} + +function paintedOverlayPixels() { + const canvas = document.getElementById('world-overlay-canvas'); + if (!canvas) return -1; + const pixels = canvas + .getContext('2d') + .getImageData(0, 0, canvas.width, canvas.height).data; + let count = 0; + for (let i = 3; i < pixels.length; i += 4) if (pixels[i] > 0) count++; + return count; +} + +async function enableAndSettle(page) { + await page.evaluate((id) => { + const panel = document.getElementById('data-panel'); + if (panel?.classList.contains('collapsed')) + panel.querySelector('[data-collapse-target="data-panel"]')?.click(); + return window.__godsEyeView.dataManager.setEnabled(id, true); + }, LAYER_ID); + await page.waitForFunction( + (id) => { + const stats = window.__godsEyeView.dataManager.layers + .get(id) + .module.getStats(); + return !stats.loading && stats.count > 0; + }, + { timeout: TIMEOUT_MS, polling: 500 }, + LAYER_ID, + ); +} + +const stats = (page) => + page.evaluate( + (id) => window.__godsEyeView.dataManager.layers.get(id).module.getStats(), + LAYER_ID, + ); +const sources = (page) => + page.evaluate(`(${ghostSources})(${JSON.stringify(`${LAYER_ID}:`)})`); + +async function showRow(page) { + await page.evaluate((id) => { + document + .querySelector(`[data-layer-id="${id}"]`) + ?.scrollIntoView({ block: 'center' }); + }, LAYER_ID); + await sleep(400); +} + +async function main() { + fs.mkdirSync(SHOTS_DIR, { recursive: true }); + const browser = await puppeteer.launch({ + headless: !HEADFUL, + args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'], + defaultViewport: { width: 1440, height: 900 }, + }); + try { + // ---- (i) LIVE --------------------------------------------------------- + const page = await browser.newPage(); + // Start clean once; a reload must keep what the page stored. + await page.evaluateOnNewDocument(() => { + try { + if (sessionStorage.getItem('qa-ghostmaps-clean')) return; + localStorage.clear(); + sessionStorage.setItem('qa-ghostmaps-clean', '1'); + } catch { + /* sandboxed frames have no storage */ + } + }); + page.on('pageerror', (error) => + console.log(` [page error] ${error.message}`), + ); + await boot(page); + const catalog = await page.evaluate(() => + fetch('/api/ghostmaps/catalog').then((r) => r.json()), + ); + record( + 'LIVE: proxy catalog names a commit and the default products', + /^[0-9a-f]{40}$/.test(catalog.commit || '') && + ['cip', 'kinetic-30d'].every((id) => + catalog.products.some((p) => p.id === id && p.defaultOn), + ), + `${catalog.commit?.slice(0, 7)} "${catalog.message}", ${catalog.products.length} products`, + ); + const t0 = Date.now(); + await enableAndSettle(page); + const live = await stats(page); + const liveSources = await sources(page); + record( + 'LIVE: default products load as one data source each', + liveSources.length === 2 && + liveSources.every((s) => s.count > 0) && + live.products.sort().join() === 'cip,kinetic-30d', + `${liveSources.map((s) => `${s.name}=${s.count}`).join(', ')} in ${Date.now() - t0} ms`, + ); + record( + 'LIVE: layer reports the proxy commit and no error', + live.commit === catalog.commit && !live.error, + `commit ${live.commit?.slice(0, 7)}, error ${live.error}`, + ); + await showRow(page); + const chips = await page.evaluate( + (id) => + [ + ...document.querySelectorAll( + `[data-layer-id="${id}"] .data-toggle-chip`, + ), + ].map((chip) => ({ + id: chip.dataset.chipId, + active: chip.getAttribute('aria-pressed') === 'true', + })), + LAYER_ID, + ); + record( + 'LIVE: one chip per product, defaults pressed', + chips.length === catalog.products.length && + chips.every( + (chip) => + chip.active === + catalog.products.find((p) => p.id === chip.id)?.defaultOn, + ), + chips.map((c) => `${c.id}${c.active ? '*' : ''}`).join(' '), + ); + const stream = await page + .waitForFunction( + (id) => + window.__godsEyeView.dataManager.layers.get(id).module.getStats() + .stream === 'open', + { timeout: 15000, polling: 250 }, + LAYER_ID, + ) + .then( + () => true, + () => false, + ); + record('LIVE: the /api/ghostmaps/events stream is open', stream); + await page.screenshot({ path: path.join(SHOTS_DIR, 'ghostmaps-live.png') }); + + // ---- (ii) PICK ---------------------------------------------------------- + const target = await page.evaluate((id) => { + const gev = window.__godsEyeView; + const ds = [...Array(gev.viewer.dataSources.length).keys()] + .map((i) => gev.viewer.dataSources.get(i)) + .find((item) => item.name === `${id}:cip`); + const entity = ds.entities.values.find((e) => e.billboard); + const carto = gev.viewer.scene.globe.ellipsoid.cartesianToCartographic( + entity.position.getValue(gev.viewer.clock.currentTime), + ); + try { + gev.viewer.camera.cancelFlight(); + } catch { + /* no flight */ + } + gev.viewer.camera.setView({ + destination: gev.viewer.scene.globe.ellipsoid.cartographicToCartesian({ + longitude: carto.longitude, + latitude: carto.latitude, + height: 40000, + }), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + gev.viewer.scene.requestRender?.(); + return entity.id; + }, LAYER_ID); + await page + .waitForFunction( + () => window.__godsEyeView.viewer.scene.globe.tilesLoaded, + { timeout: 30000 }, + ) + .catch(() => {}); + // The horizon cull reveals the pin on the frame after the camera moves. + await page + .waitForFunction( + () => { + const v = window.__godsEyeView.viewer; + v.scene.requestRender?.(); + const c = v.scene.canvas; + return v.scene + .drillPick({ x: c.clientWidth / 2, y: c.clientHeight / 2 }, 8) + .some((p) => + String(p?.id?.id ?? p?.id ?? '').startsWith('ghostmaps:cip:'), + ); + }, + { timeout: 15000, polling: 500 }, + ) + .catch(() => {}); + const probe = await page.evaluate(() => { + const v = window.__godsEyeView.viewer; + const c = v.scene.canvas; + const box = c.getBoundingClientRect(); + const centre = { x: c.clientWidth / 2, y: c.clientHeight / 2 }; + const picked = v.scene.drillPick(centre, 8); + // Empty ground: the first point below the marker (the card is drawn + // above it) that picks nothing at all; markers can be dense in a city. + let empty = null; + for (let r = 120; r < 420 && !empty; r += 60) + for (const a of [2, 1, 3, 0, 4]) { + const p = { + x: centre.x + r * Math.cos((a * Math.PI) / 4), + y: centre.y + r * Math.sin((a * Math.PI) / 4), + }; + if (!v.scene.pick(p)) { + empty = p; + break; + } + } + empty ||= { x: centre.x + 400, y: centre.y + 300 }; + return { + ids: picked.map((p) => String(p?.id?.id ?? p?.id ?? '')), + centre: { x: centre.x + box.left, y: centre.y + box.top }, + empty: { x: empty.x + box.left, y: empty.y + box.top }, + }; + }); + record( + 'PICK: the centred marker picks as a GhostMaps entity', + probe.ids.some((id) => id.startsWith('ghostmaps:cip:')), + `${target} → [${probe.ids.slice(0, 3).join(', ')}]`, + ); + const before = await page.evaluate(paintedOverlayPixels); + await page.mouse.click(probe.centre.x, probe.centre.y); + const painted = await page + .waitForFunction(`(${paintedOverlayPixels})() > ${before + 100}`, { + timeout: 10000, + polling: 250, + }) + .then( + () => true, + () => false, + ); + const after = await page.evaluate(paintedOverlayPixels); + record( + 'PICK: clicking the marker paints its report card', + painted, + `${before} → ${after} pixels`, + ); + await page.screenshot({ path: path.join(SHOTS_DIR, 'ghostmaps-card.png') }); + const cardState = () => + page.evaluate((id) => { + const d = window.__gevWorldOverlay?.getDiagnostics?.(); + return { + entries: d?.entriesBySource?.[id] ?? null, + painted: d?.paintedBySource?.[id] ?? null, + }; + }, LAYER_ID); + const selectedState = await cardState(); + record( + 'PICK: the overlay host holds and paints exactly one card', + selectedState.entries === 1 && selectedState.painted === 1, + JSON.stringify(selectedState), + ); + await page.mouse.click(probe.empty.x, probe.empty.y); + // The overlay canvas is `desynchronized`, so headless read-back can + // return a stale buffer; the host's own model is the authority here. + const cleared = await page + .waitForFunction( + (id) => { + const d = window.__gevWorldOverlay.getDiagnostics(); + return ( + d.entriesBySource?.[id] === 0 && !(d.paintedBySource?.[id] > 0) + ); + }, + { timeout: 10000, polling: 250 }, + LAYER_ID, + ) + .then( + () => true, + () => false, + ); + record( + 'PICK: clicking empty ground clears the card', + cleared, + JSON.stringify(await cardState()), + ); + + // ---- (vii) FAR SIDE --------------------------------------------------- + // Pins skip the depth test; with Google 3D tiles nothing else hides the + // far side. A pin clearly behind the planet (sphere test with margin) must + // be hidden, and pins facing the camera must still show. + const horizonCounts = (lon, lat) => + page.evaluate( + async (id, lo, la) => { + const gev = window.__godsEyeView; + const d2r = Math.PI / 180; + try { + gev.viewer.camera.cancelFlight(); + } catch { + /* no flight */ + } + gev.viewer.camera.setView({ + destination: + gev.viewer.scene.globe.ellipsoid.cartographicToCartesian({ + longitude: lo * d2r, + latitude: la * d2r, + height: 18_000_000, + }), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + gev.viewer.scene.requestRender?.(); + await new Promise((r) => setTimeout(r, 1200)); + const c = gev.viewer.camera.positionWC; + const norm = (v) => Math.hypot(v.x, v.y, v.z); + let far = 0; + let nearShown = 0; + for (let i = 0; i < gev.viewer.dataSources.length; i++) { + const ds = gev.viewer.dataSources.get(i); + if (!ds.name?.startsWith(`${id}:`)) continue; + for (const e of ds.entities.values) { + if (!e.billboard) continue; + const p = e.position.getValue(gev.viewer.clock.currentTime); + // Angle from the camera's nadir to the pin, against the + // geometric horizon angle; the cull's 1 km margin shows pins up + // to about 1° past it, so "clearly behind" is beyond 2°. + const angle = Math.acos( + (p.x * c.x + p.y * c.y + p.z * c.z) / (norm(p) * norm(c)), + ); + const horizon = Math.acos(norm(p) / norm(c)); + const margin = (2 * Math.PI) / 180; + if (e.show && angle > horizon + margin) far++; + if (e.show && angle < horizon - margin) nearShown++; + } + } + return { far, nearShown }; + }, + LAYER_ID, + lon, + lat, + ); + const fromIndianOcean = await horizonCounts(80, -30); + record( + 'FAR SIDE: pins behind the planet are hidden', + fromIndianOcean.far === 0, + JSON.stringify(fromIndianOcean), + ); + await page.screenshot({ + path: path.join(SHOTS_DIR, 'ghostmaps-far-side.png'), + }); + const fromAmerica = await horizonCounts(-98, 39); + record( + 'FAR SIDE: pins facing the camera show again', + fromAmerica.far === 0 && fromAmerica.nearShown > 100, + JSON.stringify(fromAmerica), + ); + + // ---- (iv) CHIPS ------------------------------------------------------- + const clickChip = async (id) => { + // Row controls render on the next frame after the layer settles. + await page.waitForSelector( + `[data-layer-id="${LAYER_ID}"] .data-toggle-chip[data-chip-id="${id}"]`, + { timeout: 15000 }, + ); + return page.evaluate( + (layer, chip) => + document + .querySelector( + `[data-layer-id="${layer}"] .data-toggle-chip[data-chip-id="${chip}"]`, + ) + ?.click(), + LAYER_ID, + id, + ); + }; + await clickChip('kinetic-30d'); + await page.waitForFunction( + (id) => + !window.__godsEyeView.dataManager.layers + .get(id) + .module.getStats() + .products.includes('kinetic-30d'), + { timeout: 15000 }, + LAYER_ID, + ); + const without = await sources(page); + record( + 'CHIPS: turning a product off removes only its data source', + without.length === 1 && without[0].name === `${LAYER_ID}:cip`, + without.map((s) => s.name).join(', '), + ); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForFunction(() => window.__godsEyeView?.dataManager, { + timeout: TIMEOUT_MS, + }); + await sleep(3000); + await enableAndSettle(page); + const kept = await stats(page); + record( + 'CHIPS: the product choice survives a reload', + kept.products.join() === 'cip', + kept.products.join(', '), + ); + await showRow(page); + await clickChip('kinetic-30d'); + await page.waitForFunction( + (id) => + window.__godsEyeView.dataManager.layers + .get(id) + .module.getStats() + .products.includes('kinetic-30d'), + { timeout: 30000 }, + LAYER_ID, + ); + record( + 'CHIPS: turning it back on restores it', + (await sources(page)).length === 2, + ); + + // ---- (v) DISABLE ------------------------------------------------------ + await page.evaluate( + (id) => window.__godsEyeView.dataManager.setEnabled(id, false), + LAYER_ID, + ); + await sleep(500); + record( + 'DISABLE: every GhostMaps data source leaves the viewer', + (await sources(page)).length === 0, + ); + await page.close(); + + // ---- (iii) PUSH (synthetic) ---------------------------------------------- + const push = await browser.newPage(); + await push.evaluateOnNewDocument(() => { + localStorage.clear(); + // A controllable stand-in for the real stream. + class QaEventSource { + constructor(url) { + this.url = url; + this.listeners = new Set(); + (window.__qaStreams ||= []).push(this); + } + addEventListener(type, listener) { + if (type === 'catalog') this.listeners.add(listener); + } + removeEventListener(type, listener) { + this.listeners.delete(listener); + } + close() { + this.closed = true; + } + emit(catalog) { + for (const listener of this.listeners) + listener({ data: JSON.stringify(catalog) }); + } + } + window.EventSource = QaEventSource; + }); + await boot(push); + await enableAndSettle(push); + const identity = () => + push.evaluate((id) => { + const { dataSources } = window.__godsEyeView.viewer; + window.__qaIds ||= new WeakMap(); + window.__qaNext ||= 1; + const out = {}; + for (let i = 0; i < dataSources.length; i++) { + const ds = dataSources.get(i); + if (!ds.name?.startsWith(`${id}:`)) continue; + if (!window.__qaIds.has(ds)) + window.__qaIds.set(ds, window.__qaNext++); + out[ds.name] = window.__qaIds.get(ds); + } + return out; + }, LAYER_ID); + const first = await identity(); + const pushed = Date.now(); + await push.evaluate(async (id) => { + const catalog = await fetch('/api/ghostmaps/catalog').then((r) => + r.json(), + ); + const kinetic = catalog.products.find((p) => p.id === 'kinetic-30d'); + kinetic.version = 'f'.repeat(40); + catalog.message = 'QA push'; + window.__qaStreams + .filter((s) => !s.closed) + .forEach((s) => s.emit(catalog)); + }, LAYER_ID); + await push.waitForFunction( + (id) => { + const layer = window.__godsEyeView.dataManager.layers.get(id).module; + return ( + !layer.getStats().loading && + layer.getRowControls().info.includes('QA push') + ); + }, + { timeout: 20000, polling: 100 }, + LAYER_ID, + ); + await sleep(500); + const second = await identity(); + record( + 'PUSH: a new edition reloads only that product', + Object.keys(second).length === 2 && + second[`${LAYER_ID}:kinetic-30d`] !== + first[`${LAYER_ID}:kinetic-30d`] && + second[`${LAYER_ID}:cip`] === first[`${LAYER_ID}:cip`], + `${JSON.stringify(first)} → ${JSON.stringify(second)} in ${Date.now() - pushed} ms`, + ); + await push.evaluate(async () => { + const catalog = await fetch('/api/ghostmaps/catalog').then((r) => + r.json(), + ); + catalog.products = catalog.products.filter((p) => p.id !== 'kinetic-30d'); + window.__qaStreams + .filter((s) => !s.closed) + .forEach((s) => s.emit(catalog)); + }); + await sleep(1000); + const third = await identity(); + record( + 'PUSH: a product leaving the catalog leaves the globe', + Object.keys(third).join() === `${LAYER_ID}:cip`, + Object.keys(third).join(', '), + ); + await push.close(); + + // ---- (vi) VIEWPORT ---------------------------------------------------- + const phone = await browser.newPage(); + await phone.setViewport({ width: 390, height: 844, isMobile: true }); + await phone.evaluateOnNewDocument(() => localStorage.clear()); + await boot(phone); + await enableAndSettle(phone); + await showRow(phone); + const fit = await phone.evaluate((id) => { + const row = document.querySelector(`[data-layer-id="${id}"]`); + const panel = document.getElementById('data-panel'); + const controls = row?.querySelector('.data-toggle-controls'); + return { + row: Boolean(row), + overflow: controls ? controls.scrollWidth - controls.clientWidth : -1, + pageOverflow: + document.documentElement.scrollWidth - + document.documentElement.clientWidth, + panelRight: panel?.getBoundingClientRect().right, + width: window.innerWidth, + }; + }, LAYER_ID); + record( + 'VIEWPORT: chips fit the phone-width panel', + fit.row && fit.overflow <= 1 && fit.pageOverflow <= 0, + JSON.stringify(fit), + ); + await phone.screenshot({ + path: path.join(SHOTS_DIR, 'ghostmaps-phone.png'), + }); + await phone.close(); + } finally { + await browser.close(); + } + const failed = results.filter((r) => !r.ok); + console.log( + `\n${results.length - failed.length}/${results.length} passed. Screenshots: ${SHOTS_DIR}`, + ); + process.exit(failed.length ? 1 : 0); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/scripts/qa-gnss.mjs b/scripts/qa-gnss.mjs new file mode 100644 index 000000000..41933141e --- /dev/null +++ b/scripts/qa-gnss.mjs @@ -0,0 +1,988 @@ +#!/usr/bin/env node +/** + * qa-gnss.mjs — headless proof for the GNSS Integrity layer + * (id `gnss-integrity`): low navigation accuracy reported by ADS-B. + * + * Drives the REAL app in headless Chromium against a dev server (keyless). + * The live section reads adsb.lol through `/api/gnss-integrity` (60 s server + * cache, one upstream read per whole-degree anchor); the other sections + * stub that route in the page so they are deterministic. + * + * (i) LIVE — over Poland and the southern Baltic the layer settles with no error, + * one geometry per cell and legend band counts that sum to the cell + * count; cells are required only when the returned rows, binned + * with the layer's own rules, reach the per-cell minimum (live + * traffic varies by hour). Requires a non-stale response no older than 60 s. + * (ii) BANDS (synthetic) — a 10-aircraft cell with 5 degraded is high, + * a 30-aircraft cell with 2 degraded is medium, a 3-aircraft cell + * with 1 degraded is low (first bad discounted), a clean cell at sea + * is low, a 2-aircraft cell is withheld; `stale: true` reaches + * getStats. Every band is drawn and low is shown over land and sea. + * The row reads as low navigation accuracy, and stats carry the + * machine-readable provenance (GEV classifier, gpsjam bands, window). + * PICK verifies actual perimeter and empty-ground clicks under GNSS. + * CAMERA/GLOBE verify automatic sampling and the screen-centre anchor. + * (iii) FAILURE — the route stubbed to 502: stats.error is set and the + * cells already on the globe are kept. + * (iv) DISABLE — owned ground primitives are hidden. + * (v) KEYBOARD — the row's toggle button, focused, turns the layer on + * with Enter and off with Space, keeps focus and names its state. + * (vi) VIEWPORT — at a 390x844 phone viewport the open row and its legend + * fit the panel width with no horizontal overflow. + * (vii) AGE (synthetic) — a fresh page whose stubbed proxy replays the same + * stale snapshot observed 31 minutes ago draws nothing and reports no + * error; observed 29 minutes ago it draws its cells. The replay keeps + * its observation time instead of restarting the 30-minute window. + * + * Screenshots wait until every cell's ground geometry is built and show the + * open Data Layers row with its legend. Visual proof saved to + * qa-shots/gnss-*.png (gitignored). + * + * Run: node scripts/qa-gnss.mjs --url http://localhost:4173 + * (also against a built preview: npm run build && npm run preview, + * then pass the preview URL) + * Optional: --timeout-ms 180000 for a slow boot. + * Exits non-zero on any FAIL. Does not commit anything. + */ + +import puppeteer from 'puppeteer'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { + accumulateGnssObservations, + binGnssCells, +} from '../src/layers/gnss/records.js'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const REPO_ROOT = path.resolve(__dirname, '..'); +const SHOTS_DIR = path.join(REPO_ROOT, 'qa-shots'); + +const argv = process.argv.slice(2); +const getOpt = (name, dflt) => { + const i = argv.indexOf(name); + return i >= 0 && argv[i + 1] ? argv[i + 1] : dflt; +}; +const APP_URL = getOpt('--url', 'http://localhost:4173'); +const HEADFUL = argv.includes('--headful'); +const TIMEOUT_MS = Number(getOpt('--timeout-ms', '60000')); +const LAYER_ID = 'gnss-integrity'; + +const results = []; +function record(name, ok, detail) { + results.push({ name, ok, detail }); + const tag = ok ? '\x1b[32mPASS\x1b[0m' : '\x1b[31mFAIL\x1b[0m'; + console.log(` [${tag}] ${name}${detail ? ` — ${detail}` : ''}`); +} +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** Boot the app, dismiss the intro and place the camera straight down. */ +async function boot(page, { lon, lat, height }) { + await page.goto(`${APP_URL}/?welcome=0`, { + waitUntil: 'domcontentloaded', + timeout: TIMEOUT_MS, + }); + await page.waitForFunction( + () => window.__godsEyeView?.viewer && window.__godsEyeView?.dataManager, + { timeout: TIMEOUT_MS }, + ); + await sleep(5000); + await page.keyboard.press('Escape'); + await page.evaluate( + (lo, la, h) => { + const gev = window.__godsEyeView; + const d2r = Math.PI / 180; + // The app's intro flyTo animation clobbers a setView issued mid-flight. + try { + gev.viewer.camera.cancelFlight(); + } catch { + /* no flight active */ + } + gev.viewer.camera.setView({ + destination: gev.viewer.scene.globe.ellipsoid.cartographicToCartesian({ + longitude: lo * d2r, + latitude: la * d2r, + height: h, + }), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + gev.viewer.scene.requestRender?.(); + }, + lon, + lat, + height, + ); +} + +/** Enable (or refresh) the layer and poll until it settles. */ +async function enableAndSettle(page, { refresh = false } = {}) { + return page.evaluate( + async (id, again) => { + const dm = window.__godsEyeView.dataManager; + const layer = dm.layers.get(id).module; + if (again) await dm.refreshLayer(id); + else await dm.setEnabled(id, true); + const stats = layer.getStats(); + const rowControls = layer.getRowControls().legend; + const legend = rowControls.map(({ label, count }) => ({ label, count })); + const blurb = rowControls[0]?.blurb ?? ''; + const rowName = + document.querySelector(`[data-layer-id="${id}"] .data-name`) + ?.textContent ?? ''; + const all = window.__godsEyeView.viewer.scene.groundPrimitives; + const ds = Array.from({ length: all.length }, (_, i) => all.get(i)).find( + (item) => item.id === id, + ); + return { + stats, + legend, + blurb, + rowName, + name: layer.name, + entities: ds?.get(0)?.geometryInstances.length ?? 0, + shown: ds?.show ?? null, + }; + }, + LAYER_ID, + refresh, + ); +} + +/** Open the Data Layers panel and bring the GNSS row into view. */ +async function showLayerRow(page) { + await page.evaluate((id) => { + const panel = document.getElementById('data-panel'); + if (panel.classList.contains('collapsed')) + panel.querySelector('[data-collapse-target="data-panel"]').click(); + document + .querySelector(`[data-layer-id="${id}"]`) + ?.scrollIntoView({ block: 'center' }); + }, LAYER_ID); + await sleep(800); +} + +/** Actual card pixels on the shared canvas, available in dev and production. */ +function paintedOverlayPixels() { + const canvas = document.getElementById('world-overlay-canvas'); + if (!canvas) return -1; + const pixels = canvas + .getContext('2d') + .getImageData(0, 0, canvas.width, canvas.height).data; + let count = 0; + for (let i = 3; i < pixels.length; i += 4) if (pixels[i] > 0) count++; + return count; +} + +async function shoot(page, name) { + await page + .waitForFunction( + () => window.__godsEyeView.viewer.scene.globe.tilesLoaded, + { timeout: TIMEOUT_MS }, + ) + .catch(() => {}); + await showLayerRow(page); + await page.screenshot({ path: path.join(SHOTS_DIR, `gnss-${name}.png`) }); +} + +/** Bounding-sphere state of every GNSS cell: DONE = 0, PENDING = 1, FAILED = 2. */ +function cellStates(id) { + const { viewer } = window.__godsEyeView; + const all = viewer.scene.groundPrimitives; + const ds = Array.from({ length: all.length }, (_, i) => all.get(i)).find( + (item) => item.id === id, + ); + if (!ds?.length) return []; + return [ds.get(0).ready ? 0 : 1]; +} + +/** Wait until every GNSS cell's ground rectangle has finished building. */ +async function waitForBuiltCells(page, timeoutMs = 60000) { + const built = await page + .waitForFunction( + `(${cellStates})(${JSON.stringify(LAYER_ID)}).every((state) => state === 0)`, + { timeout: timeoutMs, polling: 250 }, + ) + .then( + () => true, + () => false, + ); + const states = await page.evaluate( + `(${cellStates})(${JSON.stringify(LAYER_ID)})`, + ); + return { built, detail: `states=${JSON.stringify(states)}` }; +} + +const fixtureRow = (hex, lat, lon, degraded) => ({ + hex, + lat, + lon, + nic: degraded ? 0 : 8, + nacp: degraded ? 0 : 10, + gpsLost: false, + degraded, +}); + +/** + * Synthetic 0.5° cells: high at sea (5/10 bad), medium on land (2/30 bad), + * low on land (1/3 bad), low at sea (0/4 bad), withheld (2 aircraft). + */ +function fixturePayload() { + const rows = []; + const hex = (prefix, i) => `${prefix}${i.toString(16).padStart(2, '0')}`; + for (let i = 0; i < 10; i++) + rows.push(fixtureRow(hex('a000', i), 55.1 + i * 0.01, 19.1, i < 5)); + for (let i = 0; i < 30; i++) + rows.push(fixtureRow(hex('d000', i), 54.1 + i * 0.01, 19.6, i < 2)); + for (let i = 0; i < 3; i++) + rows.push(fixtureRow(hex('b000', i), 54.1 + i * 0.01, 18.1, i === 0)); + for (let i = 0; i < 4; i++) + rows.push(fixtureRow(hex('e000', i), 55.1 + i * 0.01, 18.1, false)); + for (let i = 0; i < 2; i++) + rows.push(fixtureRow(hex('c000', i), 53.1 + i * 0.01, 17.1, true)); + return { + fetchedAt: Date.now(), + anchor: { lat: 55, lon: 19 }, + radiusNm: 250, + rows, + stale: true, + }; +} + +/** Answer /api/gnss-integrity in-page from `fixturePayload()`. */ +async function stubRoute(page, { ageMs = 0, initialFailures = 0, stale } = {}) { + await page.evaluateOnNewDocument( + (payload, age, failures, staleOverride) => { + window.__gnssQaAgeMs = age; + window.__gnssQaRequests = []; + window.__gnssQaFailures = failures; + const realFetch = window.fetch.bind(window); + window.__gnssQaMode = 'fixture'; + window.fetch = (input, init) => { + const url = typeof input === 'string' ? input : input?.url || ''; + if (!url.includes('/api/gnss-integrity')) return realFetch(input, init); + window.__gnssQaRequests.push(url); + if (window.__gnssQaFailures > 0) { + window.__gnssQaFailures--; + return Promise.resolve( + Response.json( + { error: 'rate_limited' }, + { + status: 429, + headers: { 'Retry-After': '5' }, + }, + ), + ); + } + const ok = window.__gnssQaMode === 'fixture'; + const body = ok + ? { + ...payload, + fetchedAt: Date.now() - (window.__gnssQaAgeMs || 0), + ageMs: window.__gnssQaAgeMs || 0, + stale: staleOverride ?? payload.stale, + } + : { error: 'gnss_integrity_unavailable' }; + return Promise.resolve( + new Response(JSON.stringify(body), { + status: ok ? 200 : 502, + headers: { 'Content-Type': 'application/json' }, + }), + ); + }; + }, + fixturePayload(), + ageMs, + initialFailures, + stale, + ); +} + +/** Toggle button of the GNSS row, as the panel draws it. */ +function toggleState(id) { + const button = document.querySelector( + `[data-layer-id="${id}"] .data-toggle-btn`, + ); + const layer = window.__godsEyeView.dataManager.layers.get(id); + return { + focused: document.activeElement === button, + label: button?.getAttribute('aria-label') ?? '', + enabled: Boolean(layer?.enabled), + count: layer?.module.getStats().count ?? -1, + }; +} + +/** Press a key on the focused GNSS toggle and wait for the lifecycle to settle. */ +async function pressToggle(page, key, wantEnabled) { + await page.evaluate((id) => { + document.querySelector(`[data-layer-id="${id}"] .data-toggle-btn`)?.focus(); + }, LAYER_ID); + await page.keyboard.press(key); + await page + .waitForFunction( + (id, want) => { + const layer = window.__godsEyeView.dataManager.layers.get(id); + return ( + Boolean(layer?.enabled) === want && + (!want || layer.module.getStats().count > 0) + ); + }, + { timeout: 30000, polling: 250 }, + LAYER_ID, + wantEnabled, + ) + .catch(() => {}); + return page.evaluate(`(${toggleState})(${JSON.stringify(LAYER_ID)})`); +} + +async function main() { + console.log('\nGNSS Integrity proof (qa-gnss)'); + console.log(` App URL : ${APP_URL}\n`); + try { + const res = await fetch(APP_URL); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + } catch (e) { + console.error( + `\x1b[31mDev server not reachable at ${APP_URL} (${e.message}).\x1b[0m`, + ); + process.exit(2); + } + fs.mkdirSync(SHOTS_DIR, { recursive: true }); + const executablePath = + process.env.PUPPETEER_EXECUTABLE_PATH || + (await puppeteer.executablePath().catch(() => null)) || + undefined; + const browser = await puppeteer.launch({ + headless: HEADFUL ? false : 'new', + ...(executablePath && fs.existsSync(executablePath) + ? { executablePath } + : {}), + args: [ + '--use-gl=angle', + '--use-angle=swiftshader', + '--disable-dev-shm-usage', + '--disable-background-timer-throttling', + '--disable-renderer-backgrounding', + '--window-size=1440,900', + ], + }); + + let exitCode = 0; + const errors = []; + try { + // ── (i) LIVE ────────────────────────────────────────────────────────── + console.log( + '(i) LIVE — adsb.lol integrity snapshot over Poland and the southern Baltic...', + ); + const live = await browser.newPage(); + await live.setViewport({ width: 1440, height: 900 }); + live.on('pageerror', (e) => errors.push(e.message)); + const liveBodies = []; + live.on('response', (res) => { + if (res.url().includes('/api/gnss-integrity') && res.ok()) + liveBodies.push(res.json()); + }); + await boot(live, { lon: 19.6, lat: 52.6, height: 1_100_000 }); + const l = await enableAndSettle(live); + const legendTotal = l.legend.reduce((sum, { count }) => sum + count, 0); + // Bin what adsb.lol actually returned with the layer's own rules: live + // traffic varies by hour, so cells are required only when some cell + // really reached the minimum aircraft count. + const liveSnapshots = (await Promise.allSettled(liveBodies)) + .filter((r) => r.status === 'fulfilled') + .map((r) => r.value); + record( + 'LIVE: a successful, dated integrity response was received', + liveSnapshots.length > 0 && + liveSnapshots.every( + (body) => + Array.isArray(body.rows) && + Number.isFinite(body.ageMs) && + body.ageMs >= 0 && + body.ageMs <= 60000 && + body.stale !== true && + body.classifier === 'gev-nic-nacp-v2', + ), + `successful responses=${liveSnapshots.length}`, + ); + const liveRows = liveSnapshots.reduce( + (sum, body) => sum + (body.rows?.length || 0), + 0, + ); + const expectedStore = new Map(); + for (const body of liveSnapshots) { + const at = Date.now(); + accumulateGnssObservations(expectedStore, body.rows, at, { + observedAt: at - body.ageMs, + }); + } + const expectedCells = binGnssCells(expectedStore).length; + record( + 'LIVE: no error, one geometry per cell', + !l.stats.error && l.entities === l.stats.count, + `cells=${l.stats.count} entities=${l.entities} error=${JSON.stringify(l.stats.error)}`, + ); + if (expectedCells > 0) { + record( + 'LIVE: a snapshot with a qualifying cell yields cells', + l.stats.count > 0, + `rows=${liveRows} expected=${expectedCells} cells=${l.stats.count}`, + ); + } else { + console.log( + ` [info] ${liveRows} live rows, no cell reaches the minimum — cell count not asserted`, + ); + } + record( + 'LIVE: legend band counts sum to the cell count', + legendTotal === l.stats.count, + JSON.stringify(l.legend), + ); + const liveBuilt = await waitForBuiltCells(live); + record( + 'LIVE: every cell rectangle is built on a parked camera', + liveBuilt.built, + liveBuilt.detail, + ); + await shoot(live, 'live-poland-baltic'); + await live.close(); + + // ── (ii) BANDS ──────────────────────────────────────────────────────── + console.log( + '\n(ii) BANDS — synthetic integrity rows through the real layer...', + ); + const page = await browser.newPage(); + await page.setViewport({ width: 1440, height: 900 }); + page.on('pageerror', (e) => errors.push(e.message)); + // Stub the route in-page rather than with request interception: an + // intercepted page stalls Cesium's geometry workers, so ground rectangles + // never finish building and the screenshot would not show real behaviour. + await stubRoute(page); + await boot(page, { lon: 18.6, lat: 54.6, height: 450_000 }); + const f = await enableAndSettle(page); + const band = (prefix) => + f.legend.find(({ label }) => label.startsWith(prefix))?.count; + record( + 'BANDS: 4 cells shown, the 2-aircraft cell withheld', + f.stats.count === 4 && f.entities === 4, + `cells=${f.stats.count} entities=${f.entities}`, + ); + record( + 'BANDS: 5/10 is high, 2/30 is medium, 1/3 and 0/4 are low', + band('Low-accuracy score >') === 1 && + band('Low-accuracy score 2') === 1 && + band('Low-accuracy score <') === 2, + JSON.stringify(f.legend), + ); + const prov = f.stats.provenance; + record( + 'PROVENANCE: GEV classifier, gpsjam bands and visited-view window are machine-readable', + prov?.classifier?.id === 'gev-nic-nacp-v2' && + prov.classifier.definedBy === 'GEV' && + prov.classifier.validated === false && + prov.aggregation?.source === 'https://gpsjam.org/faq' && + JSON.stringify(prov.aggregation.bands) === '[2,10]' && + prov.window?.minutes === 30 && + prov.window.scope === 'visited-view' && + prov.interpretation?.validated === false, + JSON.stringify(prov?.classifier), + ); + record( + 'WORDING: the row leads with low navigation accuracy, interference only as the hedged reading', + f.name === 'GNSS Integrity' && + f.rowName.includes('GNSS Integrity') && + !/interference/i.test(f.rowName) && + f.legend.every(({ label }) => label.startsWith('Low-accuracy score')) && + /one aircraft is discounted/.test(f.blurb) && + /not a detection/.test(f.blurb), + `name=${JSON.stringify(f.name)}`, + ); + record( + 'BANDS: stale snapshot is reported', + f.stats.stale === true, + `stale=${f.stats.stale}`, + ); + const bandsBuilt = await waitForBuiltCells(page); + record( + 'BANDS: every cell rectangle is built on a parked camera', + bandsBuilt.built, + bandsBuilt.detail, + ); + await shoot(page, 'synthetic-bands'); + + // GNSS fills must not own map input, including over a real perimeter. + await page.evaluate(async () => { + const original = window.fetch.bind(window); + window.fetch = (input, init) => { + const url = typeof input === 'string' ? input : input.url; + if (url.includes('/api/fire-perimeters/inciweb')) + return Promise.resolve(Response.json({ rows: [] })); + if (url.includes('/api/fire-perimeters')) + return Promise.resolve( + Response.json({ + rows: [ + { + stableId: 'gnss-pick-qa', + name: 'GNSS PICK QA FIRE', + containedPct: 0, + acres: 100, + polygons: [ + [ + [ + [18.247, 54.247], + [18.253, 54.247], + [18.253, 54.253], + [18.247, 54.253], + [18.247, 54.247], + ], + ], + ], + }, + ], + }), + ); + return original(input, init); + }; + const { viewer, dataManager } = window.__godsEyeView; + viewer.camera.cancelFlight(); + viewer.camera.setView({ + destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({ + longitude: (18.25 * Math.PI) / 180, + latitude: (54.25 * Math.PI) / 180, + height: 2500, + }), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + await dataManager.setEnabled('fire-perimeters', true); + viewer.scene.requestRender(); + }); + await page.waitForFunction( + () => { + const v = window.__godsEyeView.viewer, + p = v.scene.pick({ + x: v.scene.canvas.clientWidth / 2, + y: v.scene.canvas.clientHeight / 2, + }); + return String(p?.id?.id ?? p?.id ?? '').startsWith( + 'fire-perimeter:gnss-pick-qa:', + ); + }, + { timeout: TIMEOUT_MS, polling: 250 }, + ); + const pickProbe = await page.evaluate(() => { + const v = window.__godsEyeView.viewer, + c = v.scene.canvas; + const centre = { x: c.clientWidth / 2, y: c.clientHeight / 2 }; + const empty = { x: centre.x + 300, y: centre.y }; + const picked = v.scene.pick(empty), + box = c.getBoundingClientRect(); + return { + centre: { x: centre.x + box.left, y: centre.y + box.top }, + empty: { x: empty.x + box.left, y: empty.y + box.top }, + surface: !picked || picked.id === undefined, + height: v.camera.positionCartographic.height, + }; + }); + record('PICK: a perimeter remains selectable under GNSS', true); + record( + 'PICK: street ground remains a surface pick under GNSS', + pickProbe.surface, + ); + const beforeCardPixels = await page.evaluate(paintedOverlayPixels); + await page.mouse.click(pickProbe.centre.x, pickProbe.centre.y); + await page.waitForFunction( + `(${paintedOverlayPixels})() > ${beforeCardPixels + 100}`, + { timeout: 10000, polling: 250 }, + ); + const selectedCardPixels = await page.evaluate(paintedOverlayPixels); + record( + 'PICK: actual perimeter click paints its incident card', + selectedCardPixels > beforeCardPixels + 100, + `${beforeCardPixels} → ${selectedCardPixels} pixels`, + ); + await page.screenshot({ + path: path.join(SHOTS_DIR, 'gnss-perimeter-selected.png'), + }); + await page.mouse.click(pickProbe.empty.x, pickProbe.empty.y); + await page.waitForFunction( + `(${paintedOverlayPixels})() <= ${beforeCardPixels}`, + { timeout: 10000, polling: 250 }, + ); + const clearedCardPixels = await page.evaluate(paintedOverlayPixels); + record( + 'PICK: empty ground clears the perimeter card', + clearedCardPixels <= beforeCardPixels, + `${selectedCardPixels} → ${clearedCardPixels} pixels`, + ); + await page.mouse.click(pickProbe.empty.x, pickProbe.empty.y, { + clickCount: 2, + }); + await sleep(1000); + record( + 'PICK: empty double-click does not zoom to a GNSS cell', + await page.evaluate( + (height) => + Math.abs( + window.__godsEyeView.viewer.camera.positionCartographic.height - + height, + ) < 200, + pickProbe.height, + ), + ); + await page.evaluate(async () => { + await window.__godsEyeView.dataManager.setEnabled( + 'fire-perimeters', + false, + ); + }); + console.log('\nCAMERA — automatic regional refresh without toggling...'); + const beforeMove = await page.evaluate( + () => window.__gnssQaRequests.length, + ); + await page.evaluate(() => { + const { viewer } = window.__godsEyeView; + viewer.camera.setView({ + destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({ + longitude: (139.7 * Math.PI) / 180, + latitude: (35.7 * Math.PI) / 180, + height: 1_100_000, + }), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + viewer.scene.requestRender(); + }); + await page.waitForFunction( + () => { + const url = window.__gnssQaRequests.at(-1); + return ( + url && + Math.abs( + Number(new URL(url, location.origin).searchParams.get('lon')) - + 139.7, + ) < 1 + ); + }, + { timeout: 15000 }, + ); + await sleep(3500); + const moved = await page.evaluate( + (id) => ({ + requests: window.__gnssQaRequests.length, + enabled: window.__godsEyeView.dataManager.isEnabled(id), + coverage: window.__godsEyeView.dataManager.layers + .get(id) + .module.getStats().coverage, + info: document.querySelector( + `[data-layer-id="${id}"] .data-toggle-controls-info`, + )?.textContent, + }), + LAYER_ID, + ); + record( + 'CAMERA: moving to Tokyo automatically refreshes the new region and updates the row', + moved.enabled && + moved.requests > beforeMove && + moved.requests <= beforeMove + 2 && + moved.coverage?.longitude === 140 && + /Regional sample.*250 nm radius/.test(moved.info), + JSON.stringify(moved), + ); + await shoot(page, 'camera-refresh'); + await page.evaluate(() => { + const { viewer } = window.__godsEyeView; + viewer.camera.setView({ + destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({ + longitude: (12.4 * Math.PI) / 180, + latitude: (41.9 * Math.PI) / 180, + height: 16_000_000, + }), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + viewer.scene.requestRender(); + }); + await page.waitForFunction( + () => { + const url = window.__gnssQaRequests.at(-1); + const params = url && new URL(url, location.origin).searchParams; + return ( + params && + Math.abs(Number(params.get('lon')) - 12.4) < 1 && + Math.abs(Number(params.get('lat')) - 41.9) < 1 + ); + }, + { timeout: 15000 }, + ); + const world = await page.evaluate((id) => { + const { viewer, dataManager } = window.__godsEyeView; + const bounds = viewer.camera.computeViewRectangle( + viewer.scene.globe.ellipsoid, + ); + return { + enabled: dataManager.isEnabled(id), + height: viewer.camera.positionCartographic.height, + boundsMidLongitude: + bounds && ((bounds.west + bounds.east) * 90) / Math.PI, + coverage: dataManager.layers.get(id).module.getStats().coverage, + }; + }, LAYER_ID); + record( + 'GLOBE: zoomed-out sampling stays centred on Rome and exposes its regional radius', + world.enabled && + world.height > 15_000_000 && + world.coverage?.longitude === 12 && + world.coverage?.latitude === 42 && + world.coverage?.radiusNm === 250, + JSON.stringify(world), + ); + await shoot(page, 'globe-regional'); + await page.evaluate(() => { + const { viewer } = window.__godsEyeView; + viewer.camera.setView({ + destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({ + longitude: (18.6 * Math.PI) / 180, + latitude: (54.6 * Math.PI) / 180, + height: 450_000, + }), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + viewer.scene.requestRender(); + }); + await page.waitForFunction( + () => { + const url = window.__gnssQaRequests.at(-1); + return ( + url && + Math.abs( + Number(new URL(url, location.origin).searchParams.get('lon')) - + 18.6, + ) < 1 + ); + }, + { timeout: 15000 }, + ); + await sleep(3500); + + // ── (iii) FAILURE ───────────────────────────────────────────────────── + console.log('\n(iii) FAILURE — /api/gnss-integrity stubbed to 502...'); + await page.evaluate(() => { + window.__gnssQaMode = 'error'; + }); + const e = await enableAndSettle(page, { refresh: true }); + record( + 'FAILURE: error surfaced, cells kept', + Boolean(e.stats.error) && e.stats.count === 4 && e.entities === 4, + `error=${JSON.stringify(e.stats.error)} cells=${e.stats.count}`, + ); + await shoot(page, 'failure'); + + // ── (iv) DISABLE ────────────────────────────────────────────────────── + console.log('\n(iv) DISABLE...'); + const shown = await page.evaluate(async (id) => { + await window.__godsEyeView.dataManager.setEnabled(id, false); + const all = window.__godsEyeView.viewer.scene.groundPrimitives; + return Array.from({ length: all.length }, (_, i) => all.get(i)).find( + (item) => item.id === id, + )?.show; + }, LAYER_ID); + record('DISABLE: data source hidden', shown === false, `show=${shown}`); + await shoot(page, 'disabled'); + + // ── (v) KEYBOARD ────────────────────────────────────────────────────── + console.log('\n(v) KEYBOARD — the row toggle, from the keyboard...'); + await page.evaluate(() => { + window.__gnssQaMode = 'fixture'; + }); + await showLayerRow(page); + const on = await pressToggle(page, 'Enter', true); + record( + 'KEYBOARD: Enter on the focused toggle enables the layer and keeps focus', + on.enabled && + on.focused && + on.count === 4 && + /^GNSS Integrity: /.test(on.label) && + !/OFF$/.test(on.label), + JSON.stringify(on), + ); + const off = await pressToggle(page, ' ', false); + record( + 'KEYBOARD: Space on the focused toggle disables it and the label says OFF', + !off.enabled && off.focused && /^GNSS Integrity: OFF$/.test(off.label), + JSON.stringify(off), + ); + + // ── (vi) VIEWPORT ───────────────────────────────────────────────────── + console.log( + '\n(vi) VIEWPORT — the open row on a 390x844 phone viewport...', + ); + await page.close(); + // A fresh page: switching an open page to isMobile reloads it, which + // would measure a half-booted app instead of the open row. + const phone = await browser.newPage(); + await phone.setViewport({ width: 390, height: 844, isMobile: true }); + phone.on('pageerror', (e) => errors.push(e.message)); + await stubRoute(phone); + await boot(phone, { lon: 18.6, lat: 54.6, height: 450_000 }); + await showLayerRow(phone); + await pressToggle(phone, 'Enter', true); + await showLayerRow(phone); + const fit = await phone.evaluate((id) => { + const row = document.querySelector(`[data-layer-id="${id}"]`); + const legend = [...row.querySelectorAll('.data-toggle-legend-item')]; + const rect = row.getBoundingClientRect(); + return { + width: window.innerWidth, + rowLeft: Math.round(rect.left), + rowRight: Math.round(rect.right), + overflow: row.scrollWidth - row.clientWidth, + legendItems: legend.length, + coverageInfo: row.querySelector('.data-toggle-controls-info') + ?.textContent, + legendInside: legend.every((item) => { + const r = item.getBoundingClientRect(); + return ( + r.width > 0 && r.left >= rect.left - 1 && r.right <= rect.right + 1 + ); + }), + }; + }, LAYER_ID); + record( + 'VIEWPORT: row and legend fit a 390 px viewport without horizontal overflow', + fit.rowLeft >= 0 && + fit.rowRight <= fit.width && + fit.overflow <= 0 && + fit.legendItems === 3 && + /Regional sample.*250 nm radius/.test(fit.coverageInfo) && + fit.legendInside, + JSON.stringify(fit), + ); + await phone.screenshot({ path: path.join(SHOTS_DIR, 'gnss-phone.png') }); + await phone.close(); + + console.log( + '\nSTARTUP — initial rate limit stays enabled and recovers automatically...', + ); + const retry = await browser.newPage(); + await retry.setViewport({ width: 1440, height: 900 }); + retry.on('pageerror', (e) => errors.push(e.message)); + // Pages share the disposable test context's storage. Start this one cold, + // so a previous fixture cannot auto-enable GNSS before the START test. + await retry.evaluateOnNewDocument(() => localStorage.clear()); + await stubRoute(retry, { initialFailures: 1, stale: false }); + await boot(retry, { lon: 18.6, lat: 54.6, height: 450_000 }); + await showLayerRow(retry); + await retry.evaluate((id) => { + window.__gnssQaFailedStarts = 0; + window.__godsEyeView.dataManager.subscribe((change) => { + if (change.layerId === id && change.type === 'visibility-failed') + window.__gnssQaFailedStarts++; + }); + }, LAYER_ID); + const initial = await enableAndSettle(retry); + const limited = await retry.evaluate((id) => { + const dm = window.__godsEyeView.dataManager; + const row = document.querySelector(`[data-layer-id="${id}"]`); + return { + enabled: dm.isEnabled(id), + failedStarts: window.__gnssQaFailedStarts, + label: row.querySelector('.data-toggle-btn').textContent, + info: row.querySelector('.data-toggle-controls-info').textContent, + }; + }, LAYER_ID); + record( + 'STARTUP: first 429 keeps the layer enabled and shows automatic retry timing', + limited.enabled && + limited.failedStarts === 0 && + limited.label === 'UNAVAILABLE' && + initial.stats.count === 0 && + initial.stats.retryInSec > 0 && + /rate limited.*Retrying automatically at/.test(limited.info), + JSON.stringify(limited), + ); + await retry.screenshot({ + path: path.join(SHOTS_DIR, 'gnss-startup-retrying.png'), + }); + await retry.waitForFunction( + (id) => { + const layer = window.__godsEyeView.dataManager.layers.get(id); + return ( + layer.enabled && + layer.module.getStats().error === null && + layer.module.getStats().count === 4 + ); + }, + { timeout: 20000 }, + LAYER_ID, + ); + const recovered = await retry.evaluate( + (id) => ({ + requests: window.__gnssQaRequests.length, + enabled: window.__godsEyeView.dataManager.isEnabled(id), + label: document.querySelector( + `[data-layer-id="${id}"] .data-toggle-btn`, + ).textContent, + info: document.querySelector( + `[data-layer-id="${id}"] .data-toggle-controls-info`, + ).textContent, + }), + LAYER_ID, + ); + record( + 'STARTUP: one automatic retry recovers to ON without toggling and clears the warning', + recovered.enabled && + recovered.requests === 2 && + recovered.label === 'ON' && + !/Retrying/.test(recovered.info), + JSON.stringify(recovered), + ); + await shoot(retry, 'startup-recovered'); + await retry.close(); + + // ── (vii) AGE ───────────────────────────────────────────────────────── + console.log( + '\n(vii) AGE — a replayed stale snapshot keeps its observation time...', + ); + const aged = await browser.newPage(); + await aged.setViewport({ width: 1440, height: 900 }); + aged.on('pageerror', (e) => errors.push(e.message)); + await stubRoute(aged, { ageMs: 31 * 60_000 }); + await boot(aged, { lon: 18.6, lat: 54.6, height: 450_000 }); + const old = await enableAndSettle(aged, {}); + record( + 'AGE: a snapshot observed 31 min ago adds no cells and is not an error', + old.stats.count === 0 && old.entities === 0 && !old.stats.error, + `cells=${old.stats.count} entities=${old.entities} error=${JSON.stringify(old.stats.error)}`, + ); + await aged.evaluate(() => { + window.__gnssQaAgeMs = 29 * 60_000; + }); + const recent = await enableAndSettle(aged, { refresh: true }); + record( + 'AGE: the same snapshot observed 29 min ago is still inside the window', + recent.stats.count === 4 && recent.entities === 4, + `cells=${recent.stats.count} entities=${recent.entities}`, + ); + await aged.close(); + record( + 'no uncaught browser errors', + errors.length === 0, + errors.slice(0, 3).join(' | '), + ); + } catch (err) { + console.error('\x1b[31mHarness error:\x1b[0m', err); + exitCode = 3; + } finally { + await browser.close(); + } + + const pass = results.filter((r) => r.ok).length; + const fail = results.length - pass; + console.log('\n' + '─'.repeat(60)); + console.log(` RESULT: ${pass} passed, ${fail} failed`); + console.log(` Shots : ${SHOTS_DIR}/gnss-*.png`); + console.log('─'.repeat(60) + '\n'); + process.exit(exitCode || (fail > 0 ? 1 : 0)); +} + +main().catch((e) => { + console.error(e); + process.exit(3); +}); diff --git a/scripts/qa-l9-matrix.mjs b/scripts/qa-l9-matrix.mjs index 2a3d7328e..8709366de 100644 --- a/scripts/qa-l9-matrix.mjs +++ b/scripts/qa-l9-matrix.mjs @@ -1884,7 +1884,7 @@ async function runBrowserGroup(record) { await step('C15', async () => { // CRT/NVG/FLIR are DISPLAY LABELS; the real style ids are retro / - // surveillance / thermal (src/ui.js STYLE_STATUS_LABELS). Passing the + // surveillance / thermal (src/ui/visualPresets.js STYLE_STATUS_LABELS). Passing the // labels made every call a silent no-op that still "passed" — so assert // the returned visual state actually changed to the requested style. const wanted = [['retro', 'CRT'], ['surveillance', 'NVG'], ['thermal', 'FLIR'], ['normal', 'Normal']]; @@ -2006,8 +2006,9 @@ async function runBrowserGroup(record) { for (let i = 0; i < 20; i += 1) { // eslint-disable-next-line no-await-in-loop await new Promise((r) => setTimeout(r, 500)); - const status = document.getElementById('gev-voice-status')?.textContent?.trim() || ''; - if (status && status !== 'CONNECTING') break; + // The label is translated; the machine state is on the control. + const status = document.getElementById('gev-voice-control')?.dataset.status || ''; + if (status && status !== 'connecting') break; } let diag = null; try { diag = vc.getDiagnostics?.(); } catch { /* not started */ } diff --git a/scripts/qa-labels.mjs b/scripts/qa-labels.mjs index 8d26dcb30..fb04d0025 100644 --- a/scripts/qa-labels.mjs +++ b/scripts/qa-labels.mjs @@ -86,14 +86,6 @@ function percentile(values, pct) { return sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * pct) - 1)]; } -function parseJson(value, fallback) { - try { - return JSON.parse(value); - } catch { - return fallback; - } -} - function analyzeMembership(samples) { let replacements = 0; let exposure = 0; diff --git a/scripts/qa-layer-panel.mjs b/scripts/qa-layer-panel.mjs index 1282c6b50..5cfa08905 100644 --- a/scripts/qa-layer-panel.mjs +++ b/scripts/qa-layer-panel.mjs @@ -87,17 +87,21 @@ try { row().querySelector('.data-toggle-btn').dataset.feedState === 'stale', ]); const ui = window.__godsEyeView.styleManager; - ui._clearSelectedLayersBtn.click(); + const clearButton = document.getElementById('clear-selected-layers'); + clearButton.click(); + // The bar renders the busy state on Vue's next flush. + await Promise.resolve(); result.push([ 'native clear activation presents busy state', - ui._clearSelectedLayersBtn.getAttribute('aria-busy') === 'true' && + clearButton.getAttribute('aria-busy') === 'true' && !!ui._contextControls._clearSelectedLayersPromise, ]); await ui._contextControls._clearSelectedLayersPromise; + await Promise.resolve(); result.push([ 'clear settles through the existing layer transaction', !manager.isEnabled(id) && - ui._clearSelectedLayersBtn.getAttribute('aria-busy') === 'false', + clearButton.getAttribute('aria-busy') === 'false', ]); await manager.setEnabled(id, true); const final = row().querySelector('.data-toggle-btn'); diff --git a/scripts/qa-layer-visibility.mjs b/scripts/qa-layer-visibility.mjs new file mode 100644 index 000000000..8a903918e --- /dev/null +++ b/scripts/qa-layer-visibility.mjs @@ -0,0 +1,124 @@ +#!/usr/bin/env node +/** + * Real-browser proof for manager-owned periodic work and document visibility. + * Uses the app's development-only layer registration seam; no provider keys. + * Run: node scripts/qa-layer-visibility.mjs --url http://localhost:4173 + * Hiding uses a real background tab, never a patched document.hidden getter. + */ +import assert from 'node:assert/strict'; +import puppeteer from 'puppeteer'; +import { chromeExecutablePath } from './qa-chrome.mjs'; + +const args = process.argv.slice(2); +const urlIndex = args.indexOf('--url'); +const url = new URL( + (urlIndex >= 0 ? args[urlIndex + 1] : undefined) || + process.env.QA_BASE_URL || + 'http://localhost:4173', +); +url.searchParams.set('welcome', '0'); +const browser = await puppeteer.launch({ + executablePath: chromeExecutablePath(), + headless: true, + args: [ + '--no-sandbox', + '--disable-background-timer-throttling', + '--disable-renderer-backgrounding', + ], +}); +const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const check = (name, actual, expected) => { + assert.equal(actual, expected, name); + console.log(`PASS ${name}: ${actual}`); +}; +try { + const page = await browser.newPage(); + const focus = await page.createCDPSession(); + await focus.send('Emulation.setFocusEmulationEnabled', { enabled: true }); + await page.goto(url.href, { waitUntil: 'domcontentloaded' }); + await page.waitForFunction( + () => window.__gevQaRegisterLayer && window.__godsEyeView?.dataManager, + ); + await page.evaluate(async () => { + const manager = window.__godsEyeView.dataManager; + window.__qaVisibilityUpdates = 0; + window.__gevQaRegisterLayer(manager, { + id: 'qa-document-visibility', + name: 'Visibility QA', + updateInterval: 750, + init() {}, + enable() {}, + disable() {}, + destroy() {}, + async update() { + window.__qaVisibilityUpdates++; + return true; + }, + getStats() { + return { count: window.__qaVisibilityUpdates }; + }, + }); + await manager.setEnabled('qa-document-visibility', true, { origin: 'qa' }); + }); + const count = () => page.evaluate(() => window.__qaVisibilityUpdates); + await page.waitForFunction(() => window.__qaVisibilityUpdates >= 3); + check('periodic updates run while visible', (await count()) >= 3, true); + await focus.send('Emulation.setFocusEmulationEnabled', { enabled: false }); + const cover = await browser.newPage(); + await cover.bringToFront(); + await page.waitForFunction(() => document.visibilityState === 'hidden'); + const hiddenCount = await count(); + await pause(2200); + check('hidden tab makes no periodic updates', await count(), hiddenCount); + check( + 'explicit refresh remains available while hidden', + await page.evaluate(() => + window.__godsEyeView.dataManager.refreshLayer('qa-document-visibility'), + ), + true, + ); + check('explicit hidden refresh runs once', await count(), hiddenCount + 1); + await focus.send('Emulation.setFocusEmulationEnabled', { enabled: true }); + await page.waitForFunction( + () => + document.visibilityState === 'visible' && + window.__qaVisibilityUpdates > 0, + ); + await pause(200); + check( + 'resume performs one overdue refresh without a catch-up burst', + await count(), + hiddenCount + 2, + ); + await page.evaluate(() => + window.__godsEyeView.dataManager.setEnabled( + 'qa-document-visibility', + false, + { origin: 'qa' }, + ), + ); + const stopped = await count(); + await focus.send('Emulation.setFocusEmulationEnabled', { enabled: false }); + await cover.bringToFront(); + await page.waitForFunction(() => document.visibilityState === 'hidden'); + await focus.send('Emulation.setFocusEmulationEnabled', { enabled: true }); + await pause(1100); + check( + 'disabled layer does not resume on visibility change', + await count(), + stopped, + ); + check( + 'QA layer destroys cleanly', + await page.evaluate(() => + window.__gevQaUnregisterLayer( + window.__godsEyeView.dataManager, + 'qa-document-visibility', + ), + ), + true, + ); + console.log('RESULT: 7 passed'); +} finally { + await browser.close(); +} diff --git a/scripts/qa-location-controls.mjs b/scripts/qa-location-controls.mjs index 606d67b83..dc80bd279 100644 --- a/scripts/qa-location-controls.mjs +++ b/scripts/qa-location-controls.mjs @@ -62,13 +62,17 @@ try { ); check( 'orbit controls and indicator agree', - await page.evaluate(() => { + await page.evaluate(async () => { const ui = window.__godsEyeView.styleManager; + // Vue renders on a microtask; a task later the indicator shows it. + const rendered = () => new Promise((resolve) => setTimeout(resolve)); ui.setOrbit(true); + await rendered(); const active = ui.orbitController.active && document.getElementById('orbit-indicator').classList.contains('active'); ui.setOrbit(false); + await rendered(); return ( active && !ui.orbitController.active && @@ -84,6 +88,66 @@ try { () => window.__godsEyeView.styleManager._activePoiIndex === 1, ), ); + const geocoderRequests = []; + const recordGeocoderRequest = (request) => { + const url = new URL(request.url()); + if ( + url.pathname === '/api/geocode' || + url.pathname === '/api/google/geocode' || + (url.hostname === 'photon.komoot.io' && url.pathname === '/api/') + ) + geocoderRequests.push(request.url()); + }; + page.on('request', recordGeocoderRequest); + await page.$eval('#location-search', (input) => { + input.value = 'geo:39.7392,-104.9903'; + input.focus(); + }); + await page.keyboard.press('Enter'); + await page.waitForFunction( + () => { + const state = + window.__godsEyeView.styleManager._locationLookup.getState(); + return ( + state.query === 'geo:39.7392,-104.9903' && state.status === 'found' + ); + }, + { timeout: 30000 }, + ); + await page.waitForFunction( + () => !window.__godsEyeView.viewer.camera._currentFlight, + { timeout: 10000 }, + ); + check( + 'native geo URI search shows the decimal coordinate readout', + await page.evaluate(() => { + const ui = window.__godsEyeView.styleManager; + return ( + ui._searchedLocationLabel === '39.7392° N, 104.9903° W' && + document + .getElementById('location-mini-city') + .textContent.includes('39.7392° N') && + document.getElementById('location-mini-poi').textContent === + '104.9903° W' + ); + }), + ); + check( + 'geo URI navigation settles near the requested coordinate', + await page.evaluate(() => { + const position = window.__godsEyeView.viewer.camera.positionCartographic; + const degrees = 180 / Math.PI; + return ( + Math.abs(position.latitude * degrees - 39.7392) < 0.05 && + Math.abs(position.longitude * degrees + 104.9903) < 0.05 + ); + }), + ); + check( + 'geo URI search makes no geocoder request', + geocoderRequests.length === 0, + ); + page.off('request', recordGeocoderRequest); await page.evaluate(() => { const lookup = window.__godsEyeView.styleManager._locationLookup; window.__qaSearchRequests = []; @@ -96,6 +160,7 @@ try { window.__qaSearchRequests.push({ query, options, resolve }), ); document.getElementById('location-search').value = 'First'; + document.getElementById('location-search').focus(); }); await page.keyboard.press('Enter'); await page.waitForFunction(() => window.__qaSearchRequests.length === 1); @@ -136,8 +201,11 @@ try { const ui = window.__godsEyeView.styleManager; return ( ui._searchedLocationLabel === 'Second landmark, Test city' && - ui._locationMiniCity.textContent.includes('Second landmark') && - ui._locationMiniPoi.textContent === 'Test city' && + document + .getElementById('location-mini-city') + .textContent.includes('Second landmark') && + document.getElementById('location-mini-poi').textContent === + 'Test city' && ui.activeStyle === 'normal' && !ui._locationSearch.classList.contains('searching') ); @@ -169,8 +237,10 @@ try { requestAnimationFrame(() => requestAnimationFrame(resolve)), ); return ( - !ui._poiRow.classList.contains('expanded') && - !ui._locationBarDivider.classList.contains('visible') + !document.getElementById('poi-row').classList.contains('expanded') && + !document + .getElementById('location-bar-divider') + .classList.contains('visible') ); }, cityId), ); @@ -226,7 +296,7 @@ try { 'native reset returns through the existing camera handoff', await page.evaluate(async () => { const ui = window.__godsEyeView.styleManager; - ui._resetGlobeBtn.click(); + document.getElementById('reset-globe-view').click(); const pending = ui._globeResetPromise; if (!pending) return false; await pending; @@ -243,8 +313,11 @@ try { ui._locationControls.destroy(); ui._locationLookup.destroy(); const before = ui._navigationGeneration; - ui._locationPills.querySelector('button').click(); - ui._resetGlobeBtn.click(); + document + .getElementById('location-pills') + .querySelector('button') + ?.click(); + document.getElementById('reset-globe-view').click(); ui._locationSearch.dispatchEvent( new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }), ); diff --git a/scripts/qa-map-source-controls.mjs b/scripts/qa-map-source-controls.mjs index c03e96a79..d72961ca0 100644 --- a/scripts/qa-map-source-controls.mjs +++ b/scripts/qa-map-source-controls.mjs @@ -69,9 +69,10 @@ try { await page.evaluate(() => { const manager = window.__godsEyeView.styleManager; return ( - manager._mapStackChips.querySelector('[aria-pressed="true"]')?.dataset - .stackId === 'osm' && - manager._mapStackStatus.textContent === + document + .getElementById('map-stack-chips') + .querySelector('[aria-pressed="true"]')?.dataset.stackId === 'osm' && + document.getElementById('map-stack-status').textContent === manager.mapStackController.getState().activeStack.shortLabel ); }), @@ -81,32 +82,38 @@ try { await page.evaluate(async () => { const manager = window.__godsEyeView.styleManager; const result = await manager.setMapStack('esri-imagery'); + // The dock renders the published row on Vue's next flush. + await new Promise((resolve) => setTimeout(resolve, 0)); const active = manager.mapStackController.getActiveId(); return ( window.__qaMapSelections.at(-1) === 'esri-imagery' && - manager._mapStackChips.querySelector('[aria-pressed="true"]')?.dataset - .stackId === active && + document + .getElementById('map-stack-chips') + .querySelector('[aria-pressed="true"]')?.dataset.stackId === active && (result.ok || !!manager.mapStackController.getState().lastError) ); }), ); check( - 'refresh revokes retained old chips', - await page.evaluate(() => { + 'refresh re-presents the chips without duplicating them', + await page.evaluate(async () => { const manager = window.__godsEyeView.styleManager; - const old = manager._mapStackChips.querySelector('[data-stack-id="osm"]'); manager._mapSourceControls.refresh(); - const before = window.__qaMapSelections.length; - old.click(); - return window.__qaMapSelections.length === before; + await new Promise((resolve) => setTimeout(resolve, 0)); + return ( + document.querySelectorAll('#map-stack-chips [data-stack-id="osm"]') + .length === 1 + ); }), ); check( 'refreshed chips still select once', await page.evaluate(async () => { - const manager = window.__godsEyeView.styleManager; const before = window.__qaMapSelections.length; - manager._mapStackChips.querySelector('[data-stack-id="osm"]').click(); + document + .getElementById('map-stack-chips') + .querySelector('[data-stack-id="osm"]') + .click(); await Promise.resolve(); return window.__qaMapSelections.length === before + 1; }), @@ -188,7 +195,10 @@ try { const manager = window.__godsEyeView.styleManager; const before = window.__qaMapSelections.length; manager._mapSourceControls.destroy(); - manager._mapStackChips.querySelector('[data-stack-id="osm"]').click(); + document + .getElementById('map-stack-chips') + .querySelector('[data-stack-id="osm"]') + .click(); const result = await manager._mapSourceControls.select('esri-imagery'); return result === null && window.__qaMapSelections.length === before; }), diff --git a/scripts/qa-map-source-tray.mjs b/scripts/qa-map-source-tray.mjs index 17b19f4c9..231725997 100644 --- a/scripts/qa-map-source-tray.mjs +++ b/scripts/qa-map-source-tray.mjs @@ -156,16 +156,52 @@ const pressTabs = async (count, backwards = false) => { // The row scrolls smoothly when native Tab brings an edge button into view. await new Promise((resolve) => setTimeout(resolve, 250)); }; +// Phones (≤720px) present the dock's Presets inline in the More tab's sheet. +// It opens from the keyboard, as a keyboard user would, so the focus it moves +// into the sheet shows a ring. +const openPhoneMoreSheet = async () => { + const tab = '#mobile-tab-bar [data-mobile-sheet="more"]'; + if (await page.evaluate(() => document.body.dataset.mobileSheet === 'more')) { + await page.focus(tab); + await page.keyboard.press('Enter'); + } + await page.focus(tab); + await page.keyboard.press('Enter'); + await page.evaluate(() => new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(resolve)); + })); +}; + +// Media-query changes reach the page on a rendering step; wait until the +// phone shell agrees with the viewport before measuring. +const waitForShellSettled = () => page.waitForFunction(() => ( + document.body.classList.contains('mobile-shell') + === matchMedia('(max-width: 720px)').matches +), { timeout: 10_000, polling: 100 }); + +// The dock slides back into place when the layout leaves the phone shell. +const waitForDockSettled = () => page.waitForFunction(() => ( + !document.getElementById('command-dock').getAnimations({ subtree: true }) + .some((animation) => animation.playState === 'running') +), { timeout: 5_000 }); + const checkResponsiveStyleFocus = async (width) => { // The disclosure is only the starting boundary. Every style target below is // reached by actual Tab events, never by focusing the style under test. const selectedMapBefore = await page.evaluate(() => ( window.__godsEyeView.styleManager.mapStackController.getActiveId() )); - await page.focus('#control-panel-toggle'); - await pressTabs(2); // disclosure -> pin -> Normal - for (const [index, style] of ['normal', 'thermal', 'snow'].entries()) { - if (index) await pressTabs(3); + if (width <= 720) { + // Phones show Presets in the More tab's sheet, which focuses its first + // visible control (Normal) when it opens; the tray toggle and pin are + // desktop chrome there. + await openPhoneMoreSheet(); + } else { + await page.focus('#control-panel-toggle'); + await pressTabs(2); // disclosure -> pin -> Normal + } + for (const [tabs, style] of [[0, 'normal'], [3, 'thermal'], [2, 'noir']]) { + if (tabs) await pressTabs(tabs); const state = await styleFocusMetrics(); check(`${width} px ${style} keyboard ring is visible and unclipped`, hasVisibleStyleFocus(state, style) && state.selectedStyle === 'normal' @@ -215,7 +251,16 @@ const layerFocusState = async (id) => ({ ...await page.evaluate((layerId) => { const manager = window.__godsEyeView.dataManager; const button = document.querySelector(`[data-layer-id="${layerId}"] .data-toggle-btn`); - const list = document.getElementById('data-toggles'); + // The list scrolls on its own on desktop; in a phone sheet the sheet + // scrolls instead. Measure whichever container actually scrolls. + let list = document.getElementById('data-toggles'); + for (let node = list; node; node = node.parentElement) { + const overflow = getComputedStyle(node).overflowY; + if ((overflow === 'auto' || overflow === 'scroll') && node.scrollHeight > node.clientHeight) { + list = node; + break; + } + } return { lifecycle: manager.getLayerLifecycleState(layerId), feedState: button?.dataset.feedState, label: button?.textContent.trim(), @@ -522,13 +567,13 @@ try { // Visual Styles precede the five Map Source tiles. Keep the existing opening // handoff to selected OSM, then use the user's real Shift+Tab path into styles. await pressTabs(5, true); - const snowFocus = await styleFocusMetrics(); - check('Shift+Tab reaches Snow with a visible ring while Normal and OSM stay selected', - hasVisibleStyleFocus(snowFocus, 'snow') && !snowFocus.selected - && snowFocus.selectedStyle === 'normal' && snowFocus.selectedMap === 'osm', - JSON.stringify(snowFocus)); + const noirFocus = await styleFocusMetrics(); + check('Shift+Tab reaches Noir with a visible ring while Normal and OSM stay selected', + hasVisibleStyleFocus(noirFocus, 'noir') && !noirFocus.selected + && noirFocus.selectedStyle === 'normal' && noirFocus.selectedMap === 'osm', + JSON.stringify(noirFocus)); await page.screenshot({ path: path.join(shotsDir, 'keyboard-style-focus.png') }); - await pressTabs(3, true); + await pressTabs(2, true); const middleFocus = await styleFocusMetrics(); check('Shift+Tab traverses the middle FLIR style without activating it', hasVisibleStyleFocus(middleFocus, 'thermal') && !middleFocus.selected @@ -826,6 +871,9 @@ try { return originalSetStack(stackId); }; const switchPromise = styleManager._setMapStack('osm', { syncShare: false }); + // The dock renders the published row on Vue's next flush. + const rendered = () => new Promise((resolve) => setTimeout(resolve, 0)); + await rendered(); const during = { status: document.getElementById('map-stack-status').textContent, active: [...document.querySelectorAll('.map-stack-chip')] @@ -834,6 +882,7 @@ try { }; release(); await switchPromise; + await rendered(); const after = { status: document.getElementById('map-stack-status').textContent, active: [...document.querySelectorAll('.map-stack-chip')] @@ -1146,6 +1195,8 @@ try { await page.setViewport({ width: 620, height: 900, deviceScaleFactor: 1 }); await new Promise((resolve) => setTimeout(resolve, 180)); + await waitForShellSettled(); + await openPhoneMoreSheet(); const at620 = await trayMetrics(); check( '620 px tray uses two rows without clipping', @@ -1179,7 +1230,13 @@ try { await page.screenshot({ path: path.join(shotsDir, '480-open.png') }); await checkResponsiveStyleFocus(480); + // Pinning and the compact wing are the narrow desktop dock (721–900 px); + // phones use the tab bar instead. + await page.setViewport({ width: 800, height: 900, deviceScaleFactor: 1 }); + await waitForShellSettled(); + await waitForDockSettled(); await page.click('.dock-pin-btn[data-pin-target="control-panel"]'); + await waitForDockSettled(); await page.click('#control-panel-toggle'); const cdp = await page.createCDPSession(); await cdp.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 1 }); @@ -1374,6 +1431,27 @@ try { for (const width of [1000, 620, 480]) { await page.setViewport({ width, height: 900, deviceScaleFactor: 1 }); + await waitForShellSettled(); + if (width <= 720) { + // Phones present Location as the Search tab's sheet: the keyboard opens + // it onto the field, and Escape returns focus to the tab. + const searchTab = '#mobile-tab-bar [data-mobile-sheet="search"]'; + await page.focus(searchTab); + await page.keyboard.press('Enter'); + await new Promise((resolve) => setTimeout(resolve, 250)); + const field = await focusMetrics('#location-search'); + check(`Search: ${width} px keyboard opens the sheet on the location field`, + field.focusedId === 'location-search' && field.visible && field.insideViewport, + JSON.stringify(field)); + await page.screenshot({ path: path.join(shotsDir, `${width}-search-open.png`) }); + await page.keyboard.press('Escape'); + await new Promise((resolve) => setTimeout(resolve, 250)); + const tab = await focusMetrics(searchTab); + const closedSheet = await page.evaluate(() => !document.body.dataset.mobileSheet); + check(`Search: ${width} px Escape closes the sheet with a visible ring on its tab`, + closedSheet && hasVisibleControlFocus(tab), JSON.stringify({ closedSheet, tab })); + continue; + } await page.evaluate(() => { const manager = window.__godsEyeView.styleManager; manager.setPanelCollapsed('control-panel', true, { persist: false, syncShare: false }); @@ -1489,6 +1567,12 @@ try { if (dataSetup.ready) { for (const width of [1000, 620, 480]) { await page.setViewport({ width, height: 900, deviceScaleFactor: 1 }); + await waitForShellSettled(); + if (width <= 720 && !(await page.evaluate(() => document.body.dataset.mobileSheet === 'layers'))) { + // Phones present Data Layers in the Layers tab's sheet. + await page.focus('#mobile-tab-bar [data-mobile-sheet="layers"]'); + await page.keyboard.press('Enter'); + } await page.evaluate(() => window.__godsEyeView.styleManager.setPanelCollapsed('data-panel', false, { persist: false, syncShare: false })); // Resizing schedules rail placement on animation frames. Wait for that // pass and its CSS transitions before comparing a focus rectangle with @@ -1549,6 +1633,7 @@ try { ))); await page.setViewport({ width: 1000, height: 900, deviceScaleFactor: 1 }); + await waitForShellSettled(); await page.evaluate(() => window.__godsEyeView.styleManager.setPanelCollapsed('data-panel', false, { persist: false, syncShare: false })); await page.focus('#data-panel .panel-collapse-btn'); const transitionTab = await tabTo(`[data-layer-id="${dataSetup.transitionId}"] .data-toggle-btn`); diff --git a/scripts/qa-overpass-offload.mjs b/scripts/qa-overpass-offload.mjs index e04a05b86..8f6594011 100644 --- a/scripts/qa-overpass-offload.mjs +++ b/scripts/qa-overpass-offload.mjs @@ -306,7 +306,16 @@ try { await observeNetwork(page); page.on('pageerror', (error) => result.errors.push(error.message)); page.on('console', (message) => { - if (message.type() === 'error' && result.consoleErrors.length < 30) + if (message.type() !== 'error') return; + // A keyless server does not offer optional Google tokens. Keep every other + // HTTP or JavaScript error visible, including failures of this route other + // than its expected capability-miss 404. + const optionalTokenMiss = + message.location().url === new URL('/api/google/tiles-token', url).href && + /^Failed to load resource: the server responded with a status of 404\b/.test( + message.text(), + ); + if (!optionalTokenMiss && result.consoleErrors.length < 30) result.consoleErrors.push(message.text()); }); page.on('requestfailed', (request) => { diff --git a/scripts/qa-panel-resize.mjs b/scripts/qa-panel-resize.mjs deleted file mode 100644 index 026b6f2fb..000000000 --- a/scripts/qa-panel-resize.mjs +++ /dev/null @@ -1,456 +0,0 @@ -#!/usr/bin/env node -/** - * Browser QA for the floating CCTV panel: lift, resize from every handle, - * minimum size, reload, and dock again. `--fail-on-retry` (or - * QA_FAIL_ON_RETRY=1) fails on any header-press retry. - */ -import assert from 'node:assert/strict'; -import { pathToFileURL } from 'node:url'; -import { RESIZE_DIRECTIONS, resizeBox } from '../src/ui/panelResize.js'; -import { - describePress, - dockPanelByDoubleClick, - dragPointer, - liftPanelByHeader, - nextFrames, -} from './qa-panelDrag.mjs'; -import { - hookRenderErrors, - readRenderErrors, - saveFailureArtifacts, - watchPage, -} from './qa-browserEvidence.mjs'; - -export const PANEL_ID = 'cctv-panel'; -export const STORAGE_KEY = `godsEyeView.v8.panelPos.${PANEL_ID}`; -export const MIN_SIZE = { width: 300, height: 160 }; -export const ARTIFACT_DIR = 'qa-artifacts/panel-resize'; -const VIEWPORT = { width: 1400, height: 900 }; -const EDGE_BY_SIDE = { n: 'top', s: 'bottom', e: 'right', w: 'left' }; - -/** Box edges a resize in `dir` must leave exactly where they were. */ -export function pinnedEdges(dir) { - return Object.entries(EDGE_BY_SIDE) - .filter(([side]) => !dir.includes(side)) - .map(([, edge]) => edge); -} - -/** Pointer travel that grows a panel by `amount` on every edge named in `dir`. */ -export function growthDelta(dir, amount) { - return { - dx: dir.includes('e') ? amount : dir.includes('w') ? -amount : 0, - dy: dir.includes('s') ? amount : dir.includes('n') ? -amount : 0, - }; -} - -/** - * Viewport point inside the handle for `dir`, given the panel's client rect. - * Edge strips straddle the border by 3px; corners and the grip sit inside. - */ -export function handlePoint(rect, dir) { - const inset = dir.length === 2 ? 4 : 1; - const x = dir.includes('w') - ? rect.left + inset - : dir.includes('e') - ? rect.right - inset - : rect.left + rect.width / 2; - const y = dir.includes('n') - ? rect.top + inset - : dir.includes('s') - ? rect.bottom - inset - : rect.top + rect.height / 2; - return { x, y }; -} - -/** Pinned edges that moved during a resize in `dir`. */ -export function driftedEdges(before, after, dir, tolerance = 1.5) { - const edges = (box) => ({ - left: box.left, - top: box.top, - right: box.left + box.width, - bottom: box.top + box.height, - }); - const a = edges(before); - const b = edges(after); - return pinnedEdges(dir).filter( - (edge) => Math.abs(a[edge] - b[edge]) > tolerance, - ); -} - -function near(actual, expected, tolerance, label) { - assert.ok( - Math.abs(actual - expected) <= tolerance, - `${label}: expected ${expected} ± ${tolerance}, got ${actual}`, - ); -} - -async function main() { - const { default: puppeteer } = await import('puppeteer'); - const args = process.argv.slice(2); - const urlIndex = args.indexOf('--url'); - const url = urlIndex >= 0 ? args[urlIndex + 1] : 'http://localhost:4173'; - if (args.includes('--fail-on-retry')) process.env.QA_FAIL_ON_RETRY = '1'; - const browser = await puppeteer.launch({ - headless: true, - executablePath: - process.env.PUPPETEER_EXECUTABLE_PATH || - (await puppeteer.executablePath()), - args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader'], - }); - const monitors = []; - try { - const page = await browser.newPage(); - await page.setViewport(VIEWPORT); - const errors = []; - monitors.push(watchPage(page, { name: 'panel', errors })); - await hookRenderErrors(page); - - const boot = async () => { - await page.goto(`${url}/`, { waitUntil: 'domcontentloaded' }); - await page.waitForFunction(() => window.__godsEyeView?.viewer, { - timeout: 90_000, - }); - await page.waitForSelector(`#${PANEL_ID} .panel-header`); - await page.evaluate(() => { - document.querySelector('.first-run-explore')?.click(); - }); - await page.keyboard.press('Escape'); - await page.evaluate(() => { - document.getElementById('first-run-launcher')?.remove(); - for (const node of document.querySelectorAll('[class*=first-run]')) - node.remove(); - }); - await page.mouse.click(VIEWPORT.width / 2, VIEWPORT.height / 2); - await nextFrames(page); - }; - const readPanel = () => - page.evaluate((id) => { - const panel = document.getElementById(id); - const rect = panel.getBoundingClientRect(); - return { - left: rect.left, - top: rect.top, - width: rect.width, - height: rect.height, - // handlePoint() reads the far edges for s/e handles. - right: rect.right, - bottom: rect.bottom, - floating: panel.classList.contains('panel-floating'), - collapsed: panel.classList.contains('collapsed'), - inRail: panel.parentElement?.id === 'right-context-rail', - allocated: panel.style.getPropertyValue( - '--right-panel-allocated-height', - ), - inlineWidth: panel.style.width, - inlineHeight: panel.style.height, - stored: localStorage.getItem(`godsEyeView.v8.panelPos.${id}`), - }; - }, PANEL_ID); - /** - * Best effort: wait for the box to hold still for half a second. The lift - * is checked against the box at pointerdown, so a timeout only costs time. - */ - const settle = async () => { - try { - await page.waitForFunction( - (id) => { - const r = document.getElementById(id).getBoundingClientRect(); - const box = [r.left, r.top, r.width, r.height] - .map(Math.round) - .join(','); - const now = performance.now(); - if (window.__qaLastBox !== box) { - window.__qaLastBox = box; - window.__qaSince = now; - } - return now - window.__qaSince >= 500; - }, - { polling: 100, timeout: 20_000 }, - PANEL_ID, - ); - } catch (error) { - if (error?.name !== 'TimeoutError') throw error; - console.log('note: the CCTV panel was still moving; lifting anyway'); - } - }; - const headerPoint = async () => { - const rect = await page.evaluate((id) => { - const title = document.querySelector( - `#${id} .panel-header .panel-title`, - ); - const r = title.getBoundingClientRect(); - return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; - }, PANEL_ID); - return rect; - }; - const drag = (from, dx, dy) => dragPointer(page, from, dx, dy); - - await page.goto(`${url}/`, { waitUntil: 'domcontentloaded' }); - await page.evaluate((key) => { - localStorage.removeItem(key); - localStorage.removeItem('godsEyeView.v8.panelFloatHintShown'); - }, STORAGE_KEY); - await boot(); - - await page.evaluate((id) => { - const panel = document.getElementById(id); - if (panel.classList.contains('collapsed')) - document - .querySelector(`.panel-collapse-btn[data-collapse-target="${id}"]`) - .click(); - }, PANEL_ID); - await page.waitForFunction( - (id) => !document.getElementById(id).classList.contains('collapsed'), - {}, - PANEL_ID, - ); - // The rail animates panel heights, and on a slow software renderer the - // panels above CCTV can still be moving after a fixed sleep. - await settle(); - const docked = await readPanel(); - assert.equal(docked.floating, false); - assert.equal(docked.inRail, true); - - // Names whatever above CCTV in the rail shifted it, for a retry note. - const railAbove = () => - page.evaluate((id) => { - const out = []; - for (const node of document.getElementById('right-context-rail') - ?.children || []) { - if (node.id === id) break; - out.push( - `${node.id || node.className}:${Math.round(node.offsetHeight)}`, - ); - } - return out.join(' '); - }, PANEL_ID); - const aboveAtDock = await railAbove(); - // On CI a panel above CCTV grows after load and can shift the header out - // from under the press; the helper retries only such a provable miss. - const attempt = await liftPanelByHeader(page, PANEL_ID, { - dx: -200, - dy: -100, - note: async () => - `rail above CCTV ${aboveAtDock} -> ${await railAbove()}`, - }); - const { pressed } = attempt; - const lifted = await readPanel(); - assert.equal( - lifted.floating, - true, - `a header drag lifts the panel out (${describePress(attempt)}; panel docked at ${docked.top}, at press ${pressed?.top})`, - ); - assert.equal( - lifted.collapsed, - false, - 'the drag-ending click must not collapse', - ); - const moved = `docked at ${docked.left},${docked.top}; pressed at ${pressed.left},${pressed.top}`; - near( - lifted.left, - Math.max(6, pressed.left - 200), - 2, - `lifted left (${moved})`, - ); - near( - lifted.top, - Math.max(6, pressed.top - 100), - 2, - `lifted top (${moved})`, - ); - near(lifted.width, pressed.width, 2, 'lifted width'); - // The rail lets go of the lifted panel on its next layout pass. - await page - .waitForFunction( - (id) => - document - .getElementById(id) - .style.getPropertyValue('--right-panel-allocated-height') === '', - { timeout: 5_000 }, - PANEL_ID, - ) - .catch(() => {}); - const afterLayout = await readPanel(); - assert.equal(afterLayout.allocated, '', 'the rail no longer allocates it'); - const railExcludes = await page.evaluate((id) => { - const rail = document.getElementById('right-context-rail'); - // Same rule as the rail: hidden panels take no room. - const counted = [...rail.children].filter((panel) => - panel.matches( - '[data-panel-id]:not(.panel-floating):not(.collapsed):not([hidden])', - ), - ); - return { - expandedCount: rail.dataset.expandedCount, - counted: counted.length, - includesPanel: counted.some((panel) => panel.id === id), - }; - }, PANEL_ID); - assert.equal(railExcludes.includesPanel, false); - if (railExcludes.expandedCount !== undefined) - assert.equal(Number(railExcludes.expandedCount), railExcludes.counted); - const storedAfterLift = JSON.parse(afterLayout.stored); - assert.equal(storedAfterLift.floating, true); - assert.equal( - 'height' in storedAfterLift, - false, - 'a drag alone must not freeze the measured height', - ); - console.log('PASS: header drag lifts CCTV out of the rail'); - - // Park near the top: the voice dock would cover the south corners once - // the loop below has grown the window. - { - const header = await headerPoint(); - await drag(header, 0, 120 - header.y); - } - - const limits = { - minWidth: MIN_SIZE.width, - minHeight: MIN_SIZE.height, - viewportWidth: VIEWPORT.width, - viewportHeight: VIEWPORT.height, - }; - for (const dir of RESIZE_DIRECTIONS) { - const before = await readPanel(); - const { dx, dy } = growthDelta(dir, 40); - const point = handlePoint(before, dir); - const hit = await page.evaluate(({ x, y }) => { - const node = document.elementFromPoint(x, y); - if (!node) return 'nothing'; - const dirAttr = node.dataset?.dir - ? `[data-dir=${node.dataset.dir}]` - : ''; - return `${node.tagName.toLowerCase()}${node.id ? `#${node.id}` : ''}.${[...node.classList].join('.')}${dirAttr}`; - }, point); - await drag(point, dx, dy); - const after = await readPanel(); - const expected = resizeBox(before, dir, dx, dy, limits); - for (const key of ['left', 'top', 'width', 'height']) - near(after[key], expected[key], 2, `${dir} ${key} (pointer on ${hit})`); - assert.deepEqual(driftedEdges(before, after, dir, 2), [], `${dir} pins`); - } - console.log('PASS: eight resize handles keep the opposite edge pinned'); - - let before = await readPanel(); - await drag(handlePoint(before, 'se'), -2000, -2000); - let after = await readPanel(); - near(after.width, MIN_SIZE.width, 2, 'min width (se)'); - near(after.height, MIN_SIZE.height, 2, 'min height (se)'); - assert.deepEqual(driftedEdges(before, after, 'se', 2), []); - before = after; - await drag(handlePoint(before, 'nw'), 2000, 2000); - after = await readPanel(); - near(after.width, MIN_SIZE.width, 2, 'min width (nw)'); - near(after.height, MIN_SIZE.height, 2, 'min height (nw)'); - assert.deepEqual(driftedEdges(before, after, 'nw', 2), []); - console.log('PASS: minimum size holds from both corners'); - - const saved = await readPanel(); - const record = JSON.parse(saved.stored); - assert.equal(record.floating, true); - await boot(); - const restored = await readPanel(); - assert.equal(restored.floating, true, 'floating survives a reload'); - for (const key of ['left', 'top', 'width', 'height']) - near(restored[key], record[key], 2, `restored ${key}`); - console.log('PASS: reload restores position and size'); - - // A collapsed window keeps the height chosen for it, through a drag of - // its header strip and a reload. - const setCollapsed = async (collapsed) => { - await page.evaluate( - (id, want) => { - const panel = document.getElementById(id); - if (panel.classList.contains('collapsed') !== want) - document - .querySelector( - `.panel-collapse-btn[data-collapse-target="${id}"]`, - ) - .click(); - }, - PANEL_ID, - collapsed, - ); - await page.waitForFunction( - (id, want) => - document.getElementById(id).classList.contains('collapsed') === want, - {}, - PANEL_ID, - collapsed, - ); - await nextFrames(page); - }; - await drag(handlePoint(await readPanel(), 'se'), 0, 200); - const chosen = await readPanel(); - assert.ok( - chosen.height > MIN_SIZE.height + 150, - `the window grew to ${chosen.height}px`, - ); - await setCollapsed(true); - const strip = await readPanel(); - assert.ok(strip.height < chosen.height - 100, 'collapsed to its header'); - await drag(await headerPoint(), 40, 30); - const movedStrip = await readPanel(); - assert.equal(movedStrip.floating, true, 'the strip stays a window'); - near( - JSON.parse(movedStrip.stored).height, - chosen.height, - 2, - 'stored height while collapsed', - ); - await boot(); - await setCollapsed(false); - near( - (await readPanel()).height, - chosen.height, - 2, - 'height after expanding', - ); - console.log( - 'PASS: a collapsed window keeps its height through a drag and a reload', - ); - - const dock = await dockPanelByDoubleClick(page, PANEL_ID); - const snapped = await readPanel(); - assert.equal( - snapped.floating, - false, - `double-click snaps back (${describePress(dock)})`, - ); - assert.equal(snapped.inRail, true); - assert.equal(snapped.inlineWidth, ''); - assert.equal(snapped.inlineHeight, ''); - assert.equal(snapped.stored, null, 'the storage key is gone'); - console.log('PASS: header double-click returns the panel to the rail'); - - const renderErrors = await readRenderErrors(page); - assert.deepEqual( - [...errors, ...renderErrors.map((text) => `scene.renderError: ${text}`)], - [], - 'no page errors and no Cesium render-loop errors', - ); - console.log('PASS: no page errors and no render-loop errors'); - } catch (error) { - const dir = await saveFailureArtifacts({ - dir: ARTIFACT_DIR, - browser, - monitors, - error, - }).catch(() => null); - if (dir) console.error(`failure evidence saved in ${dir}/`); - throw error; - } finally { - await browser.close(); - } -} - -if ( - process.argv[1] && - import.meta.url === pathToFileURL(process.argv[1]).href -) { - main().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); - }); -} diff --git a/scripts/qa-panelDrag.mjs b/scripts/qa-panelDrag.mjs deleted file mode 100644 index fa6cc0c3a..000000000 --- a/scripts/qa-panelDrag.mjs +++ /dev/null @@ -1,319 +0,0 @@ -/** - * Header press-and-verify for the QA gates that lift a rail panel into a - * floating window and dock it again. The rail animates panel heights, so a - * point read once can be under another panel by the time the pointer goes - * down. Only a provable miss (a recorded press outside the header) is - * retried, with a GitHub `::warning::`. With QA_FAIL_ON_RETRY=1 a miss the - * panel's own movement cannot explain fails the run instead. - */ - -const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - -/** Retries after the first attempt, and the pause before each. */ -export const PRESS_RETRIES = 2; -const RETRY_PAUSE_MS = 1000; - -/** Whether a retry fails the run (QA_FAIL_ON_RETRY=1 or --fail-on-retry). */ -export function failOnRetryDefault( - env = process.env, - argv = process.argv.slice(2), -) { - return env.QA_FAIL_ON_RETRY === '1' || argv.includes('--fail-on-retry'); -} - -/** - * A failed attempt whose press landed outside the header. No recorded press - * is a failure, not a miss: a retry would only hide it. - * @param {{done: boolean, pressed: {inHeader: boolean}|null}} attempt - */ -export function pressMissed(attempt) { - return !attempt.done && attempt.pressed?.inHeader === false; -} - -/** Whether the panel's box changed by more than 2 px between two reads. */ -export function panelMoved(before, after) { - if (!before || !after) return false; - return ['left', 'top', 'width', 'height'].some( - (key) => Math.abs((after[key] ?? NaN) - (before[key] ?? NaN)) > 2, - ); -} - -/** The panel's box, rounded, as `left,top widthxheight`. */ -export function formatBox(box) { - if (!box) return 'unknown'; - const r = (value) => Math.round(value ?? NaN); - return `${r(box.left)},${r(box.top)} ${r(box.width)}x${r(box.height)}`; -} - -function panelBox(page, panelId) { - return page.evaluate((id) => { - const r = document.getElementById(id).getBoundingClientRect(); - return { left: r.left, top: r.top, width: r.width, height: r.height }; - }, panelId); -} - -export function headerPoint(page, panelId) { - return page.evaluate((id) => { - const title = document.querySelector(`#${id} .panel-header .panel-title`); - const r = title.getBoundingClientRect(); - return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; - }, panelId); -} - -/** Name the element at a point, and whether it is the panel's header. */ -export function hitAt(page, point, panelId) { - return page.evaluate( - ({ x, y, id }) => { - const node = document.elementFromPoint(x, y); - if (!node) return { target: 'nothing', inHeader: false }; - return { - target: `${node.tagName.toLowerCase()}${node.id ? `#${node.id}` : ''}.${[...node.classList].join('.')}`, - inHeader: Boolean(node.closest(`#${id} .panel-header`)), - }; - }, - { ...point, id: panelId }, - ); -} - -/** - * Re-resolve the header point until it hits the header or the wait runs out - * (the press then records the miss). - */ -export async function headerTarget( - page, - panelId, - { tries = 20, intervalMs = 500 } = {}, -) { - let point = await headerPoint(page, panelId); - let hit = await hitAt(page, point, panelId); - for (let i = 0; i < tries && !hit.inHeader; i++) { - await delay(intervalMs); - point = await headerPoint(page, panelId); - hit = await hitAt(page, point, panelId); - } - const box = await panelBox(page, panelId); - return { point, hit, timedOut: !hit.inHeader, box }; -} - -/** - * Best effort: wait until the panel's box has held still for `stillMs`, so - * the header does not move between the hit check and the press. - */ -export async function waitForStill( - page, - panelId, - { stillMs = 300, timeout = 5000 } = {}, -) { - try { - await page.waitForFunction( - (id, ms) => { - const r = document.getElementById(id).getBoundingClientRect(); - const box = [r.left, r.top, r.width, r.height].map(Math.round).join(); - const now = performance.now(); - if (window.__qaStillBox !== box) { - window.__qaStillBox = box; - window.__qaStillSince = now; - } - return now - window.__qaStillSince >= ms; - }, - { polling: 100, timeout }, - panelId, - stillMs, - ); - return true; - } catch (error) { - if (error?.name !== 'TimeoutError') throw error; - return false; - } -} - -/** Record the next pointerdown's target and the panel's box at that moment. */ -export function recordNextPress(page, panelId) { - return page.evaluate((id) => { - window.__qaPressBox = null; - window.addEventListener( - 'pointerdown', - (event) => { - const r = document.getElementById(id).getBoundingClientRect(); - const target = event.target; - window.__qaPressBox = { - left: r.left, - top: r.top, - width: r.width, - height: r.height, - target: `${target.tagName?.toLowerCase()}${target.id ? `#${target.id}` : ''}.${[...(target.classList || [])].join('.')}`, - inHeader: Boolean(target.closest?.(`#${id} .panel-header`)), - }; - }, - { capture: true, once: true }, - ); - }, panelId); -} - -function readPress(page) { - return page.evaluate(() => window.__qaPressBox ?? null); -} - -export async function waitForFloating( - page, - panelId, - floating, - { timeout = 3000 } = {}, -) { - try { - await page.waitForFunction( - (id, want) => - document.getElementById(id).classList.contains('panel-floating') === - want, - { polling: 50, timeout }, - panelId, - floating, - ); - return true; - } catch (error) { - if (error?.name !== 'TimeoutError') throw error; - return false; - } -} - -/** Two paints: by then every layout change an input caused is on screen. */ -export function nextFrames(page) { - return page.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())), - ), - ); -} - -export async function dragPointer(page, from, dx, dy, { steps = 6 } = {}) { - await page.mouse.move(from.x, from.y); - await page.mouse.down(); - await page.mouse.move(from.x + dx / 2, from.y + dy / 2, { steps }); - await page.mouse.move(from.x + dx, from.y + dy, { steps }); - await page.mouse.up(); - await nextFrames(page); -} - -export function describeRetry( - panelId, - attempt, - { round, retries, extra = '' }, -) { - const { hit, pressed, timedOut, still, box } = attempt; - return [ - `retry ${round + 1}/${retries}: the press missed the ${panelId} header (on ${pressed?.target ?? hit.target})`, - `pre-press hit check ${timedOut ? `timed out (on ${hit.target})` : 'passed'}`, - `stillness ${still === false ? 'timed out' : 'held'}`, - `panel box at hit check ${formatBox(box)} -> at press ${formatBox(pressed)}`, - ] - .concat(extra ? [extra] : []) - .join('; '); -} - -/** Retry `press` only while it provably misses the header. */ -async function pressUntilDecided( - page, - panelId, - press, - { - retries, - log, - note, - pauseMs = RETRY_PAUSE_MS, - failOnRetry = failOnRetryDefault(), - }, -) { - for (let round = 0; ; round++) { - const still = await waitForStill(page, panelId); - await recordNextPress(page, panelId); - const { point, hit, timedOut, box } = await headerTarget(page, panelId); - const done = await press(point); - const attempt = { - point, - hit, - timedOut, - still, - box, - done, - pressed: await readPress(page), - retries: round, - }; - if (round >= retries || !pressMissed(attempt)) return attempt; - const why = describeRetry(panelId, attempt, { - round, - retries, - extra: note ? await note() : '', - }); - if (failOnRetry && !panelMoved(box, attempt.pressed)) - throw new Error( - `QA_FAIL_ON_RETRY=1 turns this retry into a failure: ${why}`, - ); - log(`note: ${why}; retrying`); - log(`::warning title=Panel press retried::${why}`); - await delay(pauseMs); - } -} - -/** - * Lift a docked panel into a floating window with a header drag. - * @returns {Promise<{point: {x: number, y: number}, hit: {target: string, inHeader: boolean}, done: boolean, pressed: object|null}>} - */ -export function liftPanelByHeader( - page, - panelId, - { - dx, - dy, - retries = PRESS_RETRIES, - log = console.log, - note, - pauseMs, - failOnRetry, - } = {}, -) { - return pressUntilDecided( - page, - panelId, - async (point) => { - await dragPointer(page, point, dx, dy); - return waitForFloating(page, panelId, true); - }, - { retries, log, note, pauseMs, failOnRetry }, - ); -} - -/** Dock a floating panel with a header double-click; same result as lifting. */ -export function dockPanelByDoubleClick( - page, - panelId, - { - retries = PRESS_RETRIES, - log = console.log, - note, - pauseMs, - failOnRetry, - } = {}, -) { - return pressUntilDecided( - page, - panelId, - async (point) => { - await page.mouse.click(point.x, point.y, { clickCount: 1 }); - await page.mouse.click(point.x, point.y, { clickCount: 2 }); - return waitForFloating(page, panelId, false); - }, - { retries, log, note, pauseMs, failOnRetry }, - ); -} - -/** Where an attempt pressed, for an assertion message. */ -export function describePress(attempt) { - const { point, hit, pressed } = attempt; - const where = `pressed ${Math.round(point.x)},${Math.round(point.y)}`; - if (!pressed) - return `${where}: no pointerdown reached the page (hit check on ${hit.target}, in header: ${hit.inHeader})`; - const n = attempt.retries || 0; - const retried = n ? `, after ${n} ${n === 1 ? 'retry' : 'retries'}` : ''; - return `${where} on ${pressed.target}, in header: ${pressed.inHeader}${retried}`; -} diff --git a/scripts/qa-perf.mjs b/scripts/qa-perf.mjs index 6aa5f9e89..33302a884 100644 --- a/scripts/qa-perf.mjs +++ b/scripts/qa-perf.mjs @@ -310,7 +310,7 @@ try { countFrames(2_500), page.evaluate(() => new Promise((resolve) => setTimeout(() => { // Drive the actual sharpen slider: input event → handler → - // _applySharpenIntensity → governorRequestRender. Proves the wiring, + // _setSharpenIntensity → governorRequestRender. Proves the wiring, // not just the facade. const slider = document.getElementById('sharpen-intensity-slider'); if (!slider) { resolve({ ok: false }); return; } diff --git a/scripts/qa-radio.mjs b/scripts/qa-radio.mjs index adbbfdf81..f0cbfbef3 100644 --- a/scripts/qa-radio.mjs +++ b/scripts/qa-radio.mjs @@ -81,6 +81,32 @@ function check(name, ok, detail = '') { const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +// Radio lives only inside Context; a user reaches its controls by expanding +// Context and then Radio. Returns the prior collapse state so a step can put +// the panels back for the scenarios that follow. +async function revealRadioControls(page, targetId) { + const prior = await page.evaluate(async (id) => { + const manager = window.__godsEyeView.styleManager; + const collapsed = (panelId) => document.getElementById(panelId).classList.contains('collapsed'); + const state = { context: collapsed('global-context-panel'), radio: collapsed('radio-panel') }; + manager.setPanelCollapsed('global-context-panel', false, { explicit: true }); + manager.setPanelCollapsed('radio-panel', false, { explicit: true }); + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + document.getElementById(id).scrollIntoView({ block: 'nearest' }); + return state; + }, targetId); + await page.waitForSelector(`#${targetId}`, { visible: true }); + return prior; +} + +async function restoreRadioPanels(page, prior) { + await page.evaluate(({ context, radio }) => { + const manager = window.__godsEyeView.styleManager; + manager.setPanelCollapsed('radio-panel', radio); + manager.setPanelCollapsed('global-context-panel', context); + }, prior); +} + // Native pick buffers and clustered overlay entries settle on rendered frames, // not on wall-clock sleeps, particularly with software rendering. async function settleRadioFrames(page) { @@ -167,6 +193,13 @@ async function main() { page.on('request', (request) => { const url = new URL(request.url()); + // Radio QA uses keyless maps; an optional Google token is not offered. + if (request.method() === 'GET' && url.origin === APP_ORIGIN + && url.pathname === '/api/google/tiles-token') { + request.respond({ status: 200, contentType: 'application/json', body: '{}' }); + return; + } + // These scenarios exercise Context lifecycle and keyboard ownership, not // live orbit accuracy. Reuse the tracking suite's fixed element sets so // CelesTrak outages cannot invalidate an otherwise clean UI run. @@ -278,31 +311,16 @@ async function main() { window.__godsEyeView.styleManager.setPanelCollapsed('global-context-panel', true); }); + const enablePanels = await revealRadioControls(page, 'radio-enable-btn'); const enableStartedAt = Date.now(); - const initialDisclosure = await page.evaluate(() => { - const button = document.getElementById('context-radio-toggle-btn'); - const mini = document.getElementById('context-radio-mini'); - const enabledBefore = window.__godsEyeView.dataManager.isEnabled('radio'); - button.click(); - return { - enabledBefore, - enabledAfterDisclosure: window.__godsEyeView.dataManager.isEnabled('radio'), - expanded: button.getAttribute('aria-expanded'), - miniHidden: mini.hidden, - }; - }); - check( - 'Radio launcher discloses compact controls without changing power', - !initialDisclosure.enabledBefore && !initialDisclosure.enabledAfterDisclosure - && initialDisclosure.expanded === 'true' && !initialDisclosure.miniHidden, - JSON.stringify(initialDisclosure), - ); - await page.$eval('#context-radio-mini-enable-btn', (button) => button.click()); + await page.click('#radio-enable-btn'); await page.waitForFunction(() => { const state = window.__godsEyeView.dataManager.layers.get('radio').module.getUIState(); return state.enabled && !state.loading && state.stationCount === 750; }); const enableElapsedMs = Date.now() - enableStartedAt; + // Later scenarios start from the collapsed rail this step began with. + await restoreRadioPanels(page, enablePanels); const initial = await page.evaluate(() => { const module = window.__godsEyeView.dataManager.layers.get('radio').module; const state = module.getUIState(); @@ -321,9 +339,6 @@ async function main() { color: entry.dataset.radioColor, })), enablePressed: document.getElementById('radio-enable-btn').getAttribute('aria-pressed'), - launcherExpanded: document.getElementById('context-radio-toggle-btn').getAttribute('aria-expanded'), - launcherActive: document.getElementById('context-radio-toggle-btn').classList.contains('active'), - compactEnablePressed: document.getElementById('context-radio-mini-enable-btn').getAttribute('aria-pressed'), fullPlayEnabled: !document.getElementById('radio-play-btn').disabled, fullPlayLabel: document.getElementById('radio-play-btn').getAttribute('aria-label'), tunerVisible: !document.getElementById('radio-tuner').hidden, @@ -334,9 +349,8 @@ async function main() { check('750-station catalog renders within the browser budget', initial.state.stationCount === 750 && enableElapsedMs < 5000, `${enableElapsedMs}ms`); check('enable does not autoplay', initial.plays === 0 && initial.state.audioState === 'stopped'); check( - 'compact and detailed Radio power controls reflect the layer manager independently of disclosure', - initial.enablePressed === 'true' && initial.compactEnablePressed === 'true' - && initial.launcherExpanded === 'true' && initial.launcherActive, + 'Radio power control reflects the layer manager after the panels collapse again', + initial.enablePressed === 'true', ); check('dynamic canonical and genre categories reach the UI', initial.filterOptions >= 10, `${initial.filterOptions} options`); const musicOption = initial.filterPalette.find((entry) => entry.id === 'music'); @@ -412,14 +426,10 @@ async function main() { prevDisabled: document.getElementById('radio-prev-btn').disabled, playDisabled: document.getElementById('radio-play-btn').disabled, volumeDisabled: document.getElementById('radio-volume').disabled, - disclosureLabel: document.getElementById('context-radio-toggle-btn').getAttribute('aria-label'), - compactPowerLabel: document.getElementById('context-radio-mini-enable-btn').getAttribute('aria-label'), - compactPowerText: document.getElementById('context-radio-mini-enable-btn').textContent, fullLabel: document.getElementById('radio-enable-btn').getAttribute('aria-label'), fullText: document.getElementById('radio-enable-btn').textContent, layerState: document.getElementById('radio-layer-state').textContent, playbackMessage: document.getElementById('radio-playback-state').textContent, - miniStation: document.getElementById('context-radio-mini-station').textContent, dataRailText: document.querySelector('[data-layer-id="radio"] .data-toggle-btn')?.textContent, dataRailState: document.querySelector('[data-layer-id="radio"] .data-toggle-btn')?.dataset.feedState, dataRailLabel: document.querySelector('[data-layer-id="radio"] .data-toggle-btn')?.getAttribute('aria-label'), @@ -461,14 +471,10 @@ async function main() { && uncertainPresentation.prevDisabled && uncertainPresentation.playDisabled && uncertainPresentation.volumeDisabled - && /compact Radio controls/i.test(uncertainPresentation.disclosureLabel) - && /uncertain/i.test(uncertainPresentation.compactPowerLabel) - && uncertainPresentation.compactPowerText === 'RECONCILE' && /uncertain/i.test(uncertainPresentation.fullLabel) && uncertainPresentation.fullText === 'RECONCILE' && uncertainPresentation.layerState === 'UNCERTAIN' && /uncertain/i.test(uncertainPresentation.playbackMessage) - && uncertainPresentation.miniStation === 'RADIO STATE UNCERTAIN' && uncertainPresentation.dataRailText === 'UNCERTAIN' && uncertainPresentation.dataRailState === 'uncertain' && /uncertain/i.test(uncertainPresentation.dataRailLabel) @@ -510,10 +516,6 @@ async function main() { presentationActive: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().presentationActive, markerSourceVisible: window.__godsEyeView.viewer.dataSources.getByName('Radio stations')[0]?.show, full: document.getElementById('radio-enable-btn').textContent, - disclosure: document.getElementById('context-radio-toggle-btn').getAttribute('aria-label'), - disclosureControls: document.getElementById('context-radio-toggle-btn').getAttribute('aria-controls'), - disclosureExpanded: document.getElementById('context-radio-toggle-btn').getAttribute('aria-expanded'), - compactPower: document.getElementById('context-radio-mini-enable-btn').textContent, layerState: document.getElementById('radio-layer-state').textContent, message: document.getElementById('radio-playback-state').textContent, stopDisabled: document.getElementById('radio-stop-btn').disabled, @@ -527,8 +529,6 @@ async function main() { && disablingPresentation.presentationActive === false && disablingPresentation.markerSourceVisible === false && disablingPresentation.full === 'DISABLING' - && /compact Radio controls/i.test(disablingPresentation.disclosure) - && disablingPresentation.compactPower === 'DISABLING' && disablingPresentation.layerState === 'DISABLING' && /disabling/i.test(disablingPresentation.message) && disablingPresentation.stopDisabled @@ -585,10 +585,6 @@ async function main() { presentationActive: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().presentationActive, markerSourceVisible: window.__godsEyeView.viewer.dataSources.getByName('Radio stations')[0]?.show, full: document.getElementById('radio-enable-btn').textContent, - disclosure: document.getElementById('context-radio-toggle-btn').getAttribute('aria-label'), - disclosureControls: document.getElementById('context-radio-toggle-btn').getAttribute('aria-controls'), - disclosureExpanded: document.getElementById('context-radio-toggle-btn').getAttribute('aria-expanded'), - compactPower: document.getElementById('context-radio-mini-enable-btn').textContent, layerState: document.getElementById('radio-layer-state').textContent, message: document.getElementById('radio-playback-state').textContent, tunerHidden: document.getElementById('radio-tuner').hidden, @@ -603,10 +599,6 @@ async function main() { && enablingPresentation.presentationActive === false && enablingPresentation.markerSourceVisible === false && enablingPresentation.full === 'ENABLING' - && enablingPresentation.disclosure === 'Go to expanded Radio section' - && enablingPresentation.disclosureControls === 'radio-panel' - && enablingPresentation.disclosureExpanded === 'true' - && enablingPresentation.compactPower === 'ENABLING' && enablingPresentation.layerState === 'ENABLING' && /enabling/i.test(enablingPresentation.message) && enablingPresentation.tunerHidden @@ -1108,7 +1100,7 @@ async function main() { document.getElementById('installations-search-btn').click(); await new Promise((resolve) => setTimeout(resolve, 50)); const installationFalseMessage = document.getElementById('toast').textContent; - const installationFalseReleased = !document.getElementById('installations-search-btn').disabled; + const installationFalseReleased = document.getElementById('installations-search-btn').getAttribute('aria-busy') === 'false'; dataManager.setEnabled = async (layerId, shouldEnable) => { if (layerId === 'military-installations' && shouldEnable) { @@ -1119,7 +1111,7 @@ async function main() { document.getElementById('installations-search-btn').click(); await new Promise((resolve) => setTimeout(resolve, 50)); const installationEnableRejectionMessage = document.getElementById('toast').textContent; - const installationEnableRejectionReleased = !document.getElementById('installations-search-btn').disabled; + const installationEnableRejectionReleased = document.getElementById('installations-search-btn').getAttribute('aria-busy') === 'false'; dataManager.setEnabled = async (layerId, shouldEnable) => { if (layerId === 'military-installations' && shouldEnable) enabled.add(layerId); @@ -1131,13 +1123,13 @@ async function main() { document.getElementById('installations-search-btn').click(); await new Promise((resolve) => setTimeout(resolve, 50)); const installationRejectionMessage = document.getElementById('toast').textContent; - const installationRejectionReleased = !document.getElementById('installations-search-btn').disabled; + const installationRejectionReleased = document.getElementById('installations-search-btn').getAttribute('aria-busy') === 'false'; if (installations) installations.searchNearby = async () => false; document.getElementById('installations-search-btn').click(); await new Promise((resolve) => setTimeout(resolve, 50)); const installationSearchFalseMessage = document.getElementById('toast').textContent; - const installationSearchFalseReleased = !document.getElementById('installations-search-btn').disabled; + const installationSearchFalseReleased = document.getElementById('installations-search-btn').getAttribute('aria-busy') === 'false'; await new Promise((resolve) => setTimeout(resolve, 0)); return { semanticFalseMessage, @@ -1284,8 +1276,6 @@ async function main() { const clusterBadge = await page.evaluate(async () => { const viewer = window.__godsEyeView.viewer; const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); - const { distanceFade } = await import('/src/overlays/worldOverlayDraw.js'); - const { radioStationIdFromPick } = await import('/src/data/radio.js'); const baselineSolveRevision = getWorldOverlayDiagnostics().solveRevision; const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) .find((item) => item.name === 'Radio stations'); @@ -1576,112 +1566,9 @@ async function main() { JSON.stringify(directoryRefreshContinuity), ); await page.select('#radio-filter', 'news'); - check('launcher enables Radio without forcing Context open', !initial.panelExpanded && !initial.contextExpanded && initial.nestedInContext); + check('enabled Radio stays nested in Context and leaves both panels collapsed', !initial.panelExpanded && !initial.contextExpanded && initial.nestedInContext); check('full Play is available before a station is selected', !initial.state.selected && initial.fullPlayEnabled && initial.fullPlayLabel === 'Play nearest radio station'); - const hoverOnlyDisclosure = await page.evaluate(() => { - const button = document.getElementById('context-radio-toggle-btn'); - if (button.getAttribute('aria-expanded') === 'true') button.click(); - return { - expanded: button.getAttribute('aria-expanded'), - hidden: document.getElementById('context-radio-mini').hidden, - }; - }); - await page.hover('#context-radio-toggle-btn'); - await sleep(100); - const hoverOnlyVisible = await page.$eval('#context-radio-mini', (mini) => ( - !mini.hidden && getComputedStyle(mini).display !== 'none' - )); - check( - 'hover alone does not disclose compact Radio controls', - hoverOnlyDisclosure.expanded === 'false' && hoverOnlyDisclosure.hidden && !hoverOnlyVisible, - JSON.stringify({ hoverOnlyDisclosure, hoverOnlyVisible }), - ); - await page.click('#context-radio-toggle-btn'); - await page.waitForFunction(() => { - const button = document.getElementById('context-radio-toggle-btn'); - const mini = document.getElementById('context-radio-mini'); - return button.getAttribute('aria-expanded') === 'true' - && !mini.hidden && getComputedStyle(mini).display !== 'none'; - }); - const compact = await page.evaluate(() => { - const mini = document.getElementById('context-radio-mini'); - const toggle = document.getElementById('context-radio-toggle-btn'); - const dock = document.getElementById('context-radio-dock'); - const miniRect = mini.getBoundingClientRect(); - const toggleRect = toggle.getBoundingClientRect(); - const miniStyle = getComputedStyle(mini); - return { - visible: miniStyle.display !== 'none' && miniRect.width > 0 && miniRect.height > 0, - display: miniStyle.display, - visibility: miniStyle.visibility, - opacity: miniStyle.opacity, - miniRect: { top: miniRect.top, left: miniRect.left, width: miniRect.width, height: miniRect.height }, - toggleRect: { top: toggleRect.top, left: toggleRect.left, width: toggleRect.width, height: toggleRect.height }, - dockRect: (() => { - const rect = dock.getBoundingClientRect(); - return { top: rect.top, left: rect.left, width: rect.width, height: rect.height }; - })(), - offsetParent: mini.offsetParent?.id || mini.offsetParent?.className || null, - prevEnabled: !document.getElementById('context-radio-mini-prev-btn').disabled, - playEnabled: !document.getElementById('context-radio-mini-play-btn').disabled, - playLabel: document.getElementById('context-radio-mini-play-btn').getAttribute('aria-label'), - nextEnabled: !document.getElementById('context-radio-mini-next-btn').disabled, - volumeEnabled: !document.getElementById('context-radio-mini-volume').disabled, - offsetBelowToggle: Math.round(miniRect.top - toggleRect.bottom), - }; - }); - check( - 'explicit launcher disclosure reveals enabled compact Radio controls', - compact.visible && compact.prevEnabled && compact.playEnabled && compact.nextEnabled && compact.volumeEnabled, - JSON.stringify(compact), - ); - check('compact Play is available before a station is selected', compact.playLabel === 'Play nearest radio station'); - check('compact Radio controls sit 20px below the launcher', compact.offsetBelowToggle === 20, `${compact.offsetBelowToggle}px`); - const compactCloseDisclosure = await page.evaluate(() => { - const launcher = document.getElementById('context-radio-toggle-btn'); - const close = document.getElementById('context-radio-mini-close-btn'); - close.focus(); - close.click(); - const result = { - launcherExpanded: launcher.getAttribute('aria-expanded'), - compactHidden: document.getElementById('context-radio-mini').hidden, - focusRestored: document.activeElement === launcher, - radioCollapsed: document.getElementById('radio-panel').classList.contains('collapsed'), - }; - launcher.click(); - return result; - }); - check( - 'dedicated compact close hides only the compact Radio disclosure and restores launcher focus', - compactCloseDisclosure.launcherExpanded === 'false' - && compactCloseDisclosure.compactHidden - && compactCloseDisclosure.focusRestored - && compactCloseDisclosure.radioCollapsed, - JSON.stringify(compactCloseDisclosure), - ); - const compactTouchDisclosure = await page.evaluate(() => { - const button = document.getElementById('context-radio-toggle-btn'); - button.click(); - const closed = button.getAttribute('aria-expanded') === 'false' - && document.getElementById('context-radio-mini').hidden; - button.dispatchEvent(new PointerEvent('pointerdown', { - bubbles: true, - pointerType: 'touch', - isPrimary: true, - })); - button.click(); - return { - closed, - reopened: button.getAttribute('aria-expanded') === 'true' - && !document.getElementById('context-radio-mini').hidden, - }; - }); - check( - 'touch/coarse-pointer activation can close and reopen compact Radio controls', - compactTouchDisclosure.closed && compactTouchDisclosure.reopened, - JSON.stringify(compactTouchDisclosure), - ); const multiExpandedPanelLayout = await page.evaluate(async () => { const manager = window.__godsEyeView.styleManager; const ids = ['data-panel', 'scene-panel', 'pp-toggles', 'cctv-panel', 'global-context-panel']; @@ -1829,7 +1716,14 @@ async function main() { else panel.setAttribute('style', state.style); if (state.ariaHidden === null) panel.removeAttribute('aria-hidden'); else panel.setAttribute('aria-hidden', state.ariaHidden); - manager._syncPanelCollapseButton(panel); + // The restored classes are the panel's state again. + const has = (name) => panel.classList.contains(name); + manager._presentPanel(panel, { + collapsed: has('collapsed'), + pinned: has('dock-pinned'), + pinnedTop: has('dock-pinned-top'), + auto: has('layout-auto-collapsed') ? 'layout' : has('accordion-collapsed') ? 'accordion' : null, + }); } for (const [id, state] of Object.entries(prior.stacks)) { const stack = document.getElementById(id); @@ -2057,7 +1951,6 @@ async function main() { hudVariant: manager.hud.getVariant(), displayExpanded: display.getAttribute('aria-expanded') === 'true', radioExpanded: radio.getAttribute('aria-expanded') === 'true', - contextRadioExpanded: document.getElementById('context-radio-toggle-btn')?.getAttribute('aria-expanded') === 'true', focusId: document.activeElement?.id || null, detectionMode: manager.getDetectionState().detectionMode, models3dEnabled: manager._models3dEnabled, @@ -2088,7 +1981,7 @@ async function main() { manager._setCockpitDisplayPortalActive(true); hud.hidden = false; signal.hidden = false; - dataPanel.classList.remove('collapsed'); + manager._presentPanel(dataPanel, { collapsed: false }); window.__godsEyeView.styleManager._syncLeftPanelAdaptiveLayout(); window.__godsEyeView.styleManager.cockpitView.syncSignalLayout(); if (display.getAttribute('aria-expanded') === 'true') display.click(); @@ -2153,11 +2046,13 @@ async function main() { for (let index = 0; index < 5; index += 1) { recordLayoutStep(); if (index < 4) { - if (index < 2) { - hudLayout.value = index === 0 ? 'operator' : 'minimal'; - hudLayout.dispatchEvent(new Event('change', { bubbles: true })); - } else { + // Off and back on in Minimal, so the toggle must restore a + // non-default layout before the cycle returns to Tactical. + if (index === 1 || index === 2) { hudToggle.click(); + } else { + hudLayout.value = index === 0 ? 'minimal' : 'tactical'; + hudLayout.dispatchEvent(new Event('change', { bubbles: true })); } await waitForHudSettle(); } @@ -2171,8 +2066,7 @@ async function main() { contextCard.hidden = false; // Expand the panel the same way this block already does at entry, so the // portaled Display groups measured further down keep their DOM home. - dataPanel.classList.remove('collapsed', 'layout-auto-collapsed'); - manager._syncPanelCollapseButton(dataPanel); + manager._presentPanel(dataPanel, { collapsed: false, auto: null }); manager._syncLeftPanelAdaptiveLayout(); await waitForLayout(); const panelRect = dataPanel.getBoundingClientRect(); @@ -2266,24 +2160,27 @@ async function main() { .every((control) => control.closest('.pp-toggle-group')?.parentElement ?.closest('#cockpit-display-panel')); display.click(); + await waitForLayout(); manager.cockpitView.syncSignalLayout(); radio.click(); + await waitForLayout(); const radioOpened = radio.getAttribute('aria-expanded') === 'true' && !document.getElementById('cockpit-radio-panel').hidden; const mutuallyExclusive = display.getAttribute('aria-expanded') === 'false'; radio.click(); + await waitForLayout(); manager.cockpitView.syncSignalLayout(); radio.click(); + await waitForLayout(); const radioNavigationAvailable = [ document.getElementById('cockpit-radio-prev-btn'), document.getElementById('cockpit-radio-next-btn'), ].every((button) => button?.isConnected && !button.disabled); const detailsExcluded = !document.querySelector( - '#cockpit-radio-panel #context-radio-details-btn, ' - + '#cockpit-radio-panel #radio-filter, #cockpit-radio-panel #radio-tuner', + '#cockpit-radio-panel #radio-filter, #cockpit-radio-panel #radio-tuner', ); const scenesHidden = getComputedStyle(scene).display === 'none'; radio.click(); @@ -2326,7 +2223,7 @@ async function main() { scenesHidden, mapProviderUtilityStable, hudInteractionsExact: layoutSteps.map((step) => step.hud).join('>') - === 'TACTICAL>OPERATOR>MINIMAL>OFF>MINIMAL', + === 'TACTICAL>MINIMAL>OFF>MINIMAL>TACTICAL', // The accordion clears the topline, Cockpit cards, and Cesium credits // across every HUD layout. Its list owns any overflow internally. leftLaneClearAcrossHudCycle: layoutSteps.every((step) => ( @@ -2376,7 +2273,6 @@ async function main() { manager.setPanelCollapsed('global-context-panel', prior.contextCollapsed); if (display.getAttribute('aria-expanded') !== String(prior.displayExpanded)) display.click(); if (radio.getAttribute('aria-expanded') !== String(prior.radioExpanded)) radio.click(); - manager._setRadioDisclosure(prior.contextRadioExpanded); hud.hidden = prior.hudHidden; signal.hidden = prior.signalHidden; if (prior.utilityTop) hud.style.setProperty('--cockpit-utility-top', prior.utilityTop); @@ -2397,7 +2293,14 @@ async function main() { else panel.setAttribute('style', state.style); if (state.ariaHidden === null) panel.removeAttribute('aria-hidden'); else panel.setAttribute('aria-hidden', state.ariaHidden); - manager._syncPanelCollapseButton(panel); + // The restored classes are the panel's state again. + const has = (name) => panel.classList.contains(name); + manager._presentPanel(panel, { + collapsed: has('collapsed'), + pinned: has('dock-pinned'), + pinnedTop: has('dock-pinned-top'), + auto: has('layout-auto-collapsed') ? 'layout' : has('accordion-collapsed') ? 'accordion' : null, + }); } manager._panelLayout._leftStackPreferredPanelId = prior.preferredLeftPanelId; localStorage.clear(); @@ -2411,7 +2314,6 @@ async function main() { && document.getElementById('global-context-panel').classList.contains('collapsed') === prior.contextCollapsed && display.getAttribute('aria-expanded') === String(prior.displayExpanded) && radio.getAttribute('aria-expanded') === String(prior.radioExpanded) - && document.getElementById('context-radio-toggle-btn')?.getAttribute('aria-expanded') === String(prior.contextRadioExpanded) && hud.hidden === prior.hudHidden && signal.hidden === prior.signalHidden && intelHud.style.getPropertyValue('transition') === priorHudTransition @@ -2467,21 +2369,20 @@ async function main() { check('first Play scenario starts without a leaked Radio selection', firstPlayPrecondition === null, `selected=${firstPlayPrecondition}`); await page.select('#radio-filter', 'all'); - await page.$eval('#context-radio-toggle-btn', (button) => { - if (button.getAttribute('aria-expanded') !== 'true') button.click(); - }); await page.evaluate(() => { const camera = window.__godsEyeView.viewer.camera; window.__qaFirstPlayFlyToCalls = []; window.__qaFirstPlayOriginalFlyTo = camera.flyTo; camera.flyTo = (options) => window.__qaFirstPlayFlyToCalls.push(options); - document.getElementById('context-radio-toggle-btn').focus(); }); - await page.$eval('#context-radio-mini-play-btn', (button) => button.click()); + const firstPlayPanels = await revealRadioControls(page, 'radio-play-btn'); + await page.focus('#radio-play-btn'); + await page.click('#radio-play-btn'); await page.waitForFunction(() => { const state = window.__godsEyeView.dataManager.layers.get('radio').module.getUIState(); return state.audioState === 'playing' || state.audioState === 'error'; }); + await restoreRadioPanels(page, firstPlayPanels); const postMicroDragPlayback = await page.evaluate(async () => { const mod = window.__godsEyeView.dataManager.layers.get('radio').module; let state = mod.getUIState(); @@ -2588,59 +2489,19 @@ async function main() { ); await page.select('#radio-filter', 'news'); - await page.$eval('#context-radio-mini-volume', (input) => { + await page.$eval('#radio-volume', (input) => { input.value = '35'; input.dispatchEvent(new Event('input', { bubbles: true })); }); - const compactVolume = await page.evaluate(() => ({ + const radioVolume = await page.evaluate(() => ({ volume: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().volume, full: document.getElementById('radio-volume').value, - mini: document.getElementById('context-radio-mini-volume').value, + label: document.getElementById('radio-volume-value').textContent, })); - check('compact volume shares the full Radio player state', Math.abs(compactVolume.volume - 0.35) < 0.001 && compactVolume.full === '35' && compactVolume.mini === '35'); - - const compactDisclosureContinuity = await page.evaluate(async () => { - const radio = window.__godsEyeView.dataManager.layers.get('radio').module; - const manager = window.__godsEyeView.styleManager; - manager.setPanelCollapsed('global-context-panel', true); - manager._setRadioDisclosure(true); - await radio.play({ origin: 'user' }); - const before = radio.getUIState(); - const disclosure = document.getElementById('context-radio-toggle-btn'); - if (disclosure.getAttribute('aria-expanded') !== 'true') disclosure.click(); - disclosure.click(); - const closed = { - expanded: disclosure.getAttribute('aria-expanded'), - hidden: document.getElementById('context-radio-mini').hidden, - state: radio.getUIState(), - }; - disclosure.click(); - return { - before, - closed, - reopened: disclosure.getAttribute('aria-expanded'), - miniHidden: document.getElementById('context-radio-mini').hidden, - after: radio.getUIState(), - }; - }); check( - 'compact disclosure preserves playback, station, filter, and volume continuity', - compactDisclosureContinuity.closed.expanded === 'false' - && compactDisclosureContinuity.closed.hidden - && compactDisclosureContinuity.reopened === 'true' - && !compactDisclosureContinuity.miniHidden - && compactDisclosureContinuity.before.audioState === 'playing' - && compactDisclosureContinuity.closed.state.audioState === 'playing' - && compactDisclosureContinuity.after.audioState === 'playing' - && compactDisclosureContinuity.after.selected?.id === compactDisclosureContinuity.before.selected?.id - && compactDisclosureContinuity.after.filter === compactDisclosureContinuity.before.filter - && compactDisclosureContinuity.after.volume === compactDisclosureContinuity.before.volume, - JSON.stringify({ - before: compactDisclosureContinuity.before, - closed: compactDisclosureContinuity.closed, - reopened: compactDisclosureContinuity.reopened, - after: compactDisclosureContinuity.after, - }), + 'full Radio volume drives the Radio player state', + Math.abs(radioVolume.volume - 0.35) < 0.001 && radioVolume.full === '35' && radioVolume.label === '35%', + JSON.stringify(radioVolume), ); const voicePause = await page.evaluate(async () => { @@ -2704,11 +2565,13 @@ async function main() { idleVoice.audioState === 'paused', idleVoice.audioState, ); - const manualPlayTarget = await page.evaluate(() => { + const manualPlayTarget = await page.evaluate(async () => { const manager = window.__godsEyeView.styleManager; - manager.setPanelCollapsed('global-context-panel', true); - manager._setRadioDisclosure(true); - const button = document.getElementById('context-radio-mini-play-btn'); + manager.setPanelCollapsed('global-context-panel', false); + manager.setPanelCollapsed('radio-panel', false); + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + const button = document.getElementById('radio-play-btn'); + button.scrollIntoView({ block: 'nearest' }); const rect = button.getBoundingClientRect(); const style = getComputedStyle(button); return { @@ -2723,12 +2586,12 @@ async function main() { }; }); check( - 'manual voice takeover targets the visible compact Radio Play control', + 'manual voice takeover targets the visible full Radio Play control', manualPlayTarget.visible && manualPlayTarget.enabled, JSON.stringify(manualPlayTarget), ); if (manualPlayTarget.visible && manualPlayTarget.enabled) { - await page.click('#context-radio-mini-play-btn'); + await page.click('#radio-play-btn'); await page.waitForFunction(() => ( window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().audioState === 'playing' && window.__godsEyeView.voiceCommands.status === 'idle' @@ -2754,13 +2617,16 @@ async function main() { const beforeSpace = radio.getUIState().audioState; // Simulate an already-started hold-Space session; click-started open mic // deliberately ignores Space takeover, and short taps never claim voice. - const priorPushToTalkMode = voice.pushToTalkMode; - voice.pushToTalkMode = true; + // The provider facade forwards reads, not writes. Set the mounted + // controller's input owner; assigning on the facade only shadows it. + const controller = voice.session.adapter.controller; + const priorPushToTalkMode = controller.pushToTalkMode; + controller.pushToTalkMode = true; document.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, code: 'Space', key: ' ' })); await new Promise((resolve) => setTimeout(resolve, 700)); const afterSpace = radio.getUIState().audioState; document.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, cancelable: true, code: 'Space', key: ' ' })); - voice.pushToTalkMode = priorPushToTalkMode; + controller.pushToTalkMode = priorPushToTalkMode; await radio.play(); voice.setVoiceSpeaker('ai'); return { beforeSpace, afterSpace, afterAi: radio.getUIState().audioState }; @@ -2773,7 +2639,6 @@ async function main() { await page.evaluate(() => window.__godsEyeView.voiceCommands.setStatus('idle', 'QA complete')); await page.evaluate(async () => { const manager = window.__godsEyeView.styleManager; - manager._setRadioDisclosure(false); manager.setPanelCollapsed('global-context-panel', false); manager.setPanelCollapsed('radio-panel', false); await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); @@ -2852,14 +2717,20 @@ async function main() { }; const playsBefore = window.__qaRadioPlayCalls.length; const frozenSignature = style._radioControls._radioTunerBandSignature; + // The tuner renders from the Radio store; let Vue patch before reading. + const rendered = () => Promise.resolve(); pointer('pointerdown', xFor(0)); + await rendered(); const left = snapshot(); const centerCoordinate = (count - 1) / 2; pointer('pointermove', xFor(centerCoordinate)); + await rendered(); const center = snapshot(); pointer('pointermove', xFor(centerCoordinate + 2)); + await rendered(); const shifted = snapshot(); pointer('pointermove', xFor(count - 1)); + await rendered(); const right = snapshot(); const shiftedByIndex = new Map(shifted.ticks.map((tick) => [tick.index, tick.x])); const sharedTick = center.ticks.find((tick) => shiftedByIndex.has(tick.index)); @@ -2916,7 +2787,7 @@ async function main() { tapeDelta: absoluteTuner.tapeDelta, }), ); - const tunerCancelRestore = await page.evaluate(() => { + const tunerCancelRestore = await page.evaluate(async () => { const gev = window.__godsEyeView; const style = gev.styleManager; const radio = gev.dataManager.layers.get('radio').module; @@ -2949,11 +2820,14 @@ async function main() { const targetIndex = before.slot < beforeStations.length - 2 ? before.slot + 2 : before.slot - 2; pointer('pointerdown', before.slot); pointer('pointermove', targetIndex); + // The tuner renders from the Radio store; let Vue patch before reading. + await Promise.resolve(); const shiftedSlot = Number(slider.value); const previewBeforeCancel = gev.viewer.entities.values .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null; const flyToCallsBeforeCancel = flyToCalls.length; pointer('pointercancel', targetIndex); + await Promise.resolve(); const afterStations = style._radioControls._radioTunerStations; const afterState = radio.getUIState(); const after = { @@ -3109,7 +2983,7 @@ async function main() { await page.evaluate(async () => { await window.__godsEyeView.dataManager.layers.get('radio').module.update(); }); - const tunerRefreshRelease = await page.evaluate((target) => { + const tunerRefreshRelease = await page.evaluate(async (target) => { const gev = window.__godsEyeView; const slider = document.getElementById('radio-tuner-slider'); const displayedBeforeRelease = document.getElementById('radio-tuner-station').textContent; @@ -3122,6 +2996,10 @@ async function main() { clientY: target.clientY, })); const state = gev.dataManager.layers.get('radio').module.getUIState(); + // The playback line renders from the Radio store once Vue flushes. + const message = await Promise.resolve().then( + () => document.getElementById('radio-playback-state').textContent, + ); return { displayedBeforeRelease, frozenGeneration, @@ -3130,7 +3008,7 @@ async function main() { plays: window.__qaRadioPlayCalls.length, value: document.getElementById('radio-tuner-value').textContent, stationText: document.getElementById('radio-tuner-station').textContent, - message: document.getElementById('radio-playback-state').textContent, + message, targetId: target.id, }; }, tunerRefreshTarget); @@ -3177,6 +3055,8 @@ async function main() { pointer('pointermove', targetIndex); const previewPlays = window.__qaRadioPlayCalls.length; pointer('pointerup', targetIndex); + // The tuner renders from the Radio store; sample once Vue has patched. + await Promise.resolve(); const samples = [needle.getBoundingClientRect().left]; await new Promise((resolve) => requestAnimationFrame(resolve)); samples.push(needle.getBoundingClientRect().left); @@ -3827,22 +3707,22 @@ async function main() { gev.dataManager.layers.get('flights').enabled = true; }); await sleep(500); - await page.evaluate(() => window.__godsEyeView.styleManager.setPanelCollapsed('global-context-panel', true)); await page.evaluate(() => { - const button = document.getElementById('context-radio-toggle-btn'); - if (button.getAttribute('aria-expanded') !== 'true') button.click(); + const manager = window.__godsEyeView.styleManager; + manager.setPanelCollapsed('global-context-panel', false); + manager.setPanelCollapsed('radio-panel', false); }); - await page.waitForSelector('#context-radio-mini', { visible: true }); + await page.waitForSelector('#radio-next-btn', { visible: true }); await page.evaluate(() => { window.__qaRadioCameraHeight = window.__godsEyeView.viewer.camera.positionCartographic.height; }); const radioOnlyNextDispatched = await page.evaluate(() => { - const button = document.getElementById('context-radio-mini-next-btn'); + const button = document.getElementById('radio-next-btn'); if (!button) return false; button.click(); return true; }); - if (!radioOnlyNextDispatched) throw new Error('Radio compact next button unavailable'); + if (!radioOnlyNextDispatched) throw new Error('Radio next button unavailable'); await page.waitForFunction(() => typeof window.__qaRejectRadioPlay === 'function'); await page.evaluate(() => { const viewer = window.__godsEyeView.viewer; @@ -3877,7 +3757,7 @@ async function main() { flyToCalls: window.__qaRadioFlyToCalls.length, flightTargets, cameraHeight: window.__qaRadioCameraHeight, - compactPlayLabel: document.getElementById('context-radio-mini-play-btn').getAttribute('aria-label'), + playLabel: document.getElementById('radio-play-btn').getAttribute('aria-label'), regularMarkerSize: Array.from({ length: window.__godsEyeView.viewer.dataSources.length }, (_, index) => window.__godsEyeView.viewer.dataSources.get(index)) .find((item) => item.name === 'Radio stations')?.entities.values[0]?.point?.pixelSize?.getValue(), selectedMarkerSize: selectedEntity?.point?.pixelSize?.getValue(), @@ -3890,7 +3770,7 @@ async function main() { }; }); check( - 'compact Next follows stable directory order and retries its next available station', + 'Radio Next follows stable directory order and retries its next available station', playing.state.selected?.id === playing.expectedFallback?.id && playing.calls[0] === playing.expectedPrimary?.streamUrl && playing.calls[1] === playing.expectedFallback?.streamUrl, @@ -3901,9 +3781,9 @@ async function main() { fallback: playing.expectedFallback?.id, }), ); - check('compact next is explicit playback and updates play/pause state', playing.calls.length === 2 && playing.compactPlayLabel.startsWith('Pause')); + check('Radio next is explicit playback and updates play/pause state', playing.calls.length === 2 && playing.playLabel.startsWith('Pause')); check( - 'compact next rotates toward its station without changing zoom, including fallback', + 'Radio next rotates toward its station without changing zoom, including fallback', playing.flyToCalls === 2 && Math.abs(playing.flightTargets[0]?.lat - playing.expectedPrimary?.lat) < 0.001 && Math.abs(playing.flightTargets[0]?.lon - playing.expectedPrimary?.lon) < 0.001 @@ -3942,11 +3822,11 @@ async function main() { }; return [ await run('flights', 'radio-next-btn'), - await run('military', 'context-radio-mini-prev-btn'), + await run('military', 'radio-prev-btn'), ]; }); check( - 'full and compact Radio navigation preserve Flights/Military camera ownership', + 'full Radio Next and Prev navigation preserve Flights/Military camera ownership', trackedRadioControls.every((sample) => sample.afterStationId && sample.afterStationId !== sample.beforeStationId && sample.flyToDelta === 0 @@ -3960,7 +3840,7 @@ async function main() { viewer.trackedEntity = undefined; window.__qaRadioDelayNextFailure = true; const beforeFlyToCalls = window.__qaRadioFlyToCalls.length; - document.getElementById('context-radio-mini-next-btn')?.click(); + document.getElementById('radio-next-btn')?.click(); return { beforeFlyToCalls }; }); await page.waitForFunction(() => typeof window.__qaRejectRadioPlay === 'function'); @@ -4236,7 +4116,7 @@ async function main() { window.__godsEyeView.dataManager.layers.get('flights').enabled = false; }); const radioOnlyNextClicked = await page.evaluate(() => { - const button = document.getElementById('context-radio-mini-next-btn'); + const button = document.getElementById('radio-next-btn'); if (!(button instanceof HTMLButtonElement)) return false; button.click(); return true; @@ -4500,106 +4380,12 @@ async function main() { && companion.radioCollapsed && !companion.contextCollapsed && companion.nested, ); - const expandedContextRadioBefore = await page.evaluate(() => { - const gev = window.__godsEyeView; - const scroller = document.querySelector('#global-context-panel .global-context-panel-inner'); - scroller.scrollTop = 0; - const camera = gev.viewer.camera.positionWC; - return { - scrollTop: scroller.scrollTop, - pageY: window.scrollY, - camera: { x: camera.x, y: camera.y, z: camera.z }, - plays: window.__qaRadioPlayCalls.length, - }; - }); - await page.click('#context-radio-toggle-btn'); - await page.waitForFunction(() => !document.getElementById('radio-panel').classList.contains('collapsed')); - await page.waitForFunction((priorScroll) => ( - document.activeElement?.getAttribute('data-collapse-target') === 'radio-panel' - && document.querySelector('#global-context-panel .global-context-panel-inner').scrollTop > priorScroll - ), { timeout: 10_000 }, expandedContextRadioBefore.scrollTop); - const expandedContextRadioAfter = await page.evaluate(() => { - const gev = window.__godsEyeView; - gev.styleManager._renderRadioState(gev.dataManager.layers.get('radio').module.getUIState()); - const launcher = document.getElementById('context-radio-toggle-btn'); - const radio = document.getElementById('radio-panel'); - const scroller = document.querySelector('#global-context-panel .global-context-panel-inner'); - const camera = gev.viewer.camera.positionWC; - return { - ariaControls: launcher.getAttribute('aria-controls'), - expanded: launcher.getAttribute('aria-expanded'), - label: launcher.getAttribute('aria-label'), - radioCollapsed: radio.classList.contains('collapsed'), - compactHidden: document.getElementById('context-radio-mini').hidden, - scrollTop: scroller.scrollTop, - focusTarget: document.activeElement?.getAttribute('data-collapse-target'), - pageY: window.scrollY, - camera: { x: camera.x, y: camera.y, z: camera.z }, - plays: window.__qaRadioPlayCalls.length, - state: gev.dataManager.layers.get('radio').module.getUIState().audioState, - }; - }); - const expandedContextRadioCameraDelta = Math.hypot( - expandedContextRadioAfter.camera.x - expandedContextRadioBefore.camera.x, - expandedContextRadioAfter.camera.y - expandedContextRadioBefore.camera.y, - expandedContextRadioAfter.camera.z - expandedContextRadioBefore.camera.z, - ); - check( - 'expanded Context Radio icon reveals and scrolls to embedded Radio without an overlay or playback/camera theft', - expandedContextRadioAfter.ariaControls === 'radio-panel' - && expandedContextRadioAfter.expanded === 'true' - && expandedContextRadioAfter.label === 'Go to expanded Radio section' - && !expandedContextRadioAfter.radioCollapsed - && expandedContextRadioAfter.compactHidden - && expandedContextRadioAfter.scrollTop > expandedContextRadioBefore.scrollTop - && expandedContextRadioAfter.focusTarget === 'radio-panel' - && expandedContextRadioAfter.pageY === expandedContextRadioBefore.pageY - && expandedContextRadioCameraDelta < 0.01 - && expandedContextRadioAfter.plays === expandedContextRadioBefore.plays - && expandedContextRadioAfter.state === 'playing', - JSON.stringify({ - before: expandedContextRadioBefore, - after: expandedContextRadioAfter, - cameraDelta: expandedContextRadioCameraDelta, - }), - ); - await page.evaluate(() => { const manager = window.__godsEyeView.styleManager; - manager.setPanelCollapsed('global-context-panel', true); - manager._setRadioDisclosure(true); + manager.setPanelCollapsed('global-context-panel', false); + manager.setPanelCollapsed('radio-panel', false); }); - await page.waitForFunction(() => { - const close = document.getElementById('context-radio-mini-close-btn'); - const rect = close.getBoundingClientRect(); - return !document.getElementById('context-radio-mini').hidden && rect.width > 0 && rect.height > 0; - }); - await page.click('#context-radio-mini-close-btn'); - const closedCompact = await page.evaluate(() => { - const launcher = document.getElementById('context-radio-toggle-btn'); - return { - radioCollapsed: document.getElementById('radio-panel').classList.contains('collapsed'), - compactHidden: document.getElementById('context-radio-mini').hidden, - focusRestored: document.activeElement === launcher, - }; - }); - await page.click('#context-radio-toggle-btn'); - await page.waitForFunction(() => !document.getElementById('context-radio-mini').hidden); - await page.click('#context-radio-details-btn'); - const repeatedOpen = await page.evaluate(() => ({ - radioCollapsed: document.getElementById('radio-panel').classList.contains('collapsed'), - compactHidden: document.getElementById('context-radio-mini').hidden, - })); - const splitDetailActions = { closedCompact, repeatedOpen }; - check( - 'collapsed Context keeps compact close and full-panel open as separate stable actions', - !splitDetailActions.closedCompact.radioCollapsed - && splitDetailActions.closedCompact.compactHidden - && splitDetailActions.closedCompact.focusRestored - && !splitDetailActions.repeatedOpen.radioCollapsed - && splitDetailActions.repeatedOpen.compactHidden, - JSON.stringify(splitDetailActions), - ); + await page.waitForFunction(() => !document.getElementById('radio-panel').classList.contains('collapsed')); await page.click('#global-context-flights-btn'); await page.waitForFunction(() => !document.getElementById('context-flights-view').hidden); diff --git a/scripts/qa-recent-imagery.mjs b/scripts/qa-recent-imagery.mjs index 1460ed3b5..89d60d96f 100644 --- a/scripts/qa-recent-imagery.mjs +++ b/scripts/qa-recent-imagery.mjs @@ -12,16 +12,22 @@ * 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. + * qa-shots/recent-imagery), QA_HEADFUL=1. + * QA_RECENT_IMAGERY_SLOW_RENDER=1 permits loaded SwiftShader CI to use a + * 4 s ZOOM IN wait and 0.8 s height-stability tail (defaults: 2 s / 1.2 s). + * Every wait is bounded. Without NASA access the run skips with code 0. */ import fs from 'node:fs'; import path from 'node:path'; import puppeteer from 'puppeteer'; +import { chromeExecutablePath } from './qa-chrome.mjs'; 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 SLOW_RENDER = process.env.QA_RECENT_IMAGERY_SLOW_RENDER === '1'; +const ZOOM_TIMEOUT_MS = SLOW_RENDER ? 4_000 : 2_000; +const HEIGHT_TAIL_SAMPLES = SLOW_RENDER ? 8 : 12; const STEP_TIMEOUT = 20_000; const AUSTIN = { lon: -97.74, lat: 30.27, height: 12_000 }; const PANEL = '#recent-imagery-panel'; @@ -49,8 +55,7 @@ const browser = await puppeteer.launch({ headless: !HEADFUL, ...(HEADFUL ? { - executablePath: - '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + executablePath: chromeExecutablePath(), } : {}), args: [ @@ -308,15 +313,21 @@ const CONTROLS = { }; const measure = () => page.evaluate((controls) => { + const panel = document.getElementById('recent-imagery-panel'); const body = document.getElementById('recent-imagery-panel-body'); + const panelRect = panel?.getBoundingClientRect(); 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; + out.rects[name] = + rect && panelRect + ? [ + rect.left - panelRect.left, + rect.top - panelRect.top, + rect.width, + rect.height, + ].map((v) => Math.round(v * 10) / 10) + : null; } return out; }, CONTROLS); @@ -372,6 +383,9 @@ try { const initialStack = await page.evaluate(() => window.__riQa.activeStack()); const photoreal = initialStack === 'photoreal'; console.log(`initial map stack: ${initialStack}`); + console.log( + `stability: ${SLOW_RENDER ? 'slow-render' : 'default'} (zoom ${ZOOM_TIMEOUT_MS} ms, last ${HEIGHT_TAIL_SAMPLES} samples)`, + ); const onPhotorealOnly = (name, passed, detail) => photoreal ? check(name, passed, detail) @@ -1042,13 +1056,13 @@ try { ) <= target * 0.01, fitHeight, - 2_000, + ZOOM_TIMEOUT_MS, ); const zoomedHeight = await page.evaluate( () => window.__godsEyeView.viewer.camera.positionCartographic.height, ); check( - `ZOOM IN flies to ${Math.round(fitHeight / 1000)} km within 2 s`, + `ZOOM IN reaches target within ${ZOOM_TIMEOUT_MS / 1_000} s`, zoomed, `height=${Math.round(zoomedHeight)} target=${Math.round(fitHeight)}`, ); @@ -1258,7 +1272,8 @@ try { ); await wait(100); } - const tail = (key) => new Set(samples.slice(8).map((s) => s[key])); + const tail = (key) => + new Set(samples.slice(-HEIGHT_TAIL_SAMPLES).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(',')}`, diff --git a/scripts/qa-scene-controls.mjs b/scripts/qa-scene-controls.mjs index 9dae69cdc..bda4a407c 100644 --- a/scripts/qa-scene-controls.mjs +++ b/scripts/qa-scene-controls.mjs @@ -66,7 +66,8 @@ try { ); }), ); - await page.click('#scene-capture-btn'); + await page.focus('#scene-capture-btn'); + await page.keyboard.press('Space'); await page.waitForFunction( () => document.querySelectorAll('.scene-shot-row').length === 1, ); @@ -105,6 +106,39 @@ try { ), ), ); + // A long rename keeps its editor visible inside the shot row. + await page.click('.scene-shot-label', { count: 2 }); + await page.waitForSelector('.scene-shot-rename', { visible: true }); + await page.type( + '.scene-shot-rename', + ' with a much longer title that runs well past the shot row', + ); + await page.keyboard.press('End'); + check( + 'A long rename keeps the editor visible inside its shot row', + await page.evaluate(() => { + // The label clips with an ellipsis, which hides an editor that + // overflows it, so its content must fit its width. + const input = document.querySelector('.scene-shot-rename'); + const label = input?.closest('.scene-shot-label'); + const box = input?.getBoundingClientRect(); + const style = input && getComputedStyle(input); + return ( + !!box && + box.width > 120 && + box.height > 10 && + label.scrollWidth <= label.clientWidth + 1 && + style.visibility === 'visible' && + style.borderTopWidth !== '0px' && + document.activeElement === input + ); + }), + ); + await page.keyboard.press('Escape'); + await page.waitForFunction( + () => !document.querySelector('.scene-shot-rename'), + ); + await page.click('#scene-capture-btn'); await page.waitForFunction( () => document.querySelectorAll('.scene-shot-row').length === 2, @@ -328,6 +362,9 @@ try { await page.keyboard.press('Escape'); await page.screenshot({ path: path.join(shots, 'desktop.png') }); await page.setViewport({ width: 390, height: 844 }); + // Phones present Scenes in the Layers tab's sheet. + await page.click('#mobile-tab-bar [data-mobile-sheet="layers"]'); + await new Promise((resolve) => setTimeout(resolve, 400)); await page.screenshot({ path: path.join(shots, 'narrow.png') }); check( 'Scene controls stay inside the narrow viewport', @@ -405,12 +442,12 @@ try { return '{"scenes":[]}'; }, }); + // A shot row held across disposal must not act once it is revoked. + const retainedLabel = document.querySelector('.scene-shot-label'); const stopping = director.destroy(); const notificationsAtStop = window.__qaSceneState.length; - const stoppedSynchronously = - controls.destroyed && - controls.removers.length === 0 && - controls.rowRemovers.length === 0; + const stoppedSynchronously = controls.destroyed; + retainedLabel?.click(); document.getElementById('scene-new-btn').click(); controls.run('capture'); finish(); @@ -419,6 +456,7 @@ try { await director.destroy(); return { stoppedSynchronously, + heldRowAction: Boolean(retainedLabel), stateStopped: window.__qaSceneState.length === notificationsAtStop, sameProject: director._project === project, noLateStatus: @@ -428,7 +466,9 @@ try { }); check( 'Disposal revokes fixed and row actions before waiting for scene work', - teardown.stoppedSynchronously && teardown.rowsGone, + teardown.stoppedSynchronously && + teardown.heldRowAction && + teardown.rowsGone, ); check( 'Late import completion cannot replace the disposed project or status', diff --git a/scripts/qa-scene-dialog-file-drop.mjs b/scripts/qa-scene-dialog-file-drop.mjs new file mode 100644 index 000000000..d6806ff72 --- /dev/null +++ b/scripts/qa-scene-dialog-file-drop.mjs @@ -0,0 +1,113 @@ +#!/usr/bin/env node +/** + * qa-scene-dialog-file-drop — the SHARE SCENE dialog's file control accepts a + * file dropped from the desktop, proved in a real browser. + * + * The dialog draws a translated row over the native file input + * (src/ui/views/panels/SceneDialog.vue). The input must still cover the row, + * or drops miss it. Drops a file on the row's centre via CDP and expects + * `input.files` to hold it. + * + * Usage: + * node scripts/qa-scene-dialog-file-drop.mjs + * + * Needs the repository's puppeteer (devDependencies). Exit status 0 when the + * drop selects the file, 1 otherwise. + */ +import http from 'node:http'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import vue from '@vitejs/plugin-vue'; +import puppeteer from 'puppeteer'; +import { createServer } from 'vite'; +import { VUE_PLUGIN_OPTIONS } from '../build/vueOptions.js'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +// The scene panels view draws the dialog; Vite compiles it for the page. +const PAGE = ` +
+`; + +async function dropOn(client, x, y, file) { + const data = { items: [], files: [file], dragOperationsMask: 1 }; + for (const type of ['dragEnter', 'dragOver', 'drop']) { + await client.send('Input.dispatchDragEvent', { type, x, y, data }); + } +} + +async function main() { + const dir = await mkdtemp(path.join(tmpdir(), 'qa-scene-dialog-drop-')); + const pack = path.join(dir, 'pack.json'); + await writeFile(pack, '{}'); + const vite = await createServer({ + root: ROOT, + configFile: false, + logLevel: 'error', + plugins: [vue(VUE_PLUGIN_OPTIONS)], + server: { middlewareMode: true, hmr: false }, + appType: 'custom', + }); + const server = http.createServer((req, res) => { + if (req.url === '/') { + res.writeHead(200, { 'content-type': 'text/html' }); + res.end(PAGE); + return; + } + vite.middlewares(req, res, () => res.writeHead(404).end()); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const url = `http://127.0.0.1:${server.address().port}/`; + const browser = await puppeteer.launch({ headless: true }); + try { + const page = await browser.newPage(); + await page.setViewport({ width: 1000, height: 800 }); + const errors = []; + page.on('pageerror', (error) => errors.push(String(error))); + await page.goto(url); + await page.waitForFunction(() => window.ready === true); + const point = await page.evaluate(() => window.openDialog()); + const client = await page.createCDPSession(); + await dropOn(client, point.x, point.y, pack); + const names = await page.evaluate(() => + [...window.filesInput.files].map((file) => file.name), + ); + console.log(JSON.stringify({ names, errors })); + if (errors.length) throw new Error(`page errors: ${errors.join('; ')}`); + if (names.length !== 1 || names[0] !== 'pack.json') { + throw new Error( + `expected the dropped pack.json to be selected, got ${JSON.stringify(names)}`, + ); + } + console.log('OK: a file dropped on the visible control is selected'); + } finally { + await browser.close(); + server.close(); + await vite.close(); + await rm(dir, { recursive: true, force: true }); + } +} + +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/scripts/qa-scope-hud.mjs b/scripts/qa-scope-hud.mjs new file mode 100644 index 000000000..1607b2631 --- /dev/null +++ b/scripts/qa-scope-hud.mjs @@ -0,0 +1,674 @@ +#!/usr/bin/env node +/** + * Scope and HUD browser acceptance. Requires the development server. + * Run: node scripts/qa-scope-hud.mjs + * Optional: QA_BASE_URL, QA_SCREENSHOT_DIR (screenshots stay outside the repo). + * Proves a fresh boot defaults to Scope ON at 100%, native checkbox click/Space, + * feather 0/11/100/200, layout independence, + * share/scene restore, and visible text backing including rotated metadata. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import puppeteer from 'puppeteer'; + +const browser = await puppeteer.launch({ + headless: true, + args: [ + '--no-sandbox', + ...(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(error.message)); +let failures = 0; +const check = (name, passed, detail) => { + console.log(`[${passed ? 'PASS' : 'FAIL'}] ${name}`); + if (!passed) { + failures += 1; + if (detail) console.log(JSON.stringify(detail)); + } +}; +const readScope = () => + page.evaluate(() => { + const scope = window.__godsEyeView.styleManager.getVisualState().scope; + const canvas = document.getElementById('scope-mask'); + const context = canvas.getContext('2d'); + const radialX = Math.round( + canvas.width / 2 + Math.min(canvas.width, canvas.height) * 0.35, + ); + return { + enabled: scope.enabled, + feather: scope.featherPct / 100, + cornerAlpha: context.getImageData(1, 1, 1, 1).data[3], + radialAlpha: context.getImageData( + radialX, + Math.round(canvas.height / 2), + 1, + 1, + ).data[3], + checked: document.getElementById('scope-toggle').checked, + disabled: document.getElementById('scope-feather-slider').disabled, + value: Number(document.getElementById('scope-feather-slider').value), + readout: document.getElementById('scope-feather-value').textContent, + }; + }); + +const readHudGlyphs = () => + page.evaluate(() => { + const hud = document.getElementById('intel-hud'); + const probe = document.createElement('span'); + probe.style.display = 'none'; + hud.appendChild(probe); + const baseline = { + color: getComputedStyle(probe).color, + shadow: getComputedStyle(probe).textShadow, + }; + probe.remove(); + const glyphs = [ + '.hud-mode', + '.hud-system', + '.hud-summary-label', + '.hud-summary', + '.hud-orbital', + '#hud-mgrs', + '#hud-coll', + ].map((selector) => { + const el = hud.querySelector(selector); + const style = getComputedStyle(el); + let opacity = 1; + for ( + let current = el; + current && current !== hud; + current = current.parentElement + ) + opacity *= Number(getComputedStyle(current).opacity); + return { + selector, + color: style.color, + shadow: style.textShadow, + opacity, + }; + }); + return { baseline, glyphs }; + }); + +async function settleTextBackings(enabled) { + // The pre-existing active-style value transitions all properties for 300ms. + // Wait for its backing to finish changing before inspecting or capturing it. + await page + .waitForFunction( + (scopeEnabled) => { + const expected = scopeEnabled + ? 'rgba(0, 0, 0, 0)' + : 'rgba(0, 0, 0, 0.7)'; + return [ + ...document.querySelectorAll( + '#intel-hud .hud-readout, .scene-text-holdout', + ), + ].every( + (el) => + getComputedStyle(el).backgroundColor === expected && + getComputedStyle(el).boxShadow === 'none', + ); + }, + { timeout: 2_000 }, + enabled, + ) + .catch(() => null); +} + +const readSceneChrome = () => + page.evaluate(() => { + const title = document.querySelector('#title-bar h1'); + const eye = title.querySelector('.title-logo'); + const subtitle = document.querySelector('#title-bar .subtitle'); + const label = document.querySelector('#style-indicator .indicator-label'); + const rect = (el, text = false) => { + if (!el.getClientRects().length) return null; + const range = document.createRange(); + range.selectNodeContents(el); + const box = text + ? range.getBoundingClientRect() + : el.getBoundingClientRect(); + return { + left: box.left, + top: box.top, + right: box.right, + bottom: box.bottom, + }; + }; + const titleBox = rect(title); + const eyeBox = rect(eye); + const backing = getComputedStyle(title, '::before'); + const plate = { + left: titleBox.left + parseFloat(backing.left), + top: titleBox.top + parseFloat(backing.top), + right: titleBox.right - parseFloat(backing.right), + bottom: titleBox.bottom - parseFloat(backing.bottom), + }; + const contains = (box) => + Object.entries(box).every(([side, value]) => + ['left', 'top'].includes(side) + ? plate[side] <= value + 0.5 + : plate[side] >= value - 0.5, + ); + const probe = document.createElement('span'); + document.body.appendChild(probe); + probe.style.color = 'var(--text-dim)'; + const dim = getComputedStyle(probe).color; + probe.style.color = 'var(--text-secondary)'; + const secondary = getComputedStyle(probe).color; + probe.remove(); + return { + positions: { + title: titleBox, + eye: eyeBox, + text: rect(title.querySelector('[translate="no"]'), true), + subtitle: rect(subtitle, true), + }, + titleUnbacked: backing.backgroundColor === 'rgba(0, 0, 0, 0)', + titleCovered: + backing.position === 'absolute' && + backing.backgroundColor === 'rgba(0, 0, 0, 0.7)' && + contains(titleBox) && + contains(eyeBox), + leftAligned: + !rect(subtitle) || Math.abs(plate.left - rect(subtitle).left) <= 0.5, + colors: [getComputedStyle(subtitle).color, getComputedStyle(label).color], + dim, + secondary, + }; + }); + +function checkSceneChrome(name, before, after) { + const stable = Object.keys(before.positions).every((key) => { + const a = before.positions[key]; + const b = after.positions[key]; + return a && b + ? Object.keys(a).every((side) => Math.abs(a[side] - b[side]) <= 0.5) + : a === b; + }); + check(`${name}: title, eye and subtitle stay in place across Scope`, stable, { + before, + after, + }); + check( + `${name}: OFF title plate covers the eye and aligns with the subtitle`, + before.titleUnbacked && after.titleCovered && after.leftAligned, + after, + ); + check( + `${name}: secondary labels brighten only with Scope OFF`, + before.colors.every((color) => color === before.dim) && + after.colors.every((color) => color === after.secondary), + { before: before.colors, after: after.colors }, + ); +} + +async function openApplication(url) { + await page.goto(url.href, { waitUntil: 'domcontentloaded' }); + await page.waitForFunction( + () => window.__godsEyeView?.styleManager?._applicationShortcuts, + { timeout: 60_000 }, + ); + await page.waitForFunction( + () => { + const cover = document.getElementById('loading-screen'); + return ( + cover?.classList.contains('hidden') && + Number(getComputedStyle(cover).opacity) === 0 + ); + }, + { timeout: 60_000 }, + ); +} + +try { + await page.setViewport({ width: 1440, height: 900 }); + const url = new URL(process.env.QA_BASE_URL || 'http://127.0.0.1:4173'); + url.searchParams.set('welcome', '0'); + // This browser has a fresh profile. Start without authored state so the + // first assertion exercises the defaults rather than a share-link restore. + url.hash = ''; + await openApplication(url); + const fresh = await readScope(); + check( + 'bare-URL fresh boot opens Scope ON with 100% feather', + fresh.enabled && + fresh.checked && + !fresh.disabled && + fresh.feather === 1 && + fresh.value === 100 && + fresh.readout === '100%' && + fresh.cornerAlpha > 0, + fresh, + ); + + // Use a known city view for canvas and readability checks below. + url.hash = + 'v=2&lat=30.2672&lon=-97.7431&alt=2500&heading=0&pitch=-45&roll=0&map=esri&sc=1&scf=100&l='; + // Changing only the hash does not rerun startup restoration. Leave the app + // document first so this fixture is applied by a new application boot. + await page.goto('about:blank'); + await openApplication(url); + await page.evaluate(() => { + const manager = window.__godsEyeView.styleManager; + manager.setPanelCollapsed('pp-toggles', false, { + persist: false, + syncShare: false, + }); + manager.hud.setMode('on'); + manager.setStyle('normal'); + }); + const initial = await readScope(); + check( + 'Austin fixture restores Scope ON and 100% feather', + initial.enabled && + initial.checked && + !initial.disabled && + initial.feather === 1 && + initial.value === 100 && + initial.readout === '100%' && + initial.cornerAlpha > 0, + initial, + ); + const name = await page.$eval('#scope-toggle', (el) => ({ + type: el.type, + label: el.labels?.[0]?.textContent.trim(), + })); + check( + 'Scope uses a native checkbox with a visible label', + name.type === 'checkbox' && name.label?.includes('Scope'), + name, + ); + await page.click('#scope-toggle'); + const off = await readScope(); + check( + 'click disables Scope and its feather slider', + !off.enabled && + !off.checked && + off.disabled && + off.feather === 1 && + off.cornerAlpha === 0, + off, + ); + await page.focus('#scope-toggle'); + await page.keyboard.press('Space'); + const on = await readScope(); + check( + 'Space re-enables the native checkbox without losing feather', + on.enabled && + on.checked && + !on.disabled && + on.feather === 1 && + on.cornerAlpha > 0, + on, + ); + + const paintedAlpha = []; + for (const pct of [0, 11, 100, 200]) { + await page.$eval( + '#scope-feather-slider', + (el, value) => { + el.value = String(value); + el.dispatchEvent(new Event('input', { bubbles: true })); + }, + pct, + ); + const state = await readScope(); + paintedAlpha.push(state.radialAlpha); + check( + `feather ${pct}% reaches the mask and readout`, + state.value === pct && + state.feather === pct / 100 && + state.readout === `${pct}%`, + state, + ); + } + check( + 'painted gradient widens beyond the old 100% ceiling', + paintedAlpha[0] === 0 && + paintedAlpha[1] === 0 && + paintedAlpha[2] > 0 && + paintedAlpha[3] > paintedAlpha[2], + paintedAlpha, + ); + await page.focus('#scope-feather-slider'); + await page.keyboard.press('Home'); + check('native Home reaches the hard edge', (await readScope()).feather === 0); + await page.keyboard.press('End'); + check( + 'native End reaches the expanded 200% maximum', + (await readScope()).feather === 2, + ); + await page.click('#scope-toggle'); + for (const layout of ['minimal', 'cyber', 'tactical']) { + await page.select('#hud-layout-select', layout); + const state = await readScope(); + check( + `Scope OFF and 200% survive ${layout}`, + !state.enabled && + !state.checked && + state.disabled && + state.feather === 2 && + state.value === 200 && + state.cornerAlpha === 0, + state, + ); + } + + const restored = await page.evaluate(async () => { + const manager = window.__godsEyeView.styleManager; + const links = manager.shareLinkManager; + manager._syncShareState(); + const params = links._buildHashParams(); + const encoded = { enabled: params.get('sc'), feather: params.get('scf') }; + await manager.applyVisualState({ scope: { enabled: true, featherPct: 0 } }); + await manager._visualSettings.restoreShareState({ + scopeEnabled: encoded.enabled === '1', + scopeFeatherPct: Number(encoded.feather), + }); + const shared = manager.getVisualState().scope; + await manager.applyVisualState({ + scope: { enabled: true, featherPct: 200 }, + }); + const scene = manager.getVisualState().scope; + await manager.applyVisualState({ + scope: { enabled: false, featherPct: 200 }, + }); + return { encoded, shared, scene }; + }); + check( + 'share state serializes and restores Scope OFF with 200%', + restored.encoded.enabled === '0' && + restored.encoded.feather === '200' && + restored.shared.enabled === false && + restored.shared.featherPct === 200, + restored, + ); + check( + 'scene state restores Scope ON with 200%', + restored.scene.enabled === true && restored.scene.featherPct === 200, + restored, + ); + + for (const layout of ['minimal', 'tactical']) { + await page.select('#hud-layout-select', layout); + await page.evaluate(() => + window.__godsEyeView.styleManager.applyVisualState({ + scope: { enabled: true, featherPct: 100 }, + }), + ); + await settleTextBackings(true); + const originalGlyphs = await readHudGlyphs(); + const originalChrome = await readSceneChrome(); + const original = await page.evaluate(() => { + const hud = document.getElementById('intel-hud'); + const wrappers = [...hud.querySelectorAll('.hud-readout')]; + const scene = [...document.querySelectorAll('.scene-text-holdout')]; + const unexpectedBackings = [...wrappers, ...scene] + .map((el) => { + const style = getComputedStyle(el); + return { + selector: el.id || el.className, + background: style.backgroundColor, + shadow: style.boxShadow, + }; + }) + .filter( + (style) => + style.background !== 'rgba(0, 0, 0, 0)' || style.shadow !== 'none', + ); + return { + markerAbsent: !document.documentElement.hasAttribute('data-scope-mask'), + unbacked: unexpectedBackings.length === 0, + unexpectedBackings, + wrappersTransparent: wrappers.every( + (el) => getComputedStyle(el).display === 'contents', + ), + }; + }); + check( + `${layout}: Scope ON retains the original presentation without new backplates`, + original.markerAbsent && + original.unbacked && + original.wrappersTransparent, + original, + ); + check( + `${layout}: original HUD color, glow and metadata alpha remain intact`, + originalGlyphs.glyphs.every( + (glyph) => + glyph.color === originalGlyphs.baseline.color && + glyph.shadow === originalGlyphs.baseline.shadow, + ) && + originalGlyphs.glyphs.find( + (glyph) => glyph.selector === '.hud-summary-label', + ).opacity === 0.55 && + originalGlyphs.glyphs.find((glyph) => glyph.selector === '.hud-orbital') + .opacity === 0.7 && + originalGlyphs.glyphs.find((glyph) => glyph.selector === '#hud-coll') + .opacity === 0.5, + originalGlyphs, + ); + if (process.env.QA_SCREENSHOT_DIR) { + fs.mkdirSync(process.env.QA_SCREENSHOT_DIR, { recursive: true }); + await page.screenshot({ + path: path.join( + process.env.QA_SCREENSHOT_DIR, + `scope-on-${layout}.png`, + ), + }); + } + await page.evaluate(() => + window.__godsEyeView.styleManager.applyVisualState({ + scope: { enabled: false }, + }), + ); + await settleTextBackings(false); + const backedGlyphs = await readHudGlyphs(); + checkSceneChrome(layout, originalChrome, await readSceneChrome()); + check( + `${layout}: Scope OFF adds backing without changing glyph styles`, + JSON.stringify(backedGlyphs) === JSON.stringify(originalGlyphs), + backedGlyphs, + ); + const coverage = await page.evaluate(() => { + const hud = document.getElementById('intel-hud'); + const walker = document.createTreeWalker(hud, NodeFilter.SHOW_TEXT); + const missing = []; + let visible = 0; + let node; + while ((node = walker.nextNode())) { + if ( + !node.textContent.trim() || + node.parentElement.closest('.hud-bracket') + ) + continue; + const range = document.createRange(); + range.selectNodeContents(node); + if ( + ![...range.getClientRects()].some( + (rect) => rect.width > 0 && rect.height > 0, + ) + ) + continue; + visible += 1; + const backing = node.parentElement.closest('.hud-readout'); + const color = backing && getComputedStyle(backing).backgroundColor; + if ( + !backing || + color !== 'rgba(0, 0, 0, 0.7)' || + getComputedStyle(backing).boxShadow !== 'none' || + backing.parentElement.closest('.hud-readout') + ) + missing.push(node.textContent.trim()); + } + const wrapped = [...hud.querySelectorAll('.hud-readout')].filter( + (el) => el.offsetWidth > 0 && el.offsetHeight > 0, + ); + const empty = wrapped.filter((el) => !el.innerText.trim()).length; + const overlaps = []; + for (const parent of new Set(wrapped.map((el) => el.parentElement))) { + const siblings = wrapped.filter((el) => el.parentElement === parent); + for (let i = 1; i < siblings.length; i += 1) { + const previous = siblings[i - 1].getBoundingClientRect(); + const current = siblings[i].getBoundingClientRect(); + const horizontal = + Math.min(previous.right, current.right) - + Math.max(previous.left, current.left); + const vertical = + Math.min(previous.bottom, current.bottom) - + Math.max(previous.top, current.top); + // Horizontal bars share a vertical band. Only intersecting text boxes + // can stack their backing alpha; allow subpixel layout rounding. + if (horizontal > 0.5 && vertical > 0.5) { + overlaps.push({ + parent: parent.className, + previous: siblings[i - 1].innerText, + current: siblings[i].innerText, + vertical, + }); + } + } + } + const lineIds = [ + 'hud-mgrs', + 'hud-latlon', + 'hud-gsd', + 'hud-alt', + 'hud-timestamp', + 'hud-bottom-line', + ]; + const multiline = lineIds.filter((id) => { + const el = document.getElementById(id); + if (!el.getClientRects().length) return false; + const range = document.createRange(); + range.selectNodeContents(el); + return ( + range.getBoundingClientRect().height > + parseFloat(getComputedStyle(el).lineHeight) * 1.5 + ); + }); + const edges = [...hud.querySelectorAll('.hud-edge')] + .filter((el) => getComputedStyle(el).display !== 'none') + .map((el) => { + const box = el.querySelector('.hud-readout').getBoundingClientRect(); + return ( + getComputedStyle(el).transform !== 'none' && + box.height > box.width && + Number(getComputedStyle(el).opacity) === 1 + ); + }); + const broadBackings = [ + ...hud.querySelectorAll('.hud-corner, .hud-bottom-bar'), + ].filter( + (el) => + el.offsetWidth > 0 && + getComputedStyle(el).backgroundColor !== 'rgba(0, 0, 0, 0)', + ); + return { + scopeOff: document.documentElement.dataset.scopeMask === 'off', + visible, + missing, + empty, + overlaps, + multiline, + edges, + broadBackings: broadBackings.length, + }; + }); + check( + `${layout}: all visible HUD text has one backing`, + coverage.scopeOff && + coverage.visible > 0 && + coverage.missing.length === 0 && + coverage.empty === 0 && + coverage.broadBackings === 0, + coverage, + ); + check( + `${layout}: adjacent readout backings do not overlap`, + coverage.overlaps.length === 0, + coverage, + ); + check( + `${layout}: desktop telemetry remains single line; rotated backing follows the labels`, + coverage.multiline.length === 0 && coverage.edges.every(Boolean), + coverage, + ); + if (process.env.QA_SCREENSHOT_DIR) { + fs.mkdirSync(process.env.QA_SCREENSHOT_DIR, { recursive: true }); + await page.screenshot({ + path: path.join( + process.env.QA_SCREENSHOT_DIR, + `scope-off-${layout}.png`, + ), + }); + } + } + const details = await page.evaluate(() => { + const summary = document.getElementById('hud-summary'); + summary.textContent = 'LONG TELEMETRY SUMMARY '.repeat(30); + const ais = document.getElementById('hud-ais-vessel'); + ais.textContent = 'AIS: 4 VESSELS\nLATEST OBSERVATION'; + return { + summaryClipped: + summary.scrollWidth > summary.clientWidth && + getComputedStyle(summary).textOverflow === 'ellipsis', + aisMultiline: + getComputedStyle(ais).whiteSpace === 'pre-line' && + ais.textContent.split('\n').length === 2 && + ais.getBoundingClientRect().height + 0.5 >= + parseFloat(getComputedStyle(ais).lineHeight) * 2, + recColor: getComputedStyle(document.getElementById('hud-rec-dot')).color, + }; + }); + check( + 'summary clipping, multiline AIS and red REC dot retain their behavior', + details.summaryClipped && + details.aisMultiline && + details.recColor === 'rgb(255, 51, 51)', + details, + ); + await page.setViewport({ width: 390, height: 844 }); + await page.select('#hud-layout-select', 'minimal'); + const narrow = await page.evaluate(() => + [...document.querySelectorAll('#intel-hud .hud-readout')] + .filter( + (el) => + el.getClientRects().length && + getComputedStyle(el).display !== 'contents', + ) + .every((el) => { + const box = el.getBoundingClientRect(); + return box.left >= 0 && box.right <= innerWidth; + }), + ); + check('narrow HUD text backings stay within the viewport', narrow); + for (const layout of ['minimal', 'tactical']) { + await page.select('#hud-layout-select', layout); + await page.evaluate(() => + window.__godsEyeView.styleManager.applyVisualState({ + scope: { enabled: true }, + }), + ); + await settleTextBackings(true); + const before = await readSceneChrome(); + await page.evaluate(() => + window.__godsEyeView.styleManager.applyVisualState({ + scope: { enabled: false }, + }), + ); + await settleTextBackings(false); + checkSceneChrome(`narrow ${layout}`, before, await readSceneChrome()); + } + check('runtime has no uncaught browser errors', errors.length === 0, errors); +} finally { + await browser.close(); +} +console.log(`RESULT: ${failures} failures`); +process.exitCode = failures ? 1 : 0; diff --git a/scripts/qa-segmented-controls.mjs b/scripts/qa-segmented-controls.mjs new file mode 100644 index 000000000..8612c2f23 --- /dev/null +++ b/scripts/qa-segmented-controls.mjs @@ -0,0 +1,322 @@ +#!/usr/bin/env node +/** Run against a dev server or built preview with QA_BASE_URL (default :4179). */ +import fs from 'node:fs'; +import puppeteer from 'puppeteer'; + +const browser = await puppeteer.launch({ + executablePath: + process.env.PUPPETEER_EXECUTABLE_PATH || (await puppeteer.executablePath()), + headless: true, + args: ['--use-gl=angle', '--use-angle=swiftshader'], +}); +const page = await browser.newPage(); +const errors = []; +const failures = []; +page.on('pageerror', (error) => errors.push(error.message)); +const check = (name, passed, detail = '') => { + console.log( + `[${passed ? 'PASS' : 'FAIL'}] ${name}${detail ? ` — ${detail}` : ''}`, + ); + if (!passed) failures.push(name); +}; +const base = process.env.QA_BASE_URL || 'http://localhost:4179'; +const shots = process.env.QA_SHOTS_DIR || 'qa-shots/segmented-controls'; +fs.mkdirSync(shots, { recursive: true }); + +try { + await page.setViewport({ width: 1440, height: 900 }); + await page.goto(`${base}/?welcome=0`, { waitUntil: 'domcontentloaded' }); + await page.waitForFunction( + () => window.__godsEyeView?.styleManager?._applicationShortcuts, + { timeout: 60000 }, + ); + await page.waitForFunction( + () => + document.getElementById('loading-screen')?.classList.contains('hidden'), + { timeout: 60000 }, + ); + await page.evaluate(() => + window.__godsEyeView.styleManager.setPanelCollapsed('pp-toggles', false, { + persist: false, + syncShare: false, + }), + ); + + const surface = await page.evaluate(() => { + const groups = [...document.querySelectorAll('[role="radiogroup"]')]; + const buttons = groups.flatMap((group) => [ + ...group.querySelectorAll('[role="radio"]'), + ]); + return { + groups: groups.length, + buttons: buttons.length, + shared: + groups.every((g) => g.classList.contains('gev-segmented')) && + buttons.every((b) => { + const style = getComputedStyle(b); + return ( + b.classList.contains('gev-segment') && + style.fontSize === '9px' && + style.minHeight === '24px' && + style.borderRadius === '0px' + ); + }), + }; + }); + check( + 'all six one-of-many groups use the shared surface', + surface.groups === 6 && surface.buttons === 15 && surface.shared, + JSON.stringify(surface), + ); + + await page.evaluate(() => + document.getElementById('models3d-mode-all').click(), + ); + check( + 'model selection reaches both aircraft layers', + await page.evaluate(() => { + const dm = window.__godsEyeView.dataManager; + return ( + ['flights', 'military'].every( + (id) => dm.layers.get(id).module.getParams().models3dMode === 'all', + ) && + document + .getElementById('models3d-mode-all') + .getAttribute('aria-checked') === 'true' + ); + }), + ); + await page.focus('#models3d-mode-all'); + await page.keyboard.press('ArrowLeft'); + check( + 'Display retains its click-only arrow policy', + await page.evaluate( + () => + document + .getElementById('models3d-mode-all') + .getAttribute('aria-checked') === 'true', + ), + ); + await page.focus('#models3d-mode-proximity'); + await page.keyboard.press('Space'); + check( + 'native Space selects model coverage', + await page.evaluate( + () => + document + .getElementById('models3d-mode-proximity') + .getAttribute('aria-checked') === 'true', + ), + ); + await page.evaluate(() => + document.getElementById('detection-allocation-weighted').click(), + ); + check( + 'allocation selection still updates application tuning', + await page.evaluate( + () => + window.__godsEyeView.styleManager._detectionAllocationPreference === + 'WEIGHTED' && + document + .getElementById('detection-allocation-weighted') + .getAttribute('aria-checked') === 'true', + ), + ); + + await page.evaluate(() => + document.querySelector('[data-shape="pin"]').click(), + ); + check( + 'drawing shape still uses its existing feature action', + await page.evaluate( + () => + window.__gevDrawTool?.shape === 'pin' && + document + .querySelector('[data-shape="pin"]') + .getAttribute('aria-checked') === 'true', + ), + ); + + // Off-layer controls still own params; no catalog/provider request is needed. + await page.evaluate(() => + document.querySelector('[data-sl-pano="flat"]').click(), + ); + check( + 'panorama choice reaches the Street Level layer', + await page.evaluate( + () => + window.__godsEyeView.dataManager.layers + .get('street-level') + .module.getParams().pano === 'flat', + ), + ); + await page.evaluate(() => + document.querySelector('[data-sl-pano="flat"]').dispatchEvent( + new KeyboardEvent('keydown', { + key: 'Home', + bubbles: true, + cancelable: true, + }), + ), + ); + check( + 'Street Level Home retains selection and roving tab state', + await page.evaluate( + () => + window.__godsEyeView.dataManager.layers + .get('street-level') + .module.getParams().pano === 'all' && + document + .querySelector('[data-sl-pano="all"]') + .getAttribute('tabindex') === '0', + ), + ); + await page.evaluate(() => + document.querySelector('[data-sl-render="fill"]').click(), + ); + check( + 'fit/fill keeps its stored render preference', + await page.evaluate( + () => + localStorage.getItem('gev:street-level:render-mode') === 'fill' && + document + .querySelector('[data-sl-render="fill"]') + .getAttribute('aria-checked') === 'true', + ), + ); + + await page.evaluate(() => + document.querySelector('.ri-mode-btn[data-mode="ab"]').click(), + ); + check( + 'imagery mode reaches its controlled layer state', + await page.evaluate( + () => + window.__godsEyeView.dataManager.layers + .get('recent-imagery') + .module.getSnapshot().mode === 'ab', + ), + ); + await page.evaluate(() => + document.getElementById('ri-mode').dispatchEvent( + new KeyboardEvent('keydown', { + key: 'ArrowRight', + bubbles: true, + cancelable: true, + }), + ), + ); + check( + 'imagery arrows wrap from the current selected value', + await page.evaluate( + () => + window.__godsEyeView.dataManager.layers + .get('recent-imagery') + .module.getSnapshot().mode === 'image' && + document + .querySelector('.ri-mode-btn[data-mode="image"]') + .getAttribute('aria-checked') === 'true', + ), + ); + + await page.evaluate(() => { + const manager = window.__godsEyeView.styleManager; + manager._setDetectionAllocation('ELASTIC', { + syncShare: false, + persist: false, + }); + document + .getElementById('models3d-mode-proximity') + .scrollIntoView({ block: 'center' }); + }); + await page.screenshot({ path: `${shots}/desktop.png` }); + await page.setViewport({ width: 620, height: 900 }); + await page.evaluate(() => + document + .getElementById('models3d-mode-proximity') + .scrollIntoView({ block: 'center' }), + ); + await page.screenshot({ path: `${shots}/narrow.png` }); + check( + 'narrow selectors stay within their panel', + await page.evaluate(() => + [...document.querySelectorAll('.pp-mode-seg')] + .filter((g) => g.getClientRects().length) + .every((group) => group.scrollWidth <= group.clientWidth + 1), + ), + ); + const cyber = await page.evaluate(() => { + const root = document.documentElement; + const previous = root.getAttribute('data-ui-theme'); + root.setAttribute('data-ui-theme', 'cyber'); + const selected = [ + ...document.querySelectorAll('.gev-segment[aria-checked="true"]'), + ]; + // Check the final theme colors, independent of software-GL frame cadence. + for (const button of selected) + for (const animation of button.getAnimations()) animation.finish(); + const backgrounds = selected.map( + (button) => getComputedStyle(button).backgroundColor, + ); + const radii = [...document.querySelectorAll('.gev-segmented')].map( + (group) => getComputedStyle(group).borderRadius, + ); + const consistent = + selected.length === 6 && + backgrounds.every((color) => color === backgrounds[0]) && + radii.every((radius) => radius === '1px'); + if (previous === null) root.removeAttribute('data-ui-theme'); + else root.setAttribute('data-ui-theme', previous); + return { consistent, count: selected.length, backgrounds, radii }; + }); + check( + 'Cyber theme styles every selected segment consistently', + cyber.consistent, + JSON.stringify(cyber), + ); + await page.evaluate(async () => { + const { dataManager, styleManager } = window.__godsEyeView; + await dataManager.setEnabled('recent-imagery', true); + styleManager.setPanelCollapsed('recent-imagery-panel', false, { + persist: false, + syncShare: false, + }); + }); + for (const width of [1440, 620, 390]) { + await page.setViewport({ width, height: 900 }); + await page.focus('.ri-mode-btn[aria-checked="true"]'); + const modeLayout = await page.evaluate(() => { + const group = document.getElementById('ri-mode'); + const bounds = group.getBoundingClientRect(); + const style = getComputedStyle(group); + const top = bounds.top + parseFloat(style.borderTopWidth); + const bottom = bounds.bottom - parseFloat(style.borderBottomWidth); + const buttons = [...group.querySelectorAll('[role="radio"]')]; + return { + visible: bounds.width > 0 && bounds.height > 0, + contained: buttons.every((button) => { + const rect = button.getBoundingClientRect(); + return rect.top >= top - 0.5 && rect.bottom <= bottom + 0.5; + }), + groupHeight: bounds.height, + buttonHeights: buttons.map( + (button) => button.getBoundingClientRect().height, + ), + }; + }); + check( + `imagery mode buttons and focus outline fit their row at ${width}px`, + modeLayout.visible && modeLayout.contained, + JSON.stringify(modeLayout), + ); + } + check('no uncaught browser errors', errors.length === 0, errors.join(' | ')); +} catch (error) { + console.error('Browser errors:', errors); + await page.screenshot({ path: `${shots}/failure.png` }).catch(() => {}); + throw error; +} finally { + await browser.close(); +} +console.log(`RESULT: ${failures.length} failures`); +process.exitCode = failures.length ? 1 : 0; diff --git a/scripts/qa-sky-model-lighting.mjs b/scripts/qa-sky-model-lighting.mjs new file mode 100644 index 000000000..2f401506b --- /dev/null +++ b/scripts/qa-sky-model-lighting.mjs @@ -0,0 +1,147 @@ +#!/usr/bin/env node +/** + * Lit airplane regression: StarrySky must match a black environment baseline. + * A white environment is a positive control: it must visibly brighten the + * same model. Each case uses a fresh scene and dynamic environment map. + * Usage: node scripts/qa-sky-model-lighting.mjs [--url http://localhost:4333/] + */ +import assert from 'node:assert/strict'; +import puppeteer from 'puppeteer'; + +const i = process.argv.indexOf('--url'); +const base = i > 0 ? process.argv[i + 1] : 'http://localhost:4333/'; +const url = new URL('/__qa_sky_model__', base); +const browser = await puppeteer.launch({ + headless: true, + args: ['--no-sandbox', '--ignore-gpu-blocklist'], +}); +try { + const page = await browser.newPage(); + page.on('pageerror', (error) => console.log('PAGEERR', error.message)); + await page.setRequestInterception(true); + page.on('request', (request) => { + if (request.url() === url.href) + request.respond({ + contentType: 'text/html', + body: '', + }); + else if (new URL(request.url()).origin !== url.origin) request.abort(); + else request.continue(); + }); + await page.goto(url.href); + const results = await page.evaluate(async () => { + window.CESIUM_BASE_URL = '/cesium/'; + // Use StarrySky's exact Vite dependency URL, including its version query. + const source = await fetch('/src/sky/starrySky.js').then((r) => r.text()); + const cesiumUrl = source.match( + /from ["']([^"']*\/cesium\.js[^"']*)["']/, + )?.[1]; + if (!cesiumUrl) throw new Error('run against the Vite dev server'); + const C = await import(cesiumUrl); + const { StarrySky } = await import('/src/sky/starrySky.js'); + const time = C.JulianDate.fromIso8601('2026-10-19T00:00:00Z'); + const results = {}; + for (const kind of ['black', 'starry', 'white']) { + const canvas = document.createElement('canvas'); + canvas.width = 400; + canvas.height = 300; + document.body.append(canvas); + const scene = new C.Scene({ canvas }); + scene.rethrowRenderErrors = true; + let cubeMap; + try { + scene.backgroundColor = C.Color.BLACK; + scene.light = new C.DirectionalLight({ + direction: new C.Cartesian3(1, 0, 0), + intensity: 0.2, + }); + if (kind === 'starry') { + scene.skyBox = new StarrySky({ requestRender() {} }); + scene.skyBox._loading = true; // visible sky is outside this probe + } else { + const value = kind === 'white' ? 255 : 0; + const face = { + width: 1, + height: 1, + arrayBufferView: new Uint8Array([value, value, value, 255]), + }; + cubeMap = new C.CubeMap({ + context: scene.context, + source: Object.fromEntries( + [...C.CubeMap.faceNames()].map((name) => [name, face]), + ), + }); + scene.skyBox = { _cubeMap: cubeMap, update() {}, destroy() {} }; + } + const position = C.Cartesian3.fromDegrees(0, 0, 10000); + const model = await C.Model.fromGltfAsync({ + url: '/models/airplane.glb', + modelMatrix: C.Transforms.eastNorthUpToFixedFrame(position), + }); + scene.primitives.add(model); + scene.camera.lookAt(position, new C.HeadingPitchRange(0.4, -0.5, 45)); + let framed = false; + for (let frame = 0; frame < 240; frame++) { + scene.initializeFrame(); + scene.render(time); + if (model.ready && !framed) { + scene.camera.viewBoundingSphere( + model.boundingSphere, + new C.HeadingPitchRange( + 0.4, + -0.5, + model.boundingSphere.radius * 3, + ), + ); + framed = true; + } + await new Promise(requestAnimationFrame); + } + if (!model.ready || !model.environmentMapManager.radianceCubeMap) + throw new Error(`${kind}: model or dynamic lighting did not load`); + scene.initializeFrame(); + scene.render(time); + const gl = scene.context._gl; + const px = new Uint8Array(canvas.width * canvas.height * 4); + gl.readPixels( + 0, + 0, + canvas.width, + canvas.height, + gl.RGBA, + gl.UNSIGNED_BYTE, + px, + ); + let total = 0; + let visible = 0; + for (let p = 0; p < px.length; p += 4) { + const luma = 0.299 * px[p] + 0.587 * px[p + 1] + 0.114 * px[p + 2]; + total += luma; + if (luma > 1) visible++; + } + results[kind] = { total, visible }; + } finally { + scene.destroy(); + cubeMap?.destroy(); + canvas.remove(); + } + } + return results; + }); + console.log(JSON.stringify(results)); + assert.ok(results.black.visible > 100, 'the lit model must be visible'); + assert.ok( + Math.abs(results.starry.total - results.black.total) <= + results.black.total * 0.01, + 'StarrySky must match black environment lighting within 1%', + ); + assert.ok( + results.white.total > results.black.total * 1.03, + 'white environment control must brighten the model by at least 3%', + ); + console.log( + 'PASS: lit airplane matches black sky; white control is brighter', + ); +} finally { + await browser.close(); +} diff --git a/scripts/qa-status-badges.mjs b/scripts/qa-status-badges.mjs new file mode 100644 index 000000000..1d3b7347b --- /dev/null +++ b/scripts/qa-status-badges.mjs @@ -0,0 +1,278 @@ +#!/usr/bin/env node +/** Badge acceptance on dev/preview. Camera state is a disposable controller fixture. */ +import fs from 'node:fs'; +import puppeteer from 'puppeteer'; + +const browser = await puppeteer.launch({ + headless: true, + args: ['--use-gl=angle', '--use-angle=swiftshader'], +}); +const page = await browser.newPage(); +page.setDefaultNavigationTimeout(60000); +const errors = []; +page.on('pageerror', (error) => errors.push(error.message)); +let checks = 0; +let failures = 0; +const check = (name, passed, detail) => { + checks++; + console.log(`[${passed ? 'PASS' : 'FAIL'}] ${name}`); + if (!passed) { + failures++; + console.log(JSON.stringify(detail)); + } +}; +const out = 'qa-shots/status-badges'; +fs.mkdirSync(out, { recursive: true }); +try { + for (const lang of ['en', 'ru']) { + await page.setViewport({ width: 1440, height: 900 }); + await page.goto( + `${process.env.QA_BASE_URL || 'http://127.0.0.1:4189'}/?welcome=0&lang=${lang}`, + { waitUntil: 'domcontentloaded' }, + ); + await page.waitForFunction( + () => + window.__godsEyeView?.styleManager?._cctvControls && + document.getElementById('loading-screen')?.classList.contains('hidden'), + { timeout: 60000 }, + ); + await page.evaluate(async () => { + const { dataManager, styleManager: manager } = window.__godsEyeView; + await dataManager.setEnabled('wind', true); + manager.setPanelCollapsed('weather-panel', false, { + persist: false, + syncShare: false, + }); + manager.setPanelCollapsed('cctv-panel', false, { + persist: false, + syncShare: false, + }); + const owner = manager._cctvControls; + owner._cctvUnsubscribe?.(); + owner._cctvUnsubscribe = null; + owner.actions = { ...owner.actions, isEnabled: () => true }; + owner._renderCctvState({ + enabled: true, + activeCameraId: 'badge-fixture', + cameras: [{ id: 'badge-fixture', city: 'QA', name: 'Badge fixture' }], + activeCamera: { + id: 'badge-fixture', + city: 'QA', + headingDeg: 30, + pitchDeg: -10, + fovDeg: 45, + rangeM: 120, + mountHeightM: 8, + sourceKind: 'snapshot', + sourceStatus: 'degraded', + calBadge: 'curated', + calDirty: false, + }, + }); + }); + await page.waitForSelector('.weather-coverage.gev-status-badge'); + const inventory = await page.evaluate(() => { + const source = document.getElementById('cctv-source-badge'); + const quality = document.getElementById('cctv-quality-chip'); + const coverage = [...document.querySelectorAll('.weather-coverage')]; + return { + shared: [source, quality, ...coverage].every((node) => + node.classList.contains('gev-status-badge'), + ), + live: + source.getAttribute('role') === 'status' && + source.getAttribute('aria-live') === 'polite', + silent: [quality, ...coverage].every( + (node) => + !node.hasAttribute('aria-live') && + !node.hasAttribute('role') && + !node.hasAttribute('tabindex'), + ), + coverage: + coverage.length > 0 && + coverage.every( + (node) => + node.textContent && + !node.hidden && + node.classList.contains('gev-status-badge--plain'), + ), + source: source.textContent, + }; + }); + check( + `${lang}: CCTV and populated Weather badges share the view`, + inventory.shared && inventory.coverage, + inventory, + ); + check( + `${lang}: existing announcement and read-only semantics remain intact`, + inventory.live && inventory.silent, + inventory, + ); + check( + `${lang}: source wording uses the active locale`, + lang === 'en' + ? inventory.source === 'SNAPSHOT · DEGRADED' + : inventory.source !== 'SNAPSHOT · DEGRADED', + inventory, + ); + + for (const state of ['loading', 'error', 'retained', 'ready', 'idle']) { + const result = await page.evaluate(async (state) => { + const owner = window.__godsEyeView.styleManager._cctvControls; + const frame = owner._frame; + owner._frame = { + ...frame, + loading: state === 'loading', + error: ['error', 'retained'].includes(state), + hasFrame: state === 'retained', + }; + owner._syncCctvSourceBadge( + owner._cctvState.activeCamera, + state !== 'idle', + ); + owner._frame = frame; + // The panel view renders the badge on Vue's next flush. + await new Promise((resolve) => requestAnimationFrame(resolve)); + const badge = document.getElementById('cctv-source-badge'); + return { + state: badge.dataset.frameState, + text: badge.textContent, + color: getComputedStyle(badge).color, + }; + }, state); + const expected = { + loading: ['loading', 'rgb(255, 229, 155)'], + error: ['error', 'rgb(255, 176, 176)'], + retained: ['ready', 'rgb(157, 239, 255)'], + ready: ['ready', 'rgb(157, 239, 255)'], + idle: ['idle', 'rgb(157, 239, 255)'], + }[state]; + check( + `${lang}: ${state} keeps its frame state and palette`, + result.state === expected[0] && + result.color === expected[1] && + (!['ready', 'retained'].includes(state) || + result.text === inventory.source), + result, + ); + } + for (const [calBadge, dirty, color] of [ + ['raw-prior', false, 'rgb(143, 231, 255)'], + ['curated', false, 'rgb(255, 230, 162)'], + ['calibrated', false, 'rgb(173, 255, 191)'], + ['curated', true, 'rgb(255, 208, 138)'], + ]) { + const result = await page.evaluate( + async ({ calBadge, dirty }) => { + const owner = window.__godsEyeView.styleManager._cctvControls; + document.getElementById('cctv-next-btn').focus(); + owner._renderCctvState({ + ...owner._cctvState, + activeCamera: { + ...owner._cctvState.activeCamera, + calBadge, + calDirty: dirty, + }, + }); + // The panel view renders the chip on Vue's next flush. + await new Promise((resolve) => requestAnimationFrame(resolve)); + const badge = document.getElementById('cctv-quality-chip'); + return { + state: badge.dataset.calBadge, + color: getComputedStyle(badge).color, + focus: document.activeElement.id, + }; + }, + { calBadge, dirty }, + ); + check( + `${lang}: ${dirty ? 'edited' : calBadge} keeps provenance color and control focus`, + result.state === (dirty ? 'edited' : calBadge) && + result.color === color && + result.focus === 'cctv-next-btn', + result, + ); + } + for (const theme of ['tactical', 'cyber']) { + await page.evaluate( + (theme) => window.__godsEyeView.styleManager._setHudVariant(theme), + theme, + ); + for (const width of [1440, 620, 390]) { + await page.setViewport({ width, height: 900 }); + for (const panelId of ['cctv-panel', 'weather-panel']) { + await page.evaluate(async (panelId) => { + const manager = window.__godsEyeView.styleManager; + for (const other of ['cctv-panel', 'weather-panel']) { + if (other !== panelId) + manager.setPanelCollapsed(other, true, { + persist: false, + syncShare: false, + }); + } + manager.setPanelCollapsed(panelId, false, { + persist: false, + syncShare: false, + }); + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(resolve)), + ); + }, panelId); + const layout = await page.evaluate((panelId) => { + const selector = + panelId === 'cctv-panel' + ? '#cctv-source-badge, #cctv-quality-chip' + : '.weather-coverage'; + return [...document.querySelectorAll(selector)].map((node) => { + const rect = node.getBoundingClientRect(); + const panel = node.closest(`#${panelId}`).getBoundingClientRect(); + return { + id: node.id || 'weather-coverage', + text: node.textContent, + width: rect.width, + height: rect.height, + scroll: node.scrollWidth, + client: node.clientWidth, + left: rect.left, + right: rect.right, + panelLeft: panel.left, + panelRight: panel.right, + fits: + rect.width > 0 && + rect.height > 0 && + rect.left >= panel.left - 1 && + rect.right <= panel.right + 1 && + node.scrollWidth <= node.clientWidth + 1, + }; + }); + }, panelId); + check( + `${lang}/${theme}: ${panelId} badges fit at ${width}px`, + layout.length >= (panelId === 'cctv-panel' ? 2 : 1) && + layout.every((node) => node.fits), + layout, + ); + if (width === 390) + await page.screenshot({ + path: `${out}/${lang}-${theme}-${panelId}-${width}.png`, + }); + } + } + } + const disposed = await page.evaluate(() => { + const owner = window.__godsEyeView.styleManager._cctvControls; + const badge = document.getElementById('cctv-quality-chip'); + const text = badge.textContent; + owner.destroy(); + owner._renderCctvState(null); + return badge.textContent === text; + }); + check(`${lang}: disposal prevents late state painting`, disposed); + } + check('no uncaught browser errors', errors.length === 0, errors); +} finally { + await browser.close(); +} +console.log(`${checks} checks; ${failures} failures`); +process.exitCode = failures ? 1 : 0; diff --git a/scripts/qa-street-level.mjs b/scripts/qa-street-level.mjs index f8d50f85f..0dd841acf 100644 --- a/scripts/qa-street-level.mjs +++ b/scripts/qa-street-level.mjs @@ -1,29 +1,19 @@ #!/usr/bin/env node /** - * Browser QA for the Street Level layer against a running server. Run with + * Browser QA for the Street Level layer against a running server: * `npm run qa:street-level -- --url http://localhost:4173`. * - * `--fixtures` (the CI mode) answers every *.mapillary.com request from - * fixtures, so nothing reaches Mapillary. The server still needs a token - * because the bundle carries it; CI uses a dummy one. Fixture runs also stage - * a rejected key and a keyless second server. - * - * `--strict` fails on any skip not in STRICT_ALLOWED_SKIPS. `--fail-on-retry` - * (or QA_FAIL_ON_RETRY=1) fails a missed header press unless the panel moved. - * A failed run saves evidence under qa-artifacts/street-level/. + * `--fixtures` (CI) answers every *.mapillary.com, KartaView and Panoramax + * request and the coverage tile route from fixtures, so nothing reaches those + * providers; the server still needs a (dummy) Mapillary token because the + * bundle carries it. `--strict` fails on any + * skip other than "fixtures only". A failed run saves evidence under + * qa-artifacts/street-level/. */ import assert from 'node:assert/strict'; import { pathToFileURL } from 'node:url'; -import { LAYER_STATE_REGISTRY } from '../src/data/layerState.js'; import { tileBounds } from '../src/layers/streetLevel/tileMath.js'; import { encodeCoverageTile } from '../src/layers/streetLevel/providers/mapillary/coverageFixture.mjs'; -import { COVERAGE_MOVE_DEBOUNCE_MS } from '../src/layers/streetLevel/providers/mapillary/policy.js'; -import { - describePress, - dockPanelByDoubleClick, - liftPanelByHeader, - waitForStill, -} from './qa-panelDrag.mjs'; import { hookRenderErrors, readRenderErrors, @@ -37,266 +27,188 @@ import { PHOTO_SEQUENCE_ID, photoImages, } from './fixtures/street-level/mapillaryGraph.mjs'; +import { + answerKartaViewRequest, + describeKartaViewCall, + KV_SEQUENCE_ID, + kartaViewPhotos, + resetKartaViewFixture, +} from './fixtures/street-level/kartaView.mjs'; +import { + answerPanoramaxRequest, + describePanoramaxCall, + PNX_PARK, + panoramaxPictures, + resetPanoramaxFixture, +} from './fixtures/street-level/panoramax.mjs'; -const PANEL_ID = 'street-level-panel'; - -/** Where a failed run leaves its screenshots and logs. */ -export const ARTIFACT_DIR = 'qa-artifacts/street-level'; - -export const VIEWPORTS = Object.freeze([ - { width: 1440, height: 900 }, - { width: 1280, height: 800 }, -]); - -/** Provider chips the panel must show, in order. */ -export const EXPECTED_PROVIDERS = Object.freeze(['mapillary']); - -/** - * Skips no setup can avoid: CI forks have no Google key, and live runs cannot - * stage fixture-only cases. `no Mapillary key` is not accepted: CI's dummy - * token runs the keyed flow, so a keyless strict run means that wiring broke. - */ -export const STRICT_ALLOWED_SKIPS = Object.freeze([ - 'no Google 3D', - 'fixtures only', -]); - -export function strictViolations(skips) { - return skips.filter((skip) => !STRICT_ALLOWED_SKIPS.includes(skip.reason)); -} - -const STREET_LEVEL_TOKEN = LAYER_STATE_REGISTRY.find( - (entry) => entry.id === 'street-level', -).token; - -/** The Street Level panel's token in the share link's `ui` panel state. */ -export const PANEL_UI_TOKEN = 't'; - -/** Right-rail order once the layout controller has run. */ -export const RAIL_ORDER = Object.freeze([ - 'pp-toggles', - 'cctv-panel', - 'weather-panel', - 'recent-imagery-panel', - 'street-level-panel', - 'global-context-panel', -]); - -/** Over downtown Sacramento, looking north and down. */ -export const PARK = Object.freeze({ - lon: -121.4944, - lat: 38.5816, - height: 900, - pitch: -1.3, -}); - -export function isCollapsed(classList) { - return [...classList].includes('collapsed'); -} - -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - +const VIEWPORT = { width: 1440, height: 900 }; +/** Over downtown Sacramento, above the fixture photo line, looking down. */ +const PARK = { lon: PHOTO_LINE.lon, lat: 38.5816, height: 900, pitch: -1.3 }; const DAY_MS = 86_400_000; /** - * Deterministic coverage for any tile: a grid of mixed 360°/flat, new/old - * sequences plus the photo sequence (PHOTO_LINE), or a few overview points. - * @returns {Uint8Array} empty for zooms that carry nothing + * Coverage for any street-zoom tile: a grid of 360°/flat, recent/old + * sequences, plus the photo sequence where PHOTO_LINE crosses the tile. + * @returns {Uint8Array} empty below z11, which the layer never asks for */ -export function fixtureTile(z, x, y, now = Date.now()) { - const tile = { x, y, z }; +function fixtureTile(z, x, y, now = Date.now()) { + if (z < 11) return new Uint8Array(0); const { west, east, south, north } = tileBounds(x, y, z); const at = (t, lo, hi) => lo + (hi - lo) * t; - if (z <= 5) - return encodeCoverageTile(tile, { - overview: [0.25, 0.5, 0.75].map((t, i) => ({ - id: `fx-${z}-${x}-${y}-o${i}`, - lon: at(t, west, east), - lat: at(t, south, north), - isPano: i === 1, - capturedAt: now - 30 * DAY_MS, - })), - }); - if (z < 11) return new Uint8Array(0); const margin = (east - west) * 0.05; const sequences = []; for (let i = 1; i <= 4; i++) { const t = i / 5; const old = i > 2; - sequences.push({ - id: `fx-${z}-${x}-${y}-h${i}`, - isPano: i % 2 === 0, - capturedAt: now - (old ? 1100 : 30) * DAY_MS, - parts: [ - [ - [west + margin, at(t, south, north)], - [east - margin, at(t, south, north)], + const lat = at(t, south, north); + const lon = at(t, west, east); + sequences.push( + { + id: `fx-${z}-${x}-${y}-h${i}`, + isPano: i % 2 === 0, + capturedAt: now - (old ? 1100 : 30) * DAY_MS, + parts: [ + [ + [west + margin, lat], + [east - margin, lat], + ], ], - ], - }); - sequences.push({ - id: `fx-${z}-${x}-${y}-v${i}`, - isPano: i % 2 === 1, - capturedAt: now - (old ? 30 : 1100) * DAY_MS, - parts: [ - [ - [at(t, west, east), south + margin], - [at(t, west, east), north - margin], + }, + { + id: `fx-${z}-${x}-${y}-v${i}`, + isPano: i % 2 === 1, + capturedAt: now - (old ? 30 : 1100) * DAY_MS, + parts: [ + [ + [lon, south + margin], + [lon, north - margin], + ], ], - ], - }); + }, + ); } - const photoSouth = Math.max(PHOTO_LINE.south, south); - const photoNorth = Math.min(PHOTO_LINE.north, north); - if ( - PHOTO_LINE.lon >= west && - PHOTO_LINE.lon < east && - photoSouth < photoNorth - ) + const lineSouth = Math.max(PHOTO_LINE.south, south); + const lineNorth = Math.min(PHOTO_LINE.north, north); + if (PHOTO_LINE.lon >= west && PHOTO_LINE.lon < east && lineSouth < lineNorth) sequences.push({ id: PHOTO_SEQUENCE_ID, isPano: false, capturedAt: now - 30 * DAY_MS, parts: [ [ - [PHOTO_LINE.lon, photoSouth], - [PHOTO_LINE.lon, photoNorth], + [PHOTO_LINE.lon, lineSouth], + [PHOTO_LINE.lon, lineNorth], ], ], }); - return encodeCoverageTile(tile, { sequences }); + return encodeCoverageTile({ x, y, z }, { sequences }); } -/** - * Ask the real status route from Node, outside the page's interception, so a - * server that never registered it fails even in fixture runs. Node sends no - * Origin, so the same-site gate admits it. - * @returns {Promise<{configured: boolean}>} - */ -export async function assertRealStatusRoute(url, fetchImpl = fetch) { - const route = new URL('/api/mapillary/status', url).href; - let response; - try { - response = await fetchImpl(route, { - headers: { Accept: 'application/json' }, - }); - } catch (error) { - throw new Error(`${route} is unreachable: ${error?.message || error}`, { - cause: error, - }); - } - const type = response.headers.get('content-type') || ''; - const text = await response.text(); - assert.equal( - response.status, - 200, - `${route} must be the server's Mapillary route (HTTP ${response.status}: ${text.slice(0, 120)})`, - ); - assert.match(type, /application\/json/, `${route} answers JSON, not ${type}`); - let body; - try { - body = JSON.parse(text); - } catch { - assert.fail(`${route} answered unparseable JSON: ${text.slice(0, 120)}`); - } - assert.equal( - typeof body?.configured, - 'boolean', - `${route} reports a boolean \`configured\`: ${text.slice(0, 120)}`, - ); - return body; -} +/** Fixture answers and call names per keyless provider host. */ +const KEYLESS_HOSTS = [ + { + host: /(^|\.)(kartaview|openstreetcam)\.org$/, + describe: describeKartaViewCall, + answer: answerKartaViewRequest, + }, + { + host: /^(api\.panoramax\.xyz|panoramax\.openstreetmap\.fr)$/, + describe: describePanoramaxCall, + answer: answerPanoramaxRequest, + }, +]; /** - * Answer the page's Mapillary requests from `fixture`, which steps may change - * mid-run. `configured: undefined` lets the server's real status route answer. - * @param {{configured?: boolean, tiles: 'ok'|'rejected', tileRequests: number, images: Array, calls: Set, unknown: Array}} fixture + * Answer the page's Mapillary, KartaView and Panoramax requests from + * `fixture`, which steps may change mid-run. `configured: undefined` lets the + * server's real status route answer. */ -export async function serveFixtures(page, fixture) { - // CDP Fetch on just these URLs: Puppeteer's page-wide interception stalls - // Cesium's worker scripts, leaving nothing to click. +async function serveFixtures(page, fixture) { + // CDP Fetch on just these URLs: page-wide interception stalls Cesium workers. const cdp = await page.createCDPSession(); await cdp.send('Fetch.enable', { patterns: [ { urlPattern: '*://*.mapillary.com/*' }, { urlPattern: '*/api/mapillary/*' }, + { urlPattern: '*://api.kartaview.org/*' }, + { urlPattern: '*://cdn.kartaview.org/*' }, + { urlPattern: '*://*.openstreetcam.org/*' }, + { urlPattern: '*://api.panoramax.xyz/*' }, + { urlPattern: '*://panoramax.openstreetmap.fr/*' }, ], }); - const fulfil = (requestId, { status, headers = {}, contentType, body }) => - cdp.send('Fetch.fulfillRequest', { - requestId, - responseCode: status, - responseHeaders: Object.entries({ - ...headers, - ...(contentType ? { 'Content-Type': contentType } : {}), - }).map(([name, value]) => ({ name, value: String(value) })), - body: Buffer.from(body ?? '').toString('base64'), - }); const json = (status, payload) => ({ status, contentType: 'application/json', body: JSON.stringify(payload), }); - cdp.on('Fetch.requestPaused', ({ requestId, request }) => { - const address = new URL(request.url); - const method = request.method; - let answer = null; + const answerFor = (method, address) => { if (/(^|\.)mapillary\.com$/.test(address.hostname)) { const call = describeCall(method, address); - answer = answerMapillaryRequest({ + const answer = answerMapillaryRequest({ method, - url: request.url, + url: address.href, images: fixture.images, }); fixture.calls.add(call); if (!answer.known) fixture.unknown.push(call); - } else if ( - address.pathname === '/api/mapillary/status' && - fixture.configured !== undefined - ) { - answer = json(200, { configured: fixture.configured }); - } else { - const tile = address.pathname.match( - /^\/api\/mapillary\/tiles\/coverage\/(\d+)\/(\d+)\/(\d+)$/, - ); - if (tile) { - fixture.tileRequests++; - if (fixture.configured === false) - answer = json(503, { error: 'no_key', keyRequired: true }); - else if (fixture.tiles === 'rejected') - answer = json(403, { - error: 'Mapillary rejected the access token', - keyRejected: true, - }); - else { - const bytes = fixtureTile( - Number(tile[1]), - Number(tile[2]), - Number(tile[3]), - ); - answer = bytes.length - ? { - status: 200, - contentType: 'application/x-protobuf', - body: Buffer.from(bytes), - } - : { status: 204, body: '' }; - } - } + return answer; } + const keyless = KEYLESS_HOSTS.find(({ host }) => + host.test(address.hostname), + ); + if (keyless) { + const call = keyless.describe(method, address); + const answer = keyless.answer({ method, url: address.href }); + fixture.calls.add(call); + if (!answer.known) fixture.unknown.push(call); + return answer; + } + if (address.pathname === '/api/mapillary/status') + return fixture.configured === undefined + ? null + : json(200, { configured: fixture.configured }); + const tile = address.pathname.match( + /^\/api\/mapillary\/tiles\/coverage\/(\d+)\/(\d+)\/(\d+)$/, + ); + if (!tile) return null; + if (fixture.configured === false) + return json(503, { error: 'no_key', keyRequired: true }); + if (fixture.rejected) + return json(403, { + error: 'Mapillary rejected the access token', + keyRejected: true, + }); + const bytes = fixtureTile(...tile.slice(1).map(Number)); + return bytes.length + ? { status: 200, contentType: 'application/x-protobuf', body: bytes } + : { status: 204, body: '' }; + }; + cdp.on('Fetch.requestPaused', ({ requestId, request }) => { + const answer = answerFor(request.method, new URL(request.url)); const done = answer - ? fulfil(requestId, answer) + ? cdp.send('Fetch.fulfillRequest', { + requestId, + responseCode: answer.status, + responseHeaders: Object.entries({ + ...answer.headers, + ...(answer.contentType + ? { 'Content-Type': answer.contentType } + : {}), + }).map(([name, value]) => ({ name, value: String(value) })), + body: Buffer.from(answer.body ?? '').toString('base64'), + }) : cdp.send('Fetch.continueRequest', { requestId }); // A page that navigated or closed meanwhile has no request to answer. done.catch(() => {}); }); } -export function newFixture(overrides = {}) { +function newFixture(overrides = {}) { return { configured: undefined, - tiles: 'ok', - tileRequests: 0, + rejected: false, images: photoImages(), calls: new Set(), unknown: [], @@ -304,32 +216,15 @@ export function newFixture(overrides = {}) { }; } -/** Wait for `fn` in the page; false (not a throw) when it does not come true. */ -async function settle(page, fn, arg, { timeout = 10_000 } = {}) { - try { - await page.waitForFunction(fn, { timeout, polling: 100 }, arg); - return true; - } catch (error) { - if (error?.name !== 'TimeoutError') throw error; - return false; - } -} - -async function clearFirstRun(page) { +/** Load the app and dismiss the first-run dialog. */ +async function boot(page, url) { + await page.goto(url, { waitUntil: 'domcontentloaded' }); await page.waitForFunction(() => Boolean(window.__godsEyeView?.dataManager), { timeout: 150_000, }); await page.evaluate(() => document.querySelector('.first-run-explore')?.click(), ); - await settle( - page, - () => !document.querySelector('.first-run-explore'), - null, - { - timeout: 3_000, - }, - ); await page.keyboard.press('Escape'); await page.evaluate(() => { for (const el of document.querySelectorAll( @@ -339,186 +234,160 @@ async function clearFirstRun(page) { }); } +/** Run `test(uiState, arg)` in the page until it is true. */ +const uiUntil = (page, test, arg = null, timeout = 30_000) => + page.waitForFunction( + `(${test})(window.__godsEyeView.dataManager.layers.get('street-level').module.getUIState(), ${JSON.stringify(arg)})`, + { timeout, polling: 100 }, + ); + +/** `id` is the one provider lit. */ +const litAlone = (u, id) => + u.providers.find((p) => p.id === id)?.on === true && + u.providers.filter((p) => p.on).length === 1; + +const getUI = (page) => + page.evaluate(() => + window.__godsEyeView.dataManager.layers + .get('street-level') + .module.getUIState(), + ); + +const statusIs = (page, text) => + page.waitForFunction( + (want) => document.getElementById('sl-status').textContent === want, + { timeout: 30_000 }, + text, + ); + +const waitForCoverage = (page) => + uiUntil( + page, + (u) => + u.enabled && + u.coverage.count > 0 && + !u.coverage.loading && + !u.keyRequired, + null, + 90_000, + ); + /** - * Click a panel control once the panel holds still and the control is what - * lies under its centre: the rail animates panel heights, so a point read - * once can miss by the time the pointer goes down. + * Press a panel control through the DOM: the rail animates panel heights, so + * a pointer aimed from one frame's layout can miss in the next. */ -async function clickPanelControl(page, selector, { timeout = 5_000 } = {}) { - await waitForStill(page, PANEL_ID); - const deadline = Date.now() + timeout; - for (;;) { - const hit = await page.$eval(selector, (el) => { - el.scrollIntoView({ block: 'nearest' }); - const r = el.getBoundingClientRect(); - const x = r.left + r.width / 2; - const y = r.top + r.height / 2; - const top = document.elementFromPoint(x, y); - return { - x, - y, - ok: Boolean(top && (top === el || el.contains(top))), - target: top - ? `${top.tagName.toLowerCase()}${top.id ? `#${top.id}` : ''}` - : 'nothing', - }; - }); - if (hit.ok) return page.mouse.click(hit.x, hit.y); - if (Date.now() > deadline) - throw new Error(`${selector} is covered by ${hit.target}`); - await new Promise((resolve) => setTimeout(resolve, 200)); - } -} +const press = (page, selector) => + page.$eval(selector, (control) => control.click()); -/** Load the app and clear the first-run dialog. */ -export async function boot(page, url) { - await page.goto(url, { waitUntil: 'domcontentloaded' }); - await clearFirstRun(page); -} - -function readPanel(page) { - return page.evaluate(() => { - const el = document.getElementById('street-level-panel'); - const rail = document.getElementById('right-context-rail'); - const box = el.getBoundingClientRect(); - return { - order: rail ? [...rail.children].map((child) => child.id) : [], - classes: [...el.classList], - width: Math.round(box.width), - right: Math.round(box.right), - status: document.getElementById('sl-status').textContent, - controlsDisabled: document.getElementById('sl-controls').disabled, - bodyDisplay: getComputedStyle(document.getElementById('sl-body')).display, - }; - }); -} - -/** Wait until Street Level is on, drawn, settled and not key-gated. */ -function waitForCoverage(page, { timeout = 90_000 } = {}) { - return page.waitForFunction( - () => { - const dm = window.__godsEyeView.dataManager; - const u = dm.layers.get('street-level').module.getUIState(); - return ( - dm.isEnabled('street-level') && - u.coverage.count > 0 && - !u.coverage.loading && - !u.keyRequired - ); - }, - { timeout }, +/** Expand the strip; a panel state stored by an earlier page may have done so. */ +async function expandPanel(page) { + const collapsed = await page.$eval('#street-level-panel', (node) => + node.classList.contains('collapsed'), + ); + if (collapsed) + await press( + page, + '.panel-collapse-btn[data-collapse-target="street-level-panel"]', + ); + await page.waitForFunction( + () => + getComputedStyle(document.getElementById('sl-body')).display === 'flex', + { timeout: 10_000 }, ); } -async function assertKeylessGate(page) { +async function assertKeyRequired(page) { await page.evaluate(() => window.__godsEyeView.dataManager.setEnabled('street-level', true, { origin: 'user', }), ); - await page.waitForFunction( - () => document.getElementById('sl-status').textContent === 'KEY REQUIRED', - { timeout: 30_000 }, - ); - const info = await readPanel(page); - assert.equal(info.controlsDisabled, true); - assert.equal(info.status, 'KEY REQUIRED'); - const chip = await page.$eval( - '#sl-provider-chips [data-chip-id="mapillary"]', - (node) => ({ - error: node.classList.contains('chip-error'), - title: node.title, - }), - ); - assert.equal(chip.error, true, 'the keyless provider chip reads as an error'); - assert.match(chip.title, /MAPILLARY_CLIENT_TOKEN/); + await statusIs(page, 'KEY REQUIRED'); + const shown = await page.evaluate(() => ({ + disabled: document.getElementById('sl-controls').disabled, + hint: document.getElementById('sl-error').hidden + ? '' + : document.getElementById('sl-error').textContent, + })); + assert.equal(shown.disabled, true, 'controls are gated'); + assert.match(shown.hint, /MAPILLARY_CLIENT_TOKEN/, 'names the key to add'); } /** - * Runs in the page. Find a point where a real click picks `prefix` + `id` (any - * id when null), searched around `points` ([lon, lat]), the aimed billboards, - * or else a grid mid-screen. Only points where the canvas is topmost count. - * @returns {{x: number, y: number, id: string}|null} client coordinates + * Client coordinates of the first thing drawn whose pick id starts with + * `prefix`, scanning `box` ({x, y, w, h} in canvas pixels; default: a row + * across the middle) every `step` px; null when nothing matches. */ -export function findPickPoint({ - prefix, - id, - points, - billboardIds, - billboardPrefix = null, -}) { - const viewer = window.__godsEyeView.viewer; - const scene = viewer.scene; - const canvas = scene.canvas; - const rect = canvas.getBoundingClientRect(); - const Cartographic = viewer.camera.positionCartographic.constructor; - let Cartesian2 = null; - const windowPoint = (x, y) => (Cartesian2 ? new Cartesian2(x, y) : { x, y }); - const wanted = (picked) => { - const pid = - typeof picked?.id === 'string' ? picked.id : (picked?.id?.id ?? null); - if (typeof pid !== 'string' || !pid.startsWith(prefix)) return null; - const rest = pid.slice(prefix.length).split('~')[0]; - return id === null || rest === id ? rest : null; - }; - const tryAt = (x, y) => { - if (x < 2 || y < 2 || x > rect.width - 2 || y > rect.height - 2) - return null; - const top = document.elementFromPoint(rect.left + x, rect.top + y); - if (top !== canvas) return null; - const hit = wanted(scene.pick(windowPoint(x, y))); - return hit ? { x: rect.left + x, y: rect.top + y, id: hit } : null; - }; - const centres = []; - const aimed = (billboardId) => - typeof billboardId === 'string' && - ((billboardIds || []).includes(billboardId) || - (billboardPrefix !== null && billboardId.startsWith(billboardPrefix))); - if ((billboardIds && billboardIds.length) || billboardPrefix !== null) { - for (let i = 0; i < scene.primitives.length; i++) { - const collection = scene.primitives.get(i); - if (typeof collection?.get !== 'function' || !collection.length) continue; - for (let j = 0; j < collection.length; j++) { - const billboard = collection.get(j); - if (!aimed(billboard?.id) || !billboard.show) continue; - const at = billboard.computeScreenSpacePosition?.(scene); - if (at) { - Cartesian2 ??= at.constructor; - centres.push([at.x, at.y]); +const findPick = (page, prefix, { box = null, step = 3 } = {}) => + page.evaluate( + (want, area, stride) => { + const { scene } = window.__godsEyeView.viewer; + const rect = scene.canvas.getBoundingClientRect(); + const { x, y, w, h } = area || { + x: 0, + y: Math.round(rect.height / 2), + w: rect.width, + h: 1, + }; + for (let py = y; py < y + h; py += stride) + for (let px = x; px < x + w; px += stride) { + const id = scene.pick({ x: px, y: py })?.id; + if (typeof id === 'string' && id.startsWith(want)) + return { + x: rect.left + px, + y: rect.top + py, + local: { x: px, y: py }, + id, + }; } - } - } + return null; + }, + prefix, + box, + step, + ); + +/** + * `findPick`, retried until a hit or `timeout`: draped lines build in a + * worker after their tile decoded, so a scan right after LOADING clears can + * come too early on a slow machine. + */ +async function findPickUntil( + page, + prefix, + { timeout = 30_000, box = null, step } = {}, +) { + const deadline = Date.now() + timeout; + for (;;) { + const hit = await findPick(page, prefix, { box, step }); + if (hit || Date.now() >= deadline) return hit; + await new Promise((resolve) => setTimeout(resolve, 500)); } - for (const [lon, lat] of points || []) { - const at = scene.cartesianToCanvasCoordinates( - scene.globe.ellipsoid.cartographicToCartesian( - Cartographic.fromDegrees(lon, lat, 0), - ), - ); - if (at) { - Cartesian2 ??= at.constructor; - centres.push([at.x, at.y]); - } +} + +/** Park the camera at `at`; a late startup flight can move it. */ +async function park(page, at = PARK) { + for (let attempt = 0; attempt < 5; attempt++) { + const stayed = await page.evaluate(async (at) => { + const v = window.__godsEyeView.viewer; + v.camera.cancelFlight?.(); + const C = v.camera.positionCartographic.constructor; + v.camera.setView({ + destination: v.scene.globe.ellipsoid.cartographicToCartesian( + C.fromDegrees(at.lon, at.lat, at.height), + ), + orientation: { heading: 0, pitch: at.pitch, roll: 0 }, + }); + await new Promise((resolve) => setTimeout(resolve, 1500)); + const c = v.camera.positionCartographic; + return ( + Math.abs((c.longitude * 180) / Math.PI - at.lon) < 0.001 && + Math.abs((c.latitude * 180) / Math.PI - at.lat) < 0.001 + ); + }, at); + if (stayed) return; } - for (const [cx, cy] of centres) - for (let r = 0; r <= 16; r += 2) - for (const [dx, dy] of [ - [0, 0], - [r, 0], - [-r, 0], - [0, r], - [0, -r], - ]) { - const hit = tryAt(cx + dx, cy + dy); - if (hit) return hit; - } - if (points || billboardIds) return null; - for (let y = rect.height * 0.25; y < rect.height * 0.8; y += 18) - for (let x = rect.width * 0.25; x < rect.width * 0.7; x += 6) { - const hit = tryAt(x, y); - if (hit) return hit; - } - return null; + throw new Error(`the camera would not stay parked at ${JSON.stringify(at)}`); } async function main() { @@ -528,39 +397,35 @@ async function main() { const url = urlIndex >= 0 ? args[urlIndex + 1] : 'http://localhost:4173'; const fixtures = args.includes('--fixtures'); const strict = args.includes('--strict'); - if (args.includes('--fail-on-retry')) process.env.QA_FAIL_ON_RETRY = '1'; const browser = await puppeteer.launch({ headless: true, executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || (await puppeteer.executablePath()), - defaultViewport: VIEWPORTS[0], + defaultViewport: VIEWPORT, protocolTimeout: 300_000, args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader'], }); let count = 0; const skips = []; - /** `fn` gets `skip(reason)`: the step runs what it can but reports a skip. */ - const step = async (label, fn) => { - let skipped = null; - const result = await fn({ - skip: (reason) => { - skipped = reason; - }, - }); - count++; - if (skipped) { - skips.push({ reason: skipped, label }); - console.log(`skip (${skipped}) ${count} ${label}`); - } else console.log(`ok ${count} ${label}`); - return result; + const skip = (reason, label) => { + skips.push(reason); + console.log(`skip (${reason}) ${++count} ${label}`); }; - /** A step this mode cannot run at all. */ - const skipStep = (reason, label) => step(label, ({ skip }) => skip(reason)); + // `fn` may call `skipped(reason)` when a live run has nothing to test. + const step = async (label, fn) => { + let reason = null; + await fn({ skipped: (why) => (reason = why) }); + if (reason) skip(reason, label); + else console.log(`ok ${++count} ${label}`); + }; + const fixtureStep = (label, fn) => + fixtures ? step(label, fn) : skip('fixtures only', label); const errors = []; const monitors = []; - /** The layer only warns on listener exceptions, so count those as errors. */ - const watch = async (page, name) => { + // The layer only warns on listener exceptions, so count those as errors. + const open = async (name, fixture) => { + const page = await browser.newPage(); monitors.push( watchPage(page, { name, @@ -569,167 +434,109 @@ async function main() { }), ); await hookRenderErrors(page); - }; - const renderErrorsSeen = []; - try { - await step( - 'the server registers the real Mapillary status route', - async () => { - const real = await assertRealStatusRoute(url); - console.log(` (server status: configured=${real.configured})`); - if (fixtures) - assert.equal( - real.configured, - true, - 'fixture runs need a server started with MAPILLARY_CLIENT_TOKEN (CI uses a dummy, non-secret one): the browser bundle carries the token, and without it no photo can open', - ); - }, - ); - const page = await browser.newPage(); - const fixture = newFixture(); - await watch(page, 'main'); - if (fixtures) await serveFixtures(page, fixture); + if (fixture) await serveFixtures(page, fixture); await boot(page, url); - const panel = () => readPanel(page); - const status = await page.evaluate(() => - fetch('/api/mapillary/status').then((res) => res.json()), - ); - for (const viewport of VIEWPORTS) { - await page.setViewport(viewport); - await step( - `panel is a collapsed right-rail strip at ${viewport.width}×${viewport.height}`, - async () => { - await settle( - page, - (width) => { - const box = document - .getElementById('street-level-panel') - .getBoundingClientRect(); - return box.width <= 200 && box.right <= width; - }, - viewport.width, - ); - const info = await panel(); - assert.deepEqual(info.order, RAIL_ORDER); - assert.ok(isCollapsed(info.classes)); - assert.equal(info.bodyDisplay, 'none'); - assert.ok(info.width <= 200 && info.right <= viewport.width); - }, - ); - } - await page.setViewport(VIEWPORTS[0]); - const expandStrip = async (target = page) => { - await target.click( - '.panel-collapse-btn[data-collapse-target="street-level-panel"]', - ); - assert.ok( - await settle( - target, - () => - !document - .getElementById('street-level-panel') - .classList.contains('collapsed') && - getComputedStyle(document.getElementById('sl-body')).display === - 'flex', - ), - 'Street Level panel did not expand before the timeout', - ); - }; - await expandStrip(); - await step( - 'expanding the strip shows the body, one chip per provider and the legend', - async () => { - const info = await panel(); - assert.ok(!isCollapsed(info.classes)); - assert.equal(info.bodyDisplay, 'flex'); - const chips = await page.evaluate(() => - [ - ...document.querySelectorAll( - '#sl-provider-chips .data-toggle-chip', - ), - ].map((chip) => chip.dataset.chipId), - ); - assert.deepEqual(chips, EXPECTED_PROVIDERS); - // One swatch per source plus "Selected"; each chip wears its colour. - assert.equal( - await page.evaluate( - () => document.querySelectorAll('#sl-legend li').length, - ), - EXPECTED_PROVIDERS.length + 1, - ); - assert.equal( - await page.$eval('[data-chip-id="mapillary"]', (chip) => - chip.style.getPropertyValue('--chip-color'), - ), - '#05cb63', - ); - }, - ); - if (!status.configured) { - await step( - 'keyless install gates the controls and reports KEY REQUIRED', - () => assertKeylessGate(page), - ); - await skipStep( - 'no Mapillary key', - 'the keyed steps (coverage, filters, photos, panel window)', - ); - console.log( - 'keyless run complete (no MAPILLARY_CLIENT_TOKEN on the server)', - ); - } else { - await keyedSteps(); - } - await step('no page errors and no Cesium render-loop errors', async () => { - renderErrorsSeen.push( - ...(await readRenderErrors(page)).map( - (text) => `[main] scene.renderError: ${text}`, - ), - ); - assert.deepEqual([...errors, ...renderErrorsSeen], []); - }); - if (strict) - await step('strict: no skips beyond the documented ones', () => { - assert.deepEqual( - strictViolations(skips), - [], - `--strict accepts only skips for: ${STRICT_ALLOWED_SKIPS.join(', ')}`, - ); - }); - console.log( - `${count} steps: ${count - skips.length} ok, ${skips.length} skipped`, + return page; + }; + const collectRenderErrors = async (page, name) => + errors.push( + ...(await readRenderErrors(page)).map( + (text) => `[${name}] scene.renderError: ${text}`, + ), ); - async function keyedSteps() { - // A late startup flight only shows itself by moving the camera, so park - // and check it stays put rather than reading a state. - const park = async () => { - for (let attempt = 0; attempt < 6; attempt++) { - await page.evaluate((at) => { - const v = window.__godsEyeView.viewer; - v.camera.cancelFlight?.(); - const C = v.camera.positionCartographic.constructor; - v.camera.setView({ - destination: v.scene.globe.ellipsoid.cartographicToCartesian( - C.fromDegrees(at.lon, at.lat, at.height), - ), - orientation: { heading: 0, pitch: at.pitch, roll: 0 }, - }); - }, PARK); - await sleep(1500); - const stable = await page.evaluate((at) => { - const c = window.__godsEyeView.viewer.camera.positionCartographic; - return ( - Math.abs((c.longitude * 180) / Math.PI - at.lon) < 0.001 && - Math.abs((c.latitude * 180) / Math.PI - at.lat) < 0.001 - ); - }, PARK); - if (stable) return; - } - }; - await park(); + /** + * A keyless provider: lighting its chip darkens the others and draws its + * coverage with its credit; a click on a line opens a photo from it; × + * closes it. Leaves that provider lit. + */ + const keylessProviderStep = ({ + id, + name, + at, + linePrefix, + box, + reset, + check, + }) => + step( + `${name}: its chip draws keyless coverage and its credit, a line opens its photo, × closes it`, + async ({ skipped }) => { + reset(); + await park(page, at); + await press(page, `#sl-provider-chips [data-chip-id="${id}"]`); + await uiUntil(page, litAlone, id); + await waitForCoverage(page); + await page.waitForFunction( + (credit) => document.body.innerHTML.includes(credit), + { timeout: 15_000 }, + `${name} contributors`, + ); + const area = + box === 'column' + ? await page.evaluate(() => { + const { height, width } = + window.__godsEyeView.viewer.scene.canvas.getBoundingClientRect(); + return { x: Math.round(width * 0.3), y: 0, w: 1, h: height }; + }) + : null; + const line = await findPickUntil(page, linePrefix, { box: area }); + if (!line && !fixtures) return skipped(`no ${name} line in view`); + assert.ok(line, `a ${name} line in view`); + await page.mouse.click(line.x, line.y); + await uiUntil( + page, + (u) => (u.street.imageId && !u.street.loading) || u.street.error, + null, + 90_000, + ); + const { street } = await getUI(page); + if (!fixtures && /No street-level imagery/.test(street.error || '')) + return skipped(`no ${name} photo near the line`); + assert.equal(street.error, null, `viewer error: ${street.error}`); + assert.equal(street.providerId, id); + assert.equal( + await page.$eval('#sl-viewer-wrap', (node) => node.hidden), + false, + ); + if (fixtures) + check(street, line.id.slice(linePrefix.length).split('~')[0]); + await press(page, '#sl-viewer-close'); + await uiUntil( + page, + (u) => !u.street.open && u.sequence.selectedId === null, + ); + assert.equal( + await page.$eval('#sl-viewer-wrap', (node) => node.hidden), + true, + ); + }, + ); + let page = null; + + try { + const fixture = newFixture(); + page = await open('main', fixtures && fixture); + const { configured } = await page.evaluate(() => + fetch('/api/mapillary/status').then((res) => res.json()), + ); + if (fixtures) + assert.equal( + configured, + true, + 'fixture runs need a server started with MAPILLARY_CLIENT_TOKEN (CI uses a dummy one)', + ); + + await expandPanel(page); + if (!configured) { + await step('keyless server: KEY REQUIRED gates the controls', () => + assertKeyRequired(page), + ); + skip('no Mapillary key', 'the keyed steps'); + } else { + await park(page); await step( - 'enabling draws coverage and registers the on-globe credit', + 'enabling draws coverage and the Mapillary credit', async () => { await page.evaluate(() => window.__godsEyeView.dataManager.setEnabled('street-level', true, { @@ -737,9 +544,11 @@ async function main() { }), ); await waitForCoverage(page); - const info = await panel(); - assert.equal(info.controlsDisabled, false); - // Cesium paints on-screen credits a frame or two after they register. + await statusIs(page, 'ON'); + assert.equal( + await page.$eval('#sl-controls', (node) => node.disabled), + false, + ); await page.waitForFunction( () => document.body.innerHTML.includes('Mapillary contributors'), @@ -747,1074 +556,240 @@ async function main() { ); }, ); - const ui = () => - page.evaluate(() => - window.__godsEyeView.dataManager.layers - .get('street-level') - .module.getUIState(), - ); - /** `test(u, arg)` runs in the page, so it must be self-contained. */ - const uiUntil = (test, arg = null, options) => - settle( - page, - `(${test})(window.__godsEyeView.dataManager.layers.get('street-level').module.getUIState(), ${JSON.stringify(arg)})`, - undefined, - options, - ); - const chip = '#sl-provider-chips [data-chip-id="mapillary"]'; - const stacks = { - active: () => - page.evaluate(() => - window.__godsEyeView.mapStackController.getActiveId(), - ), - photoreal: () => - page.evaluate(() => - window.__godsEyeView.mapStackController.isStackAvailable( - 'photoreal', + + await fixtureStep( + 'a rejected key reads KEY REJECTED and clears when switched off', + async () => { + fixture.rejected = true; + await press(page, '#sl-status'); + await statusIs(page, 'OFF'); + await press(page, '#sl-status'); + await statusIs(page, 'KEY REJECTED'); + const shown = await page.evaluate(() => ({ + error: document.getElementById('sl-error').textContent, + hidden: document.getElementById('sl-error').hidden, + disabled: document.getElementById('sl-controls').disabled, + })); + assert.match(shown.error, /rejected MAPILLARY_CLIENT_TOKEN/); + assert.equal(shown.hidden, false); + assert.equal(shown.disabled, true); + await press(page, '#sl-status'); + await statusIs(page, 'OFF'); + assert.equal( + await page.$eval( + '#sl-error', + (node) => node.hidden || !node.textContent, ), - ), - set: async (id) => { - await page.evaluate( - (stackId) => - window.__godsEyeView.mapStackController.setStack(stackId), - id, + true, + 'no stale error while off', ); - await settle( + fixture.rejected = false; + await press(page, '#sl-status'); + await waitForCoverage(page); + await statusIs(page, 'ON'); + }, + ); + + await park(page); + await waitForCoverage(page); + await step( + 'a line selects its sequence, and a cone opens its photo with a caption', + async () => { + // Fixtures answer lookups for the photo sequence only. + const line = await findPickUntil( page, - (stackId) => - window.__godsEyeView.mapStackController.getActiveId() === stackId, - id, + fixtures ? `mly:seq:${PHOTO_SEQUENCE_ID}` : 'mly:seq:', ); - }, - }; - await step( - 'the header ON/OFF pill switches the layer off and on', - async () => { - assert.equal( - await page.$eval('#sl-status', (node) => - [ - node.tagName, - node.textContent, - node.getAttribute('aria-pressed'), - ].join(':'), - ), - 'BUTTON:ON:true', - ); - await clickPanelControl(page, '#sl-status'); - await page.waitForFunction( - () => !window.__godsEyeView.dataManager.isEnabled('street-level'), - { timeout: 15_000 }, - ); - await page.waitForFunction( - () => document.getElementById('sl-status').textContent === 'OFF', - { timeout: 5_000 }, - ); - assert.equal((await ui()).coverage.count, 0); - await clickPanelControl(page, '#sl-status'); - await waitForCoverage(page); - assert.equal( - await page.$eval('#sl-status', (node) => - node.getAttribute('aria-pressed'), - ), - 'true', - ); - }, - ); - await step( - 'the only lit provider chip switches the whole layer off, credit and all', - async () => { - await clickPanelControl(page, chip); - await page.waitForFunction( - () => - !window.__godsEyeView.dataManager.isEnabled('street-level') && - window.__godsEyeView.dataManager.layers - .get('street-level') - .module.getUIState().coverage.count === 0, - { timeout: 15_000 }, - ); - await page.waitForFunction( - () => - !document.body.innerHTML.includes('Mapillary contributors'), - { timeout: 15_000 }, - ); - assert.equal( - await page.$eval(chip, (node) => node.getAttribute('aria-pressed')), - 'false', - ); - // The provider stays switched on, so the layer comes back with it. - assert.equal((await ui()).providers[0].on, true); - }, - ); - await step( - 'lighting the chip turns the layer back on with coverage', - async () => { - await clickPanelControl(page, chip); - await waitForCoverage(page); - assert.equal( - await page.$eval(chip, (node) => node.getAttribute('aria-pressed')), - 'true', - ); - }, - ); - await step( - 'the 360° filter keeps at most the unfiltered sequence count', - async () => { - const before = (await ui()).coverage.count; - await clickPanelControl(page, '[data-sl-pano="pano"]'); - await uiUntil((u) => u.filter.pano === 'pano' && !u.coverage.loading); - const after = (await ui()).coverage.count; - assert.ok(after <= before, `${after} ≤ ${before}`); - // The fixtures hold flat sequences too, so the filter must drop some. - if (fixtures) assert.ok(after < before, `${after} < ${before}`); - assert.equal((await ui()).filter.pano, 'pano'); - // The click is a user params request, so the share link records it - // under Street Level's share token, whatever the ledger assigned. - await page.waitForFunction( - (option) => - (new URLSearchParams(location.hash.slice(1)).get('lo') || '') - .split('_') - .includes(option), - { timeout: 10_000 }, - `${STREET_LEVEL_TOKEN}.p.p`, - ); - await clickPanelControl(page, '[data-sl-pano="all"]'); + assert.ok(line, 'a sequence line across the middle of the view'); + await page.mouse.click(line.x, line.y); await uiUntil( - (u, n) => u.filter.pano === 'all' && u.coverage.count === n, - before, - ); - assert.equal((await ui()).coverage.count, before); - }, - ); - await step( - 'the SINCE slider narrows coverage and names its cut-off date', - async () => { - const before = (await ui()).coverage.count; - const setStop = (index) => - page.$eval( - '#sl-since', - (input, value) => { - input.value = String(value); - input.dispatchEvent(new Event('input', { bubbles: true })); - input.dispatchEvent(new Event('change', { bubbles: true })); - }, - index, - ); - await setStop(5); - await uiUntil((u) => u.filter.sinceDays === 365); - const narrowed = await ui(); - assert.equal(narrowed.filter.sinceDays, 365); - if (fixtures) - assert.ok( - narrowed.coverage.count < before, - `fixtures hold older sequences: ${narrowed.coverage.count} < ${before}`, - ); - assert.ok( - narrowed.coverage.count <= before, - `${narrowed.coverage.count} ≤ ${before}`, - ); - await settle(page, () => - /^LAST YEAR/.test( - document.getElementById('sl-since-label').textContent, - ), - ); - assert.match( - await page.$eval('#sl-since-label', (node) => node.textContent), - /^LAST YEAR · SINCE \d{4}-\d{2}-\d{2}$/, - ); - await setStop(0); - await uiUntil((u) => u.filter.sinceDays === 0); - await settle( page, - () => - document.getElementById('sl-since-label').textContent === - 'ANY DATE', + (u) => u.sequence.selectedId && !u.sequence.loading, ); - assert.equal((await ui()).filter.sinceDays, 0); - assert.equal( - await page.$eval('#sl-since-label', (node) => node.textContent), - 'ANY DATE', - ); - }, - ); - await step( - 'the MapillaryJS viewer loads ahead of the first photo', - async () => { - // Catches a broken dynamic import before the first click would. - await page.waitForSelector( - '#sl-viewer.mapillary-viewer .mapillary-dom', - { timeout: 60_000 }, - ); - }, - ); - const statusText = (text) => - page.waitForFunction( - (expected) => - document.getElementById('sl-status').textContent === expected, - { timeout: 30_000 }, - text, - ); - const panTo = (lon, lat) => - page.evaluate( - (at) => { - const v = window.__godsEyeView.viewer; - const C = v.camera.positionCartographic.constructor; - v.camera.setView({ - destination: v.scene.globe.ellipsoid.cartographicToCartesian( - C.fromDegrees(at.lon, at.lat, 900), - ), - orientation: { heading: 0, pitch: -1.3, roll: 0 }, - }); - window.__godsEyeView.dataManager.layers - .get('street-level') - .module.refreshCoverage(); - }, - { lon, lat }, - ); - /** Wait until no tile request has arrived for `quietMs`. */ - const tileRequestsQuiet = async (quietMs, timeout = 30_000) => { - const start = Date.now(); - let last = fixture.tileRequests; - let since = Date.now(); - while (Date.now() - start < timeout) { - await sleep(100); - if (fixture.tileRequests !== last) { - last = fixture.tileRequests; - since = Date.now(); - } else if (Date.now() - since >= quietMs) return last; - } - return last; - }; - const QUIET_MS = 2 * COVERAGE_MOVE_DEBOUNCE_MS + 200; - if (fixtures) - await step( - 'a key Mapillary rejects reads KEY REJECTED, stops asking (a pan that asks while accepted asks nothing while rejected), and clears when switched off', - async () => { - // Positive control: with the key accepted, the same pan-and-wait - // the rejected half uses does see new tile requests. - await tileRequestsQuiet(QUIET_MS); - const idle = fixture.tileRequests; - await panTo(-121.46, 38.6); - const asked = await tileRequestsQuiet(QUIET_MS); - assert.ok( - asked > idle, - `a pan while accepted requests tiles (${idle} → ${asked})`, - ); - fixture.tiles = 'rejected'; - await clickPanelControl(page, '#sl-status'); - await statusText('OFF'); - await clickPanelControl(page, '#sl-status'); - await statusText('KEY REJECTED'); - const shown = await page.evaluate(() => ({ - error: document.getElementById('sl-error').textContent, - errorHidden: document.getElementById('sl-error').hidden, - controls: document.getElementById('sl-controls').disabled, - chip: document - .querySelector('#sl-provider-chips [data-chip-id="mapillary"]') - .classList.contains('chip-error'), - })); - assert.match(shown.error, /rejected MAPILLARY_CLIENT_TOKEN/); - assert.equal(shown.errorHidden, false); - assert.equal(shown.controls, true); - assert.equal(shown.chip, true); - // Panning asks for nothing more: the verdict holds for every tile. - const rejectedAt = await tileRequestsQuiet(QUIET_MS); - await panTo(-121.42, 38.63); - const after = await tileRequestsQuiet(QUIET_MS); - assert.equal(after, rejectedAt, 'no tile requests while rejected'); - // Off clears the message; with a good key it comes back as ON. - await clickPanelControl(page, '#sl-status'); - await statusText('OFF'); - assert.equal( - await page.$eval( - '#sl-error', - (node) => node.hidden || !node.textContent, - ), - true, - 'no stale error while the layer is off', - ); - fixture.tiles = 'ok'; - await clickPanelControl(page, '#sl-status'); - await waitForCoverage(page); - await statusText('ON'); - }, - ); - else - await skipStep( - 'fixtures only', - 'a key Mapillary rejects reads KEY REJECTED and stops asking', - ); - - const fixtureIds = new Map( - fixture.images.map((image, index) => [image.id, { ...image, index }]), - ); - const waitForImage = (id = null) => - page.waitForFunction( - (want) => { - const s = window.__godsEyeView.dataManager.layers - .get('street-level') - .module.getUIState().street; - return ( - (s.imageId && !s.loading && (!want || s.imageId === want)) || - s.error - ); - }, - { timeout: 90_000 }, - id, - ); - const openById = async (id) => { - await page.evaluate((imageId) => { - void window.__godsEyeView.dataManager.layers - .get('street-level') - .module.openImage('mapillary', imageId); - }, id); - await waitForImage(id); - const street = (await ui()).street; - assert.equal(street.error, null, `viewer error: ${street.error}`); - return street; - }; - - await park(); - await waitForCoverage(page); - await step( - 'a click on a coverage line selects its sequence and draws its cones', - async () => { - const original = await stacks.active(); - // Draped lines on flat imagery: the line is where it is drawn. - await stacks.set('esri-imagery'); - await uiUntil((u) => u.surface === 'draped'); - await waitForCoverage(page); - const target = fixtures ? PHOTO_SEQUENCE_ID : null; - const along = Array.from({ length: 9 }, (_, i) => [ - PHOTO_LINE.lon, - PHOTO_LINE.south + - ((i + 2) / 13) * (PHOTO_LINE.north - PHOTO_LINE.south), - ]); - // Ground primitives are built over a few frames: poll for a pick. - const handle = await page.waitForFunction( - findPickPoint, - { timeout: 30_000, polling: 250 }, - { - prefix: 'mly:seq:', - id: target, - points: fixtures ? along : null, - billboardIds: null, + // Cones clamp to the ground: on a slow GPU (CI's SwiftShader) they + // can take a few frames after the selection to become pickable. + const cone = await findPickUntil(page, 'mly:img:', { + box: { + x: Math.max(0, line.local.x - 150), + y: Math.max(0, line.local.y - 150), + w: 300, + h: 300, }, - ); - const at = await handle.jsonValue(); - await page.mouse.click(at.x, at.y); - const selected = await uiUntil( - (u, id) => - u.sequence.selectedId === id && - !u.sequence.loading && - u.sequence.images > 0, - at.id, - { timeout: 30_000 }, - ); - const sequence = (await ui()).sequence; - assert.ok( - selected, - `the click at ${Math.round(at.x)},${Math.round(at.y)} on ${at.id} selected it: ${JSON.stringify(sequence)}`, - ); - if (fixtures) - assert.equal(sequence.images, fixture.images.length, 'every photo'); - // The cones are on the globe: one of them picks as an image. - const cone = await page.waitForFunction( - findPickPoint, - { timeout: 15_000, polling: 250 }, - { - prefix: 'mly:img:', - id: null, - points: fixtures - ? fixture.images.map((image) => [image.lon, image.lat]) - : null, - billboardIds: null, - // Live: the cones' positions are only known from the globe. - billboardPrefix: fixtures ? null : 'mly:img:', - }, - ); - assert.ok(await cone.jsonValue(), 'an image cone is pickable'); - await page.evaluate(() => - window.__godsEyeView.dataManager.layers - .get('street-level') - .module.clearSequence(), - ); - await uiUntil((u) => u.sequence.selectedId === null); - await stacks.set(original); - }, - ); - - let firstImageId = null; - await park(); - await waitForCoverage(page); - await step( - 'opening the nearest image shows the viewer with a caption', - async () => { - // Fire and forget: the open can outlive one CDP call, so poll instead. - await page.evaluate(() => { - void window.__godsEyeView.dataManager.layers - .get('street-level') - .module.openNearest(); + step: 8, }); - await waitForImage(); - const street = (await ui()).street; - assert.equal(street.error, null, `viewer error: ${street.error}`); - // Some images carry no creator name; the date/bearing side always fills. - const filled = await settle( + assert.ok(cone, 'an image cone near the selected line'); + await page.mouse.click(cone.x, cone.y); + await uiUntil( page, + (u) => (u.street.imageId && !u.street.loading) || u.street.error, + null, + 90_000, + ); + const { street } = await getUI(page); + assert.equal(street.error, null, `viewer error: ${street.error}`); + await page.waitForSelector('#sl-viewer .mapillary-dom', { + timeout: 60_000, + }); + await page.waitForFunction( () => document.getElementById('sl-image-when').textContent.trim() .length > 0, - null, { timeout: 30_000 }, ); - if (!filled) { - const dump = await page.evaluate(() => { - const u = window.__godsEyeView.dataManager.layers - .get('street-level') - .module.getUIState(); - return { - street: u.street, - captionNodes: - document.querySelectorAll('#sl-image-when').length, - captionNow: - document.getElementById('sl-image-when').textContent, - wrapHidden: document.getElementById('sl-viewer-wrap').hidden, - collapsed: document - .getElementById('street-level-panel') - .classList.contains('collapsed'), - }; - }); - throw new Error(`caption never filled: ${JSON.stringify(dump)}`); - } const view = await page.evaluate(() => ({ hidden: document.getElementById('sl-viewer-wrap').hidden, - when: document.getElementById('sl-image-when').textContent.trim(), - link: document.getElementById('sl-image-link').textContent.trim(), - href: document.getElementById('sl-image-link').href, - width: Math.round( - document.getElementById('sl-viewer').getBoundingClientRect() - .width, - ), + width: document.getElementById('sl-viewer').getBoundingClientRect() + .width, + link: document.getElementById('sl-image-link').href, })); assert.equal(view.hidden, false); - assert.ok(view.width > 200); - assert.ok(view.when.length > 0, 'caption shows the capture date'); - assert.equal(street.providerId, 'mapillary'); - firstImageId = street.imageId; - assert.equal(view.link, 'MAPILLARY ↗'); + assert.ok(view.width > 200, `viewer width ${view.width}`); + assert.match(view.link, /mapillary\.com\/app\/\?pKey=/); if (fixtures) { - const known = fixtureIds.get(street.imageId); - assert.ok(known, `a fixture photo opened (${street.imageId})`); - assert.equal(street.isPano, known.isPano, 'pano flag from the ent'); + assert.ok( + fixture.images.some((image) => image.id === street.imageId), + `fixture photo ${street.imageId}`, + ); assert.equal(street.sequenceId, PHOTO_SEQUENCE_ID); } - const fit = await page.evaluate(() => { - const inner = document.querySelector('.street-level-panel-inner'); - const box = inner.getBoundingClientRect(); - const wrap = document - .getElementById('sl-viewer-wrap') - .getBoundingClientRect(); - return { - scrollTop: inner.scrollTop, - top: wrap.top - box.top, - overflowBottom: wrap.bottom - box.bottom, - }; - }); - assert.equal(fit.scrollTop, 0, 'panel not scrolled'); - assert.ok( - fit.top >= 0 && fit.top < 80, - `viewer right under the header (${fit.top}px)`, - ); - assert.ok( - fit.overflowBottom <= 1, - `whole viewer visible (${fit.overflowBottom}px cut)`, - ); - assert.match(view.href, /mapillary\.com\/app\/\?pKey=/); - // The open selects the photo's sequence: its cones are drawn. - assert.ok( - await uiUntil( - (u) => u.sequence.selectedId === u.street.sequenceId, - null, - { timeout: 30_000 }, - ), - 'the open photo’s sequence is selected', - ); - }, - ); - if (fixtures) - await step( - 'a click on a neighbouring cone steps the viewer to that photo (360° and flat)', - async () => { - // Let the framing flight land, so the cone does not move under the click. - await settle( - page, - () => !window.__godsEyeView.viewer.camera._currentFlight, - null, - { timeout: 10_000 }, - ); - await uiUntil((u) => u.sequence.images > 0 && !u.sequence.loading); - const current = fixtureIds.get(firstImageId); - const neighbour = [1, -1, 2, -2, 4, -4] - .map((offset) => fixture.images[current.index + offset]) - .find((image) => image && image.isPano !== current.isPano); - assert.ok(neighbour, 'a neighbour of the other camera type'); - const handle = await page.waitForFunction( - findPickPoint, - { timeout: 15_000, polling: 250 }, - { - prefix: 'mly:img:', - id: neighbour.id, - points: null, - billboardIds: [`mly:img:${neighbour.id}`], - }, - ); - const at = await handle.jsonValue(); - await page.mouse.click(at.x, at.y); - await waitForImage(neighbour.id); - const street = (await ui()).street; - assert.equal(street.error, null); - assert.equal(street.imageId, neighbour.id, 'stepped to the cone'); - assert.equal(street.isPano, neighbour.isPano); - assert.notEqual(street.isPano, current.isPano, 'both kinds shown'); - await openById(firstImageId); - }, - ); - else - await skipStep( - 'fixtures only', - 'a click on a neighbouring cone steps the viewer to that photo', - ); - await step( - 'FOLLOW is offered only on the Google 3D map', - async ({ skip }) => { - const follow = () => - page.$eval('#sl-follow-btn', (node) => ({ - disabled: node.disabled, - pressed: node.getAttribute('aria-pressed'), - title: node.title, - })); - const followIs = (disabled, pressed = null) => - settle( - page, - ([d, p]) => { - const node = document.getElementById('sl-follow-btn'); - return ( - node.disabled === d && - (p === null || node.getAttribute('aria-pressed') === p) - ); - }, - [disabled, pressed], - ); - const original = await stacks.active(); - await stacks.set('esri-imagery'); - await followIs(true); - let state = await follow(); - assert.equal(state.disabled, true, 'disabled on Esri'); - assert.match(state.title, /needs the Google 3D map/); - if (await stacks.photoreal()) { - await stacks.set('photoreal'); - await followIs(false); - state = await follow(); - assert.equal(state.disabled, false, 'enabled on Google 3D'); - await clickPanelControl(page, '#sl-follow-btn'); - await followIs(false, 'true'); - assert.equal((await follow()).pressed, 'true'); - await stacks.set('esri-imagery'); - await followIs(true, 'false'); - state = await follow(); - assert.equal( - state.pressed, - 'false', - 'leaving Google 3D stops following', - ); - assert.equal(state.disabled, true); - } else { - console.log( - ' (Google 3D unavailable here: only the disabled path ran)', - ); - skip('no Google 3D'); - } - await stacks.set(original); - }, - ); - await park(); - await step( - 'closing a photo stops the framing flight toward it', - async () => { - // Opening frames the photo with a 1.6 s camera flight; closing right - // away must cancel it, leaving the camera where it was. - const result = await page.evaluate(async (id) => { - const v = window.__godsEyeView.viewer; - const module = - window.__godsEyeView.dataManager.layers.get( - 'street-level', - ).module; - const opened = await module.openImage('mapillary', id); - const flying = Boolean(v.camera._currentFlight); - const from = v.camera.positionCartographic.clone(); - module.closeViewer(); - const stillFlying = Boolean(v.camera._currentFlight); - const frames = (n) => - new Promise((resolve) => { - const tick = () => - --n <= 0 ? resolve() : requestAnimationFrame(tick); - requestAnimationFrame(tick); - }); - await frames(20); - const to = v.camera.positionCartographic; - return { - opened, - flying, - stillFlying, - moved: Math.hypot( - (to.longitude - from.longitude) * 6_371_000, - (to.latitude - from.latitude) * 6_371_000, - to.height - from.height, - ), - height: to.height, - }; - }, firstImageId); - assert.equal(result.opened, true, 'the photo opened'); - assert.equal(result.flying, true, 'opening started a framing flight'); - assert.equal(result.stillFlying, false, 'closing cancelled it'); - assert.ok( - result.moved < 0.5, - `the camera stopped where it was (moved ${result.moved.toFixed(2)} m)`, - ); - assert.ok( - result.height > PARK.height / 2, - `the camera never reached the photo (${Math.round(result.height)} m up)`, - ); - assert.equal((await ui()).street.open, false); - }, - ); - await step( - 'coverage sits on the bare earth on Google 3D and drapes elsewhere', - async ({ skip }) => { - const surface = () => - page.evaluate(() => { - const u = window.__godsEyeView.dataManager.layers - .get('street-level') - .module.getUIState(); - return { surface: u.surface, count: u.coverage.count }; - }); - const original = await stacks.active(); - await stacks.set('esri-imagery'); - await page.waitForFunction( - () => - window.__godsEyeView.dataManager.layers - .get('street-level') - .module.getUIState().surface === 'draped', - { timeout: 10_000 }, - ); - const coverageLoaded = () => - waitForCoverage(page, { timeout: 60_000 }); - await coverageLoaded(); - assert.equal((await surface()).surface, 'draped', 'draped on Esri'); - if (await stacks.photoreal()) { - await stacks.set('photoreal'); - await page.waitForFunction( - () => - window.__godsEyeView.dataManager.layers - .get('street-level') - .module.getUIState().surface === 'terrain', - { timeout: 15_000 }, - ); - await coverageLoaded(); - assert.equal((await surface()).surface, 'terrain'); - } else { - console.log( - ' (Google 3D unavailable here: only the draped path ran)', - ); - skip('no Google 3D'); - } - await stacks.set(original); - }, - ); - const expanded = () => - page.evaluate(() => - document - .getElementById('sl-viewer-wrap') - .classList.contains('sl-viewer-wrap-expanded'), - ); - await step( - 'EXPAND opens a modal dialog (the rest of inert) and Esc returns focus to the button', - async () => { - await openById(firstImageId); - const inertBefore = await page.evaluate( - () => - [...document.body.children].filter((node) => node.inert).length, - ); - await clickPanelControl(page, '#sl-viewer-expand'); - await settle(page, () => - document - .getElementById('sl-viewer-wrap') - .classList.contains('sl-viewer-wrap-expanded'), - ); - const dialog = await page.evaluate(() => { - const wrap = document.getElementById('sl-viewer-wrap'); - const others = [...document.body.children].filter( - (node) => node !== wrap, - ); - return { - role: wrap.getAttribute('role'), - modal: wrap.getAttribute('aria-modal'), - inside: wrap.contains(document.activeElement), - width: Math.round(wrap.getBoundingClientRect().width), - onBody: wrap.parentElement === document.body, - notInert: others - .filter((node) => !node.inert) - .map((node) => node.id || node.tagName.toLowerCase()), - wrapInert: wrap.inert, - }; - }); - assert.equal(dialog.role, 'dialog'); - assert.equal(dialog.modal, 'true'); - assert.equal(dialog.inside, true); - assert.ok(dialog.width > 900); - assert.equal(dialog.onBody, true); - assert.deepEqual( - dialog.notInert, - [], - 'every other body child is inert', - ); - assert.equal(dialog.wrapInert, false); - await page.keyboard.press('Escape'); - await settle( - page, - () => - !document - .getElementById('sl-viewer-wrap') - .classList.contains('sl-viewer-wrap-expanded'), - ); - const after = await page.evaluate(() => ({ - expanded: document - .getElementById('sl-viewer-wrap') - .classList.contains('sl-viewer-wrap-expanded'), - focus: document.activeElement?.id, - inert: [...document.body.children].filter((node) => node.inert) - .length, - })); - assert.equal( - `${after.expanded}:${after.focus}`, - 'false:sl-viewer-expand', - ); - assert.equal( - after.inert, - inertBefore, - 'the application is live again', - ); - }, - ); - await step( - '× closes the image and deselects it on the globe', - async () => { - await clickPanelControl(page, '#sl-viewer-close'); + // Opening selects the photo's sequence, so its cones are drawn. await uiUntil( - (u) => !u.street.open && u.sequence.selectedId === null, + page, + (u) => u.sequence.selectedId === u.street.sequenceId, ); - const after = await ui(); - assert.equal(after.street.open, false); - assert.equal(after.sequence.selectedId, null); }, ); - const floating = () => - page.$eval('#street-level-panel', (node) => - node.classList.contains('panel-floating'), - ); - const center = (selector) => - page.$eval(selector, (node) => { - const r = node.getBoundingClientRect(); - return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; - }); - // Right after a dock the rail is still animating, so the shared helpers - // re-resolve the header and retry only a press that provably missed it. - const floatPanel = async () => { - const attempt = await liftPanelByHeader(page, PANEL_ID, { - dx: -400, - dy: 80, - }); - assert.equal( - attempt.done, - true, - `a header drag lifts the panel out of the rail (${describePress(attempt)})`, - ); - assert.equal(await floating(), true); - }; + await step( - 'the panel floats on a header drag, resizes, and the viewer takes the room', + 'FIT/FILL keeps native selection, keyboard focus and persistence with a photo open', async () => { - await openById(firstImageId); - await floatPanel(); - const viewerHeight = () => - page.$eval('#sl-viewer', (node) => - Math.round(node.getBoundingClientRect().height), - ); - const before = await viewerHeight(); - const grip = await center('#street-level-panel .panel-resize-grip'); - await page.mouse.move(grip.x, grip.y); - await page.mouse.down(); - await page.mouse.move(grip.x + 120, grip.y + 160, { steps: 10 }); - await page.mouse.up(); - await settle( - page, - (height) => - document.getElementById('sl-viewer').getBoundingClientRect() - .height > - height + 60, - before, - ); - const after = await viewerHeight(); - assert.ok( - after > before + 60, - `viewer grew with the window (${before} → ${after}px)`, - ); + await page.click('[data-sl-render="fill"]'); + await uiUntil(page, (u) => u.street.renderMode === 'fill'); assert.equal( - await page.$eval( - '.sl-settings', - (node) => getComputedStyle(node).overflowY, + await page.evaluate(() => + localStorage.getItem('gev:street-level:render-mode'), ), - 'auto', - 'only the settings block scrolls', + 'fill', ); - }, - ); - await step( - 'SHRINK after EXPAND docks the window back in the rail at its default size, viewer inside the panel', - async () => { - await clickPanelControl(page, '#sl-viewer-expand'); - await settle(page, () => - document - .getElementById('sl-viewer-wrap') - .classList.contains('sl-viewer-wrap-expanded'), - ); - assert.equal(await expanded(), true, 'expanded'); - await clickPanelControl(page, '#sl-viewer-expand'); - await settle( - page, - () => - !document - .getElementById('street-level-panel') - .classList.contains('panel-floating') && - !document - .getElementById('sl-viewer-wrap') - .classList.contains('sl-viewer-wrap-expanded'), - ); - assert.equal(await floating(), false, 'docked again'); - const style = await page.$eval('#street-level-panel', (node) => ({ - width: node.style.width, - height: node.style.height, - parent: node.parentElement.id, - })); - assert.deepEqual(style, { - width: '', - height: '', - parent: 'right-context-rail', - }); - const home = await page.evaluate(() => { - const wrap = document.getElementById('sl-viewer-wrap'); - return { - inPanel: Boolean(wrap.closest('#street-level-panel')), - onBody: wrap.parentElement === document.body, - }; - }); + await page.keyboard.press('Home'); + await uiUntil(page, (u) => u.street.renderMode === 'letterbox'); assert.deepEqual( - home, - { inPanel: true, onBody: false }, - 'the viewer returned into the panel', + await page.$eval('[data-sl-render="letterbox"]', (node) => ({ + selected: node.getAttribute('aria-checked'), + tabIndex: node.tabIndex, + focused: document.activeElement === node, + })), + { selected: 'true', tabIndex: 0, focused: true }, ); + await page.keyboard.press('End'); + await uiUntil(page, (u) => u.street.renderMode === 'fill'); }, ); - await step('a header double-click docks a floating window', async () => { - await floatPanel(); - const attempt = await dockPanelByDoubleClick(page, PANEL_ID); + + await step('× closes the photo and deselects its sequence', async () => { + await press(page, '#sl-viewer-close'); + await uiUntil( + page, + (u) => !u.street.open && u.sequence.selectedId === null, + ); assert.equal( - attempt.done, + await page.$eval('#sl-viewer-wrap', (node) => node.hidden), true, - `docked again (${describePress(attempt)})`, ); }); + await step( - 'collapsing a floating window docks it as the rail strip', + 'panorama segments keep native arrow and Home navigation', async () => { - // The double-click just docked a panel showing a photo: let the photo - // and its sequence finish loading before pressing the header again. - await uiUntil((u) => !u.street.loading && !u.sequence.loading); - await floatPanel(); - await clickPanelControl( - page, - '.panel-collapse-btn[data-collapse-target="street-level-panel"]', - ); - await settle(page, () => { - const node = document.getElementById('street-level-panel'); - return ( - node.classList.contains('collapsed') && - !node.classList.contains('panel-floating') - ); - }); - const state = await page.$eval('#street-level-panel', (node) => ({ - floating: node.classList.contains('panel-floating'), - collapsed: node.classList.contains('collapsed'), - height: node.style.height, - })); - assert.deepEqual(state, { - floating: false, - collapsed: true, - height: '', - }); - }, - ); - await step( - 'on a phone the whole photo fits in the docked panel', - async () => { - // Width alone drives the phone layout; toggling isMobile would reload. - await page.setViewport({ width: 390, height: 844 }); - await settle(page, () => innerWidth === 390); - if ( - await page.$eval('#street-level-panel', (node) => - node.classList.contains('collapsed'), - ) - ) - await expandStrip(); - await openById(firstImageId); - const measure = () => - page.evaluate(() => { - const inner = document - .querySelector('.street-level-panel-inner') - .getBoundingClientRect(); - const meta = document - .getElementById('sl-image-meta') - .getBoundingClientRect(); - const viewer = document - .getElementById('sl-viewer') - .getBoundingClientRect(); - return { - cut: Math.round(meta.bottom - inner.bottom), - top: Math.round(viewer.top - inner.top), - height: Math.round(viewer.height), - overflowX: document.documentElement.scrollWidth > innerWidth, - }; - }); - // The panel settles its phone layout over a frame or two. - await settle(page, () => { - const inner = document - .querySelector('.street-level-panel-inner') - .getBoundingClientRect(); - const meta = document - .getElementById('sl-image-meta') - .getBoundingClientRect(); - return ( - meta.bottom - inner.bottom <= 1 && - document.getElementById('sl-viewer').getBoundingClientRect() - .height >= 100 - ); - }); - const fit = await measure(); - assert.ok(fit.cut <= 1, `photo and caption fit (${fit.cut}px cut)`); - assert.ok(fit.height >= 100, `viewer stays usable (${fit.height}px)`); - assert.equal(fit.overflowX, false, 'no sideways scroll'); - await page.setViewport(VIEWPORTS[0]); - await settle( - page, - (width) => innerWidth === width, - VIEWPORTS[0].width, - ); - }, - ); - await step( - 'a reload with the layer on keeps a collapsed panel collapsed, and the share link carries its ui token', - async () => { - await page.evaluate(() => - window.__godsEyeView.dataManager.layers - .get('street-level') - .module.closeViewer(), - ); - // Press through the DOM: a toast over the button must not make this - // step about pointer aim. - await page.$eval( - '.panel-collapse-btn[data-collapse-target="street-level-panel"]', - (button) => { - const panel = document.getElementById('street-level-panel'); - if (!panel.classList.contains('collapsed')) button.click(); - }, - ); - assert.ok( - await settle(page, () => - document - .getElementById('street-level-panel') - .classList.contains('collapsed'), - ), - 'the panel collapsed', - ); - const shared = (collapsed) => - settle( - page, - (assignment) => - (new URLSearchParams(location.hash.slice(1)).get('ui') || '') - .split('_') - .includes(assignment), - `${PANEL_UI_TOKEN}.c.${collapsed ? '1' : '0'}`, - ); - assert.ok( - await shared(true), - `the share link records the collapsed panel as ui ${PANEL_UI_TOKEN}.c.1: ${await page.evaluate(() => location.hash)}`, - ); - await page.reload({ waitUntil: 'domcontentloaded' }); - await clearFirstRun(page); + await page.click('[data-sl-pano="flat"]'); + await uiUntil(page, (u) => u.filter.pano === 'flat'); + await page.keyboard.press('ArrowRight'); + await uiUntil(page, (u) => u.filter.pano === 'all'); + await page.keyboard.press('End'); + await uiUntil(page, (u) => u.filter.pano === 'flat'); + await page.keyboard.press('Home'); + await uiUntil(page, (u) => u.filter.pano === 'all'); await waitForCoverage(page); - // The panel would open on the enable transition, before coverage. - const after = await page.evaluate(() => ({ - enabled: window.__godsEyeView.dataManager.isEnabled('street-level'), - collapsed: document - .getElementById('street-level-panel') - .classList.contains('collapsed'), - })); - assert.deepEqual( - after, - { enabled: true, collapsed: true }, - 'the restored layer did not reopen the panel', - ); - assert.ok(await shared(true), 'still shared as collapsed'); }, ); - if (fixtures) - await step( - 'keyless install (a second page, no key on the server) gates the controls and reports KEY REQUIRED', - async () => { - const keyless = await browser.newPage(); - await keyless.setViewport(VIEWPORTS[0]); - await watch(keyless, 'keyless'); - await serveFixtures(keyless, newFixture({ configured: false })); - await boot(keyless, url); - await expandStrip(keyless); - await assertKeylessGate(keyless); - renderErrorsSeen.push( - ...(await readRenderErrors(keyless)).map( - (text) => `[keyless] scene.renderError: ${text}`, - ), - ); - await keyless.close(); - }, - ); - else - await skipStep( - 'fixtures only', - 'keyless install (a second page) reports KEY REQUIRED', - ); - if (fixtures) - await step( - 'every Mapillary request was answered from a fixture', - () => { - console.log( - ` (answered: ${[...fixture.calls].sort().join(' | ')})`, - ); - assert.deepEqual(fixture.unknown, [], 'no unanswered call'); - }, - ); + + await keylessProviderStep({ + id: 'kartaview', + name: 'KartaView', + at: PARK, + linePrefix: 'kv:line:', + // A row across the middle crosses the drive, west of the old street. + box: null, + reset: resetKartaViewFixture, + check: (street) => { + assert.equal(street.sequenceId, KV_SEQUENCE_ID); + assert.ok( + kartaViewPhotos().some((photo) => photo.id === street.imageId), + `fixture photo ${street.imageId}`, + ); + }, + }); + await keylessProviderStep({ + id: 'panoramax', + name: 'Panoramax', + at: PNX_PARK, + linePrefix: 'pnx:seq:', + // The street runs east-west: scan a column left of the middle. + box: 'column', + reset: resetPanoramaxFixture, + check: (street, lineId) => { + assert.equal(street.sequenceId, lineId, 'the line clicked'); + assert.ok( + panoramaxPictures().some((photo) => photo.id === street.imageId), + `fixture picture ${street.imageId}`, + ); + }, + }); + // Back to Mapillary, where the next page and a reload expect it. + await press(page, '#sl-provider-chips [data-chip-id="mapillary"]'); + await uiUntil(page, litAlone, 'mapillary'); + await park(page); + + await fixtureStep( + 'keyless server (second page): KEY REQUIRED gates the controls', + async () => { + const keyless = await open( + 'keyless', + newFixture({ configured: false }), + ); + await expandPanel(keyless); + await assertKeyRequired(keyless); + await collectRenderErrors(keyless, 'keyless'); + await keyless.close(); + }, + ); + + await fixtureStep( + 'every Mapillary, KartaView and Panoramax request was answered from a fixture', + () => { + console.log(` (answered: ${[...fixture.calls].sort().join(' | ')})`); + assert.deepEqual(fixture.unknown, []); + }, + ); } + + await step('no page errors and no Cesium render-loop errors', async () => { + await collectRenderErrors(page, 'main'); + assert.deepEqual(errors, []); + }); + if (strict) + await step('strict: no skips other than "fixtures only"', () => + assert.deepEqual( + skips.filter((reason) => reason !== 'fixtures only'), + [], + ), + ); + console.log( + `${count} steps: ${count - skips.length} ok, ${skips.length} skipped`, + ); } catch (error) { const dir = await saveFailureArtifacts({ - dir: ARTIFACT_DIR, + dir: 'qa-artifacts/street-level', browser, monitors, error, diff --git a/scripts/qa-traffic-jamviz-ab.mjs b/scripts/qa-traffic-jamviz-ab.mjs index 73d28ca60..b236ab0b1 100644 --- a/scripts/qa-traffic-jamviz-ab.mjs +++ b/scripts/qa-traffic-jamviz-ab.mjs @@ -139,15 +139,19 @@ async function main() { try { const res = await fetch(APP_URL); + // Only the status matters; an unread body can hold the socket open. + await res.body?.cancel(); if (!res.ok) throw new Error(`HTTP ${res.status}`); } catch (e) { console.error(`Dev server not reachable at ${APP_URL} (${e.message}).`); - process.exit(2); + process.exitCode = 2; + return; } const status = await fetch(`${APP_URL}/api/tomtom/status`).then((r) => r.json()).catch(() => null); if (!status?.hasKey) { console.error('Server has no TomTom key — the A/B needs live flow.'); - process.exit(2); + process.exitCode = 2; + return; } fs.mkdirSync(OUT_DIR, { recursive: true }); diff --git a/scripts/qa-traffic-oblique.mjs b/scripts/qa-traffic-oblique.mjs index 596d2f009..6ea1c953d 100644 --- a/scripts/qa-traffic-oblique.mjs +++ b/scripts/qa-traffic-oblique.mjs @@ -80,9 +80,7 @@ try { page.evaluate(() => { const { viewer, dataManager } = window.__godsEyeView; let upper = 0, - lower = 0, - near = 0; - const camera = viewer.camera.positionWC; + lower = 0; dataManager.layers .get('traffic') .module.visitMotionDots((id, key, p) => { diff --git a/scripts/qa-traffic-preset-ab.mjs b/scripts/qa-traffic-preset-ab.mjs index 44319af0d..d1b4950fd 100644 --- a/scripts/qa-traffic-preset-ab.mjs +++ b/scripts/qa-traffic-preset-ab.mjs @@ -145,15 +145,19 @@ async function main() { try { const res = await fetch(APP_URL); + // Only the status matters; an unread body can hold the socket open. + await res.body?.cancel(); if (!res.ok) throw new Error(`HTTP ${res.status}`); } catch (e) { console.error(`Dev server not reachable at ${APP_URL} (${e.message}).`); - process.exit(2); + process.exitCode = 2; + return; } const status = await fetch(`${APP_URL}/api/tomtom/status`).then((r) => r.json()).catch(() => null); if (!status?.hasKey) { console.error('Server has no TomTom key — the A/B needs live flow.'); - process.exit(2); + process.exitCode = 2; + return; } fs.mkdirSync(OUT_DIR, { recursive: true }); diff --git a/scripts/qa-traffic.mjs b/scripts/qa-traffic.mjs index 2a04d5595..9770999df 100644 --- a/scripts/qa-traffic.mjs +++ b/scripts/qa-traffic.mjs @@ -25,12 +25,13 @@ * Visual proof saved to qa-shots/ (gitignored). * * Run: node scripts/qa-traffic.mjs --url http://localhost:4410 - * Add --fixtures for synthetic roads and the recorded flow tile without a key; - * that mode does not qualify live source access or quota accounting. + * Add --fixtures for synthetic road/flow tiles and a flat terrain surface without a key; + * that mode does not qualify geographic terrain, live source access or quota accounting. * Exits non-zero on any FAIL. Does not commit anything. */ import puppeteer from 'puppeteer'; +import { captureQaScreenshot } from './qa-chrome.mjs'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -44,10 +45,12 @@ const getOpt = (name, dflt) => { const i = argv.indexOf(name); return i >= 0 && argv[i + 1] ? argv[i + 1] : dflt; }; -const APP_URL = getOpt('--url', 'http://localhost:4410'); +const appUrl = new URL(getOpt('--url', 'http://localhost:4410')); +appUrl.searchParams.set('welcome', '0'); +const APP_URL = appUrl.href; const HEADFUL = argv.includes('--headful'); const FIXTURES = argv.includes('--fixtures'); -const fixtureResponse = FIXTURES ? (await import('./traffic-fixtures.mjs')).trafficFixtureResponse : () => null; +const { installTrafficRoutes } = await import('./traffic-fixtures.mjs'); const CHROME_EXECUTABLE_CANDIDATES = [ process.env.PUPPETEER_EXECUTABLE_PATH, @@ -80,6 +83,10 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); /** Enable traffic + teleport, then poll the layer until settled. */ async function settleTraffic(page, view, { minCount = 1, timeoutS = 30 } = {}) { + // The app deliberately stops rendering hidden pages. Programmatic camera + // changes do not activate a headful window the way a real UI click does. + await page.bringToFront(); + await page.waitForFunction(() => document.visibilityState === 'visible'); return page.evaluate(async (v, minC, tS) => { const gev = window.__godsEyeView; const dm = gev.dataManager; @@ -97,6 +104,7 @@ async function settleTraffic(page, view, { minCount = 1, timeoutS = 30 } = {}) { }); let s = null; for (let i = 0; i < tS; i++) { + if (document.visibilityState !== 'visible') throw new Error('Traffic QA page became hidden; rendering is intentionally paused'); await new Promise((r) => setTimeout(r, 1000)); s = mod.getStats(); // Retained roads from the previous city can satisfy count/loading before @@ -113,17 +121,21 @@ async function main() { try { const res = await fetch(APP_URL); + // Only the status matters; an unread body can hold the socket open. + await res.body?.cancel(); if (!res.ok) throw new Error(`HTTP ${res.status}`); } catch (e) { console.error(`\x1b[31mDev server not reachable at ${APP_URL} (${e.message}).\x1b[0m`); - process.exit(2); + process.exitCode = 2; + return; } - const statusBefore = FIXTURES ? {hasKey:true,dailyCount:0} : await fetch(`${APP_URL}/api/tomtom/status`).then((r) => r.json()).catch(() => null); - if (FIXTURES) console.log('Source mode: synthetic roads and recorded flow tiles; live quota is not qualified.'); + const statusBefore = FIXTURES ? {hasKey:true,dailyCount:0} : await fetch(`${appUrl.origin}/api/tomtom/status`).then((r) => r.json()).catch(() => null); + if (FIXTURES) console.log('Source mode: synthetic road/flow tiles and a flat terrain surface; live quota is not qualified.'); if (!statusBefore?.hasKey) { console.error('\x1b[31mServer has no TomTom key — run against the keyed dev server (:4410).\x1b[0m'); - process.exit(2); + process.exitCode = 2; + return; } fs.mkdirSync(SHOTS_DIR, { recursive: true }); @@ -131,8 +143,10 @@ async function main() { headless: HEADFUL ? false : 'new', ...(findChromeExecutable() ? { executablePath: findChromeExecutable() } : {}), args: [ - '--no-sandbox', '--disable-setuid-sandbox', '--use-gl=angle', '--use-angle=swiftshader', - '--disable-dev-shm-usage', '--disable-web-security', + '--no-sandbox', '--disable-setuid-sandbox', + ...(!HEADFUL ? ['--use-gl=angle', '--use-angle=swiftshader'] : []), + '--disable-backgrounding-occluded-windows', + '--disable-dev-shm-usage', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--window-size=1440,900', ], @@ -140,24 +154,22 @@ async function main() { let exitCode = 0; try { - const page = await browser.newPage(); - const onFixture = (request) => { - const response = fixtureResponse(request); - if (response) void request.respond(response); else void request.continue(); - }; - if (FIXTURES) { await page.setRequestInterception(true); page.on('request', onFixture); } + let page = await browser.newPage(); + // Keep this visible-page regression deterministic even if the OS starts + // Chrome minimized. Use browser focus emulation, not patched DOM getters. + const focusSession = await page.createCDPSession(); + await focusSession.send('Emulation.setFocusEmulationEnabled', { enabled: true }); await page.setViewport({ width: 1440, height: 900 }); - // Track flow-tile requests + traffic console lines for (ii)/(iii)/(v). + // Track flow-tile requests for the (iii) budget check. const flowRequests = []; page.on('request', (req) => { if (req.url().includes('/api/tomtom/flow/')) flowRequests.push(req.url()); }); - const trafficLogs = []; - page.on('console', (msg) => { - const t = msg.text(); - if (t.includes('[Data:Traffic]')) trafficLogs.push(t); - }); + const pageErrors = []; + if (FIXTURES) await installTrafficRoutes(page, { origin: appUrl.origin, fixtures: true, onError: error => pageErrors.push(error.message) }); + page.on('pageerror', error => { pageErrors.push(error.message); console.error('PAGE ERROR:', error.message); }); + page.on('console', message => { if (message.type() === 'error') console.error('BROWSER ERROR:', message.text()); }); console.log('Loading app...'); await page.goto(APP_URL, { waitUntil: 'domcontentloaded', timeout: 60000 }); @@ -190,7 +202,7 @@ async function main() { `coverage=${mumbai.flowCoveragePct}% tiles=${mumbai.tilesFetched}`); if (mumbai.mode !== 'live' || !(mumbai.count > 0) || !(colored > 0)) exitCode = 1; await sleep(1200); - await page.screenshot({ path: path.join(SHOTS_DIR, 'traffic-live-flow.png') }); + await captureQaScreenshot(page, { path: path.join(SHOTS_DIR, 'traffic-live-flow.png') }, { headful: HEADFUL }); } // ── (iv) uncovered-roads param — hide vs sim ───────────────────────────── @@ -223,7 +235,7 @@ async function main() { (hid.flowBuckets?.sim || 0) === 0 && hid.count > 0, `count=${hid.count} sim=${hid.flowBuckets?.sim}`); if ((hid.flowBuckets?.sim || 0) !== 0) exitCode = 1; - await page.screenshot({ path: path.join(SHOTS_DIR, 'traffic-live-hide-mode.png') }); + await captureQaScreenshot(page, { path: path.join(SHOTS_DIR, 'traffic-live-hide-mode.png') }, { headful: HEADFUL }); } else { record('PARAM: hide mode renders zero sim (white) dots', null, 'view had 100% coverage (no sim dots to hide) — inconclusive here, covered by unit tests'); @@ -231,30 +243,26 @@ async function main() { // ── (ii) C4 oblique bounds ─────────────────────────────────────────────── console.log('\n(ii) C4 — oblique fetch bounds land at the look-at point...'); - trafficLogs.length = 0; - await settleTraffic(page, { lon: -97.72, lat: 30.245, height: 2500, heading: 315, pitch: -20 }, { minCount: 100 }); + const oblique = await settleTraffic(page, { lon: -97.72, lat: 30.245, height: 2500, heading: 315, pitch: -20 }, { minCount: 100 }); { - const fetchLine = trafficLogs.find((t) => t.includes('fetch') && t.includes('[')); - let ok = false; let detail = 'no fetch log captured'; - if (fetchLine) { - const m = fetchLine.match(/\[(-?[\d.]+),(-?[\d.]+),(-?[\d.]+),(-?[\d.]+)\]/); - if (m) { - const [s, w, n, e] = m.slice(1).map(Number); - const cLat = (s + n) / 2; const cLon = (w + e) / 2; - const dKm = Math.sqrt(((cLat - 30.245) * 111) ** 2 + ((cLon - (-97.72)) * 111 * Math.cos(30.27 * Math.PI / 180)) ** 2); - ok = dKm > 1 && dKm <= 13; // look-at ~6.9 km ahead; clamp allows ≤12 (+margin) - detail = `box center (${cLat.toFixed(4)},${cLon.toFixed(4)}) is ${dKm.toFixed(1)} km from camera (want 1–13 km; pre-fix bug: 25+ km)`; - } + const bounds = oblique?.roadBounds; + let ok = false; let detail = 'no road bounds published'; + if (bounds) { + const cLat = (bounds.south + bounds.north) / 2; + const cLon = (bounds.west + bounds.east) / 2; + const dKm = Math.hypot((cLat - 30.245) * 111, (cLon + 97.72) * 111 * Math.cos(30.27 * Math.PI / 180)); + ok = dKm > 1 && dKm <= 13; + detail = `road box center is ${dKm.toFixed(1)} km from camera (want 1–13 km)`; } record('C4: oblique fetch box centers on the look-at point', ok, detail); if (!ok) exitCode = 1; - await page.screenshot({ path: path.join(SHOTS_DIR, 'traffic-c4-oblique.png') }); + await captureQaScreenshot(page, { path: path.join(SHOTS_DIR, 'traffic-c4-oblique.png') }, { headful: HEADFUL }); } // ── (iii) budget honesty ───────────────────────────────────────────────── console.log('\n(iii) Budget — dailyCount grew by ≤ requests this run...'); { - const statusAfter = FIXTURES ? statusBefore : await fetch(`${APP_URL}/api/tomtom/status`).then((r) => r.json()); + const statusAfter = FIXTURES ? statusBefore : await fetch(`${appUrl.origin}/api/tomtom/status`).then((r) => r.json()); const grew = statusAfter.dailyCount - statusBefore.dailyCount; const ok = grew >= 0 && grew <= flowRequests.length; record('BUDGET: /api/tomtom/status growth ≤ page tile requests', FIXTURES ? null : ok, @@ -264,25 +272,22 @@ async function main() { // ── (v) KEYLESS fallback (intercepted — server key untouched) ──────────── console.log('\n(v) KEYLESS — intercepted status, expect pure simulation...'); - if (FIXTURES) page.off('request', onFixture); - await page.setRequestInterception(true); + // Keyless is an independent fresh-session contract. Close the keyed page + // so its workers, terrain work and intercepted cache cannot leak into it. + await page.close(); + page = await browser.newPage(); + await page.setViewport({ width: 1440, height: 900 }); + const keylessFocus = await page.createCDPSession(); + await keylessFocus.send('Emulation.setFocusEmulationEnabled', { enabled: true }); + page.on('pageerror', error => { pageErrors.push(error.message); console.error('PAGE ERROR:', error.message); }); + page.on('console', message => { if (message.type() === 'error') console.error('BROWSER ERROR:', message.text()); }); const keylessFlowReqs = []; - page.on('request', (req) => { - const url = req.url(); - if (url.includes('/api/tomtom/status')) { - req.respond({ status: 200, contentType: 'application/json', body: JSON.stringify({ hasKey: false }) }); - return; - } - if (url.includes('/api/tomtom/flow/')) { - keylessFlowReqs.push(url); - req.respond({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: 'no_key' }) }); - return; - } - const response = fixtureResponse(req); - if (response) { void req.respond(response); return; } - try { req.continue(); } catch { /* already handled */ } + await installTrafficRoutes(page, { + origin: appUrl.origin, fixtures: FIXTURES, keyless: true, + onFlow: url => keylessFlowReqs.push(url), + onError: error => pageErrors.push(error.message), }); - await page.reload({ waitUntil: 'domcontentloaded', timeout: 60000 }); + await page.goto(APP_URL, { waitUntil: 'domcontentloaded', timeout: 60000 }); await page.waitForFunction( () => window.__godsEyeView?.viewer && window.__godsEyeView?.dataManager, { timeout: 60000 }, @@ -312,8 +317,9 @@ async function main() { exitCode = 1; } await sleep(1000); - await page.screenshot({ path: path.join(SHOTS_DIR, 'traffic-sim-keyless.png') }); + await captureQaScreenshot(page, { path: path.join(SHOTS_DIR, 'traffic-sim-keyless.png') }, { headful: HEADFUL }); } + record('BROWSER: no uncaught page exceptions', pageErrors.length === 0, pageErrors.join('; ')); } catch (e) { console.error('\x1b[31mHarness error:\x1b[0m', e); exitCode = 3; diff --git a/scripts/qa-transit-browser.mjs b/scripts/qa-transit-browser.mjs index eb7b59985..23925c743 100644 --- a/scripts/qa-transit-browser.mjs +++ b/scripts/qa-transit-browser.mjs @@ -47,6 +47,7 @@ export async function reportTransitVisibility(page, label) { const layer = app.dataManager.layers.get('transit').module; const state = layer._transitStateForTest(); return { + pageVisibility: document.visibilityState, total: state._vehicles.size, visible: state._visible.size, moving: state._moving.size, @@ -59,6 +60,10 @@ export async function reportTransitVisibility(page, label) { }; }); console.log(` ${label}: ${JSON.stringify(result)}`); + if (result.pageVisibility !== 'visible') + throw new Error( + `${label}: Transit QA requires a visible page; hidden pages deliberately pause polling`, + ); if (result.renderLoop === false || result.renderErrors.length) throw new Error( `${label}: Cesium render loop stopped or raised an error: ${JSON.stringify(result.renderErrors)}`, diff --git a/scripts/qa-transit-controls.mjs b/scripts/qa-transit-controls.mjs index b76e14706..70ed1503c 100644 --- a/scripts/qa-transit-controls.mjs +++ b/scripts/qa-transit-controls.mjs @@ -1,6 +1,7 @@ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export const BOSTON = { id: 'boston', + feedId: 'mbta', label: 'Boston (MBTA)', lat: 42.3554, lon: -71.0605, @@ -11,6 +12,7 @@ const LIVE_CITIES = [ BOSTON, { id: 'austin', + feedId: 'capmetro-austin', label: 'Austin (CapMetro)', lat: 30.2672, lon: -97.7431, @@ -19,6 +21,7 @@ const LIVE_CITIES = [ }, { id: 'minneapolis', + feedId: 'metrotransit-msp', label: 'Minneapolis (Metro Transit)', lat: 44.9778, lon: -93.265, @@ -27,6 +30,7 @@ const LIVE_CITIES = [ }, { id: 'helsinki', + feedId: 'hsl-helsinki', label: 'Helsinki (HSL)', lat: 60.1699, lon: 24.9384, @@ -35,6 +39,7 @@ const LIVE_CITIES = [ }, { id: 'oslo', + feedId: 'entur-norway', label: 'Oslo (Entur)', lat: 59.9139, lon: 10.7522, diff --git a/scripts/qa-transit-heading.mjs b/scripts/qa-transit-heading.mjs index a16bab9bc..c229be96c 100644 --- a/scripts/qa-transit-heading.mjs +++ b/scripts/qa-transit-heading.mjs @@ -1,11 +1,11 @@ import puppeteer from 'puppeteer'; +import { chromeExecutablePath } from './qa-chrome.mjs'; /** Prove parked and moving headings in the real scene, without live feeds. */ export async function runTransitHeadingRegression(base, check) { const browser = await puppeteer.launch({ headless: true, - executablePath: - '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + executablePath: chromeExecutablePath(), args: ['--no-sandbox', '--disable-background-timer-throttling'], }); try { diff --git a/scripts/qa-transit-recovery.mjs b/scripts/qa-transit-recovery.mjs index e5fadda49..a54e81239 100644 --- a/scripts/qa-transit-recovery.mjs +++ b/scripts/qa-transit-recovery.mjs @@ -1,5 +1,6 @@ /** Camera-jump regression against an existing server; never starts a server. */ import puppeteer from 'puppeteer'; +import { chromeExecutablePath, captureQaScreenshot } from './qa-chrome.mjs'; import { mkdir, writeFile } from 'node:fs/promises'; import { reduceTrailPixels } from '../src/layers/transit/qaMetrics.js'; @@ -8,8 +9,7 @@ const shots = process.env.QA_SHOTS || 'qa-shots/transit-recovery'; await mkdir(shots, { recursive: true }); const browser = await puppeteer.launch({ headless: false, - executablePath: - '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + executablePath: chromeExecutablePath(), args: [ '--disable-background-timer-throttling', '--disable-renderer-backgrounding', @@ -307,7 +307,7 @@ try { result.pixelPass = pixels.pass; result.pixelDetails = pixels; result.errors = errors; - await page.screenshot({ path: `${shots}/recovery.png` }); + await captureQaScreenshot(page, { path: `${shots}/recovery.png` }); await writeFile(`${shots}/recovery.json`, JSON.stringify(result, null, 2)); for (const key of ['on', 'off', 'onAgain', 'offAgain']) delete result[key]; const pass = diff --git a/scripts/qa-transit-scenes.mjs b/scripts/qa-transit-scenes.mjs index 1ceb45b22..f325cb9f7 100644 --- a/scripts/qa-transit-scenes.mjs +++ b/scripts/qa-transit-scenes.mjs @@ -1,3 +1,4 @@ +import { captureQaScreenshot } from './qa-chrome.mjs'; import { getRegisteredTransitFeed } from '../src/data/transitFeeds.js'; // Not registered or active: camera discovery and live polls never own this feed. @@ -219,7 +220,7 @@ export async function runFleetBudgets({ allocations.layerFrameBytes / allocationTrace.rows.length <= 8192, `${allocations.layerFrameBytes / allocationTrace.rows.length} transit-authored bytes/frame; whole frame ${allocations.frameBytes / allocationTrace.rows.length}; top three ${JSON.stringify(details.topAllocatorsPerFrame)}; collected objects included. Full profile saved.`, ); - await page.screenshot({ + await captureQaScreenshot(page, { path: `${shots}/${tag}-fleet-${count}.jpg`, type: 'jpeg', quality: 85, @@ -392,7 +393,7 @@ export async function runBostonMatrix({ JSON.stringify({ pixels, contrast }), { unexercised: pixels.length < 6 }, ); - await page.screenshot({ + await captureQaScreenshot(page, { path: `${shots}/${tag}-matrix-${background.name}-${look.name}-fleet.jpg`, type: 'jpeg', quality: 90, @@ -407,7 +408,7 @@ export async function runBostonMatrix({ target.key, ); await wait(500); - await page.screenshot({ + await captureQaScreenshot(page, { path: `${shots}/${tag}-matrix-${background.name}-${look.name}-${target.route}-selected.jpg`, type: 'jpeg', quality: 90, @@ -431,7 +432,7 @@ export async function runBostonMatrix({ ); } await wait(300); - await page.screenshot({ + await captureQaScreenshot(page, { path: `${shots}/${tag}-matrix-${background.name}-${look.name}-restored.jpg`, type: 'jpeg', quality: 90, @@ -579,7 +580,7 @@ export async function runBostonLive({ JSON.stringify(selection), { unexercised: !target }, ); - await page.screenshot({ + await captureQaScreenshot(page, { path: `${shots}/${tag}-boston-live-${view.name}.jpg`, type: 'jpeg', quality: 90, @@ -1010,7 +1011,7 @@ export async function runTrailVisibility({ stable: pixels.stable[i], eligible: pixels.eligible[i], })); - await page.screenshot({ + await captureQaScreenshot(page, { path: `${shots}/${tag}-${altitude}m-trail-visible.jpg`, type: 'jpeg', quality: 95, diff --git a/scripts/qa-transit.mjs b/scripts/qa-transit.mjs index aac1d8f60..49a25fd18 100644 --- a/scripts/qa-transit.mjs +++ b/scripts/qa-transit.mjs @@ -36,9 +36,11 @@ import { */ import { mkdir, readFile, writeFile } from 'node:fs/promises'; import puppeteer from 'puppeteer'; +import { chromeExecutablePath, captureQaScreenshot } from './qa-chrome.mjs'; import { createTransitHistory } from '../server/providers/transitHistory.js'; import { DETECTION_THEME_MAP } from '../src/overlays/worldOverlayTokens.js'; import { transitModeTier } from '../src/data/transitPresetStyle.js'; +import { TRANSIT_POLL_MS } from '../src/layers/transit/policy.js'; import { reduceAnchor, @@ -46,8 +48,6 @@ import { reduceScenario, reduceSensorContrast, reduceScriptedMotion, - reduceMotion, - reduceFleet, } from '../src/layers/transit/qaMetrics.js'; const BASE = process.env.QA_BASE_URL || 'http://localhost:4173'; @@ -262,10 +262,10 @@ await mkdir(SHOTS, { recursive: true }); const browser = await puppeteer.launch({ headless: false, protocolTimeout: 150000, - executablePath: - '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + executablePath: chromeExecutablePath(), args: [ '--no-sandbox', + '--disable-backgrounding-occluded-windows', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--window-size=1920,1080', @@ -273,6 +273,10 @@ const browser = await puppeteer.launch({ ], }); const page = await browser.newPage(); +// This gate measures visible-page motion. OS minimization must not silently +// switch it into the app's intentional hidden-tab polling pause. +const focus = await page.createCDPSession(); +await focus.send('Emulation.setFocusEmulationEnabled', { enabled: true }); boundPageEvaluations(page); await page.setViewport({ width: 1920, height: 1080 }); const pageErrors = []; @@ -288,11 +292,13 @@ page.on('request', (request) => { }); const shot = (name, caption) => - page - .screenshot({ path: `${SHOTS}/${name}`, type: 'jpeg', quality: 82 }) - .then(() => { - console.log(` shot ${name} — ${caption}`); - }); + captureQaScreenshot(page, { + path: `${SHOTS}/${name}`, + type: 'jpeg', + quality: 82, + }).then(() => { + console.log(` shot ${name} — ${caption}`); + }); const view = (city) => `${BASE}/?welcome=0#lat=${city.lat}&lon=${city.lon}&alt=600&heading=${city.heading}&pitch=-45`; @@ -391,22 +397,42 @@ try { orientation: { heading: 0, pitch: (-40 * Math.PI) / 180, roll: 0 }, }); }, city); - await page.waitForFunction( - () => - (window.__godsEyeView.dataManager.layers - .get('transit') - .module.getStats().count || 0) > 0, - { timeout: 90_000 }, - ); + const arrived = await page + .waitForFunction( + (feedId) => + [ + ...window.__godsEyeView.dataManager.layers + .get('transit') + .module._transitStateForTest() + ._vehicles.keys(), + ].some((key) => key.startsWith(`${feedId}:`)), + { timeout: 90_000 }, + city.feedId, + ) + .then( + () => true, + () => false, + ); + if (!arrived) { + check( + `${city.label}: live feed arrived`, + false, + `No vehicles from ${city.feedId}; retained vehicles from other cities cannot qualify this view`, + { unexercised: true }, + ); + continue; + } await wait(9_000); - const fleet = await page.evaluate(() => { + const fleet = await page.evaluate((feedId) => { const layer = window.__godsEyeView.dataManager.layers.get('transit').module; return { - count: layer._transitStateForTest()._vehicles.size, + count: [...layer._transitStateForTest()._vehicles.keys()].filter( + (key) => key.startsWith(`${feedId}:`), + ).length, stats: layer.getStats(), }; - }); + }, city.feedId); check( `${city.label}: vehicles are rendered`, fleet.count >= 20, @@ -428,6 +454,7 @@ try { .module._transitStateForTest(); let best = null; for (const entry of state._vehicles.values()) { + if (!entry.key.startsWith(`${c.feedId}:`)) continue; const d = Math.hypot(entry.to.lat - c.lat, entry.to.lon - c.lon); if (!best || d < best.d) best = { d, lat: entry.to.lat, lon: entry.to.lon, key: entry.key }; @@ -1609,6 +1636,7 @@ try { m[3] * v[0] + m[7] * v[1] + m[11] * v[2] + m[15] * v[3], ]; const frames = []; + const observedPolls = new Set(); const publicationsBefore = state._cardPublications || 0; let headSamples = 0, headErrorPx = 0, @@ -1625,6 +1653,13 @@ try { const proj = scene.camera.frustum.projectionMatrix; const p = entry.marker.position; const clip = mul(proj, mul(view, [p.x, p.y, p.z, 1])); + if ( + entry.marker.show !== false && + rect && + Number.isFinite(entry.pollSeq) + ) { + observedPolls.add(entry.pollSeq); + } frames.push({ t: performance.now() - t0, mx: ((clip[0] / clip[3]) * 0.5 + 0.5) * canvas.clientWidth, @@ -1670,7 +1705,15 @@ try { headSamples++; } } - if (performance.now() - t0 >= durationMs) finish(); + const elapsed = performance.now() - t0; + // Keep at least 20 seconds of motion and require an observed poll + // transition. A fixed 20s wall-clock window can miss a 15s poll + // when an earlier refresh is still settling. + if ( + (elapsed >= 20_000 && observedPolls.size >= 2) || + elapsed >= durationMs + ) + finish(); }; let remove; const finish = () => { @@ -1678,6 +1721,7 @@ try { remove?.(); resolve({ selected: true, + elapsedMs: performance.now() - t0, frames, textPublishes: (state._cardPublications || 0) - publicationsBefore, @@ -1692,7 +1736,7 @@ try { }); }, target.key, - 20_000, + 3 * TRANSIT_POLL_MS, ); } check( @@ -1713,8 +1757,9 @@ try { ); check( 'card text publication stays throttled while the anchor runs at frame rate', - anchor.textPublishes > 0 && anchor.textPublishes <= 20_000 / 250 + 3, - `${anchor.textPublishes} text publications in 20 s`, + anchor.textPublishes > 0 && + anchor.textPublishes <= anchor.elapsedMs / 250 + 3, + `${anchor.textPublishes} text publications in ${(anchor.elapsedMs / 1000).toFixed(1)} s`, ); } else { check( diff --git a/scripts/qa-ui-disposal.mjs b/scripts/qa-ui-disposal.mjs index d393648df..9c351f388 100644 --- a/scripts/qa-ui-disposal.mjs +++ b/scripts/qa-ui-disposal.mjs @@ -40,14 +40,12 @@ try { cancelable: true, }), ); + // The title bar renders the readout on Vue's next flush. + await Promise.resolve(); const fpsReadout = document.querySelector('.frame-rate-readout'); const fpsWasVisible = fpsReadout && !fpsReadout.hidden; const watchObserver = (name) => { - const owner = - name === '_draggableResizeObserver' - ? ui._panelPosition - : ui._panelLayout; - const observer = owner[name]; + const observer = ui._panelLayout[name]; if (!observer) return false; const disconnect = observer.disconnect.bind(observer); counts[name] = 0; @@ -59,7 +57,6 @@ try { }; const observed = [ '_commandDockTrayObserver', - '_draggableResizeObserver', '_leftStackResizeObserver', '_rightStackResizeObserver', '_leftStackMutationObserver', @@ -123,10 +120,18 @@ try { if (type === 'resize' && callback === resizeHandler) counts.resize++; return removeEventListener.call(this, type, callback, options); }; - const { setSplitFlapText } = await import('/src/splitFlap.js'); + // Through the owner, so its copy of the label and the store agree. const feedbackLabel = document.getElementById('global-loading-label'); - setSplitFlapText(feedbackLabel, 'CHECKING LIVE DATA'); - setSplitFlapText(feedbackLabel, 'LOAD COMPLETE'); + for (const label of ['CHECKING LIVE DATA', 'LOAD COMPLETE']) { + ui._feedback._publishLoading({ + hidden: false, + state: 'loading', + label, + detail: '', + }); + // Vue renders on a microtask; a task later the label shows it. + await new Promise((resolve) => setTimeout(resolve)); + } const permanentText = feedbackLabel.querySelector('.gev-flap-text')?.firstChild; let stateNotifications = 0; @@ -139,7 +144,6 @@ try { const focusBefore = document.activeElement; const stoppedBeforeRestoration = ui._panelLayout.destroyed && - ui._panelPosition.destroyed && ui._feedback.destroyed && ui._recording.destroyed && cockpit.destroyed && @@ -194,11 +198,7 @@ try { counts[field] === 1 && ui._contextControls[field] === null, ), observersReleased: observed.every( - (name) => - counts[name] === 1 && - (name === '_draggableResizeObserver' - ? ui._panelPosition - : ui._panelLayout)[name] === null, + (name) => counts[name] === 1 && ui._panelLayout[name] === null, ), subscriptionReleased: counts.cctv === 1 && ui._cctvControls._cctvUnsubscribe === null, @@ -212,6 +212,7 @@ try { feedbackLabel.querySelector('.gev-flap-text')?.firstChild === permanentText && permanentText.data === 'LOAD COMPLETE' && + document.getElementById('global-loading-status').hidden && !feedbackLabel.classList.contains('gev-flap-active') && feedbackLabel.querySelector('.gev-flap-cells')?.childNodes.length === 0, @@ -221,7 +222,9 @@ try { ui._lifetime.timers.size === 0 && ui._lifetime.removers.size === 0, frameRateReleased: - fpsWasVisible && !fpsReadout.isConnected && fpsReadout.hidden, + fpsWasVisible && + !fpsReadout.isConnected && + !document.querySelector('.frame-rate-readout'), stateStopped: stateNotifications === 0, idempotent: once === JSON.stringify(counts), }; diff --git a/scripts/qa-vessel-cards.mjs b/scripts/qa-vessel-cards.mjs index b5ad8ac87..278c1c71f 100644 --- a/scripts/qa-vessel-cards.mjs +++ b/scripts/qa-vessel-cards.mjs @@ -295,7 +295,7 @@ async function main() { ); // Wait for the photoreal tileset and at least one vessel refresh. - const settled = await page + await page .waitForFunction(() => { const gev = window.__godsEyeView; const t = gev.tileset; diff --git a/scripts/qa-visual-effects.mjs b/scripts/qa-visual-effects.mjs index db0696e08..f3b9ab8bd 100644 --- a/scripts/qa-visual-effects.mjs +++ b/scripts/qa-visual-effects.mjs @@ -80,7 +80,6 @@ try { 'thermal', 'anime', 'noir', - 'snow', 'normal', ]) { await page.evaluate( diff --git a/scripts/qa-visual-input.mjs b/scripts/qa-visual-input.mjs index 3117e1414..3c096acdc 100644 --- a/scripts/qa-visual-input.mjs +++ b/scripts/qa-visual-input.mjs @@ -57,7 +57,7 @@ try { persist: false, syncShare: false, }); - manager._sliderPanel.classList.remove('collapsed'); + manager._presentPanel(manager._sliderPanel, { collapsed: false }); const slider = manager._sliderContainer.querySelector('input'); window.__qaOldSlider = slider; const name = 'pixelation'; @@ -140,9 +140,11 @@ try { hudBefore, ), ); - const displayBefore = await page.evaluate(() => { + const displayBefore = await page.evaluate(async () => { const manager = window.__godsEyeView.styleManager; manager._setBloomEnabled(true); + // The Display view shows the slider row on its next render. + await new Promise((resolve) => requestAnimationFrame(resolve)); manager._bloomSlider.value = '80'; manager._bloomSlider.dispatchEvent(new Event('input', { bubbles: true })); manager._bloomSlider.focus(); @@ -183,6 +185,38 @@ try { return manager.bloomEnabled !== before; }), ); + const sliders = await page.evaluate(() => { + const ordinary = [ + ...document.querySelectorAll('input[type="range"]'), + ].filter( + (input) => !input.matches('#radio-tuner-slider, .bhote-event-range'), + ); + return { + count: ordinary.length, + shared: ordinary.every((input) => + input.classList.contains('gev-quantitative-slider'), + ), + surface: ordinary.every((input) => { + const style = getComputedStyle(input); + return ( + style.height === '18px' && + style.appearance === 'none' && + style.padding === '0px' && + style.borderWidth === '0px' && + (!input.disabled || + (style.opacity === '0.42' && style.cursor === 'not-allowed')) + ); + }), + tunerSeparate: !document + .getElementById('radio-tuner-slider') + .classList.contains('gev-quantitative-slider'), + }; + }); + check( + 'ordinary sliders share one native surface', + sliders.count > 10 && sliders.shared && sliders.surface, + ); + check('radio tuning keeps its specialized control', sliders.tunerSeparate); fs.mkdirSync('qa-shots/visual-input', { recursive: true }); await page.screenshot({ path: 'qa-shots/visual-input/desktop.png' }); await page.setViewport({ width: 620, height: 900 }); @@ -231,7 +265,7 @@ try { 'destroyed Display controls cannot change settings', await page.evaluate(() => { const manager = window.__godsEyeView.styleManager; - manager._displayControls.destroy(); + manager._displayBindings._detachDisplayControls(); const before = manager.bloomEnabled; const contrast = manager._bloomStage.uniforms.contrast; manager._bloomBtn.click(); diff --git a/scripts/qa-voice-auth-focus.mjs b/scripts/qa-voice-auth-focus.mjs index 6d131a22c..1382ac851 100644 --- a/scripts/qa-voice-auth-focus.mjs +++ b/scripts/qa-voice-auth-focus.mjs @@ -12,10 +12,14 @@ import { after, before, test } from 'node:test'; import puppeteer from 'puppeteer'; const root = new URL('../', import.meta.url); -const template = await readFile( - new URL('src/ui/templates/provider-settings.html', root), +const view = await readFile( + new URL('src/ui/views/ProviderSettingsView.vue', root), 'utf8', ); +const template = view.slice( + view.indexOf('